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.

277628 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. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  213. If your app doesn't need to read FLAC files, you might want to disable this to
  214. reduce the size of your codebase and build time.
  215. */
  216. #ifndef JUCE_USE_FLAC
  217. #define JUCE_USE_FLAC 1
  218. #endif
  219. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  220. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  221. reduce the size of your codebase and build time.
  222. */
  223. #ifndef JUCE_USE_OGGVORBIS
  224. #define JUCE_USE_OGGVORBIS 1
  225. #endif
  226. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  227. Unless you're using CD-burning, you should probably turn this flag off to
  228. reduce code size.
  229. */
  230. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  231. #define JUCE_USE_CDBURNER 0
  232. #endif
  233. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  234. Unless you're using CD-reading, you should probably turn this flag off to
  235. reduce code size.
  236. */
  237. #ifndef JUCE_USE_CDREADER
  238. #define JUCE_USE_CDREADER 0
  239. #endif
  240. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  241. */
  242. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  243. #define JUCE_USE_CAMERA 0
  244. #endif
  245. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  246. gets repainted will flash in a random colour, so that you can check exactly how much and how
  247. often your components are being drawn.
  248. */
  249. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  250. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  251. #endif
  252. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  253. Unless you specifically want to disable this, it's best to leave this option turned on.
  254. */
  255. #ifndef JUCE_USE_XINERAMA
  256. #define JUCE_USE_XINERAMA 1
  257. #endif
  258. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  259. turned on unless you have a good reason to disable it.
  260. */
  261. #ifndef JUCE_USE_XSHM
  262. #define JUCE_USE_XSHM 1
  263. #endif
  264. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  265. */
  266. #ifndef JUCE_USE_XRENDER
  267. #define JUCE_USE_XRENDER 0
  268. #endif
  269. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  270. unless you have a good reason to disable it.
  271. */
  272. #ifndef JUCE_USE_XCURSOR
  273. #define JUCE_USE_XCURSOR 1
  274. #endif
  275. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  276. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  277. you're building a plugin hosting app.
  278. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  279. */
  280. #ifndef JUCE_PLUGINHOST_VST
  281. #define JUCE_PLUGINHOST_VST 0
  282. #endif
  283. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  284. of course, and should only be enabled if you're building a plugin hosting app.
  285. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  286. */
  287. #ifndef JUCE_PLUGINHOST_AU
  288. #define JUCE_PLUGINHOST_AU 0
  289. #endif
  290. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  291. This should be enabled if you're writing a console application.
  292. */
  293. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  294. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  295. #endif
  296. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  297. If you're not using any embedded web-pages, turning this off may reduce your code size.
  298. */
  299. #ifndef JUCE_WEB_BROWSER
  300. #define JUCE_WEB_BROWSER 1
  301. #endif
  302. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  303. Carbon isn't required for a normal app, but may be needed by specialised classes like
  304. plugin-hosts, which support older APIs.
  305. */
  306. #ifndef JUCE_SUPPORT_CARBON
  307. #define JUCE_SUPPORT_CARBON 1
  308. #endif
  309. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  310. You might need to tweak this if you're linking to an external zlib library in your app,
  311. but for normal apps, this option should be left alone.
  312. */
  313. #ifndef JUCE_INCLUDE_ZLIB_CODE
  314. #define JUCE_INCLUDE_ZLIB_CODE 1
  315. #endif
  316. #ifndef JUCE_INCLUDE_FLAC_CODE
  317. #define JUCE_INCLUDE_FLAC_CODE 1
  318. #endif
  319. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  320. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  323. #define JUCE_INCLUDE_PNGLIB_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  326. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  327. #endif
  328. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  329. (Currently, this only affects Windows builds in debug mode).
  330. */
  331. #ifndef JUCE_CHECK_MEMORY_LEAKS
  332. #define JUCE_CHECK_MEMORY_LEAKS 1
  333. #endif
  334. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  335. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  336. are passed to the JUCEApplication::unhandledException() callback for logging.
  337. */
  338. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  339. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  340. #endif
  341. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  342. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  343. #undef JUCE_QUICKTIME
  344. #define JUCE_QUICKTIME 0
  345. #undef JUCE_OPENGL
  346. #define JUCE_OPENGL 0
  347. #undef JUCE_USE_CDBURNER
  348. #define JUCE_USE_CDBURNER 0
  349. #undef JUCE_USE_CDREADER
  350. #define JUCE_USE_CDREADER 0
  351. #undef JUCE_WEB_BROWSER
  352. #define JUCE_WEB_BROWSER 0
  353. #undef JUCE_PLUGINHOST_AU
  354. #define JUCE_PLUGINHOST_AU 0
  355. #undef JUCE_PLUGINHOST_VST
  356. #define JUCE_PLUGINHOST_VST 0
  357. #endif
  358. #endif
  359. /*** End of inlined file: juce_Config.h ***/
  360. // FORCE_AMALGAMATOR_INCLUDE
  361. #ifndef JUCE_BUILD_CORE
  362. #define JUCE_BUILD_CORE 1
  363. #endif
  364. #ifndef JUCE_BUILD_MISC
  365. #define JUCE_BUILD_MISC 1
  366. #endif
  367. #ifndef JUCE_BUILD_GUI
  368. #define JUCE_BUILD_GUI 1
  369. #endif
  370. #ifndef JUCE_BUILD_NATIVE
  371. #define JUCE_BUILD_NATIVE 1
  372. #endif
  373. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  374. #undef JUCE_BUILD_MISC
  375. #undef JUCE_BUILD_GUI
  376. #endif
  377. //==============================================================================
  378. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  379. #if JUCE_WINDOWS
  380. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  381. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  383. #ifndef STRICT
  384. #define STRICT 1
  385. #endif
  386. #undef WIN32_LEAN_AND_MEAN
  387. #define WIN32_LEAN_AND_MEAN 1
  388. #if JUCE_MSVC
  389. #pragma warning (push)
  390. #pragma warning (disable : 4100 4201 4514 4312 4995)
  391. #endif
  392. #define _WIN32_WINNT 0x0500
  393. #define _UNICODE 1
  394. #define UNICODE 1
  395. #ifndef _WIN32_IE
  396. #define _WIN32_IE 0x0400
  397. #endif
  398. #include <windows.h>
  399. #include <windowsx.h>
  400. #include <commdlg.h>
  401. #include <shellapi.h>
  402. #include <mmsystem.h>
  403. #include <vfw.h>
  404. #include <tchar.h>
  405. #include <stddef.h>
  406. #include <ctime>
  407. #include <wininet.h>
  408. #include <nb30.h>
  409. #include <iphlpapi.h>
  410. #include <mapi.h>
  411. #include <float.h>
  412. #include <process.h>
  413. #include <Exdisp.h>
  414. #include <exdispid.h>
  415. #include <shlobj.h>
  416. #if ! JUCE_MINGW
  417. #include <crtdbg.h>
  418. #include <comutil.h>
  419. #endif
  420. #if JUCE_OPENGL
  421. #include <gl/gl.h>
  422. #endif
  423. #undef PACKED
  424. #if JUCE_ASIO
  425. /*
  426. This is very frustrating - we only need to use a handful of definitions from
  427. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  428. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  429. implementation...
  430. ..unfortunately that would break Steinberg's license agreement for use of
  431. their SDK, so I'm not allowed to do this.
  432. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  433. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  434. (see www.steinberg.net/Steinberg/Developers.asp).
  435. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  436. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  437. if you prefer). Make sure that your header search path will find the
  438. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  439. files are actually needed - so to simplify things, you could just copy
  440. these into your JUCE directory).
  441. If you're compiling and you get an error here because you don't have the
  442. ASIO SDK installed, you can disable ASIO support by commenting-out the
  443. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  444. */
  445. #include "iasiodrv.h"
  446. #endif
  447. #if JUCE_USE_CDBURNER
  448. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  449. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  450. flag in juce_Config.h to avoid these includes.
  451. */
  452. #include <imapi.h>
  453. #include <imapierror.h>
  454. #endif
  455. #if JUCE_USE_CAMERA
  456. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  457. These files are provided in the normal Windows SDK, but some Microsoft plonker
  458. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  459. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  460. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  461. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  462. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  463. The dummy file just needs to contain the following content:
  464. #define __IDxtCompositor_INTERFACE_DEFINED__
  465. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  466. #define __IDxtJpeg_INTERFACE_DEFINED__
  467. #define __IDxtKey_INTERFACE_DEFINED__
  468. ..and that should be enough to convince qedit.h that you have the SDK!
  469. */
  470. #include <dshow.h>
  471. #include <qedit.h>
  472. #include <dshowasf.h>
  473. #endif
  474. #if JUCE_WASAPI
  475. #include <MMReg.h>
  476. #include <mmdeviceapi.h>
  477. #include <Audioclient.h>
  478. #include <Avrt.h>
  479. #include <functiondiscoverykeys.h>
  480. #endif
  481. #if JUCE_QUICKTIME
  482. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  483. add its header directory to your include path.
  484. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  485. flag in juce_Config.h
  486. */
  487. #include <Movies.h>
  488. #include <QTML.h>
  489. #include <QuickTimeComponents.h>
  490. #include <MediaHandlers.h>
  491. #include <ImageCodec.h>
  492. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  493. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  494. your include search path to make these import statements work.
  495. */
  496. #import <QTOLibrary.dll>
  497. #import <QTOControl.dll>
  498. #endif
  499. #if JUCE_MSVC
  500. #pragma warning (pop)
  501. #endif
  502. /** A simple COM smart pointer.
  503. Avoids having to include ATL just to get one of these.
  504. */
  505. template <class ComClass>
  506. class ComSmartPtr
  507. {
  508. public:
  509. ComSmartPtr() throw() : p (0) {}
  510. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  511. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  512. ~ComSmartPtr() { if (p != 0) p->Release(); }
  513. operator ComClass*() const throw() { return p; }
  514. ComClass& operator*() const throw() { return *p; }
  515. ComClass** operator&() throw() { return &p; }
  516. ComClass* operator->() const throw() { return p; }
  517. ComClass* operator= (ComClass* const newP)
  518. {
  519. if (newP != 0) newP->AddRef();
  520. if (p != 0) p->Release();
  521. p = newP;
  522. return newP;
  523. }
  524. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  525. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  526. {
  527. #ifndef __MINGW32__
  528. operator= (0);
  529. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  530. #else
  531. return S_FALSE;
  532. #endif
  533. }
  534. private:
  535. ComClass* p;
  536. };
  537. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  538. */
  539. template <class ComClass>
  540. class ComBaseClassHelper : public ComClass
  541. {
  542. public:
  543. ComBaseClassHelper() : refCount (1) {}
  544. virtual ~ComBaseClassHelper() {}
  545. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  546. {
  547. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  548. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  549. *result = 0;
  550. return E_NOINTERFACE;
  551. }
  552. ULONG __stdcall AddRef() { return ++refCount; }
  553. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  554. protected:
  555. int refCount;
  556. };
  557. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  558. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  559. #elif JUCE_LINUX
  560. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  561. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  563. /*
  564. This file wraps together all the linux-specific headers, so
  565. that we can include them all just once, and compile all our
  566. platform-specific stuff in one big lump, keeping it out of the
  567. way of the rest of the codebase.
  568. */
  569. #include <sched.h>
  570. #include <pthread.h>
  571. #include <sys/time.h>
  572. #include <errno.h>
  573. #include <sys/stat.h>
  574. #include <sys/dir.h>
  575. #include <sys/ptrace.h>
  576. #include <sys/vfs.h>
  577. #include <sys/wait.h>
  578. #include <fnmatch.h>
  579. #include <utime.h>
  580. #include <pwd.h>
  581. #include <fcntl.h>
  582. #include <dlfcn.h>
  583. #include <netdb.h>
  584. #include <arpa/inet.h>
  585. #include <netinet/in.h>
  586. #include <sys/types.h>
  587. #include <sys/ioctl.h>
  588. #include <sys/socket.h>
  589. #include <net/if.h>
  590. #include <sys/sysinfo.h>
  591. #include <sys/file.h>
  592. #include <signal.h>
  593. /* Got a build error here? You'll need to install the freetype library...
  594. The name of the package to install is "libfreetype6-dev".
  595. */
  596. #include <ft2build.h>
  597. #include FT_FREETYPE_H
  598. #include <X11/Xlib.h>
  599. #include <X11/Xatom.h>
  600. #include <X11/Xresource.h>
  601. #include <X11/Xutil.h>
  602. #include <X11/Xmd.h>
  603. #include <X11/keysym.h>
  604. #include <X11/cursorfont.h>
  605. #if JUCE_USE_XINERAMA
  606. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  607. #include <X11/extensions/Xinerama.h>
  608. #endif
  609. #if JUCE_USE_XSHM
  610. #include <X11/extensions/XShm.h>
  611. #include <sys/shm.h>
  612. #include <sys/ipc.h>
  613. #endif
  614. #if JUCE_USE_XRENDER
  615. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  616. #include <X11/extensions/Xrender.h>
  617. #include <X11/extensions/Xcomposite.h>
  618. #endif
  619. #if JUCE_USE_XCURSOR
  620. // If you're missing this header, try installing the libxcursor-dev package
  621. #include <X11/Xcursor/Xcursor.h>
  622. #endif
  623. #if JUCE_OPENGL
  624. /* Got an include error here?
  625. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  626. and "freeglut3-dev".
  627. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  628. want to disable it.
  629. */
  630. #include <GL/glx.h>
  631. #endif
  632. #undef KeyPress
  633. #if JUCE_ALSA
  634. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  635. not got your paths set up correctly to find its header files.
  636. The package you need to install to get ASLA support is "libasound2-dev".
  637. If you don't have the ALSA library and don't want to build Juce with audio support,
  638. just disable the JUCE_ALSA flag in juce_Config.h
  639. */
  640. #include <alsa/asoundlib.h>
  641. #endif
  642. #if JUCE_JACK
  643. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  644. installed, or you've not got your paths set up correctly to find its header files.
  645. The package you need to install to get JACK support is "libjack-dev".
  646. If you don't have the jack-audio-connection-kit library and don't want to build
  647. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  648. */
  649. #include <jack/jack.h>
  650. //#include <jack/transport.h>
  651. #endif
  652. #undef SIZEOF
  653. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  654. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  655. #elif JUCE_MAC || JUCE_IPHONE
  656. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  657. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  659. /*
  660. This file wraps together all the mac-specific code, so that
  661. we can include all the native headers just once, and compile all our
  662. platform-specific stuff in one big lump, keeping it out of the way of
  663. the rest of the codebase.
  664. */
  665. #define USE_COREGRAPHICS_RENDERING 1
  666. #if JUCE_IOS
  667. #import <Foundation/Foundation.h>
  668. #import <UIKit/UIKit.h>
  669. #import <AudioToolbox/AudioToolbox.h>
  670. #import <AVFoundation/AVFoundation.h>
  671. #import <CoreData/CoreData.h>
  672. #import <MobileCoreServices/MobileCoreServices.h>
  673. #import <QuartzCore/QuartzCore.h>
  674. #include <sys/fcntl.h>
  675. #if JUCE_OPENGL
  676. #include <OpenGLES/ES1/gl.h>
  677. #include <OpenGLES/ES1/glext.h>
  678. #endif
  679. #else
  680. #import <Cocoa/Cocoa.h>
  681. #import <CoreAudio/HostTime.h>
  682. #import <CoreAudio/AudioHardware.h>
  683. #import <CoreMIDI/MIDIServices.h>
  684. #import <QTKit/QTKit.h>
  685. #import <WebKit/WebKit.h>
  686. #import <DiscRecording/DiscRecording.h>
  687. #import <IOKit/IOKitLib.h>
  688. #import <IOKit/IOCFPlugIn.h>
  689. #import <IOKit/hid/IOHIDLib.h>
  690. #import <IOKit/hid/IOHIDKeys.h>
  691. #import <IOKit/pwr_mgt/IOPMLib.h>
  692. #include <Carbon/Carbon.h>
  693. #include <sys/dir.h>
  694. #endif
  695. #include <sys/socket.h>
  696. #include <sys/sysctl.h>
  697. #include <sys/stat.h>
  698. #include <sys/param.h>
  699. #include <sys/mount.h>
  700. #include <fnmatch.h>
  701. #include <utime.h>
  702. #include <dlfcn.h>
  703. #include <ifaddrs.h>
  704. #include <net/if_dl.h>
  705. #include <mach/mach_time.h>
  706. #include <mach-o/dyld.h>
  707. #if MACOS_10_4_OR_EARLIER
  708. #include <GLUT/glut.h>
  709. #endif
  710. #if ! CGFLOAT_DEFINED
  711. #define CGFloat float
  712. #endif
  713. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  714. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  715. #else
  716. #error "Unknown platform!"
  717. #endif
  718. #endif
  719. //==============================================================================
  720. #define DONT_SET_USING_JUCE_NAMESPACE 1
  721. #undef max
  722. #undef min
  723. #define NO_DUMMY_DECL
  724. #if JUCE_BUILD_NATIVE
  725. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  726. #endif
  727. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  728. #pragma warning (disable: 4309 4305)
  729. #endif
  730. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  731. BEGIN_JUCE_NAMESPACE
  732. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  733. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  734. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  735. /**
  736. Creates a floating carbon window that can be used to hold a carbon UI.
  737. This is a handy class that's designed to be inlined where needed, e.g.
  738. in the audio plugin hosting code.
  739. */
  740. class CarbonViewWrapperComponent : public Component,
  741. public ComponentMovementWatcher,
  742. public Timer
  743. {
  744. public:
  745. CarbonViewWrapperComponent()
  746. : ComponentMovementWatcher (this),
  747. wrapperWindow (0),
  748. embeddedView (0),
  749. recursiveResize (false)
  750. {
  751. }
  752. virtual ~CarbonViewWrapperComponent()
  753. {
  754. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  755. }
  756. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  757. virtual void removeView (HIViewRef embeddedView) = 0;
  758. virtual void mouseDown (int, int) {}
  759. virtual void paint() {}
  760. virtual bool getEmbeddedViewSize (int& w, int& h)
  761. {
  762. if (embeddedView == 0)
  763. return false;
  764. HIRect bounds;
  765. HIViewGetBounds (embeddedView, &bounds);
  766. w = jmax (1, roundToInt (bounds.size.width));
  767. h = jmax (1, roundToInt (bounds.size.height));
  768. return true;
  769. }
  770. void createWindow()
  771. {
  772. if (wrapperWindow == 0)
  773. {
  774. Rect r;
  775. r.left = getScreenX();
  776. r.top = getScreenY();
  777. r.right = r.left + getWidth();
  778. r.bottom = r.top + getHeight();
  779. CreateNewWindow (kDocumentWindowClass,
  780. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  781. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  782. &r, &wrapperWindow);
  783. jassert (wrapperWindow != 0);
  784. if (wrapperWindow == 0)
  785. return;
  786. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  787. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  788. [ownerWindow addChildWindow: carbonWindow
  789. ordered: NSWindowAbove];
  790. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  791. EventTypeSpec windowEventTypes[] =
  792. {
  793. { kEventClassWindow, kEventWindowGetClickActivation },
  794. { kEventClassWindow, kEventWindowHandleDeactivate },
  795. { kEventClassWindow, kEventWindowBoundsChanging },
  796. { kEventClassMouse, kEventMouseDown },
  797. { kEventClassMouse, kEventMouseMoved },
  798. { kEventClassMouse, kEventMouseDragged },
  799. { kEventClassMouse, kEventMouseUp},
  800. { kEventClassWindow, kEventWindowDrawContent },
  801. { kEventClassWindow, kEventWindowShown },
  802. { kEventClassWindow, kEventWindowHidden }
  803. };
  804. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  805. InstallWindowEventHandler (wrapperWindow, upp,
  806. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  807. windowEventTypes, this, &eventHandlerRef);
  808. setOurSizeToEmbeddedViewSize();
  809. setEmbeddedWindowToOurSize();
  810. creationTime = Time::getCurrentTime();
  811. }
  812. }
  813. void deleteWindow()
  814. {
  815. removeView (embeddedView);
  816. embeddedView = 0;
  817. if (wrapperWindow != 0)
  818. {
  819. RemoveEventHandler (eventHandlerRef);
  820. DisposeWindow (wrapperWindow);
  821. wrapperWindow = 0;
  822. }
  823. }
  824. void setOurSizeToEmbeddedViewSize()
  825. {
  826. int w, h;
  827. if (getEmbeddedViewSize (w, h))
  828. {
  829. if (w != getWidth() || h != getHeight())
  830. {
  831. startTimer (50);
  832. setSize (w, h);
  833. if (getParentComponent() != 0)
  834. getParentComponent()->setSize (w, h);
  835. }
  836. else
  837. {
  838. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  839. }
  840. }
  841. else
  842. {
  843. stopTimer();
  844. }
  845. }
  846. void setEmbeddedWindowToOurSize()
  847. {
  848. if (! recursiveResize)
  849. {
  850. recursiveResize = true;
  851. if (embeddedView != 0)
  852. {
  853. HIRect r;
  854. r.origin.x = 0;
  855. r.origin.y = 0;
  856. r.size.width = (float) getWidth();
  857. r.size.height = (float) getHeight();
  858. HIViewSetFrame (embeddedView, &r);
  859. }
  860. if (wrapperWindow != 0)
  861. {
  862. Rect wr;
  863. wr.left = getScreenX();
  864. wr.top = getScreenY();
  865. wr.right = wr.left + getWidth();
  866. wr.bottom = wr.top + getHeight();
  867. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  868. ShowWindow (wrapperWindow);
  869. }
  870. recursiveResize = false;
  871. }
  872. }
  873. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  874. {
  875. setEmbeddedWindowToOurSize();
  876. }
  877. void componentPeerChanged()
  878. {
  879. deleteWindow();
  880. createWindow();
  881. }
  882. void componentVisibilityChanged (Component&)
  883. {
  884. if (isShowing())
  885. createWindow();
  886. else
  887. deleteWindow();
  888. setEmbeddedWindowToOurSize();
  889. }
  890. static void recursiveHIViewRepaint (HIViewRef view)
  891. {
  892. HIViewSetNeedsDisplay (view, true);
  893. HIViewRef child = HIViewGetFirstSubview (view);
  894. while (child != 0)
  895. {
  896. recursiveHIViewRepaint (child);
  897. child = HIViewGetNextView (child);
  898. }
  899. }
  900. void timerCallback()
  901. {
  902. setOurSizeToEmbeddedViewSize();
  903. // To avoid strange overpainting problems when the UI is first opened, we'll
  904. // repaint it a few times during the first second that it's on-screen..
  905. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  906. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  907. }
  908. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  909. EventRef event)
  910. {
  911. switch (GetEventKind (event))
  912. {
  913. case kEventWindowHandleDeactivate:
  914. ActivateWindow (wrapperWindow, TRUE);
  915. return noErr;
  916. case kEventWindowGetClickActivation:
  917. {
  918. getTopLevelComponent()->toFront (false);
  919. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  920. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  921. sizeof (ClickActivationResult), &howToHandleClick);
  922. HIViewSetNeedsDisplay (embeddedView, true);
  923. return noErr;
  924. }
  925. }
  926. return eventNotHandledErr;
  927. }
  928. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  929. EventRef event, void* userData)
  930. {
  931. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  932. }
  933. protected:
  934. WindowRef wrapperWindow;
  935. HIViewRef embeddedView;
  936. bool recursiveResize;
  937. Time creationTime;
  938. EventHandlerRef eventHandlerRef;
  939. };
  940. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  941. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  942. END_JUCE_NAMESPACE
  943. #endif
  944. #define JUCE_AMALGAMATED_TEMPLATE 1
  945. //==============================================================================
  946. #if JUCE_BUILD_CORE
  947. /*** Start of inlined file: juce_FileLogger.cpp ***/
  948. BEGIN_JUCE_NAMESPACE
  949. FileLogger::FileLogger (const File& logFile_,
  950. const String& welcomeMessage,
  951. const int maxInitialFileSizeBytes)
  952. : logFile (logFile_)
  953. {
  954. if (maxInitialFileSizeBytes >= 0)
  955. trimFileSize (maxInitialFileSizeBytes);
  956. if (! logFile_.exists())
  957. {
  958. // do this so that the parent directories get created..
  959. logFile_.create();
  960. }
  961. logStream = logFile_.createOutputStream (256);
  962. jassert (logStream != 0);
  963. String welcome;
  964. welcome << "\r\n**********************************************************\r\n"
  965. << welcomeMessage
  966. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  967. << "\r\n";
  968. logMessage (welcome);
  969. }
  970. FileLogger::~FileLogger()
  971. {
  972. }
  973. void FileLogger::logMessage (const String& message)
  974. {
  975. if (logStream != 0)
  976. {
  977. DBG (message);
  978. const ScopedLock sl (logLock);
  979. (*logStream) << message << "\r\n";
  980. logStream->flush();
  981. }
  982. }
  983. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  984. {
  985. if (maxFileSizeBytes <= 0)
  986. {
  987. logFile.deleteFile();
  988. }
  989. else
  990. {
  991. const int64 fileSize = logFile.getSize();
  992. if (fileSize > maxFileSizeBytes)
  993. {
  994. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  995. jassert (in != 0);
  996. if (in != 0)
  997. {
  998. in->setPosition (fileSize - maxFileSizeBytes);
  999. String content;
  1000. {
  1001. MemoryBlock contentToSave;
  1002. contentToSave.setSize (maxFileSizeBytes + 4);
  1003. contentToSave.fillWith (0);
  1004. in->read (contentToSave.getData(), maxFileSizeBytes);
  1005. in = 0;
  1006. content = contentToSave.toString();
  1007. }
  1008. int newStart = 0;
  1009. while (newStart < fileSize
  1010. && content[newStart] != '\n'
  1011. && content[newStart] != '\r')
  1012. ++newStart;
  1013. logFile.deleteFile();
  1014. logFile.appendText (content.substring (newStart), false, false);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1020. const String& logFileName,
  1021. const String& welcomeMessage,
  1022. const int maxInitialFileSizeBytes)
  1023. {
  1024. #if JUCE_MAC
  1025. File logFile ("~/Library/Logs");
  1026. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1027. .getChildFile (logFileName);
  1028. #else
  1029. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1030. if (logFile.isDirectory())
  1031. {
  1032. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1033. .getChildFile (logFileName);
  1034. }
  1035. #endif
  1036. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1037. }
  1038. END_JUCE_NAMESPACE
  1039. /*** End of inlined file: juce_FileLogger.cpp ***/
  1040. /*** Start of inlined file: juce_Logger.cpp ***/
  1041. BEGIN_JUCE_NAMESPACE
  1042. Logger::Logger()
  1043. {
  1044. }
  1045. Logger::~Logger()
  1046. {
  1047. }
  1048. Logger* Logger::currentLogger = 0;
  1049. void Logger::setCurrentLogger (Logger* const newLogger,
  1050. const bool deleteOldLogger)
  1051. {
  1052. Logger* const oldLogger = currentLogger;
  1053. currentLogger = newLogger;
  1054. if (deleteOldLogger)
  1055. delete oldLogger;
  1056. }
  1057. void Logger::writeToLog (const String& message)
  1058. {
  1059. if (currentLogger != 0)
  1060. currentLogger->logMessage (message);
  1061. else
  1062. outputDebugString (message);
  1063. }
  1064. #if JUCE_LOG_ASSERTIONS
  1065. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1066. {
  1067. String m ("JUCE Assertion failure in ");
  1068. m << filename << ", line " << lineNum;
  1069. Logger::writeToLog (m);
  1070. }
  1071. #endif
  1072. END_JUCE_NAMESPACE
  1073. /*** End of inlined file: juce_Logger.cpp ***/
  1074. /*** Start of inlined file: juce_Random.cpp ***/
  1075. BEGIN_JUCE_NAMESPACE
  1076. Random::Random (const int64 seedValue) throw()
  1077. : seed (seedValue)
  1078. {
  1079. }
  1080. Random::~Random() throw()
  1081. {
  1082. }
  1083. void Random::setSeed (const int64 newSeed) throw()
  1084. {
  1085. seed = newSeed;
  1086. }
  1087. void Random::combineSeed (const int64 seedValue) throw()
  1088. {
  1089. seed ^= nextInt64() ^ seedValue;
  1090. }
  1091. void Random::setSeedRandomly()
  1092. {
  1093. combineSeed ((int64) (pointer_sized_int) this);
  1094. combineSeed (Time::getMillisecondCounter());
  1095. combineSeed (Time::getHighResolutionTicks());
  1096. combineSeed (Time::getHighResolutionTicksPerSecond());
  1097. combineSeed (Time::currentTimeMillis());
  1098. }
  1099. int Random::nextInt() throw()
  1100. {
  1101. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1102. return (int) (seed >> 16);
  1103. }
  1104. int Random::nextInt (const int maxValue) throw()
  1105. {
  1106. jassert (maxValue > 0);
  1107. return (nextInt() & 0x7fffffff) % maxValue;
  1108. }
  1109. int64 Random::nextInt64() throw()
  1110. {
  1111. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1112. }
  1113. bool Random::nextBool() throw()
  1114. {
  1115. return (nextInt() & 0x80000000) != 0;
  1116. }
  1117. float Random::nextFloat() throw()
  1118. {
  1119. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1120. }
  1121. double Random::nextDouble() throw()
  1122. {
  1123. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1124. }
  1125. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1126. {
  1127. BigInteger n;
  1128. do
  1129. {
  1130. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1131. }
  1132. while (n >= maximumValue);
  1133. return n;
  1134. }
  1135. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1136. {
  1137. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1138. while ((startBit & 31) != 0 && numBits > 0)
  1139. {
  1140. arrayToChange.setBit (startBit++, nextBool());
  1141. --numBits;
  1142. }
  1143. while (numBits >= 32)
  1144. {
  1145. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1146. startBit += 32;
  1147. numBits -= 32;
  1148. }
  1149. while (--numBits >= 0)
  1150. arrayToChange.setBit (startBit + numBits, nextBool());
  1151. }
  1152. Random& Random::getSystemRandom() throw()
  1153. {
  1154. static Random sysRand (1);
  1155. return sysRand;
  1156. }
  1157. END_JUCE_NAMESPACE
  1158. /*** End of inlined file: juce_Random.cpp ***/
  1159. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1160. BEGIN_JUCE_NAMESPACE
  1161. RelativeTime::RelativeTime (const double seconds_) throw()
  1162. : seconds (seconds_)
  1163. {
  1164. }
  1165. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1166. : seconds (other.seconds)
  1167. {
  1168. }
  1169. RelativeTime::~RelativeTime() throw()
  1170. {
  1171. }
  1172. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1173. {
  1174. return RelativeTime (milliseconds * 0.001);
  1175. }
  1176. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1177. {
  1178. return RelativeTime (milliseconds * 0.001);
  1179. }
  1180. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1181. {
  1182. return RelativeTime (numberOfMinutes * 60.0);
  1183. }
  1184. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1185. {
  1186. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1187. }
  1188. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1189. {
  1190. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1191. }
  1192. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1193. {
  1194. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1195. }
  1196. int64 RelativeTime::inMilliseconds() const throw()
  1197. {
  1198. return (int64)(seconds * 1000.0);
  1199. }
  1200. double RelativeTime::inMinutes() const throw()
  1201. {
  1202. return seconds / 60.0;
  1203. }
  1204. double RelativeTime::inHours() const throw()
  1205. {
  1206. return seconds / (60.0 * 60.0);
  1207. }
  1208. double RelativeTime::inDays() const throw()
  1209. {
  1210. return seconds / (60.0 * 60.0 * 24.0);
  1211. }
  1212. double RelativeTime::inWeeks() const throw()
  1213. {
  1214. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1215. }
  1216. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1217. {
  1218. if (seconds < 0.001 && seconds > -0.001)
  1219. return returnValueForZeroTime;
  1220. String result;
  1221. if (seconds < 0)
  1222. result = "-";
  1223. int fieldsShown = 0;
  1224. int n = abs ((int) inWeeks());
  1225. if (n > 0)
  1226. {
  1227. result << n << ((n == 1) ? TRANS(" week ")
  1228. : TRANS(" weeks "));
  1229. ++fieldsShown;
  1230. }
  1231. n = abs ((int) inDays()) % 7;
  1232. if (n > 0)
  1233. {
  1234. result << n << ((n == 1) ? TRANS(" day ")
  1235. : TRANS(" days "));
  1236. ++fieldsShown;
  1237. }
  1238. if (fieldsShown < 2)
  1239. {
  1240. n = abs ((int) inHours()) % 24;
  1241. if (n > 0)
  1242. {
  1243. result << n << ((n == 1) ? TRANS(" hr ")
  1244. : TRANS(" hrs "));
  1245. ++fieldsShown;
  1246. }
  1247. if (fieldsShown < 2)
  1248. {
  1249. n = abs ((int) inMinutes()) % 60;
  1250. if (n > 0)
  1251. {
  1252. result << n << ((n == 1) ? TRANS(" min ")
  1253. : TRANS(" mins "));
  1254. ++fieldsShown;
  1255. }
  1256. if (fieldsShown < 2)
  1257. {
  1258. n = abs ((int) inSeconds()) % 60;
  1259. if (n > 0)
  1260. {
  1261. result << n << ((n == 1) ? TRANS(" sec ")
  1262. : TRANS(" secs "));
  1263. ++fieldsShown;
  1264. }
  1265. if (fieldsShown < 1)
  1266. {
  1267. n = abs ((int) inMilliseconds()) % 1000;
  1268. if (n > 0)
  1269. {
  1270. result << n << TRANS(" ms");
  1271. ++fieldsShown;
  1272. }
  1273. }
  1274. }
  1275. }
  1276. }
  1277. return result.trimEnd();
  1278. }
  1279. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1280. {
  1281. seconds = other.seconds;
  1282. return *this;
  1283. }
  1284. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1285. {
  1286. return seconds == other.seconds;
  1287. }
  1288. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1289. {
  1290. return seconds != other.seconds;
  1291. }
  1292. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1293. {
  1294. return seconds > other.seconds;
  1295. }
  1296. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1297. {
  1298. return seconds < other.seconds;
  1299. }
  1300. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1301. {
  1302. return seconds >= other.seconds;
  1303. }
  1304. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1305. {
  1306. return seconds <= other.seconds;
  1307. }
  1308. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1309. {
  1310. return RelativeTime (seconds + timeToAdd.seconds);
  1311. }
  1312. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1313. {
  1314. return RelativeTime (seconds - timeToSubtract.seconds);
  1315. }
  1316. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1317. {
  1318. return RelativeTime (seconds + secondsToAdd);
  1319. }
  1320. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1321. {
  1322. return RelativeTime (seconds - secondsToSubtract);
  1323. }
  1324. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1325. {
  1326. seconds += timeToAdd.seconds;
  1327. return *this;
  1328. }
  1329. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1330. {
  1331. seconds -= timeToSubtract.seconds;
  1332. return *this;
  1333. }
  1334. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1335. {
  1336. seconds += secondsToAdd;
  1337. return *this;
  1338. }
  1339. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1340. {
  1341. seconds -= secondsToSubtract;
  1342. return *this;
  1343. }
  1344. END_JUCE_NAMESPACE
  1345. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1346. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1347. BEGIN_JUCE_NAMESPACE
  1348. SystemStats::CPUFlags SystemStats::cpuFlags;
  1349. const String SystemStats::getJUCEVersion()
  1350. {
  1351. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1352. + "." + String (JUCE_MINOR_VERSION)
  1353. + "." + String (JUCE_BUILDNUMBER);
  1354. }
  1355. const StringArray SystemStats::getMACAddressStrings()
  1356. {
  1357. int64 macAddresses [16];
  1358. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1359. StringArray s;
  1360. for (int i = 0; i < numAddresses; ++i)
  1361. {
  1362. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1363. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1364. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1365. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1366. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1367. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1368. }
  1369. return s;
  1370. }
  1371. #ifdef JUCE_DLL
  1372. void* juce_Malloc (const int size)
  1373. {
  1374. return malloc (size);
  1375. }
  1376. void* juce_Calloc (const int size)
  1377. {
  1378. return calloc (1, size);
  1379. }
  1380. void* juce_Realloc (void* const block, const int size)
  1381. {
  1382. return realloc (block, size);
  1383. }
  1384. void juce_Free (void* const block)
  1385. {
  1386. free (block);
  1387. }
  1388. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1389. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1390. {
  1391. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1392. }
  1393. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1394. {
  1395. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1396. }
  1397. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1398. {
  1399. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1400. }
  1401. void juce_DebugFree (void* const block)
  1402. {
  1403. _free_dbg (block, _NORMAL_BLOCK);
  1404. }
  1405. #endif
  1406. #endif
  1407. END_JUCE_NAMESPACE
  1408. /*** End of inlined file: juce_SystemStats.cpp ***/
  1409. /*** Start of inlined file: juce_Time.cpp ***/
  1410. #if JUCE_MSVC
  1411. #pragma warning (push)
  1412. #pragma warning (disable: 4514)
  1413. #endif
  1414. #ifndef JUCE_WINDOWS
  1415. #include <sys/time.h>
  1416. #else
  1417. #include <ctime>
  1418. #endif
  1419. #include <sys/timeb.h>
  1420. #if JUCE_MSVC
  1421. #pragma warning (pop)
  1422. #ifdef _INC_TIME_INL
  1423. #define USE_NEW_SECURE_TIME_FNS
  1424. #endif
  1425. #endif
  1426. BEGIN_JUCE_NAMESPACE
  1427. namespace TimeHelpers
  1428. {
  1429. static struct tm millisToLocal (const int64 millis) throw()
  1430. {
  1431. struct tm result;
  1432. const int64 seconds = millis / 1000;
  1433. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1434. {
  1435. // use extended maths for dates beyond 1970 to 2037..
  1436. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1437. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1438. const int days = (int) (jdm / literal64bit (86400));
  1439. const int a = 32044 + days;
  1440. const int b = (4 * a + 3) / 146097;
  1441. const int c = a - (b * 146097) / 4;
  1442. const int d = (4 * c + 3) / 1461;
  1443. const int e = c - (d * 1461) / 4;
  1444. const int m = (5 * e + 2) / 153;
  1445. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1446. result.tm_mon = m + 2 - 12 * (m / 10);
  1447. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1448. result.tm_wday = (days + 1) % 7;
  1449. result.tm_yday = -1;
  1450. int t = (int) (jdm % literal64bit (86400));
  1451. result.tm_hour = t / 3600;
  1452. t %= 3600;
  1453. result.tm_min = t / 60;
  1454. result.tm_sec = t % 60;
  1455. result.tm_isdst = -1;
  1456. }
  1457. else
  1458. {
  1459. time_t now = static_cast <time_t> (seconds);
  1460. #if JUCE_WINDOWS
  1461. #ifdef USE_NEW_SECURE_TIME_FNS
  1462. if (now >= 0 && now <= 0x793406fff)
  1463. localtime_s (&result, &now);
  1464. else
  1465. zeromem (&result, sizeof (result));
  1466. #else
  1467. result = *localtime (&now);
  1468. #endif
  1469. #else
  1470. // more thread-safe
  1471. localtime_r (&now, &result);
  1472. #endif
  1473. }
  1474. return result;
  1475. }
  1476. static int extendedModulo (const int64 value, const int modulo) throw()
  1477. {
  1478. return (int) (value >= 0 ? (value % modulo)
  1479. : (value - ((value / modulo) + 1) * modulo));
  1480. }
  1481. static uint32 lastMSCounterValue = 0;
  1482. }
  1483. Time::Time() throw()
  1484. : millisSinceEpoch (0)
  1485. {
  1486. }
  1487. Time::Time (const Time& other) throw()
  1488. : millisSinceEpoch (other.millisSinceEpoch)
  1489. {
  1490. }
  1491. Time::Time (const int64 ms) throw()
  1492. : millisSinceEpoch (ms)
  1493. {
  1494. }
  1495. Time::Time (const int year,
  1496. const int month,
  1497. const int day,
  1498. const int hours,
  1499. const int minutes,
  1500. const int seconds,
  1501. const int milliseconds,
  1502. const bool useLocalTime) throw()
  1503. {
  1504. jassert (year > 100); // year must be a 4-digit version
  1505. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1506. {
  1507. // use extended maths for dates beyond 1970 to 2037..
  1508. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1509. : 0;
  1510. const int a = (13 - month) / 12;
  1511. const int y = year + 4800 - a;
  1512. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1513. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1514. - 32045;
  1515. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1516. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1517. + milliseconds;
  1518. }
  1519. else
  1520. {
  1521. struct tm t;
  1522. t.tm_year = year - 1900;
  1523. t.tm_mon = month;
  1524. t.tm_mday = day;
  1525. t.tm_hour = hours;
  1526. t.tm_min = minutes;
  1527. t.tm_sec = seconds;
  1528. t.tm_isdst = -1;
  1529. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1530. if (millisSinceEpoch < 0)
  1531. millisSinceEpoch = 0;
  1532. else
  1533. millisSinceEpoch += milliseconds;
  1534. }
  1535. }
  1536. Time::~Time() throw()
  1537. {
  1538. }
  1539. Time& Time::operator= (const Time& other) throw()
  1540. {
  1541. millisSinceEpoch = other.millisSinceEpoch;
  1542. return *this;
  1543. }
  1544. int64 Time::currentTimeMillis() throw()
  1545. {
  1546. static uint32 lastCounterResult = 0xffffffff;
  1547. static int64 correction = 0;
  1548. const uint32 now = getMillisecondCounter();
  1549. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1550. if (now < lastCounterResult)
  1551. {
  1552. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1553. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1554. {
  1555. // get the time once using normal library calls, and store the difference needed to
  1556. // turn the millisecond counter into a real time.
  1557. #if JUCE_WINDOWS
  1558. struct _timeb t;
  1559. #ifdef USE_NEW_SECURE_TIME_FNS
  1560. _ftime_s (&t);
  1561. #else
  1562. _ftime (&t);
  1563. #endif
  1564. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1565. #else
  1566. struct timeval tv;
  1567. struct timezone tz;
  1568. gettimeofday (&tv, &tz);
  1569. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1570. #endif
  1571. }
  1572. }
  1573. lastCounterResult = now;
  1574. return correction + now;
  1575. }
  1576. uint32 juce_millisecondsSinceStartup() throw();
  1577. uint32 Time::getMillisecondCounter() throw()
  1578. {
  1579. const uint32 now = juce_millisecondsSinceStartup();
  1580. if (now < TimeHelpers::lastMSCounterValue)
  1581. {
  1582. // in multi-threaded apps this might be called concurrently, so
  1583. // make sure that our last counter value only increases and doesn't
  1584. // go backwards..
  1585. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1586. TimeHelpers::lastMSCounterValue = now;
  1587. }
  1588. else
  1589. {
  1590. TimeHelpers::lastMSCounterValue = now;
  1591. }
  1592. return now;
  1593. }
  1594. uint32 Time::getApproximateMillisecondCounter() throw()
  1595. {
  1596. jassert (TimeHelpers::lastMSCounterValue != 0);
  1597. return TimeHelpers::lastMSCounterValue;
  1598. }
  1599. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1600. {
  1601. for (;;)
  1602. {
  1603. const uint32 now = getMillisecondCounter();
  1604. if (now >= targetTime)
  1605. break;
  1606. const int toWait = targetTime - now;
  1607. if (toWait > 2)
  1608. {
  1609. Thread::sleep (jmin (20, toWait >> 1));
  1610. }
  1611. else
  1612. {
  1613. // xxx should consider using mutex_pause on the mac as it apparently
  1614. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1615. for (int i = 10; --i >= 0;)
  1616. Thread::yield();
  1617. }
  1618. }
  1619. }
  1620. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1621. {
  1622. return ticks / (double) getHighResolutionTicksPerSecond();
  1623. }
  1624. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1625. {
  1626. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1627. }
  1628. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1629. {
  1630. return Time (currentTimeMillis());
  1631. }
  1632. const String Time::toString (const bool includeDate,
  1633. const bool includeTime,
  1634. const bool includeSeconds,
  1635. const bool use24HourClock) const throw()
  1636. {
  1637. String result;
  1638. if (includeDate)
  1639. {
  1640. result << getDayOfMonth() << ' '
  1641. << getMonthName (true) << ' '
  1642. << getYear();
  1643. if (includeTime)
  1644. result << ' ';
  1645. }
  1646. if (includeTime)
  1647. {
  1648. const int mins = getMinutes();
  1649. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1650. << (mins < 10 ? ":0" : ":") << mins;
  1651. if (includeSeconds)
  1652. {
  1653. const int secs = getSeconds();
  1654. result << (secs < 10 ? ":0" : ":") << secs;
  1655. }
  1656. if (! use24HourClock)
  1657. result << (isAfternoon() ? "pm" : "am");
  1658. }
  1659. return result.trimEnd();
  1660. }
  1661. const String Time::formatted (const String& format) const throw()
  1662. {
  1663. String buffer;
  1664. int bufferSize = 128;
  1665. buffer.preallocateStorage (bufferSize);
  1666. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1667. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1668. {
  1669. bufferSize += 128;
  1670. buffer.preallocateStorage (bufferSize);
  1671. }
  1672. return buffer;
  1673. }
  1674. int Time::getYear() const throw()
  1675. {
  1676. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1677. }
  1678. int Time::getMonth() const throw()
  1679. {
  1680. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1681. }
  1682. int Time::getDayOfMonth() const throw()
  1683. {
  1684. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1685. }
  1686. int Time::getDayOfWeek() const throw()
  1687. {
  1688. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1689. }
  1690. int Time::getHours() const throw()
  1691. {
  1692. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1693. }
  1694. int Time::getHoursInAmPmFormat() const throw()
  1695. {
  1696. const int hours = getHours();
  1697. if (hours == 0)
  1698. return 12;
  1699. else if (hours <= 12)
  1700. return hours;
  1701. else
  1702. return hours - 12;
  1703. }
  1704. bool Time::isAfternoon() const throw()
  1705. {
  1706. return getHours() >= 12;
  1707. }
  1708. int Time::getMinutes() const throw()
  1709. {
  1710. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1711. }
  1712. int Time::getSeconds() const throw()
  1713. {
  1714. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1715. }
  1716. int Time::getMilliseconds() const throw()
  1717. {
  1718. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1719. }
  1720. bool Time::isDaylightSavingTime() const throw()
  1721. {
  1722. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1723. }
  1724. const String Time::getTimeZone() const throw()
  1725. {
  1726. String zone[2];
  1727. #if JUCE_WINDOWS
  1728. _tzset();
  1729. #ifdef USE_NEW_SECURE_TIME_FNS
  1730. {
  1731. char name [128];
  1732. size_t length;
  1733. for (int i = 0; i < 2; ++i)
  1734. {
  1735. zeromem (name, sizeof (name));
  1736. _get_tzname (&length, name, 127, i);
  1737. zone[i] = name;
  1738. }
  1739. }
  1740. #else
  1741. const char** const zonePtr = (const char**) _tzname;
  1742. zone[0] = zonePtr[0];
  1743. zone[1] = zonePtr[1];
  1744. #endif
  1745. #else
  1746. tzset();
  1747. const char** const zonePtr = (const char**) tzname;
  1748. zone[0] = zonePtr[0];
  1749. zone[1] = zonePtr[1];
  1750. #endif
  1751. if (isDaylightSavingTime())
  1752. {
  1753. zone[0] = zone[1];
  1754. if (zone[0].length() > 3
  1755. && zone[0].containsIgnoreCase ("daylight")
  1756. && zone[0].contains ("GMT"))
  1757. zone[0] = "BST";
  1758. }
  1759. return zone[0].substring (0, 3);
  1760. }
  1761. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1762. {
  1763. return getMonthName (getMonth(), threeLetterVersion);
  1764. }
  1765. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1766. {
  1767. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1768. }
  1769. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1770. {
  1771. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1772. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1773. monthNumber %= 12;
  1774. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1775. : longMonthNames [monthNumber]);
  1776. }
  1777. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1778. {
  1779. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1780. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1781. day %= 7;
  1782. return TRANS (threeLetterVersion ? shortDayNames [day]
  1783. : longDayNames [day]);
  1784. }
  1785. END_JUCE_NAMESPACE
  1786. /*** End of inlined file: juce_Time.cpp ***/
  1787. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1788. BEGIN_JUCE_NAMESPACE
  1789. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1790. #endif
  1791. #if JUCE_WINDOWS
  1792. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1793. #endif
  1794. #if JUCE_DEBUG
  1795. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1796. #endif
  1797. #if JUCE_DEBUG
  1798. namespace SimpleUnitTests
  1799. {
  1800. template <typename Type>
  1801. class AtomicTester
  1802. {
  1803. public:
  1804. AtomicTester() {}
  1805. static void testInteger()
  1806. {
  1807. Atomic<Type> a, b;
  1808. a.set ((Type) 10);
  1809. a += (Type) 15;
  1810. a.memoryBarrier();
  1811. a -= (Type) 5;
  1812. ++a; ++a; --a;
  1813. a.memoryBarrier();
  1814. testFloat();
  1815. }
  1816. static void testFloat()
  1817. {
  1818. Atomic<Type> a, b;
  1819. a = (Type) 21;
  1820. a.memoryBarrier();
  1821. /* These are some simple test cases to check the atomics - let me know
  1822. if any of these assertions fail on your system!
  1823. */
  1824. jassert (a.get() == (Type) 21);
  1825. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1826. jassert (a.get() == (Type) 21);
  1827. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1828. jassert (a.get() == (Type) 101);
  1829. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1830. jassert (a.get() == (Type) 101);
  1831. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1832. jassert (a.get() == (Type) 200);
  1833. jassert (a.exchange ((Type) 300) == (Type) 200);
  1834. jassert (a.get() == (Type) 300);
  1835. b = a;
  1836. jassert (b.get() == a.get());
  1837. }
  1838. };
  1839. static void runBasicTests()
  1840. {
  1841. // Some simple test code, to keep an eye on things and make sure these functions
  1842. // work ok on all platforms. Let me know if any of these assertions fail on your system!
  1843. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1844. static_jassert (sizeof (int8) == 1);
  1845. static_jassert (sizeof (uint8) == 1);
  1846. static_jassert (sizeof (int16) == 2);
  1847. static_jassert (sizeof (uint16) == 2);
  1848. static_jassert (sizeof (int32) == 4);
  1849. static_jassert (sizeof (uint32) == 4);
  1850. static_jassert (sizeof (int64) == 8);
  1851. static_jassert (sizeof (uint64) == 8);
  1852. char a1[7];
  1853. jassert (numElementsInArray(a1) == 7);
  1854. int a2[3];
  1855. jassert (numElementsInArray(a2) == 3);
  1856. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1857. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1858. jassert (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1859. // Some quick stream tests..
  1860. int randomInt = Random::getSystemRandom().nextInt();
  1861. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1862. double randomDouble = Random::getSystemRandom().nextDouble();
  1863. String randomString;
  1864. for (int i = 50; --i >= 0;)
  1865. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1866. MemoryOutputStream mo;
  1867. mo.writeInt (randomInt);
  1868. mo.writeIntBigEndian (randomInt);
  1869. mo.writeCompressedInt (randomInt);
  1870. mo.writeString (randomString);
  1871. mo.writeInt64 (randomInt64);
  1872. mo.writeInt64BigEndian (randomInt64);
  1873. mo.writeDouble (randomDouble);
  1874. mo.writeDoubleBigEndian (randomDouble);
  1875. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1876. jassert (mi.readInt() == randomInt);
  1877. jassert (mi.readIntBigEndian() == randomInt);
  1878. jassert (mi.readCompressedInt() == randomInt);
  1879. jassert (mi.readString() == randomString);
  1880. jassert (mi.readInt64() == randomInt64);
  1881. jassert (mi.readInt64BigEndian() == randomInt64);
  1882. jassert (mi.readDouble() == randomDouble);
  1883. jassert (mi.readDoubleBigEndian() == randomDouble);
  1884. AtomicTester <int>::testInteger();
  1885. AtomicTester <unsigned int>::testInteger();
  1886. AtomicTester <int32>::testInteger();
  1887. AtomicTester <uint32>::testInteger();
  1888. AtomicTester <long>::testInteger();
  1889. AtomicTester <void*>::testInteger();
  1890. AtomicTester <int*>::testInteger();
  1891. AtomicTester <float>::testFloat();
  1892. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1893. AtomicTester <int64>::testInteger();
  1894. AtomicTester <uint64>::testInteger();
  1895. AtomicTester <double>::testFloat();
  1896. #endif
  1897. }
  1898. }
  1899. #endif
  1900. static bool juceInitialisedNonGUI = false;
  1901. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1902. {
  1903. if (! juceInitialisedNonGUI)
  1904. {
  1905. juceInitialisedNonGUI = true;
  1906. JUCE_AUTORELEASEPOOL
  1907. #if JUCE_DEBUG
  1908. SimpleUnitTests::runBasicTests();
  1909. #endif
  1910. DBG (SystemStats::getJUCEVersion());
  1911. SystemStats::initialiseStats();
  1912. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1913. }
  1914. }
  1915. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1916. {
  1917. if (juceInitialisedNonGUI)
  1918. {
  1919. juceInitialisedNonGUI = false;
  1920. JUCE_AUTORELEASEPOOL
  1921. LocalisedStrings::setCurrentMappings (0);
  1922. Thread::stopAllThreads (3000);
  1923. #if JUCE_WINDOWS
  1924. juce_shutdownWin32Sockets();
  1925. #endif
  1926. #if JUCE_DEBUG
  1927. juce_CheckForDanglingStreams();
  1928. #endif
  1929. }
  1930. }
  1931. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1932. void juce_setCurrentThreadName (const String& name);
  1933. static bool juceInitialisedGUI = false;
  1934. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1935. {
  1936. if (! juceInitialisedGUI)
  1937. {
  1938. juceInitialisedGUI = true;
  1939. JUCE_AUTORELEASEPOOL
  1940. initialiseJuce_NonGUI();
  1941. MessageManager::getInstance();
  1942. LookAndFeel::setDefaultLookAndFeel (0);
  1943. juce_setCurrentThreadName ("Juce Message Thread");
  1944. #if JUCE_DEBUG
  1945. // This section is just for catching people who mess up their project settings and
  1946. // turn RTTI off..
  1947. try
  1948. {
  1949. TextButton tb (String::empty);
  1950. Component* c = &tb;
  1951. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1952. c = dynamic_cast <Button*> (c);
  1953. }
  1954. catch (...)
  1955. {
  1956. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1957. jassertfalse;
  1958. }
  1959. #endif
  1960. }
  1961. }
  1962. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1963. {
  1964. if (juceInitialisedGUI)
  1965. {
  1966. juceInitialisedGUI = false;
  1967. JUCE_AUTORELEASEPOOL
  1968. DeletedAtShutdown::deleteAll();
  1969. LookAndFeel::clearDefaultLookAndFeel();
  1970. delete MessageManager::getInstance();
  1971. shutdownJuce_NonGUI();
  1972. }
  1973. }
  1974. #endif
  1975. END_JUCE_NAMESPACE
  1976. /*** End of inlined file: juce_Initialisation.cpp ***/
  1977. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1978. BEGIN_JUCE_NAMESPACE
  1979. BigInteger::BigInteger()
  1980. : numValues (4),
  1981. highestBit (-1),
  1982. negative (false)
  1983. {
  1984. values.calloc (numValues + 1);
  1985. }
  1986. BigInteger::BigInteger (const int value)
  1987. : numValues (4),
  1988. highestBit (31),
  1989. negative (value < 0)
  1990. {
  1991. values.calloc (numValues + 1);
  1992. values[0] = abs (value);
  1993. highestBit = getHighestBit();
  1994. }
  1995. BigInteger::BigInteger (int64 value)
  1996. : numValues (4),
  1997. highestBit (63),
  1998. negative (value < 0)
  1999. {
  2000. values.calloc (numValues + 1);
  2001. if (value < 0)
  2002. value = -value;
  2003. values[0] = (unsigned int) value;
  2004. values[1] = (unsigned int) (value >> 32);
  2005. highestBit = getHighestBit();
  2006. }
  2007. BigInteger::BigInteger (const unsigned int value)
  2008. : numValues (4),
  2009. highestBit (31),
  2010. negative (false)
  2011. {
  2012. values.calloc (numValues + 1);
  2013. values[0] = value;
  2014. highestBit = getHighestBit();
  2015. }
  2016. BigInteger::BigInteger (const BigInteger& other)
  2017. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2018. highestBit (other.getHighestBit()),
  2019. negative (other.negative)
  2020. {
  2021. values.malloc (numValues + 1);
  2022. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2023. }
  2024. BigInteger::~BigInteger()
  2025. {
  2026. }
  2027. void BigInteger::swapWith (BigInteger& other) throw()
  2028. {
  2029. values.swapWith (other.values);
  2030. swapVariables (numValues, other.numValues);
  2031. swapVariables (highestBit, other.highestBit);
  2032. swapVariables (negative, other.negative);
  2033. }
  2034. BigInteger& BigInteger::operator= (const BigInteger& other)
  2035. {
  2036. if (this != &other)
  2037. {
  2038. highestBit = other.getHighestBit();
  2039. numValues = jmax (4, (highestBit >> 5) + 1);
  2040. negative = other.negative;
  2041. values.malloc (numValues + 1);
  2042. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2043. }
  2044. return *this;
  2045. }
  2046. void BigInteger::ensureSize (const int numVals)
  2047. {
  2048. if (numVals + 2 >= numValues)
  2049. {
  2050. int oldSize = numValues;
  2051. numValues = ((numVals + 2) * 3) / 2;
  2052. values.realloc (numValues + 1);
  2053. while (oldSize < numValues)
  2054. values [oldSize++] = 0;
  2055. }
  2056. }
  2057. bool BigInteger::operator[] (const int bit) const throw()
  2058. {
  2059. return bit <= highestBit && bit >= 0
  2060. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2061. }
  2062. int BigInteger::toInteger() const throw()
  2063. {
  2064. const int n = (int) (values[0] & 0x7fffffff);
  2065. return negative ? -n : n;
  2066. }
  2067. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2068. {
  2069. BigInteger r;
  2070. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2071. r.ensureSize (numBits >> 5);
  2072. r.highestBit = numBits;
  2073. int i = 0;
  2074. while (numBits > 0)
  2075. {
  2076. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2077. numBits -= 32;
  2078. startBit += 32;
  2079. }
  2080. r.highestBit = r.getHighestBit();
  2081. return r;
  2082. }
  2083. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2084. {
  2085. if (numBits > 32)
  2086. {
  2087. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2088. numBits = 32;
  2089. }
  2090. numBits = jmin (numBits, highestBit + 1 - startBit);
  2091. if (numBits <= 0)
  2092. return 0;
  2093. const int pos = startBit >> 5;
  2094. const int offset = startBit & 31;
  2095. const int endSpace = 32 - numBits;
  2096. uint32 n = ((uint32) values [pos]) >> offset;
  2097. if (offset > endSpace)
  2098. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2099. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2100. }
  2101. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2102. {
  2103. if (numBits > 32)
  2104. {
  2105. jassertfalse;
  2106. numBits = 32;
  2107. }
  2108. for (int i = 0; i < numBits; ++i)
  2109. {
  2110. setBit (startBit + i, (valueToSet & 1) != 0);
  2111. valueToSet >>= 1;
  2112. }
  2113. }
  2114. void BigInteger::clear()
  2115. {
  2116. if (numValues > 16)
  2117. {
  2118. numValues = 4;
  2119. values.calloc (numValues + 1);
  2120. }
  2121. else
  2122. {
  2123. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2124. }
  2125. highestBit = -1;
  2126. negative = false;
  2127. }
  2128. void BigInteger::setBit (const int bit)
  2129. {
  2130. if (bit >= 0)
  2131. {
  2132. if (bit > highestBit)
  2133. {
  2134. ensureSize (bit >> 5);
  2135. highestBit = bit;
  2136. }
  2137. values [bit >> 5] |= (1 << (bit & 31));
  2138. }
  2139. }
  2140. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2141. {
  2142. if (shouldBeSet)
  2143. setBit (bit);
  2144. else
  2145. clearBit (bit);
  2146. }
  2147. void BigInteger::clearBit (const int bit) throw()
  2148. {
  2149. if (bit >= 0 && bit <= highestBit)
  2150. values [bit >> 5] &= ~(1 << (bit & 31));
  2151. }
  2152. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2153. {
  2154. while (--numBits >= 0)
  2155. setBit (startBit++, shouldBeSet);
  2156. }
  2157. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2158. {
  2159. if (bit >= 0)
  2160. shiftBits (1, bit);
  2161. setBit (bit, shouldBeSet);
  2162. }
  2163. bool BigInteger::isZero() const throw()
  2164. {
  2165. return getHighestBit() < 0;
  2166. }
  2167. bool BigInteger::isOne() const throw()
  2168. {
  2169. return getHighestBit() == 0 && ! negative;
  2170. }
  2171. bool BigInteger::isNegative() const throw()
  2172. {
  2173. return negative && ! isZero();
  2174. }
  2175. void BigInteger::setNegative (const bool neg) throw()
  2176. {
  2177. negative = neg;
  2178. }
  2179. void BigInteger::negate() throw()
  2180. {
  2181. negative = (! negative) && ! isZero();
  2182. }
  2183. int BigInteger::countNumberOfSetBits() const throw()
  2184. {
  2185. int total = 0;
  2186. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2187. {
  2188. unsigned int n = values[i];
  2189. if (n == 0xffffffff)
  2190. {
  2191. total += 32;
  2192. }
  2193. else
  2194. {
  2195. while (n != 0)
  2196. {
  2197. total += (n & 1);
  2198. n >>= 1;
  2199. }
  2200. }
  2201. }
  2202. return total;
  2203. }
  2204. int BigInteger::getHighestBit() const throw()
  2205. {
  2206. for (int i = highestBit + 1; --i >= 0;)
  2207. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2208. return i;
  2209. return -1;
  2210. }
  2211. int BigInteger::findNextSetBit (int i) const throw()
  2212. {
  2213. for (; i <= highestBit; ++i)
  2214. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2215. return i;
  2216. return -1;
  2217. }
  2218. int BigInteger::findNextClearBit (int i) const throw()
  2219. {
  2220. for (; i <= highestBit; ++i)
  2221. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2222. break;
  2223. return i;
  2224. }
  2225. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2226. {
  2227. if (other.isNegative())
  2228. return operator-= (-other);
  2229. if (isNegative())
  2230. {
  2231. if (compareAbsolute (other) < 0)
  2232. {
  2233. BigInteger temp (*this);
  2234. temp.negate();
  2235. *this = other;
  2236. operator-= (temp);
  2237. }
  2238. else
  2239. {
  2240. negate();
  2241. operator-= (other);
  2242. negate();
  2243. }
  2244. }
  2245. else
  2246. {
  2247. if (other.highestBit > highestBit)
  2248. highestBit = other.highestBit;
  2249. ++highestBit;
  2250. const int numInts = (highestBit >> 5) + 1;
  2251. ensureSize (numInts);
  2252. int64 remainder = 0;
  2253. for (int i = 0; i <= numInts; ++i)
  2254. {
  2255. if (i < numValues)
  2256. remainder += values[i];
  2257. if (i < other.numValues)
  2258. remainder += other.values[i];
  2259. values[i] = (unsigned int) remainder;
  2260. remainder >>= 32;
  2261. }
  2262. jassert (remainder == 0);
  2263. highestBit = getHighestBit();
  2264. }
  2265. return *this;
  2266. }
  2267. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2268. {
  2269. if (other.isNegative())
  2270. return operator+= (-other);
  2271. if (! isNegative())
  2272. {
  2273. if (compareAbsolute (other) < 0)
  2274. {
  2275. BigInteger temp (other);
  2276. swapWith (temp);
  2277. operator-= (temp);
  2278. negate();
  2279. return *this;
  2280. }
  2281. }
  2282. else
  2283. {
  2284. negate();
  2285. operator+= (other);
  2286. negate();
  2287. return *this;
  2288. }
  2289. const int numInts = (highestBit >> 5) + 1;
  2290. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2291. int64 amountToSubtract = 0;
  2292. for (int i = 0; i <= numInts; ++i)
  2293. {
  2294. if (i <= maxOtherInts)
  2295. amountToSubtract += (int64) other.values[i];
  2296. if (values[i] >= amountToSubtract)
  2297. {
  2298. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2299. amountToSubtract = 0;
  2300. }
  2301. else
  2302. {
  2303. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2304. values[i] = (unsigned int) n;
  2305. amountToSubtract = 1;
  2306. }
  2307. }
  2308. return *this;
  2309. }
  2310. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2311. {
  2312. BigInteger total;
  2313. highestBit = getHighestBit();
  2314. const bool wasNegative = isNegative();
  2315. setNegative (false);
  2316. for (int i = 0; i <= highestBit; ++i)
  2317. {
  2318. if (operator[](i))
  2319. {
  2320. BigInteger n (other);
  2321. n.setNegative (false);
  2322. n <<= i;
  2323. total += n;
  2324. }
  2325. }
  2326. total.setNegative (wasNegative ^ other.isNegative());
  2327. swapWith (total);
  2328. return *this;
  2329. }
  2330. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2331. {
  2332. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2333. const int divHB = divisor.getHighestBit();
  2334. const int ourHB = getHighestBit();
  2335. if (divHB < 0 || ourHB < 0)
  2336. {
  2337. // division by zero
  2338. remainder.clear();
  2339. clear();
  2340. }
  2341. else
  2342. {
  2343. const bool wasNegative = isNegative();
  2344. swapWith (remainder);
  2345. remainder.setNegative (false);
  2346. clear();
  2347. BigInteger temp (divisor);
  2348. temp.setNegative (false);
  2349. int leftShift = ourHB - divHB;
  2350. temp <<= leftShift;
  2351. while (leftShift >= 0)
  2352. {
  2353. if (remainder.compareAbsolute (temp) >= 0)
  2354. {
  2355. remainder -= temp;
  2356. setBit (leftShift);
  2357. }
  2358. if (--leftShift >= 0)
  2359. temp >>= 1;
  2360. }
  2361. negative = wasNegative ^ divisor.isNegative();
  2362. remainder.setNegative (wasNegative);
  2363. }
  2364. }
  2365. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2366. {
  2367. BigInteger remainder;
  2368. divideBy (other, remainder);
  2369. return *this;
  2370. }
  2371. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2372. {
  2373. // this operation doesn't take into account negative values..
  2374. jassert (isNegative() == other.isNegative());
  2375. if (other.highestBit >= 0)
  2376. {
  2377. ensureSize (other.highestBit >> 5);
  2378. int n = (other.highestBit >> 5) + 1;
  2379. while (--n >= 0)
  2380. values[n] |= other.values[n];
  2381. if (other.highestBit > highestBit)
  2382. highestBit = other.highestBit;
  2383. highestBit = getHighestBit();
  2384. }
  2385. return *this;
  2386. }
  2387. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2388. {
  2389. // this operation doesn't take into account negative values..
  2390. jassert (isNegative() == other.isNegative());
  2391. int n = numValues;
  2392. while (n > other.numValues)
  2393. values[--n] = 0;
  2394. while (--n >= 0)
  2395. values[n] &= other.values[n];
  2396. if (other.highestBit < highestBit)
  2397. highestBit = other.highestBit;
  2398. highestBit = getHighestBit();
  2399. return *this;
  2400. }
  2401. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2402. {
  2403. // this operation will only work with the absolute values
  2404. jassert (isNegative() == other.isNegative());
  2405. if (other.highestBit >= 0)
  2406. {
  2407. ensureSize (other.highestBit >> 5);
  2408. int n = (other.highestBit >> 5) + 1;
  2409. while (--n >= 0)
  2410. values[n] ^= other.values[n];
  2411. if (other.highestBit > highestBit)
  2412. highestBit = other.highestBit;
  2413. highestBit = getHighestBit();
  2414. }
  2415. return *this;
  2416. }
  2417. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2418. {
  2419. BigInteger remainder;
  2420. divideBy (divisor, remainder);
  2421. swapWith (remainder);
  2422. return *this;
  2423. }
  2424. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2425. {
  2426. shiftBits (numBitsToShift, 0);
  2427. return *this;
  2428. }
  2429. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2430. {
  2431. return operator<<= (-numBitsToShift);
  2432. }
  2433. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2434. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2435. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2436. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2437. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2438. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2439. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2440. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2441. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2442. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2443. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2444. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2445. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2446. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2447. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2448. int BigInteger::compare (const BigInteger& other) const throw()
  2449. {
  2450. if (isNegative() == other.isNegative())
  2451. {
  2452. const int absComp = compareAbsolute (other);
  2453. return isNegative() ? -absComp : absComp;
  2454. }
  2455. else
  2456. {
  2457. return isNegative() ? -1 : 1;
  2458. }
  2459. }
  2460. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2461. {
  2462. const int h1 = getHighestBit();
  2463. const int h2 = other.getHighestBit();
  2464. if (h1 > h2)
  2465. return 1;
  2466. else if (h1 < h2)
  2467. return -1;
  2468. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2469. if (values[i] != other.values[i])
  2470. return (values[i] > other.values[i]) ? 1 : -1;
  2471. return 0;
  2472. }
  2473. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2474. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2475. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2476. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2477. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2478. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2479. void BigInteger::shiftBits (int bits, const int startBit)
  2480. {
  2481. if (highestBit < 0)
  2482. return;
  2483. if (startBit > 0)
  2484. {
  2485. if (bits < 0)
  2486. {
  2487. // right shift
  2488. for (int i = startBit; i <= highestBit; ++i)
  2489. setBit (i, operator[] (i - bits));
  2490. highestBit = getHighestBit();
  2491. }
  2492. else if (bits > 0)
  2493. {
  2494. // left shift
  2495. for (int i = highestBit + 1; --i >= startBit;)
  2496. setBit (i + bits, operator[] (i));
  2497. while (--bits >= 0)
  2498. clearBit (bits + startBit);
  2499. }
  2500. }
  2501. else
  2502. {
  2503. if (bits < 0)
  2504. {
  2505. // right shift
  2506. bits = -bits;
  2507. if (bits > highestBit)
  2508. {
  2509. clear();
  2510. }
  2511. else
  2512. {
  2513. const int wordsToMove = bits >> 5;
  2514. int top = 1 + (highestBit >> 5) - wordsToMove;
  2515. highestBit -= bits;
  2516. if (wordsToMove > 0)
  2517. {
  2518. int i;
  2519. for (i = 0; i < top; ++i)
  2520. values [i] = values [i + wordsToMove];
  2521. for (i = 0; i < wordsToMove; ++i)
  2522. values [top + i] = 0;
  2523. bits &= 31;
  2524. }
  2525. if (bits != 0)
  2526. {
  2527. const int invBits = 32 - bits;
  2528. --top;
  2529. for (int i = 0; i < top; ++i)
  2530. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2531. values[top] = (values[top] >> bits);
  2532. }
  2533. highestBit = getHighestBit();
  2534. }
  2535. }
  2536. else if (bits > 0)
  2537. {
  2538. // left shift
  2539. ensureSize (((highestBit + bits) >> 5) + 1);
  2540. const int wordsToMove = bits >> 5;
  2541. int top = 1 + (highestBit >> 5);
  2542. highestBit += bits;
  2543. if (wordsToMove > 0)
  2544. {
  2545. int i;
  2546. for (i = top; --i >= 0;)
  2547. values [i + wordsToMove] = values [i];
  2548. for (i = 0; i < wordsToMove; ++i)
  2549. values [i] = 0;
  2550. bits &= 31;
  2551. }
  2552. if (bits != 0)
  2553. {
  2554. const int invBits = 32 - bits;
  2555. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2556. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2557. values [wordsToMove] = values [wordsToMove] << bits;
  2558. }
  2559. highestBit = getHighestBit();
  2560. }
  2561. }
  2562. }
  2563. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2564. {
  2565. while (! m->isZero())
  2566. {
  2567. if (n->compareAbsolute (*m) > 0)
  2568. swapVariables (m, n);
  2569. *m -= *n;
  2570. }
  2571. return *n;
  2572. }
  2573. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2574. {
  2575. BigInteger m (*this);
  2576. while (! n.isZero())
  2577. {
  2578. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2579. return simpleGCD (&m, &n);
  2580. BigInteger temp1 (m), temp2;
  2581. temp1.divideBy (n, temp2);
  2582. m = n;
  2583. n = temp2;
  2584. }
  2585. return m;
  2586. }
  2587. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2588. {
  2589. BigInteger exp (exponent);
  2590. exp %= modulus;
  2591. BigInteger value (1);
  2592. swapWith (value);
  2593. value %= modulus;
  2594. while (! exp.isZero())
  2595. {
  2596. if (exp [0])
  2597. {
  2598. operator*= (value);
  2599. operator%= (modulus);
  2600. }
  2601. value *= value;
  2602. value %= modulus;
  2603. exp >>= 1;
  2604. }
  2605. }
  2606. void BigInteger::inverseModulo (const BigInteger& modulus)
  2607. {
  2608. if (modulus.isOne() || modulus.isNegative())
  2609. {
  2610. clear();
  2611. return;
  2612. }
  2613. if (isNegative() || compareAbsolute (modulus) >= 0)
  2614. operator%= (modulus);
  2615. if (isOne())
  2616. return;
  2617. if (! (*this)[0])
  2618. {
  2619. // not invertible
  2620. clear();
  2621. return;
  2622. }
  2623. BigInteger a1 (modulus);
  2624. BigInteger a2 (*this);
  2625. BigInteger b1 (modulus);
  2626. BigInteger b2 (1);
  2627. while (! a2.isOne())
  2628. {
  2629. BigInteger temp1, temp2, multiplier (a1);
  2630. multiplier.divideBy (a2, temp1);
  2631. temp1 = a2;
  2632. temp1 *= multiplier;
  2633. temp2 = a1;
  2634. temp2 -= temp1;
  2635. a1 = a2;
  2636. a2 = temp2;
  2637. temp1 = b2;
  2638. temp1 *= multiplier;
  2639. temp2 = b1;
  2640. temp2 -= temp1;
  2641. b1 = b2;
  2642. b2 = temp2;
  2643. }
  2644. while (b2.isNegative())
  2645. b2 += modulus;
  2646. b2 %= modulus;
  2647. swapWith (b2);
  2648. }
  2649. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2650. {
  2651. return stream << value.toString (10);
  2652. }
  2653. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2654. {
  2655. String s;
  2656. BigInteger v (*this);
  2657. if (base == 2 || base == 8 || base == 16)
  2658. {
  2659. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2660. static const char* const hexDigits = "0123456789abcdef";
  2661. for (;;)
  2662. {
  2663. const int remainder = v.getBitRangeAsInt (0, bits);
  2664. v >>= bits;
  2665. if (remainder == 0 && v.isZero())
  2666. break;
  2667. s = String::charToString (hexDigits [remainder]) + s;
  2668. }
  2669. }
  2670. else if (base == 10)
  2671. {
  2672. const BigInteger ten (10);
  2673. BigInteger remainder;
  2674. for (;;)
  2675. {
  2676. v.divideBy (ten, remainder);
  2677. if (remainder.isZero() && v.isZero())
  2678. break;
  2679. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2680. }
  2681. }
  2682. else
  2683. {
  2684. jassertfalse; // can't do the specified base!
  2685. return String::empty;
  2686. }
  2687. s = s.paddedLeft ('0', minimumNumCharacters);
  2688. return isNegative() ? "-" + s : s;
  2689. }
  2690. void BigInteger::parseString (const String& text, const int base)
  2691. {
  2692. clear();
  2693. const juce_wchar* t = text;
  2694. if (base == 2 || base == 8 || base == 16)
  2695. {
  2696. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2697. for (;;)
  2698. {
  2699. const juce_wchar c = *t++;
  2700. const int digit = CharacterFunctions::getHexDigitValue (c);
  2701. if (((unsigned int) digit) < (unsigned int) base)
  2702. {
  2703. operator<<= (bits);
  2704. operator+= (digit);
  2705. }
  2706. else if (c == 0)
  2707. {
  2708. break;
  2709. }
  2710. }
  2711. }
  2712. else if (base == 10)
  2713. {
  2714. const BigInteger ten ((unsigned int) 10);
  2715. for (;;)
  2716. {
  2717. const juce_wchar c = *t++;
  2718. if (c >= '0' && c <= '9')
  2719. {
  2720. operator*= (ten);
  2721. operator+= ((int) (c - '0'));
  2722. }
  2723. else if (c == 0)
  2724. {
  2725. break;
  2726. }
  2727. }
  2728. }
  2729. setNegative (text.trimStart().startsWithChar ('-'));
  2730. }
  2731. const MemoryBlock BigInteger::toMemoryBlock() const
  2732. {
  2733. const int numBytes = (getHighestBit() + 8) >> 3;
  2734. MemoryBlock mb ((size_t) numBytes);
  2735. for (int i = 0; i < numBytes; ++i)
  2736. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2737. return mb;
  2738. }
  2739. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2740. {
  2741. clear();
  2742. for (int i = (int) data.getSize(); --i >= 0;)
  2743. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2744. }
  2745. END_JUCE_NAMESPACE
  2746. /*** End of inlined file: juce_BigInteger.cpp ***/
  2747. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2748. BEGIN_JUCE_NAMESPACE
  2749. MemoryBlock::MemoryBlock() throw()
  2750. : size (0)
  2751. {
  2752. }
  2753. MemoryBlock::MemoryBlock (const size_t initialSize,
  2754. const bool initialiseToZero) throw()
  2755. {
  2756. if (initialSize > 0)
  2757. {
  2758. size = initialSize;
  2759. data.allocate (initialSize, initialiseToZero);
  2760. }
  2761. else
  2762. {
  2763. size = 0;
  2764. }
  2765. }
  2766. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2767. : size (other.size)
  2768. {
  2769. if (size > 0)
  2770. {
  2771. jassert (other.data != 0);
  2772. data.malloc (size);
  2773. memcpy (data, other.data, size);
  2774. }
  2775. }
  2776. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2777. const size_t sizeInBytes) throw()
  2778. : size (jmax ((size_t) 0, sizeInBytes))
  2779. {
  2780. jassert (sizeInBytes >= 0);
  2781. if (size > 0)
  2782. {
  2783. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2784. data.malloc (size);
  2785. if (dataToInitialiseFrom != 0)
  2786. memcpy (data, dataToInitialiseFrom, size);
  2787. }
  2788. }
  2789. MemoryBlock::~MemoryBlock() throw()
  2790. {
  2791. jassert (size >= 0); // should never happen
  2792. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2793. }
  2794. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2795. {
  2796. if (this != &other)
  2797. {
  2798. setSize (other.size, false);
  2799. memcpy (data, other.data, size);
  2800. }
  2801. return *this;
  2802. }
  2803. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2804. {
  2805. return matches (other.data, other.size);
  2806. }
  2807. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2808. {
  2809. return ! operator== (other);
  2810. }
  2811. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2812. {
  2813. return size == dataSize
  2814. && memcmp (data, dataToCompare, size) == 0;
  2815. }
  2816. // this will resize the block to this size
  2817. void MemoryBlock::setSize (const size_t newSize,
  2818. const bool initialiseToZero) throw()
  2819. {
  2820. if (size != newSize)
  2821. {
  2822. if (newSize <= 0)
  2823. {
  2824. data.free();
  2825. size = 0;
  2826. }
  2827. else
  2828. {
  2829. if (data != 0)
  2830. {
  2831. data.realloc (newSize);
  2832. if (initialiseToZero && (newSize > size))
  2833. zeromem (data + size, newSize - size);
  2834. }
  2835. else
  2836. {
  2837. data.allocate (newSize, initialiseToZero);
  2838. }
  2839. size = newSize;
  2840. }
  2841. }
  2842. }
  2843. void MemoryBlock::ensureSize (const size_t minimumSize,
  2844. const bool initialiseToZero) throw()
  2845. {
  2846. if (size < minimumSize)
  2847. setSize (minimumSize, initialiseToZero);
  2848. }
  2849. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2850. {
  2851. swapVariables (size, other.size);
  2852. data.swapWith (other.data);
  2853. }
  2854. void MemoryBlock::fillWith (const uint8 value) throw()
  2855. {
  2856. memset (data, (int) value, size);
  2857. }
  2858. void MemoryBlock::append (const void* const srcData,
  2859. const size_t numBytes) throw()
  2860. {
  2861. if (numBytes > 0)
  2862. {
  2863. const size_t oldSize = size;
  2864. setSize (size + numBytes);
  2865. memcpy (data + oldSize, srcData, numBytes);
  2866. }
  2867. }
  2868. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2869. {
  2870. const char* d = static_cast<const char*> (src);
  2871. if (offset < 0)
  2872. {
  2873. d -= offset;
  2874. num -= offset;
  2875. offset = 0;
  2876. }
  2877. if (offset + num > size)
  2878. num = size - offset;
  2879. if (num > 0)
  2880. memcpy (data + offset, d, num);
  2881. }
  2882. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2883. {
  2884. char* d = static_cast<char*> (dst);
  2885. if (offset < 0)
  2886. {
  2887. zeromem (d, -offset);
  2888. d -= offset;
  2889. num += offset;
  2890. offset = 0;
  2891. }
  2892. if (offset + num > size)
  2893. {
  2894. const size_t newNum = size - offset;
  2895. zeromem (d + newNum, num - newNum);
  2896. num = newNum;
  2897. }
  2898. if (num > 0)
  2899. memcpy (d, data + offset, num);
  2900. }
  2901. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2902. {
  2903. if (startByte < 0)
  2904. {
  2905. numBytesToRemove += startByte;
  2906. startByte = 0;
  2907. }
  2908. if (startByte + numBytesToRemove >= size)
  2909. {
  2910. setSize (startByte);
  2911. }
  2912. else if (numBytesToRemove > 0)
  2913. {
  2914. memmove (data + startByte,
  2915. data + startByte + numBytesToRemove,
  2916. size - (startByte + numBytesToRemove));
  2917. setSize (size - numBytesToRemove);
  2918. }
  2919. }
  2920. const String MemoryBlock::toString() const throw()
  2921. {
  2922. return String (static_cast <const char*> (getData()), size);
  2923. }
  2924. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2925. {
  2926. int res = 0;
  2927. size_t byte = bitRangeStart >> 3;
  2928. int offsetInByte = (int) bitRangeStart & 7;
  2929. size_t bitsSoFar = 0;
  2930. while (numBits > 0 && (size_t) byte < size)
  2931. {
  2932. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2933. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2934. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2935. bitsSoFar += bitsThisTime;
  2936. numBits -= bitsThisTime;
  2937. ++byte;
  2938. offsetInByte = 0;
  2939. }
  2940. return res;
  2941. }
  2942. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2943. {
  2944. size_t byte = bitRangeStart >> 3;
  2945. int offsetInByte = (int) bitRangeStart & 7;
  2946. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2947. while (numBits > 0 && (size_t) byte < size)
  2948. {
  2949. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2950. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2951. const unsigned int tempBits = bitsToSet << offsetInByte;
  2952. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2953. ++byte;
  2954. numBits -= bitsThisTime;
  2955. bitsToSet >>= bitsThisTime;
  2956. mask >>= bitsThisTime;
  2957. offsetInByte = 0;
  2958. }
  2959. }
  2960. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2961. {
  2962. ensureSize (hex.length() >> 1);
  2963. char* dest = data;
  2964. int i = 0;
  2965. for (;;)
  2966. {
  2967. int byte = 0;
  2968. for (int loop = 2; --loop >= 0;)
  2969. {
  2970. byte <<= 4;
  2971. for (;;)
  2972. {
  2973. const juce_wchar c = hex [i++];
  2974. if (c >= '0' && c <= '9')
  2975. {
  2976. byte |= c - '0';
  2977. break;
  2978. }
  2979. else if (c >= 'a' && c <= 'z')
  2980. {
  2981. byte |= c - ('a' - 10);
  2982. break;
  2983. }
  2984. else if (c >= 'A' && c <= 'Z')
  2985. {
  2986. byte |= c - ('A' - 10);
  2987. break;
  2988. }
  2989. else if (c == 0)
  2990. {
  2991. setSize (static_cast <size_t> (dest - data));
  2992. return;
  2993. }
  2994. }
  2995. }
  2996. *dest++ = (char) byte;
  2997. }
  2998. }
  2999. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3000. const String MemoryBlock::toBase64Encoding() const throw()
  3001. {
  3002. const size_t numChars = ((size << 3) + 5) / 6;
  3003. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3004. const int initialLen = destString.length();
  3005. destString.preallocateStorage (initialLen + 2 + numChars);
  3006. juce_wchar* d = destString;
  3007. d += initialLen;
  3008. *d++ = '.';
  3009. for (size_t i = 0; i < numChars; ++i)
  3010. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3011. *d++ = 0;
  3012. return destString;
  3013. }
  3014. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  3015. {
  3016. const int startPos = s.indexOfChar ('.') + 1;
  3017. if (startPos <= 0)
  3018. return false;
  3019. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3020. setSize (numBytesNeeded, true);
  3021. const int numChars = s.length() - startPos;
  3022. const juce_wchar* srcChars = s;
  3023. srcChars += startPos;
  3024. int pos = 0;
  3025. for (int i = 0; i < numChars; ++i)
  3026. {
  3027. const char c = (char) srcChars[i];
  3028. for (int j = 0; j < 64; ++j)
  3029. {
  3030. if (encodingTable[j] == c)
  3031. {
  3032. setBitRange (pos, 6, j);
  3033. pos += 6;
  3034. break;
  3035. }
  3036. }
  3037. }
  3038. return true;
  3039. }
  3040. END_JUCE_NAMESPACE
  3041. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3042. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3043. BEGIN_JUCE_NAMESPACE
  3044. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  3045. : properties (ignoreCaseOfKeyNames),
  3046. fallbackProperties (0),
  3047. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3048. {
  3049. }
  3050. PropertySet::PropertySet (const PropertySet& other) throw()
  3051. : properties (other.properties),
  3052. fallbackProperties (other.fallbackProperties),
  3053. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3054. {
  3055. }
  3056. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  3057. {
  3058. properties = other.properties;
  3059. fallbackProperties = other.fallbackProperties;
  3060. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3061. propertyChanged();
  3062. return *this;
  3063. }
  3064. PropertySet::~PropertySet()
  3065. {
  3066. }
  3067. void PropertySet::clear()
  3068. {
  3069. const ScopedLock sl (lock);
  3070. if (properties.size() > 0)
  3071. {
  3072. properties.clear();
  3073. propertyChanged();
  3074. }
  3075. }
  3076. const String PropertySet::getValue (const String& keyName,
  3077. const String& defaultValue) const throw()
  3078. {
  3079. const ScopedLock sl (lock);
  3080. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3081. if (index >= 0)
  3082. return properties.getAllValues() [index];
  3083. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3084. : defaultValue;
  3085. }
  3086. int PropertySet::getIntValue (const String& keyName,
  3087. const int defaultValue) const throw()
  3088. {
  3089. const ScopedLock sl (lock);
  3090. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3091. if (index >= 0)
  3092. return properties.getAllValues() [index].getIntValue();
  3093. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3094. : defaultValue;
  3095. }
  3096. double PropertySet::getDoubleValue (const String& keyName,
  3097. const double defaultValue) const throw()
  3098. {
  3099. const ScopedLock sl (lock);
  3100. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3101. if (index >= 0)
  3102. return properties.getAllValues()[index].getDoubleValue();
  3103. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3104. : defaultValue;
  3105. }
  3106. bool PropertySet::getBoolValue (const String& keyName,
  3107. const bool defaultValue) const throw()
  3108. {
  3109. const ScopedLock sl (lock);
  3110. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3111. if (index >= 0)
  3112. return properties.getAllValues() [index].getIntValue() != 0;
  3113. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3114. : defaultValue;
  3115. }
  3116. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3117. {
  3118. XmlDocument doc (getValue (keyName));
  3119. return doc.getDocumentElement();
  3120. }
  3121. void PropertySet::setValue (const String& keyName,
  3122. const String& value) throw()
  3123. {
  3124. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3125. if (keyName.isNotEmpty())
  3126. {
  3127. const ScopedLock sl (lock);
  3128. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3129. if (index < 0 || properties.getAllValues() [index] != value)
  3130. {
  3131. properties.set (keyName, value);
  3132. propertyChanged();
  3133. }
  3134. }
  3135. }
  3136. void PropertySet::removeValue (const String& keyName) throw()
  3137. {
  3138. if (keyName.isNotEmpty())
  3139. {
  3140. const ScopedLock sl (lock);
  3141. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3142. if (index >= 0)
  3143. {
  3144. properties.remove (keyName);
  3145. propertyChanged();
  3146. }
  3147. }
  3148. }
  3149. void PropertySet::setValue (const String& keyName, const int value) throw()
  3150. {
  3151. setValue (keyName, String (value));
  3152. }
  3153. void PropertySet::setValue (const String& keyName, const double value) throw()
  3154. {
  3155. setValue (keyName, String (value));
  3156. }
  3157. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3158. {
  3159. setValue (keyName, String (value ? "1" : "0"));
  3160. }
  3161. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3162. {
  3163. setValue (keyName, (xml == 0) ? String::empty
  3164. : xml->createDocument (String::empty, true));
  3165. }
  3166. bool PropertySet::containsKey (const String& keyName) const throw()
  3167. {
  3168. const ScopedLock sl (lock);
  3169. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3170. }
  3171. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3172. {
  3173. const ScopedLock sl (lock);
  3174. fallbackProperties = fallbackProperties_;
  3175. }
  3176. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3177. {
  3178. const ScopedLock sl (lock);
  3179. XmlElement* const xml = new XmlElement (nodeName);
  3180. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3181. {
  3182. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3183. e->setAttribute ("name", properties.getAllKeys()[i]);
  3184. e->setAttribute ("val", properties.getAllValues()[i]);
  3185. }
  3186. return xml;
  3187. }
  3188. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3189. {
  3190. const ScopedLock sl (lock);
  3191. clear();
  3192. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3193. {
  3194. if (e->hasAttribute ("name")
  3195. && e->hasAttribute ("val"))
  3196. {
  3197. properties.set (e->getStringAttribute ("name"),
  3198. e->getStringAttribute ("val"));
  3199. }
  3200. }
  3201. if (properties.size() > 0)
  3202. propertyChanged();
  3203. }
  3204. void PropertySet::propertyChanged()
  3205. {
  3206. }
  3207. END_JUCE_NAMESPACE
  3208. /*** End of inlined file: juce_PropertySet.cpp ***/
  3209. /*** Start of inlined file: juce_Identifier.cpp ***/
  3210. BEGIN_JUCE_NAMESPACE
  3211. StringPool& Identifier::getPool()
  3212. {
  3213. static StringPool pool;
  3214. return pool;
  3215. }
  3216. Identifier::Identifier() throw()
  3217. : name (0)
  3218. {
  3219. }
  3220. Identifier::Identifier (const Identifier& other) throw()
  3221. : name (other.name)
  3222. {
  3223. }
  3224. Identifier& Identifier::operator= (const Identifier& other) throw()
  3225. {
  3226. name = other.name;
  3227. return *this;
  3228. }
  3229. Identifier::Identifier (const String& name_)
  3230. : name (Identifier::getPool().getPooledString (name_))
  3231. {
  3232. /* An Identifier string must be suitable for use as a script variable or XML
  3233. attribute, so it can only contain this limited set of characters.. */
  3234. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3235. }
  3236. Identifier::Identifier (const char* const name_)
  3237. : name (Identifier::getPool().getPooledString (name_))
  3238. {
  3239. /* An Identifier string must be suitable for use as a script variable or XML
  3240. attribute, so it can only contain this limited set of characters.. */
  3241. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3242. }
  3243. Identifier::~Identifier()
  3244. {
  3245. }
  3246. END_JUCE_NAMESPACE
  3247. /*** End of inlined file: juce_Identifier.cpp ***/
  3248. /*** Start of inlined file: juce_Variant.cpp ***/
  3249. BEGIN_JUCE_NAMESPACE
  3250. class var::VariantType
  3251. {
  3252. public:
  3253. VariantType() {}
  3254. virtual ~VariantType() {}
  3255. virtual int toInt (const ValueUnion&) const { return 0; }
  3256. virtual double toDouble (const ValueUnion&) const { return 0; }
  3257. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3258. virtual bool toBool (const ValueUnion&) const { return false; }
  3259. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3260. virtual bool isVoid() const throw() { return false; }
  3261. virtual bool isInt() const throw() { return false; }
  3262. virtual bool isBool() const throw() { return false; }
  3263. virtual bool isDouble() const throw() { return false; }
  3264. virtual bool isString() const throw() { return false; }
  3265. virtual bool isObject() const throw() { return false; }
  3266. virtual bool isMethod() const throw() { return false; }
  3267. virtual void cleanUp (ValueUnion&) const throw() {}
  3268. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3269. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3270. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3271. };
  3272. class var::VariantType_Void : public var::VariantType
  3273. {
  3274. public:
  3275. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3276. bool isVoid() const throw() { return true; }
  3277. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3278. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3279. };
  3280. class var::VariantType_Int : public var::VariantType
  3281. {
  3282. public:
  3283. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3284. int toInt (const ValueUnion& data) const { return data.intValue; };
  3285. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3286. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3287. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3288. bool isInt() const throw() { return true; }
  3289. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3290. {
  3291. return otherType.toInt (otherData) == data.intValue;
  3292. }
  3293. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3294. {
  3295. output.writeCompressedInt (5);
  3296. output.writeByte (1);
  3297. output.writeInt (data.intValue);
  3298. }
  3299. };
  3300. class var::VariantType_Double : public var::VariantType
  3301. {
  3302. public:
  3303. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3304. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3305. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3306. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3307. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3308. bool isDouble() const throw() { return true; }
  3309. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3310. {
  3311. return otherType.toDouble (otherData) == data.doubleValue;
  3312. }
  3313. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3314. {
  3315. output.writeCompressedInt (9);
  3316. output.writeByte (4);
  3317. output.writeDouble (data.doubleValue);
  3318. }
  3319. };
  3320. class var::VariantType_Bool : public var::VariantType
  3321. {
  3322. public:
  3323. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3324. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3325. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3326. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3327. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3328. bool isBool() const throw() { return true; }
  3329. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3330. {
  3331. return otherType.toBool (otherData) == data.boolValue;
  3332. }
  3333. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3334. {
  3335. output.writeCompressedInt (1);
  3336. output.writeByte (data.boolValue ? 2 : 3);
  3337. }
  3338. };
  3339. class var::VariantType_String : public var::VariantType
  3340. {
  3341. public:
  3342. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3343. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3344. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3345. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3346. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3347. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3348. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3349. || data.stringValue->trim().equalsIgnoreCase ("true")
  3350. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3351. bool isString() const throw() { return true; }
  3352. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3353. {
  3354. return otherType.toString (otherData) == *data.stringValue;
  3355. }
  3356. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3357. {
  3358. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3359. output.writeCompressedInt (len + 1);
  3360. output.writeByte (5);
  3361. HeapBlock<char> temp (len);
  3362. data.stringValue->copyToUTF8 (temp, len);
  3363. output.write (temp, len);
  3364. }
  3365. };
  3366. class var::VariantType_Object : public var::VariantType
  3367. {
  3368. public:
  3369. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3370. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3371. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3372. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3373. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3374. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3375. bool isObject() const throw() { return true; }
  3376. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3377. {
  3378. return otherType.toObject (otherData) == data.objectValue;
  3379. }
  3380. void writeToStream (const ValueUnion&, OutputStream& output) const
  3381. {
  3382. jassertfalse; // Can't write an object to a stream!
  3383. output.writeCompressedInt (0);
  3384. }
  3385. };
  3386. class var::VariantType_Method : public var::VariantType
  3387. {
  3388. public:
  3389. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3390. const String toString (const ValueUnion&) const { return "Method"; }
  3391. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3392. bool isMethod() const throw() { return true; }
  3393. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3394. {
  3395. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3396. }
  3397. void writeToStream (const ValueUnion&, OutputStream& output) const
  3398. {
  3399. jassertfalse; // Can't write a method to a stream!
  3400. output.writeCompressedInt (0);
  3401. }
  3402. };
  3403. var::var() throw()
  3404. : type (VariantType_Void::getInstance())
  3405. {
  3406. }
  3407. var::~var() throw()
  3408. {
  3409. type->cleanUp (value);
  3410. }
  3411. const var var::null;
  3412. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3413. {
  3414. type->createCopy (value, valueToCopy.value);
  3415. }
  3416. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3417. {
  3418. value.intValue = value_;
  3419. }
  3420. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3421. {
  3422. value.boolValue = value_;
  3423. }
  3424. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3425. {
  3426. value.doubleValue = value_;
  3427. }
  3428. var::var (const String& value_) : type (VariantType_String::getInstance())
  3429. {
  3430. value.stringValue = new String (value_);
  3431. }
  3432. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3433. {
  3434. value.stringValue = new String (value_);
  3435. }
  3436. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3437. {
  3438. value.stringValue = new String (value_);
  3439. }
  3440. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3441. {
  3442. value.objectValue = object;
  3443. if (object != 0)
  3444. object->incReferenceCount();
  3445. }
  3446. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3447. {
  3448. value.methodValue = method_;
  3449. }
  3450. bool var::isVoid() const throw() { return type->isVoid(); }
  3451. bool var::isInt() const throw() { return type->isInt(); }
  3452. bool var::isBool() const throw() { return type->isBool(); }
  3453. bool var::isDouble() const throw() { return type->isDouble(); }
  3454. bool var::isString() const throw() { return type->isString(); }
  3455. bool var::isObject() const throw() { return type->isObject(); }
  3456. bool var::isMethod() const throw() { return type->isMethod(); }
  3457. var::operator int() const { return type->toInt (value); }
  3458. var::operator bool() const { return type->toBool (value); }
  3459. var::operator float() const { return (float) type->toDouble (value); }
  3460. var::operator double() const { return type->toDouble (value); }
  3461. const String var::toString() const { return type->toString (value); }
  3462. var::operator const String() const { return type->toString (value); }
  3463. DynamicObject* var::getObject() const { return type->toObject (value); }
  3464. void var::swapWith (var& other) throw()
  3465. {
  3466. swapVariables (type, other.type);
  3467. swapVariables (value, other.value);
  3468. }
  3469. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3470. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3471. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3472. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3473. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3474. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3475. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3476. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3477. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3478. bool var::equals (const var& other) const throw()
  3479. {
  3480. return type->equals (value, other.value, *other.type);
  3481. }
  3482. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3483. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3484. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3485. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3486. void var::writeToStream (OutputStream& output) const
  3487. {
  3488. type->writeToStream (value, output);
  3489. }
  3490. const var var::readFromStream (InputStream& input)
  3491. {
  3492. const int numBytes = input.readCompressedInt();
  3493. if (numBytes > 0)
  3494. {
  3495. switch (input.readByte())
  3496. {
  3497. case 1: return var (input.readInt());
  3498. case 2: return var (true);
  3499. case 3: return var (false);
  3500. case 4: return var (input.readDouble());
  3501. case 5:
  3502. {
  3503. MemoryOutputStream mo;
  3504. mo.writeFromInputStream (input, numBytes - 1);
  3505. return var (mo.toUTF8());
  3506. }
  3507. default: input.skipNextBytes (numBytes - 1); break;
  3508. }
  3509. }
  3510. return var::null;
  3511. }
  3512. const var var::operator[] (const Identifier& propertyName) const
  3513. {
  3514. DynamicObject* const o = getObject();
  3515. return o != 0 ? o->getProperty (propertyName) : var::null;
  3516. }
  3517. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3518. {
  3519. DynamicObject* const o = getObject();
  3520. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3521. }
  3522. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3523. {
  3524. if (isMethod())
  3525. {
  3526. DynamicObject* const target = targetObject.getObject();
  3527. if (target != 0)
  3528. return (target->*(value.methodValue)) (arguments, numArguments);
  3529. }
  3530. return var::null;
  3531. }
  3532. const var var::call (const Identifier& method) const
  3533. {
  3534. return invoke (method, 0, 0);
  3535. }
  3536. const var var::call (const Identifier& method, const var& arg1) const
  3537. {
  3538. return invoke (method, &arg1, 1);
  3539. }
  3540. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3541. {
  3542. var args[] = { arg1, arg2 };
  3543. return invoke (method, args, 2);
  3544. }
  3545. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3546. {
  3547. var args[] = { arg1, arg2, arg3 };
  3548. return invoke (method, args, 3);
  3549. }
  3550. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3551. {
  3552. var args[] = { arg1, arg2, arg3, arg4 };
  3553. return invoke (method, args, 4);
  3554. }
  3555. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3556. {
  3557. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3558. return invoke (method, args, 5);
  3559. }
  3560. END_JUCE_NAMESPACE
  3561. /*** End of inlined file: juce_Variant.cpp ***/
  3562. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3563. BEGIN_JUCE_NAMESPACE
  3564. NamedValueSet::NamedValue::NamedValue() throw()
  3565. {
  3566. }
  3567. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3568. : name (name_), value (value_)
  3569. {
  3570. }
  3571. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3572. {
  3573. return name == other.name && value == other.value;
  3574. }
  3575. NamedValueSet::NamedValueSet() throw()
  3576. {
  3577. }
  3578. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3579. : values (other.values)
  3580. {
  3581. }
  3582. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3583. {
  3584. values = other.values;
  3585. return *this;
  3586. }
  3587. NamedValueSet::~NamedValueSet()
  3588. {
  3589. }
  3590. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3591. {
  3592. return values == other.values;
  3593. }
  3594. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3595. {
  3596. return ! operator== (other);
  3597. }
  3598. int NamedValueSet::size() const throw()
  3599. {
  3600. return values.size();
  3601. }
  3602. const var& NamedValueSet::operator[] (const Identifier& name) const
  3603. {
  3604. for (int i = values.size(); --i >= 0;)
  3605. {
  3606. const NamedValue& v = values.getReference(i);
  3607. if (v.name == name)
  3608. return v.value;
  3609. }
  3610. return var::null;
  3611. }
  3612. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3613. {
  3614. const var* v = getItem (name);
  3615. return v != 0 ? *v : defaultReturnValue;
  3616. }
  3617. var* NamedValueSet::getItem (const Identifier& name) const
  3618. {
  3619. for (int i = values.size(); --i >= 0;)
  3620. {
  3621. NamedValue& v = values.getReference(i);
  3622. if (v.name == name)
  3623. return &(v.value);
  3624. }
  3625. return 0;
  3626. }
  3627. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3628. {
  3629. for (int i = values.size(); --i >= 0;)
  3630. {
  3631. NamedValue& v = values.getReference(i);
  3632. if (v.name == name)
  3633. {
  3634. if (v.value == newValue)
  3635. return false;
  3636. v.value = newValue;
  3637. return true;
  3638. }
  3639. }
  3640. values.add (NamedValue (name, newValue));
  3641. return true;
  3642. }
  3643. bool NamedValueSet::contains (const Identifier& name) const
  3644. {
  3645. return getItem (name) != 0;
  3646. }
  3647. bool NamedValueSet::remove (const Identifier& name)
  3648. {
  3649. for (int i = values.size(); --i >= 0;)
  3650. {
  3651. if (values.getReference(i).name == name)
  3652. {
  3653. values.remove (i);
  3654. return true;
  3655. }
  3656. }
  3657. return false;
  3658. }
  3659. const Identifier NamedValueSet::getName (const int index) const
  3660. {
  3661. jassert (((unsigned int) index) < (unsigned int) values.size());
  3662. return values [index].name;
  3663. }
  3664. const var NamedValueSet::getValueAt (const int index) const
  3665. {
  3666. jassert (((unsigned int) index) < (unsigned int) values.size());
  3667. return values [index].value;
  3668. }
  3669. void NamedValueSet::clear()
  3670. {
  3671. values.clear();
  3672. }
  3673. END_JUCE_NAMESPACE
  3674. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3675. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3676. BEGIN_JUCE_NAMESPACE
  3677. DynamicObject::DynamicObject()
  3678. {
  3679. }
  3680. DynamicObject::~DynamicObject()
  3681. {
  3682. }
  3683. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3684. {
  3685. var* const v = properties.getItem (propertyName);
  3686. return v != 0 && ! v->isMethod();
  3687. }
  3688. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3689. {
  3690. return properties [propertyName];
  3691. }
  3692. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3693. {
  3694. properties.set (propertyName, newValue);
  3695. }
  3696. void DynamicObject::removeProperty (const Identifier& propertyName)
  3697. {
  3698. properties.remove (propertyName);
  3699. }
  3700. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3701. {
  3702. return getProperty (methodName).isMethod();
  3703. }
  3704. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3705. const var* parameters,
  3706. int numParameters)
  3707. {
  3708. return properties [methodName].invoke (var (this), parameters, numParameters);
  3709. }
  3710. void DynamicObject::setMethod (const Identifier& name,
  3711. var::MethodFunction methodFunction)
  3712. {
  3713. properties.set (name, var (methodFunction));
  3714. }
  3715. void DynamicObject::clear()
  3716. {
  3717. properties.clear();
  3718. }
  3719. END_JUCE_NAMESPACE
  3720. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3721. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3722. BEGIN_JUCE_NAMESPACE
  3723. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3724. {
  3725. jassert (keyData != 0);
  3726. jassert (keyBytes > 0);
  3727. static const uint32 initialPValues [18] =
  3728. {
  3729. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3730. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3731. 0x9216d5d9, 0x8979fb1b
  3732. };
  3733. static const uint32 initialSValues [4 * 256] =
  3734. {
  3735. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3736. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3737. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3738. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3739. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3740. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3741. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3742. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3743. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3744. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3745. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3746. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3747. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3748. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3749. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3750. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3751. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3752. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3753. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3754. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3755. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3756. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3757. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3758. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3759. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3760. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3761. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3762. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3763. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3764. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3765. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3766. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3767. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3768. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3769. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3770. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3771. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3772. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3773. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3774. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3775. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3776. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3777. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3778. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3779. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3780. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3781. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3782. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3783. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3784. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3785. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3786. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3787. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3788. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3789. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3790. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3791. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3792. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3793. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3794. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3795. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3796. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3797. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3798. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3799. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3800. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3801. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3802. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3803. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3804. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3805. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3806. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3807. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3808. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3809. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3810. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3811. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3812. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3813. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3814. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3815. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3816. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3817. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3818. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3819. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3820. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3821. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3822. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3823. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3824. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3825. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3826. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3827. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3828. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3829. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3830. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3831. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3832. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3833. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3834. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3835. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3836. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3837. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3838. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3839. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3840. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3841. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3842. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3843. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3844. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3845. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3846. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3847. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3848. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3849. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3850. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3851. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3852. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3853. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3854. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3855. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3856. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3857. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3858. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3859. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3860. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3861. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3862. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3863. };
  3864. memcpy (p, initialPValues, sizeof (p));
  3865. int i, j = 0;
  3866. for (i = 4; --i >= 0;)
  3867. {
  3868. s[i].malloc (256);
  3869. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3870. }
  3871. for (i = 0; i < 18; ++i)
  3872. {
  3873. uint32 d = 0;
  3874. for (int k = 0; k < 4; ++k)
  3875. {
  3876. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3877. if (++j >= keyBytes)
  3878. j = 0;
  3879. }
  3880. p[i] = initialPValues[i] ^ d;
  3881. }
  3882. uint32 l = 0, r = 0;
  3883. for (i = 0; i < 18; i += 2)
  3884. {
  3885. encrypt (l, r);
  3886. p[i] = l;
  3887. p[i + 1] = r;
  3888. }
  3889. for (i = 0; i < 4; ++i)
  3890. {
  3891. for (j = 0; j < 256; j += 2)
  3892. {
  3893. encrypt (l, r);
  3894. s[i][j] = l;
  3895. s[i][j + 1] = r;
  3896. }
  3897. }
  3898. }
  3899. BlowFish::BlowFish (const BlowFish& other)
  3900. {
  3901. for (int i = 4; --i >= 0;)
  3902. s[i].malloc (256);
  3903. operator= (other);
  3904. }
  3905. BlowFish& BlowFish::operator= (const BlowFish& other)
  3906. {
  3907. memcpy (p, other.p, sizeof (p));
  3908. for (int i = 4; --i >= 0;)
  3909. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3910. return *this;
  3911. }
  3912. BlowFish::~BlowFish()
  3913. {
  3914. }
  3915. uint32 BlowFish::F (const uint32 x) const throw()
  3916. {
  3917. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3918. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3919. }
  3920. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3921. {
  3922. uint32 l = data1;
  3923. uint32 r = data2;
  3924. for (int i = 0; i < 16; ++i)
  3925. {
  3926. l ^= p[i];
  3927. r ^= F(l);
  3928. swapVariables (l, r);
  3929. }
  3930. data1 = r ^ p[17];
  3931. data2 = l ^ p[16];
  3932. }
  3933. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3934. {
  3935. uint32 l = data1;
  3936. uint32 r = data2;
  3937. for (int i = 17; i > 1; --i)
  3938. {
  3939. l ^= p[i];
  3940. r ^= F(l);
  3941. swapVariables (l, r);
  3942. }
  3943. data1 = r ^ p[0];
  3944. data2 = l ^ p[1];
  3945. }
  3946. END_JUCE_NAMESPACE
  3947. /*** End of inlined file: juce_BlowFish.cpp ***/
  3948. /*** Start of inlined file: juce_MD5.cpp ***/
  3949. BEGIN_JUCE_NAMESPACE
  3950. MD5::MD5()
  3951. {
  3952. zerostruct (result);
  3953. }
  3954. MD5::MD5 (const MD5& other)
  3955. {
  3956. memcpy (result, other.result, sizeof (result));
  3957. }
  3958. MD5& MD5::operator= (const MD5& other)
  3959. {
  3960. memcpy (result, other.result, sizeof (result));
  3961. return *this;
  3962. }
  3963. MD5::MD5 (const MemoryBlock& data)
  3964. {
  3965. ProcessContext context;
  3966. context.processBlock (data.getData(), data.getSize());
  3967. context.finish (result);
  3968. }
  3969. MD5::MD5 (const void* data, const size_t numBytes)
  3970. {
  3971. ProcessContext context;
  3972. context.processBlock (data, numBytes);
  3973. context.finish (result);
  3974. }
  3975. MD5::MD5 (const String& text)
  3976. {
  3977. ProcessContext context;
  3978. const int len = text.length();
  3979. const juce_wchar* const t = text;
  3980. for (int i = 0; i < len; ++i)
  3981. {
  3982. // force the string into integer-sized unicode characters, to try to make it
  3983. // get the same results on all platforms + compilers.
  3984. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3985. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3986. }
  3987. context.finish (result);
  3988. }
  3989. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3990. {
  3991. ProcessContext context;
  3992. if (numBytesToRead < 0)
  3993. numBytesToRead = std::numeric_limits<int64>::max();
  3994. while (numBytesToRead > 0)
  3995. {
  3996. uint8 tempBuffer [512];
  3997. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3998. if (bytesRead <= 0)
  3999. break;
  4000. numBytesToRead -= bytesRead;
  4001. context.processBlock (tempBuffer, bytesRead);
  4002. }
  4003. context.finish (result);
  4004. }
  4005. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4006. {
  4007. processStream (input, numBytesToRead);
  4008. }
  4009. MD5::MD5 (const File& file)
  4010. {
  4011. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4012. if (fin != 0)
  4013. processStream (*fin, -1);
  4014. else
  4015. zerostruct (result);
  4016. }
  4017. MD5::~MD5()
  4018. {
  4019. }
  4020. namespace MD5Functions
  4021. {
  4022. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4023. {
  4024. for (int i = 0; i < (numBytes >> 2); ++i)
  4025. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4026. }
  4027. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4028. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4029. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4030. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4031. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4032. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4033. {
  4034. a += F (b, c, d) + x + ac;
  4035. a = rotateLeft (a, s) + b;
  4036. }
  4037. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4038. {
  4039. a += G (b, c, d) + x + ac;
  4040. a = rotateLeft (a, s) + b;
  4041. }
  4042. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4043. {
  4044. a += H (b, c, d) + x + ac;
  4045. a = rotateLeft (a, s) + b;
  4046. }
  4047. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4048. {
  4049. a += I (b, c, d) + x + ac;
  4050. a = rotateLeft (a, s) + b;
  4051. }
  4052. }
  4053. MD5::ProcessContext::ProcessContext()
  4054. {
  4055. state[0] = 0x67452301;
  4056. state[1] = 0xefcdab89;
  4057. state[2] = 0x98badcfe;
  4058. state[3] = 0x10325476;
  4059. count[0] = 0;
  4060. count[1] = 0;
  4061. }
  4062. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4063. {
  4064. int bufferPos = ((count[0] >> 3) & 0x3F);
  4065. count[0] += (uint32) (dataSize << 3);
  4066. if (count[0] < ((uint32) dataSize << 3))
  4067. count[1]++;
  4068. count[1] += (uint32) (dataSize >> 29);
  4069. const size_t spaceLeft = 64 - bufferPos;
  4070. size_t i = 0;
  4071. if (dataSize >= spaceLeft)
  4072. {
  4073. memcpy (buffer + bufferPos, data, spaceLeft);
  4074. transform (buffer);
  4075. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4076. transform (static_cast <const char*> (data) + i);
  4077. bufferPos = 0;
  4078. }
  4079. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4080. }
  4081. void MD5::ProcessContext::finish (void* const result)
  4082. {
  4083. unsigned char encodedLength[8];
  4084. MD5Functions::encode (encodedLength, count, 8);
  4085. // Pad out to 56 mod 64.
  4086. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4087. const int paddingLength = (index < 56) ? (56 - index)
  4088. : (120 - index);
  4089. uint8 paddingBuffer [64];
  4090. zeromem (paddingBuffer, paddingLength);
  4091. paddingBuffer [0] = 0x80;
  4092. processBlock (paddingBuffer, paddingLength);
  4093. processBlock (encodedLength, 8);
  4094. MD5Functions::encode (result, state, 16);
  4095. zerostruct (buffer);
  4096. }
  4097. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4098. {
  4099. using namespace MD5Functions;
  4100. uint32 a = state[0];
  4101. uint32 b = state[1];
  4102. uint32 c = state[2];
  4103. uint32 d = state[3];
  4104. uint32 x[16];
  4105. encode (x, bufferToTransform, 64);
  4106. enum Constants
  4107. {
  4108. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4109. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4110. };
  4111. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4112. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4113. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4114. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4115. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4116. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4117. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4118. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4119. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4120. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4121. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4122. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4123. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4124. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4125. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4126. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4127. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4128. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4129. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4130. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4131. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4132. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4133. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4134. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4135. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4136. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4137. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4138. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4139. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4140. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4141. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4142. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4143. state[0] += a;
  4144. state[1] += b;
  4145. state[2] += c;
  4146. state[3] += d;
  4147. zerostruct (x);
  4148. }
  4149. const MemoryBlock MD5::getRawChecksumData() const
  4150. {
  4151. return MemoryBlock (result, sizeof (result));
  4152. }
  4153. const String MD5::toHexString() const
  4154. {
  4155. return String::toHexString (result, sizeof (result), 0);
  4156. }
  4157. bool MD5::operator== (const MD5& other) const
  4158. {
  4159. return memcmp (result, other.result, sizeof (result)) == 0;
  4160. }
  4161. bool MD5::operator!= (const MD5& other) const
  4162. {
  4163. return ! operator== (other);
  4164. }
  4165. END_JUCE_NAMESPACE
  4166. /*** End of inlined file: juce_MD5.cpp ***/
  4167. /*** Start of inlined file: juce_Primes.cpp ***/
  4168. BEGIN_JUCE_NAMESPACE
  4169. namespace PrimesHelpers
  4170. {
  4171. static void createSmallSieve (const int numBits, BigInteger& result)
  4172. {
  4173. result.setBit (numBits);
  4174. result.clearBit (numBits); // to enlarge the array
  4175. result.setBit (0);
  4176. int n = 2;
  4177. do
  4178. {
  4179. for (int i = n + n; i < numBits; i += n)
  4180. result.setBit (i);
  4181. n = result.findNextClearBit (n + 1);
  4182. }
  4183. while (n <= (numBits >> 1));
  4184. }
  4185. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4186. const BigInteger& smallSieve, const int smallSieveSize)
  4187. {
  4188. jassert (! base[0]); // must be even!
  4189. result.setBit (numBits);
  4190. result.clearBit (numBits); // to enlarge the array
  4191. int index = smallSieve.findNextClearBit (0);
  4192. do
  4193. {
  4194. const int prime = (index << 1) + 1;
  4195. BigInteger r (base), remainder;
  4196. r.divideBy (prime, remainder);
  4197. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4198. if (r.isZero())
  4199. i += prime;
  4200. if ((i & 1) == 0)
  4201. i += prime;
  4202. i = (i - 1) >> 1;
  4203. while (i < numBits)
  4204. {
  4205. result.setBit (i);
  4206. i += prime;
  4207. }
  4208. index = smallSieve.findNextClearBit (index + 1);
  4209. }
  4210. while (index < smallSieveSize);
  4211. }
  4212. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4213. const int numBits, BigInteger& result, const int certainty)
  4214. {
  4215. for (int i = 0; i < numBits; ++i)
  4216. {
  4217. if (! sieve[i])
  4218. {
  4219. result = base + (unsigned int) ((i << 1) + 1);
  4220. if (Primes::isProbablyPrime (result, certainty))
  4221. return true;
  4222. }
  4223. }
  4224. return false;
  4225. }
  4226. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4227. {
  4228. const BigInteger one (1), two (2);
  4229. const BigInteger nMinusOne (n - one);
  4230. BigInteger d (nMinusOne);
  4231. const int s = d.findNextSetBit (0);
  4232. d >>= s;
  4233. BigInteger smallPrimes;
  4234. int numBitsInSmallPrimes = 0;
  4235. for (;;)
  4236. {
  4237. numBitsInSmallPrimes += 256;
  4238. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4239. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4240. if (numPrimesFound > iterations + 1)
  4241. break;
  4242. }
  4243. int smallPrime = 2;
  4244. while (--iterations >= 0)
  4245. {
  4246. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4247. BigInteger r (smallPrime);
  4248. r.exponentModulo (d, n);
  4249. if (r != one && r != nMinusOne)
  4250. {
  4251. for (int j = 0; j < s; ++j)
  4252. {
  4253. r.exponentModulo (two, n);
  4254. if (r == nMinusOne)
  4255. break;
  4256. }
  4257. if (r != nMinusOne)
  4258. return false;
  4259. }
  4260. }
  4261. return true;
  4262. }
  4263. }
  4264. const BigInteger Primes::createProbablePrime (const int bitLength,
  4265. const int certainty,
  4266. const int* randomSeeds,
  4267. int numRandomSeeds)
  4268. {
  4269. using namespace PrimesHelpers;
  4270. int defaultSeeds [16];
  4271. if (numRandomSeeds <= 0)
  4272. {
  4273. randomSeeds = defaultSeeds;
  4274. numRandomSeeds = numElementsInArray (defaultSeeds);
  4275. Random r (0);
  4276. for (int j = 10; --j >= 0;)
  4277. {
  4278. r.setSeedRandomly();
  4279. for (int i = numRandomSeeds; --i >= 0;)
  4280. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4281. }
  4282. }
  4283. BigInteger smallSieve;
  4284. const int smallSieveSize = 15000;
  4285. createSmallSieve (smallSieveSize, smallSieve);
  4286. BigInteger p;
  4287. for (int i = numRandomSeeds; --i >= 0;)
  4288. {
  4289. BigInteger p2;
  4290. Random r (randomSeeds[i]);
  4291. r.fillBitsRandomly (p2, 0, bitLength);
  4292. p ^= p2;
  4293. }
  4294. p.setBit (bitLength - 1);
  4295. p.clearBit (0);
  4296. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4297. while (p.getHighestBit() < bitLength)
  4298. {
  4299. p += 2 * searchLen;
  4300. BigInteger sieve;
  4301. bigSieve (p, searchLen, sieve,
  4302. smallSieve, smallSieveSize);
  4303. BigInteger candidate;
  4304. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4305. return candidate;
  4306. }
  4307. jassertfalse;
  4308. return BigInteger();
  4309. }
  4310. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4311. {
  4312. using namespace PrimesHelpers;
  4313. if (! number[0])
  4314. return false;
  4315. if (number.getHighestBit() <= 10)
  4316. {
  4317. const int num = number.getBitRangeAsInt (0, 10);
  4318. for (int i = num / 2; --i > 1;)
  4319. if (num % i == 0)
  4320. return false;
  4321. return true;
  4322. }
  4323. else
  4324. {
  4325. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4326. return false;
  4327. return passesMillerRabin (number, certainty);
  4328. }
  4329. }
  4330. END_JUCE_NAMESPACE
  4331. /*** End of inlined file: juce_Primes.cpp ***/
  4332. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4333. BEGIN_JUCE_NAMESPACE
  4334. RSAKey::RSAKey()
  4335. {
  4336. }
  4337. RSAKey::RSAKey (const String& s)
  4338. {
  4339. if (s.containsChar (','))
  4340. {
  4341. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4342. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4343. }
  4344. else
  4345. {
  4346. // the string needs to be two hex numbers, comma-separated..
  4347. jassertfalse;
  4348. }
  4349. }
  4350. RSAKey::~RSAKey()
  4351. {
  4352. }
  4353. bool RSAKey::operator== (const RSAKey& other) const throw()
  4354. {
  4355. return part1 == other.part1 && part2 == other.part2;
  4356. }
  4357. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4358. {
  4359. return ! operator== (other);
  4360. }
  4361. const String RSAKey::toString() const
  4362. {
  4363. return part1.toString (16) + "," + part2.toString (16);
  4364. }
  4365. bool RSAKey::applyToValue (BigInteger& value) const
  4366. {
  4367. if (part1.isZero() || part2.isZero() || value <= 0)
  4368. {
  4369. jassertfalse; // using an uninitialised key
  4370. value.clear();
  4371. return false;
  4372. }
  4373. BigInteger result;
  4374. while (! value.isZero())
  4375. {
  4376. result *= part2;
  4377. BigInteger remainder;
  4378. value.divideBy (part2, remainder);
  4379. remainder.exponentModulo (part1, part2);
  4380. result += remainder;
  4381. }
  4382. value.swapWith (result);
  4383. return true;
  4384. }
  4385. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4386. {
  4387. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4388. // are fast to divide + multiply
  4389. for (int i = 2; i <= 65536; i *= 2)
  4390. {
  4391. const BigInteger e (1 + i);
  4392. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4393. return e;
  4394. }
  4395. BigInteger e (4);
  4396. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4397. ++e;
  4398. return e;
  4399. }
  4400. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4401. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4402. {
  4403. jassert (numBits > 16); // not much point using less than this..
  4404. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  4405. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  4406. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  4407. const BigInteger n (p * q);
  4408. const BigInteger m (--p * --q);
  4409. const BigInteger e (findBestCommonDivisor (p, q));
  4410. BigInteger d (e);
  4411. d.inverseModulo (m);
  4412. publicKey.part1 = e;
  4413. publicKey.part2 = n;
  4414. privateKey.part1 = d;
  4415. privateKey.part2 = n;
  4416. }
  4417. END_JUCE_NAMESPACE
  4418. /*** End of inlined file: juce_RSAKey.cpp ***/
  4419. /*** Start of inlined file: juce_InputStream.cpp ***/
  4420. BEGIN_JUCE_NAMESPACE
  4421. char InputStream::readByte()
  4422. {
  4423. char temp = 0;
  4424. read (&temp, 1);
  4425. return temp;
  4426. }
  4427. bool InputStream::readBool()
  4428. {
  4429. return readByte() != 0;
  4430. }
  4431. short InputStream::readShort()
  4432. {
  4433. char temp[2];
  4434. if (read (temp, 2) == 2)
  4435. return (short) ByteOrder::littleEndianShort (temp);
  4436. return 0;
  4437. }
  4438. short InputStream::readShortBigEndian()
  4439. {
  4440. char temp[2];
  4441. if (read (temp, 2) == 2)
  4442. return (short) ByteOrder::bigEndianShort (temp);
  4443. return 0;
  4444. }
  4445. int InputStream::readInt()
  4446. {
  4447. char temp[4];
  4448. if (read (temp, 4) == 4)
  4449. return (int) ByteOrder::littleEndianInt (temp);
  4450. return 0;
  4451. }
  4452. int InputStream::readIntBigEndian()
  4453. {
  4454. char temp[4];
  4455. if (read (temp, 4) == 4)
  4456. return (int) ByteOrder::bigEndianInt (temp);
  4457. return 0;
  4458. }
  4459. int InputStream::readCompressedInt()
  4460. {
  4461. const unsigned char sizeByte = readByte();
  4462. if (sizeByte == 0)
  4463. return 0;
  4464. const int numBytes = (sizeByte & 0x7f);
  4465. if (numBytes > 4)
  4466. {
  4467. jassertfalse; // trying to read corrupt data - this method must only be used
  4468. // to read data that was written by OutputStream::writeCompressedInt()
  4469. return 0;
  4470. }
  4471. char bytes[4] = { 0, 0, 0, 0 };
  4472. if (read (bytes, numBytes) != numBytes)
  4473. return 0;
  4474. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4475. return (sizeByte >> 7) ? -num : num;
  4476. }
  4477. int64 InputStream::readInt64()
  4478. {
  4479. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4480. if (read (n.asBytes, 8) == 8)
  4481. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4482. return 0;
  4483. }
  4484. int64 InputStream::readInt64BigEndian()
  4485. {
  4486. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4487. if (read (n.asBytes, 8) == 8)
  4488. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4489. return 0;
  4490. }
  4491. float InputStream::readFloat()
  4492. {
  4493. // the union below relies on these types being the same size...
  4494. static_jassert (sizeof (int32) == sizeof (float));
  4495. union { int32 asInt; float asFloat; } n;
  4496. n.asInt = (int32) readInt();
  4497. return n.asFloat;
  4498. }
  4499. float InputStream::readFloatBigEndian()
  4500. {
  4501. union { int32 asInt; float asFloat; } n;
  4502. n.asInt = (int32) readIntBigEndian();
  4503. return n.asFloat;
  4504. }
  4505. double InputStream::readDouble()
  4506. {
  4507. union { int64 asInt; double asDouble; } n;
  4508. n.asInt = readInt64();
  4509. return n.asDouble;
  4510. }
  4511. double InputStream::readDoubleBigEndian()
  4512. {
  4513. union { int64 asInt; double asDouble; } n;
  4514. n.asInt = readInt64BigEndian();
  4515. return n.asDouble;
  4516. }
  4517. const String InputStream::readString()
  4518. {
  4519. MemoryBlock buffer (256);
  4520. char* data = static_cast<char*> (buffer.getData());
  4521. size_t i = 0;
  4522. while ((data[i] = readByte()) != 0)
  4523. {
  4524. if (++i >= buffer.getSize())
  4525. {
  4526. buffer.setSize (buffer.getSize() + 512);
  4527. data = static_cast<char*> (buffer.getData());
  4528. }
  4529. }
  4530. return String::fromUTF8 (data, (int) i);
  4531. }
  4532. const String InputStream::readNextLine()
  4533. {
  4534. MemoryBlock buffer (256);
  4535. char* data = static_cast<char*> (buffer.getData());
  4536. size_t i = 0;
  4537. while ((data[i] = readByte()) != 0)
  4538. {
  4539. if (data[i] == '\n')
  4540. break;
  4541. if (data[i] == '\r')
  4542. {
  4543. const int64 lastPos = getPosition();
  4544. if (readByte() != '\n')
  4545. setPosition (lastPos);
  4546. break;
  4547. }
  4548. if (++i >= buffer.getSize())
  4549. {
  4550. buffer.setSize (buffer.getSize() + 512);
  4551. data = static_cast<char*> (buffer.getData());
  4552. }
  4553. }
  4554. return String::fromUTF8 (data, (int) i);
  4555. }
  4556. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4557. {
  4558. MemoryOutputStream mo (block, true);
  4559. return mo.writeFromInputStream (*this, numBytes);
  4560. }
  4561. const String InputStream::readEntireStreamAsString()
  4562. {
  4563. MemoryOutputStream mo;
  4564. mo.writeFromInputStream (*this, -1);
  4565. return mo.toString();
  4566. }
  4567. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4568. {
  4569. if (numBytesToSkip > 0)
  4570. {
  4571. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4572. HeapBlock<char> temp (skipBufferSize);
  4573. while (numBytesToSkip > 0 && ! isExhausted())
  4574. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4575. }
  4576. }
  4577. END_JUCE_NAMESPACE
  4578. /*** End of inlined file: juce_InputStream.cpp ***/
  4579. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4580. BEGIN_JUCE_NAMESPACE
  4581. #if JUCE_DEBUG
  4582. static CriticalSection activeStreamLock;
  4583. static Array<void*> activeStreams;
  4584. void juce_CheckForDanglingStreams()
  4585. {
  4586. /*
  4587. It's always a bad idea to leak any object, but if you're leaking output
  4588. streams, then there's a good chance that you're failing to flush a file
  4589. to disk properly, which could result in corrupted data and other similar
  4590. nastiness..
  4591. */
  4592. jassert (activeStreams.size() == 0);
  4593. };
  4594. #endif
  4595. OutputStream::OutputStream()
  4596. {
  4597. #if JUCE_DEBUG
  4598. const ScopedLock sl (activeStreamLock);
  4599. activeStreams.add (this);
  4600. #endif
  4601. }
  4602. OutputStream::~OutputStream()
  4603. {
  4604. #if JUCE_DEBUG
  4605. const ScopedLock sl (activeStreamLock);
  4606. activeStreams.removeValue (this);
  4607. #endif
  4608. }
  4609. void OutputStream::writeBool (const bool b)
  4610. {
  4611. writeByte (b ? (char) 1
  4612. : (char) 0);
  4613. }
  4614. void OutputStream::writeByte (char byte)
  4615. {
  4616. write (&byte, 1);
  4617. }
  4618. void OutputStream::writeShort (short value)
  4619. {
  4620. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4621. write (&v, 2);
  4622. }
  4623. void OutputStream::writeShortBigEndian (short value)
  4624. {
  4625. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4626. write (&v, 2);
  4627. }
  4628. void OutputStream::writeInt (int value)
  4629. {
  4630. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4631. write (&v, 4);
  4632. }
  4633. void OutputStream::writeIntBigEndian (int value)
  4634. {
  4635. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4636. write (&v, 4);
  4637. }
  4638. void OutputStream::writeCompressedInt (int value)
  4639. {
  4640. unsigned int un = (value < 0) ? (unsigned int) -value
  4641. : (unsigned int) value;
  4642. uint8 data[5];
  4643. int num = 0;
  4644. while (un > 0)
  4645. {
  4646. data[++num] = (uint8) un;
  4647. un >>= 8;
  4648. }
  4649. data[0] = (uint8) num;
  4650. if (value < 0)
  4651. data[0] |= 0x80;
  4652. write (data, num + 1);
  4653. }
  4654. void OutputStream::writeInt64 (int64 value)
  4655. {
  4656. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4657. write (&v, 8);
  4658. }
  4659. void OutputStream::writeInt64BigEndian (int64 value)
  4660. {
  4661. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4662. write (&v, 8);
  4663. }
  4664. void OutputStream::writeFloat (float value)
  4665. {
  4666. union { int asInt; float asFloat; } n;
  4667. n.asFloat = value;
  4668. writeInt (n.asInt);
  4669. }
  4670. void OutputStream::writeFloatBigEndian (float value)
  4671. {
  4672. union { int asInt; float asFloat; } n;
  4673. n.asFloat = value;
  4674. writeIntBigEndian (n.asInt);
  4675. }
  4676. void OutputStream::writeDouble (double value)
  4677. {
  4678. union { int64 asInt; double asDouble; } n;
  4679. n.asDouble = value;
  4680. writeInt64 (n.asInt);
  4681. }
  4682. void OutputStream::writeDoubleBigEndian (double value)
  4683. {
  4684. union { int64 asInt; double asDouble; } n;
  4685. n.asDouble = value;
  4686. writeInt64BigEndian (n.asInt);
  4687. }
  4688. void OutputStream::writeString (const String& text)
  4689. {
  4690. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4691. // if lots of large, persistent strings were to be written to streams).
  4692. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4693. HeapBlock<char> temp (numBytes);
  4694. text.copyToUTF8 (temp, numBytes);
  4695. write (temp, numBytes);
  4696. }
  4697. void OutputStream::writeText (const String& text, const bool asUnicode,
  4698. const bool writeUnicodeHeaderBytes)
  4699. {
  4700. if (asUnicode)
  4701. {
  4702. if (writeUnicodeHeaderBytes)
  4703. write ("\x0ff\x0fe", 2);
  4704. const juce_wchar* src = text;
  4705. bool lastCharWasReturn = false;
  4706. while (*src != 0)
  4707. {
  4708. if (*src == L'\n' && ! lastCharWasReturn)
  4709. writeShort ((short) L'\r');
  4710. lastCharWasReturn = (*src == L'\r');
  4711. writeShort ((short) *src++);
  4712. }
  4713. }
  4714. else
  4715. {
  4716. const char* src = text.toUTF8();
  4717. const char* t = src;
  4718. for (;;)
  4719. {
  4720. if (*t == '\n')
  4721. {
  4722. if (t > src)
  4723. write (src, (int) (t - src));
  4724. write ("\r\n", 2);
  4725. src = t + 1;
  4726. }
  4727. else if (*t == '\r')
  4728. {
  4729. if (t[1] == '\n')
  4730. ++t;
  4731. }
  4732. else if (*t == 0)
  4733. {
  4734. if (t > src)
  4735. write (src, (int) (t - src));
  4736. break;
  4737. }
  4738. ++t;
  4739. }
  4740. }
  4741. }
  4742. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4743. {
  4744. if (numBytesToWrite < 0)
  4745. numBytesToWrite = std::numeric_limits<int64>::max();
  4746. int numWritten = 0;
  4747. while (numBytesToWrite > 0 && ! source.isExhausted())
  4748. {
  4749. char buffer [8192];
  4750. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4751. if (num <= 0)
  4752. break;
  4753. write (buffer, num);
  4754. numBytesToWrite -= num;
  4755. numWritten += num;
  4756. }
  4757. return numWritten;
  4758. }
  4759. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4760. {
  4761. return stream << String (number);
  4762. }
  4763. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4764. {
  4765. return stream << String (number);
  4766. }
  4767. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4768. {
  4769. stream.writeByte (character);
  4770. return stream;
  4771. }
  4772. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4773. {
  4774. stream.write (text, (int) strlen (text));
  4775. return stream;
  4776. }
  4777. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4778. {
  4779. stream.write (data.getData(), (int) data.getSize());
  4780. return stream;
  4781. }
  4782. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4783. {
  4784. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4785. if (in != 0)
  4786. stream.writeFromInputStream (*in, -1);
  4787. return stream;
  4788. }
  4789. END_JUCE_NAMESPACE
  4790. /*** End of inlined file: juce_OutputStream.cpp ***/
  4791. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4792. BEGIN_JUCE_NAMESPACE
  4793. DirectoryIterator::DirectoryIterator (const File& directory,
  4794. bool isRecursive_,
  4795. const String& wildCard_,
  4796. const int whatToLookFor_)
  4797. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4798. wildCard (wildCard_),
  4799. path (File::addTrailingSeparator (directory.getFullPathName())),
  4800. index (-1),
  4801. totalNumFiles (-1),
  4802. whatToLookFor (whatToLookFor_),
  4803. isRecursive (isRecursive_)
  4804. {
  4805. // you have to specify the type of files you're looking for!
  4806. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4807. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4808. }
  4809. DirectoryIterator::~DirectoryIterator()
  4810. {
  4811. }
  4812. bool DirectoryIterator::next()
  4813. {
  4814. return next (0, 0, 0, 0, 0, 0);
  4815. }
  4816. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4817. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4818. {
  4819. if (subIterator != 0)
  4820. {
  4821. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4822. return true;
  4823. subIterator = 0;
  4824. }
  4825. String filename;
  4826. bool isDirectory, isHidden;
  4827. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4828. {
  4829. ++index;
  4830. if (! filename.containsOnly ("."))
  4831. {
  4832. const File fileFound (path + filename, 0);
  4833. bool matches = false;
  4834. if (isDirectory)
  4835. {
  4836. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4837. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4838. matches = (whatToLookFor & File::findDirectories) != 0;
  4839. }
  4840. else
  4841. {
  4842. matches = (whatToLookFor & File::findFiles) != 0;
  4843. }
  4844. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4845. if (matches && isRecursive)
  4846. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4847. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4848. matches = ! isHidden;
  4849. if (matches)
  4850. {
  4851. currentFile = fileFound;
  4852. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4853. if (isDirResult != 0) *isDirResult = isDirectory;
  4854. return true;
  4855. }
  4856. else if (subIterator != 0)
  4857. {
  4858. return next();
  4859. }
  4860. }
  4861. }
  4862. return false;
  4863. }
  4864. const File DirectoryIterator::getFile() const
  4865. {
  4866. if (subIterator != 0)
  4867. return subIterator->getFile();
  4868. return currentFile;
  4869. }
  4870. float DirectoryIterator::getEstimatedProgress() const
  4871. {
  4872. if (totalNumFiles < 0)
  4873. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4874. if (totalNumFiles <= 0)
  4875. return 0.0f;
  4876. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4877. : (float) index;
  4878. return detailedIndex / totalNumFiles;
  4879. }
  4880. END_JUCE_NAMESPACE
  4881. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4882. /*** Start of inlined file: juce_File.cpp ***/
  4883. #if ! JUCE_WINDOWS
  4884. #include <pwd.h>
  4885. #endif
  4886. BEGIN_JUCE_NAMESPACE
  4887. File::File (const String& fullPathName)
  4888. : fullPath (parseAbsolutePath (fullPathName))
  4889. {
  4890. }
  4891. File::File (const String& path, int)
  4892. : fullPath (path)
  4893. {
  4894. }
  4895. const File File::createFileWithoutCheckingPath (const String& path)
  4896. {
  4897. return File (path, 0);
  4898. }
  4899. File::File (const File& other)
  4900. : fullPath (other.fullPath)
  4901. {
  4902. }
  4903. File& File::operator= (const String& newPath)
  4904. {
  4905. fullPath = parseAbsolutePath (newPath);
  4906. return *this;
  4907. }
  4908. File& File::operator= (const File& other)
  4909. {
  4910. fullPath = other.fullPath;
  4911. return *this;
  4912. }
  4913. const File File::nonexistent;
  4914. const String File::parseAbsolutePath (const String& p)
  4915. {
  4916. if (p.isEmpty())
  4917. return String::empty;
  4918. #if JUCE_WINDOWS
  4919. // Windows..
  4920. String path (p.replaceCharacter ('/', '\\'));
  4921. if (path.startsWithChar (File::separator))
  4922. {
  4923. if (path[1] != File::separator)
  4924. {
  4925. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4926. If you're trying to parse a string that may be either a relative path or an absolute path,
  4927. you MUST provide a context against which the partial path can be evaluated - you can do
  4928. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4929. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4930. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4931. */
  4932. jassertfalse;
  4933. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4934. }
  4935. }
  4936. else if (! path.containsChar (':'))
  4937. {
  4938. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4939. If you're trying to parse a string that may be either a relative path or an absolute path,
  4940. you MUST provide a context against which the partial path can be evaluated - you can do
  4941. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4942. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4943. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4944. */
  4945. jassertfalse;
  4946. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4947. }
  4948. #else
  4949. // Mac or Linux..
  4950. String path (p.replaceCharacter ('\\', '/'));
  4951. if (path.startsWithChar ('~'))
  4952. {
  4953. if (path[1] == File::separator || path[1] == 0)
  4954. {
  4955. // expand a name of the form "~/abc"
  4956. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4957. + path.substring (1);
  4958. }
  4959. else
  4960. {
  4961. // expand a name of type "~dave/abc"
  4962. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4963. struct passwd* const pw = getpwnam (userName.toUTF8());
  4964. if (pw != 0)
  4965. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4966. }
  4967. }
  4968. else if (! path.startsWithChar (File::separator))
  4969. {
  4970. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4971. If you're trying to parse a string that may be either a relative path or an absolute path,
  4972. you MUST provide a context against which the partial path can be evaluated - you can do
  4973. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4974. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4975. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4976. */
  4977. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4978. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4979. }
  4980. #endif
  4981. return path.trimCharactersAtEnd (separatorString);
  4982. }
  4983. const String File::addTrailingSeparator (const String& path)
  4984. {
  4985. return path.endsWithChar (File::separator) ? path
  4986. : path + File::separator;
  4987. }
  4988. #if JUCE_LINUX
  4989. #define NAMES_ARE_CASE_SENSITIVE 1
  4990. #endif
  4991. bool File::areFileNamesCaseSensitive()
  4992. {
  4993. #if NAMES_ARE_CASE_SENSITIVE
  4994. return true;
  4995. #else
  4996. return false;
  4997. #endif
  4998. }
  4999. bool File::operator== (const File& other) const
  5000. {
  5001. #if NAMES_ARE_CASE_SENSITIVE
  5002. return fullPath == other.fullPath;
  5003. #else
  5004. return fullPath.equalsIgnoreCase (other.fullPath);
  5005. #endif
  5006. }
  5007. bool File::operator!= (const File& other) const
  5008. {
  5009. return ! operator== (other);
  5010. }
  5011. bool File::operator< (const File& other) const
  5012. {
  5013. #if NAMES_ARE_CASE_SENSITIVE
  5014. return fullPath < other.fullPath;
  5015. #else
  5016. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5017. #endif
  5018. }
  5019. bool File::operator> (const File& other) const
  5020. {
  5021. #if NAMES_ARE_CASE_SENSITIVE
  5022. return fullPath > other.fullPath;
  5023. #else
  5024. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5025. #endif
  5026. }
  5027. bool File::setReadOnly (const bool shouldBeReadOnly,
  5028. const bool applyRecursively) const
  5029. {
  5030. bool worked = true;
  5031. if (applyRecursively && isDirectory())
  5032. {
  5033. Array <File> subFiles;
  5034. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5035. for (int i = subFiles.size(); --i >= 0;)
  5036. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5037. }
  5038. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5039. }
  5040. bool File::deleteRecursively() const
  5041. {
  5042. bool worked = true;
  5043. if (isDirectory())
  5044. {
  5045. Array<File> subFiles;
  5046. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5047. for (int i = subFiles.size(); --i >= 0;)
  5048. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5049. }
  5050. return deleteFile() && worked;
  5051. }
  5052. bool File::moveFileTo (const File& newFile) const
  5053. {
  5054. if (newFile.fullPath == fullPath)
  5055. return true;
  5056. #if ! NAMES_ARE_CASE_SENSITIVE
  5057. if (*this != newFile)
  5058. #endif
  5059. if (! newFile.deleteFile())
  5060. return false;
  5061. return moveInternal (newFile);
  5062. }
  5063. bool File::copyFileTo (const File& newFile) const
  5064. {
  5065. return (*this == newFile)
  5066. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5067. }
  5068. bool File::copyDirectoryTo (const File& newDirectory) const
  5069. {
  5070. if (isDirectory() && newDirectory.createDirectory())
  5071. {
  5072. Array<File> subFiles;
  5073. findChildFiles (subFiles, File::findFiles, false);
  5074. int i;
  5075. for (i = 0; i < subFiles.size(); ++i)
  5076. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5077. return false;
  5078. subFiles.clear();
  5079. findChildFiles (subFiles, File::findDirectories, false);
  5080. for (i = 0; i < subFiles.size(); ++i)
  5081. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5082. return false;
  5083. return true;
  5084. }
  5085. return false;
  5086. }
  5087. const String File::getPathUpToLastSlash() const
  5088. {
  5089. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5090. if (lastSlash > 0)
  5091. return fullPath.substring (0, lastSlash);
  5092. else if (lastSlash == 0)
  5093. return separatorString;
  5094. else
  5095. return fullPath;
  5096. }
  5097. const File File::getParentDirectory() const
  5098. {
  5099. return File (getPathUpToLastSlash(), (int) 0);
  5100. }
  5101. const String File::getFileName() const
  5102. {
  5103. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5104. }
  5105. int File::hashCode() const
  5106. {
  5107. return fullPath.hashCode();
  5108. }
  5109. int64 File::hashCode64() const
  5110. {
  5111. return fullPath.hashCode64();
  5112. }
  5113. const String File::getFileNameWithoutExtension() const
  5114. {
  5115. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5116. const int lastDot = fullPath.lastIndexOfChar ('.');
  5117. if (lastDot > lastSlash)
  5118. return fullPath.substring (lastSlash, lastDot);
  5119. else
  5120. return fullPath.substring (lastSlash);
  5121. }
  5122. bool File::isAChildOf (const File& potentialParent) const
  5123. {
  5124. if (potentialParent == File::nonexistent)
  5125. return false;
  5126. const String ourPath (getPathUpToLastSlash());
  5127. #if NAMES_ARE_CASE_SENSITIVE
  5128. if (potentialParent.fullPath == ourPath)
  5129. #else
  5130. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5131. #endif
  5132. {
  5133. return true;
  5134. }
  5135. else if (potentialParent.fullPath.length() >= ourPath.length())
  5136. {
  5137. return false;
  5138. }
  5139. else
  5140. {
  5141. return getParentDirectory().isAChildOf (potentialParent);
  5142. }
  5143. }
  5144. bool File::isAbsolutePath (const String& path)
  5145. {
  5146. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5147. #if JUCE_WINDOWS
  5148. || (path.isNotEmpty() && path[1] == ':');
  5149. #else
  5150. || path.startsWithChar ('~');
  5151. #endif
  5152. }
  5153. const File File::getChildFile (String relativePath) const
  5154. {
  5155. if (isAbsolutePath (relativePath))
  5156. {
  5157. // the path is really absolute..
  5158. return File (relativePath);
  5159. }
  5160. else
  5161. {
  5162. // it's relative, so remove any ../ or ./ bits at the start.
  5163. String path (fullPath);
  5164. if (relativePath[0] == '.')
  5165. {
  5166. #if JUCE_WINDOWS
  5167. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5168. #else
  5169. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5170. #endif
  5171. while (relativePath[0] == '.')
  5172. {
  5173. if (relativePath[1] == '.')
  5174. {
  5175. if (relativePath [2] == 0 || relativePath[2] == separator)
  5176. {
  5177. const int lastSlash = path.lastIndexOfChar (separator);
  5178. if (lastSlash >= 0)
  5179. path = path.substring (0, lastSlash);
  5180. relativePath = relativePath.substring (3);
  5181. }
  5182. else
  5183. {
  5184. break;
  5185. }
  5186. }
  5187. else if (relativePath[1] == separator)
  5188. {
  5189. relativePath = relativePath.substring (2);
  5190. }
  5191. else
  5192. {
  5193. break;
  5194. }
  5195. }
  5196. }
  5197. return File (addTrailingSeparator (path) + relativePath);
  5198. }
  5199. }
  5200. const File File::getSiblingFile (const String& fileName) const
  5201. {
  5202. return getParentDirectory().getChildFile (fileName);
  5203. }
  5204. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5205. {
  5206. if (bytes == 1)
  5207. {
  5208. return "1 byte";
  5209. }
  5210. else if (bytes < 1024)
  5211. {
  5212. return String ((int) bytes) + " bytes";
  5213. }
  5214. else if (bytes < 1024 * 1024)
  5215. {
  5216. return String (bytes / 1024.0, 1) + " KB";
  5217. }
  5218. else if (bytes < 1024 * 1024 * 1024)
  5219. {
  5220. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5221. }
  5222. else
  5223. {
  5224. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5225. }
  5226. }
  5227. bool File::create() const
  5228. {
  5229. if (exists())
  5230. return true;
  5231. {
  5232. const File parentDir (getParentDirectory());
  5233. if (parentDir == *this || ! parentDir.createDirectory())
  5234. return false;
  5235. FileOutputStream fo (*this, 8);
  5236. }
  5237. return exists();
  5238. }
  5239. bool File::createDirectory() const
  5240. {
  5241. if (! isDirectory())
  5242. {
  5243. const File parentDir (getParentDirectory());
  5244. if (parentDir == *this || ! parentDir.createDirectory())
  5245. return false;
  5246. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5247. return isDirectory();
  5248. }
  5249. return true;
  5250. }
  5251. const Time File::getCreationTime() const
  5252. {
  5253. int64 m, a, c;
  5254. getFileTimesInternal (m, a, c);
  5255. return Time (c);
  5256. }
  5257. const Time File::getLastModificationTime() const
  5258. {
  5259. int64 m, a, c;
  5260. getFileTimesInternal (m, a, c);
  5261. return Time (m);
  5262. }
  5263. const Time File::getLastAccessTime() const
  5264. {
  5265. int64 m, a, c;
  5266. getFileTimesInternal (m, a, c);
  5267. return Time (a);
  5268. }
  5269. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5270. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5271. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5272. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5273. {
  5274. if (! existsAsFile())
  5275. return false;
  5276. FileInputStream in (*this);
  5277. return getSize() == in.readIntoMemoryBlock (destBlock);
  5278. }
  5279. const String File::loadFileAsString() const
  5280. {
  5281. if (! existsAsFile())
  5282. return String::empty;
  5283. FileInputStream in (*this);
  5284. return in.readEntireStreamAsString();
  5285. }
  5286. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5287. {
  5288. return (whatToLookFor & (isDir ? findDirectories
  5289. : findFiles)) != 0
  5290. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5291. }
  5292. int File::findChildFiles (Array<File>& results,
  5293. const int whatToLookFor,
  5294. const bool searchRecursively,
  5295. const String& wildCardPattern) const
  5296. {
  5297. // you have to specify the type of files you're looking for!
  5298. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5299. int total = 0;
  5300. if (isDirectory())
  5301. {
  5302. // find child files or directories in this directory first..
  5303. String path (addTrailingSeparator (fullPath)), filename;
  5304. bool itemIsDirectory, itemIsHidden;
  5305. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5306. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5307. {
  5308. if (! filename.containsOnly ("."))
  5309. {
  5310. const File fileFound (path + filename, 0);
  5311. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5312. {
  5313. results.add (fileFound);
  5314. ++total;
  5315. }
  5316. if (searchRecursively && itemIsDirectory
  5317. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5318. {
  5319. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5320. }
  5321. }
  5322. }
  5323. }
  5324. return total;
  5325. }
  5326. int File::getNumberOfChildFiles (const int whatToLookFor,
  5327. const String& wildCardPattern) const
  5328. {
  5329. // you have to specify the type of files you're looking for!
  5330. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5331. int count = 0;
  5332. if (isDirectory())
  5333. {
  5334. String filename;
  5335. bool itemIsDirectory, itemIsHidden;
  5336. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5337. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5338. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5339. && ! filename.containsOnly ("."))
  5340. ++count;
  5341. }
  5342. else
  5343. {
  5344. // trying to search for files inside a non-directory?
  5345. jassertfalse;
  5346. }
  5347. return count;
  5348. }
  5349. bool File::containsSubDirectories() const
  5350. {
  5351. if (isDirectory())
  5352. {
  5353. String filename;
  5354. bool itemIsDirectory;
  5355. DirectoryIterator::NativeIterator i (*this, "*");
  5356. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5357. if (itemIsDirectory)
  5358. return true;
  5359. }
  5360. return false;
  5361. }
  5362. const File File::getNonexistentChildFile (const String& prefix_,
  5363. const String& suffix,
  5364. bool putNumbersInBrackets) const
  5365. {
  5366. File f (getChildFile (prefix_ + suffix));
  5367. if (f.exists())
  5368. {
  5369. int num = 2;
  5370. String prefix (prefix_);
  5371. // remove any bracketed numbers that may already be on the end..
  5372. if (prefix.trim().endsWithChar (')'))
  5373. {
  5374. putNumbersInBrackets = true;
  5375. const int openBracks = prefix.lastIndexOfChar ('(');
  5376. const int closeBracks = prefix.lastIndexOfChar (')');
  5377. if (openBracks > 0
  5378. && closeBracks > openBracks
  5379. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5380. {
  5381. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5382. prefix = prefix.substring (0, openBracks);
  5383. }
  5384. }
  5385. // also use brackets if it ends in a digit.
  5386. putNumbersInBrackets = putNumbersInBrackets
  5387. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5388. do
  5389. {
  5390. if (putNumbersInBrackets)
  5391. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5392. else
  5393. f = getChildFile (prefix + String (num++) + suffix);
  5394. } while (f.exists());
  5395. }
  5396. return f;
  5397. }
  5398. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5399. {
  5400. if (exists())
  5401. {
  5402. return getParentDirectory()
  5403. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5404. getFileExtension(),
  5405. putNumbersInBrackets);
  5406. }
  5407. else
  5408. {
  5409. return *this;
  5410. }
  5411. }
  5412. const String File::getFileExtension() const
  5413. {
  5414. String ext;
  5415. if (! isDirectory())
  5416. {
  5417. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5418. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5419. ext = fullPath.substring (indexOfDot);
  5420. }
  5421. return ext;
  5422. }
  5423. bool File::hasFileExtension (const String& possibleSuffix) const
  5424. {
  5425. if (possibleSuffix.isEmpty())
  5426. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5427. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5428. if (semicolon >= 0)
  5429. {
  5430. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5431. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5432. }
  5433. else
  5434. {
  5435. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5436. {
  5437. if (possibleSuffix.startsWithChar ('.'))
  5438. return true;
  5439. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5440. if (dotPos >= 0)
  5441. return fullPath [dotPos] == '.';
  5442. }
  5443. }
  5444. return false;
  5445. }
  5446. const File File::withFileExtension (const String& newExtension) const
  5447. {
  5448. if (fullPath.isEmpty())
  5449. return File::nonexistent;
  5450. String filePart (getFileName());
  5451. int i = filePart.lastIndexOfChar ('.');
  5452. if (i >= 0)
  5453. filePart = filePart.substring (0, i);
  5454. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5455. filePart << '.';
  5456. return getSiblingFile (filePart + newExtension);
  5457. }
  5458. bool File::startAsProcess (const String& parameters) const
  5459. {
  5460. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5461. }
  5462. FileInputStream* File::createInputStream() const
  5463. {
  5464. if (existsAsFile())
  5465. return new FileInputStream (*this);
  5466. return 0;
  5467. }
  5468. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5469. {
  5470. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5471. if (out->failedToOpen())
  5472. return 0;
  5473. return out.release();
  5474. }
  5475. bool File::appendData (const void* const dataToAppend,
  5476. const int numberOfBytes) const
  5477. {
  5478. if (numberOfBytes > 0)
  5479. {
  5480. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5481. if (out == 0)
  5482. return false;
  5483. out->write (dataToAppend, numberOfBytes);
  5484. }
  5485. return true;
  5486. }
  5487. bool File::replaceWithData (const void* const dataToWrite,
  5488. const int numberOfBytes) const
  5489. {
  5490. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5491. if (numberOfBytes <= 0)
  5492. return deleteFile();
  5493. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5494. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5495. return tempFile.overwriteTargetFileWithTemporary();
  5496. }
  5497. bool File::appendText (const String& text,
  5498. const bool asUnicode,
  5499. const bool writeUnicodeHeaderBytes) const
  5500. {
  5501. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5502. if (out != 0)
  5503. {
  5504. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5505. return true;
  5506. }
  5507. return false;
  5508. }
  5509. bool File::replaceWithText (const String& textToWrite,
  5510. const bool asUnicode,
  5511. const bool writeUnicodeHeaderBytes) const
  5512. {
  5513. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5514. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5515. return tempFile.overwriteTargetFileWithTemporary();
  5516. }
  5517. bool File::hasIdenticalContentTo (const File& other) const
  5518. {
  5519. if (other == *this)
  5520. return true;
  5521. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5522. {
  5523. FileInputStream in1 (*this), in2 (other);
  5524. const int bufferSize = 4096;
  5525. HeapBlock <char> buffer1, buffer2;
  5526. buffer1.malloc (bufferSize);
  5527. buffer2.malloc (bufferSize);
  5528. for (;;)
  5529. {
  5530. const int num1 = in1.read (buffer1, bufferSize);
  5531. const int num2 = in2.read (buffer2, bufferSize);
  5532. if (num1 != num2)
  5533. break;
  5534. if (num1 <= 0)
  5535. return true;
  5536. if (memcmp (buffer1, buffer2, num1) != 0)
  5537. break;
  5538. }
  5539. }
  5540. return false;
  5541. }
  5542. const String File::createLegalPathName (const String& original)
  5543. {
  5544. String s (original);
  5545. String start;
  5546. if (s[1] == ':')
  5547. {
  5548. start = s.substring (0, 2);
  5549. s = s.substring (2);
  5550. }
  5551. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5552. .substring (0, 1024);
  5553. }
  5554. const String File::createLegalFileName (const String& original)
  5555. {
  5556. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5557. const int maxLength = 128; // only the length of the filename, not the whole path
  5558. const int len = s.length();
  5559. if (len > maxLength)
  5560. {
  5561. const int lastDot = s.lastIndexOfChar ('.');
  5562. if (lastDot > jmax (0, len - 12))
  5563. {
  5564. s = s.substring (0, maxLength - (len - lastDot))
  5565. + s.substring (lastDot);
  5566. }
  5567. else
  5568. {
  5569. s = s.substring (0, maxLength);
  5570. }
  5571. }
  5572. return s;
  5573. }
  5574. const String File::getRelativePathFrom (const File& dir) const
  5575. {
  5576. String thisPath (fullPath);
  5577. {
  5578. int len = thisPath.length();
  5579. while (--len >= 0 && thisPath [len] == File::separator)
  5580. thisPath [len] = 0;
  5581. }
  5582. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5583. : dir.fullPath));
  5584. const int len = jmin (thisPath.length(), dirPath.length());
  5585. int commonBitLength = 0;
  5586. for (int i = 0; i < len; ++i)
  5587. {
  5588. #if NAMES_ARE_CASE_SENSITIVE
  5589. if (thisPath[i] != dirPath[i])
  5590. #else
  5591. if (CharacterFunctions::toLowerCase (thisPath[i])
  5592. != CharacterFunctions::toLowerCase (dirPath[i]))
  5593. #endif
  5594. {
  5595. break;
  5596. }
  5597. ++commonBitLength;
  5598. }
  5599. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5600. --commonBitLength;
  5601. // if the only common bit is the root, then just return the full path..
  5602. if (commonBitLength <= 0
  5603. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5604. return fullPath;
  5605. thisPath = thisPath.substring (commonBitLength);
  5606. dirPath = dirPath.substring (commonBitLength);
  5607. while (dirPath.isNotEmpty())
  5608. {
  5609. #if JUCE_WINDOWS
  5610. thisPath = "..\\" + thisPath;
  5611. #else
  5612. thisPath = "../" + thisPath;
  5613. #endif
  5614. const int sep = dirPath.indexOfChar (separator);
  5615. if (sep >= 0)
  5616. dirPath = dirPath.substring (sep + 1);
  5617. else
  5618. dirPath = String::empty;
  5619. }
  5620. return thisPath;
  5621. }
  5622. const File File::createTempFile (const String& fileNameEnding)
  5623. {
  5624. const File tempFile (getSpecialLocation (tempDirectory)
  5625. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5626. .withFileExtension (fileNameEnding));
  5627. if (tempFile.exists())
  5628. return createTempFile (fileNameEnding);
  5629. else
  5630. return tempFile;
  5631. }
  5632. END_JUCE_NAMESPACE
  5633. /*** End of inlined file: juce_File.cpp ***/
  5634. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5635. BEGIN_JUCE_NAMESPACE
  5636. void* juce_fileOpen (const File& file, bool forWriting);
  5637. void juce_fileClose (void* handle);
  5638. int juce_fileRead (void* handle, void* buffer, int size);
  5639. int64 juce_fileSetPosition (void* handle, int64 pos);
  5640. FileInputStream::FileInputStream (const File& f)
  5641. : file (f),
  5642. currentPosition (0),
  5643. needToSeek (true)
  5644. {
  5645. totalSize = f.getSize();
  5646. fileHandle = juce_fileOpen (f, false);
  5647. }
  5648. FileInputStream::~FileInputStream()
  5649. {
  5650. juce_fileClose (fileHandle);
  5651. }
  5652. int64 FileInputStream::getTotalLength()
  5653. {
  5654. return totalSize;
  5655. }
  5656. int FileInputStream::read (void* buffer, int bytesToRead)
  5657. {
  5658. int num = 0;
  5659. if (needToSeek)
  5660. {
  5661. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5662. return 0;
  5663. needToSeek = false;
  5664. }
  5665. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5666. currentPosition += num;
  5667. return num;
  5668. }
  5669. bool FileInputStream::isExhausted()
  5670. {
  5671. return currentPosition >= totalSize;
  5672. }
  5673. int64 FileInputStream::getPosition()
  5674. {
  5675. return currentPosition;
  5676. }
  5677. bool FileInputStream::setPosition (int64 pos)
  5678. {
  5679. pos = jlimit ((int64) 0, totalSize, pos);
  5680. needToSeek |= (currentPosition != pos);
  5681. currentPosition = pos;
  5682. return true;
  5683. }
  5684. END_JUCE_NAMESPACE
  5685. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5686. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5687. BEGIN_JUCE_NAMESPACE
  5688. void* juce_fileOpen (const File& file, bool forWriting);
  5689. void juce_fileClose (void* handle);
  5690. int juce_fileWrite (void* handle, const void* buffer, int size);
  5691. int64 juce_fileSetPosition (void* handle, int64 pos);
  5692. FileOutputStream::FileOutputStream (const File& f,
  5693. const int bufferSize_)
  5694. : file (f),
  5695. bufferSize (bufferSize_),
  5696. bytesInBuffer (0)
  5697. {
  5698. fileHandle = juce_fileOpen (f, true);
  5699. if (fileHandle != 0)
  5700. {
  5701. currentPosition = getPositionInternal();
  5702. if (currentPosition < 0)
  5703. {
  5704. jassertfalse;
  5705. juce_fileClose (fileHandle);
  5706. fileHandle = 0;
  5707. }
  5708. }
  5709. buffer.malloc (jmax (bufferSize_, 16));
  5710. }
  5711. FileOutputStream::~FileOutputStream()
  5712. {
  5713. flush();
  5714. juce_fileClose (fileHandle);
  5715. }
  5716. int64 FileOutputStream::getPosition()
  5717. {
  5718. return currentPosition;
  5719. }
  5720. bool FileOutputStream::setPosition (int64 newPosition)
  5721. {
  5722. if (newPosition != currentPosition)
  5723. {
  5724. flush();
  5725. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5726. }
  5727. return newPosition == currentPosition;
  5728. }
  5729. void FileOutputStream::flush()
  5730. {
  5731. if (bytesInBuffer > 0)
  5732. {
  5733. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5734. bytesInBuffer = 0;
  5735. }
  5736. flushInternal();
  5737. }
  5738. bool FileOutputStream::write (const void* const src, const int numBytes)
  5739. {
  5740. if (bytesInBuffer + numBytes < bufferSize)
  5741. {
  5742. memcpy (buffer + bytesInBuffer, src, numBytes);
  5743. bytesInBuffer += numBytes;
  5744. currentPosition += numBytes;
  5745. }
  5746. else
  5747. {
  5748. if (bytesInBuffer > 0)
  5749. {
  5750. // flush the reservoir
  5751. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5752. bytesInBuffer = 0;
  5753. if (! wroteOk)
  5754. return false;
  5755. }
  5756. if (numBytes < bufferSize)
  5757. {
  5758. memcpy (buffer + bytesInBuffer, src, numBytes);
  5759. bytesInBuffer += numBytes;
  5760. currentPosition += numBytes;
  5761. }
  5762. else
  5763. {
  5764. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5765. currentPosition += bytesWritten;
  5766. return bytesWritten == numBytes;
  5767. }
  5768. }
  5769. return true;
  5770. }
  5771. END_JUCE_NAMESPACE
  5772. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5773. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5774. BEGIN_JUCE_NAMESPACE
  5775. FileSearchPath::FileSearchPath()
  5776. {
  5777. }
  5778. FileSearchPath::FileSearchPath (const String& path)
  5779. {
  5780. init (path);
  5781. }
  5782. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5783. : directories (other.directories)
  5784. {
  5785. }
  5786. FileSearchPath::~FileSearchPath()
  5787. {
  5788. }
  5789. FileSearchPath& FileSearchPath::operator= (const String& path)
  5790. {
  5791. init (path);
  5792. return *this;
  5793. }
  5794. void FileSearchPath::init (const String& path)
  5795. {
  5796. directories.clear();
  5797. directories.addTokens (path, ";", "\"");
  5798. directories.trim();
  5799. directories.removeEmptyStrings();
  5800. for (int i = directories.size(); --i >= 0;)
  5801. directories.set (i, directories[i].unquoted());
  5802. }
  5803. int FileSearchPath::getNumPaths() const
  5804. {
  5805. return directories.size();
  5806. }
  5807. const File FileSearchPath::operator[] (const int index) const
  5808. {
  5809. return File (directories [index]);
  5810. }
  5811. const String FileSearchPath::toString() const
  5812. {
  5813. StringArray directories2 (directories);
  5814. for (int i = directories2.size(); --i >= 0;)
  5815. if (directories2[i].containsChar (';'))
  5816. directories2.set (i, directories2[i].quoted());
  5817. return directories2.joinIntoString (";");
  5818. }
  5819. void FileSearchPath::add (const File& dir, const int insertIndex)
  5820. {
  5821. directories.insert (insertIndex, dir.getFullPathName());
  5822. }
  5823. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5824. {
  5825. for (int i = 0; i < directories.size(); ++i)
  5826. if (File (directories[i]) == dir)
  5827. return;
  5828. add (dir);
  5829. }
  5830. void FileSearchPath::remove (const int index)
  5831. {
  5832. directories.remove (index);
  5833. }
  5834. void FileSearchPath::addPath (const FileSearchPath& other)
  5835. {
  5836. for (int i = 0; i < other.getNumPaths(); ++i)
  5837. addIfNotAlreadyThere (other[i]);
  5838. }
  5839. void FileSearchPath::removeRedundantPaths()
  5840. {
  5841. for (int i = directories.size(); --i >= 0;)
  5842. {
  5843. const File d1 (directories[i]);
  5844. for (int j = directories.size(); --j >= 0;)
  5845. {
  5846. const File d2 (directories[j]);
  5847. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5848. {
  5849. directories.remove (i);
  5850. break;
  5851. }
  5852. }
  5853. }
  5854. }
  5855. void FileSearchPath::removeNonExistentPaths()
  5856. {
  5857. for (int i = directories.size(); --i >= 0;)
  5858. if (! File (directories[i]).isDirectory())
  5859. directories.remove (i);
  5860. }
  5861. int FileSearchPath::findChildFiles (Array<File>& results,
  5862. const int whatToLookFor,
  5863. const bool searchRecursively,
  5864. const String& wildCardPattern) const
  5865. {
  5866. int total = 0;
  5867. for (int i = 0; i < directories.size(); ++i)
  5868. total += operator[] (i).findChildFiles (results,
  5869. whatToLookFor,
  5870. searchRecursively,
  5871. wildCardPattern);
  5872. return total;
  5873. }
  5874. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5875. const bool checkRecursively) const
  5876. {
  5877. for (int i = directories.size(); --i >= 0;)
  5878. {
  5879. const File d (directories[i]);
  5880. if (checkRecursively)
  5881. {
  5882. if (fileToCheck.isAChildOf (d))
  5883. return true;
  5884. }
  5885. else
  5886. {
  5887. if (fileToCheck.getParentDirectory() == d)
  5888. return true;
  5889. }
  5890. }
  5891. return false;
  5892. }
  5893. END_JUCE_NAMESPACE
  5894. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5895. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5896. BEGIN_JUCE_NAMESPACE
  5897. NamedPipe::NamedPipe()
  5898. : internal (0)
  5899. {
  5900. }
  5901. NamedPipe::~NamedPipe()
  5902. {
  5903. close();
  5904. }
  5905. bool NamedPipe::openExisting (const String& pipeName)
  5906. {
  5907. currentPipeName = pipeName;
  5908. return openInternal (pipeName, false);
  5909. }
  5910. bool NamedPipe::createNewPipe (const String& pipeName)
  5911. {
  5912. currentPipeName = pipeName;
  5913. return openInternal (pipeName, true);
  5914. }
  5915. bool NamedPipe::isOpen() const
  5916. {
  5917. return internal != 0;
  5918. }
  5919. const String NamedPipe::getName() const
  5920. {
  5921. return currentPipeName;
  5922. }
  5923. // other methods for this class are implemented in the platform-specific files
  5924. END_JUCE_NAMESPACE
  5925. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5926. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5927. BEGIN_JUCE_NAMESPACE
  5928. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5929. {
  5930. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5931. "temp_" + String (Random::getSystemRandom().nextInt()),
  5932. suffix,
  5933. optionFlags);
  5934. }
  5935. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5936. : targetFile (targetFile_)
  5937. {
  5938. // If you use this constructor, you need to give it a valid target file!
  5939. jassert (targetFile != File::nonexistent);
  5940. createTempFile (targetFile.getParentDirectory(),
  5941. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5942. targetFile.getFileExtension(),
  5943. optionFlags);
  5944. }
  5945. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5946. const String& suffix, const int optionFlags)
  5947. {
  5948. if ((optionFlags & useHiddenFile) != 0)
  5949. name = "." + name;
  5950. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5951. }
  5952. TemporaryFile::~TemporaryFile()
  5953. {
  5954. // Have a few attempts at deleting the file before giving up..
  5955. for (int i = 5; --i >= 0;)
  5956. {
  5957. if (temporaryFile.deleteFile())
  5958. return;
  5959. Thread::sleep (50);
  5960. }
  5961. // Failed to delete our temporary file! Check that you've deleted all the
  5962. // file output streams that were using it!
  5963. jassertfalse;
  5964. }
  5965. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5966. {
  5967. // This method only works if you created this object with the constructor
  5968. // that takes a target file!
  5969. jassert (targetFile != File::nonexistent);
  5970. if (temporaryFile.exists())
  5971. {
  5972. // Have a few attempts at overwriting the file before giving up..
  5973. for (int i = 5; --i >= 0;)
  5974. {
  5975. if (temporaryFile.moveFileTo (targetFile))
  5976. return true;
  5977. Thread::sleep (100);
  5978. }
  5979. }
  5980. else
  5981. {
  5982. // There's no temporary file to use. If your write failed, you should
  5983. // probably check, and not bother calling this method.
  5984. jassertfalse;
  5985. }
  5986. return false;
  5987. }
  5988. END_JUCE_NAMESPACE
  5989. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5990. /*** Start of inlined file: juce_Socket.cpp ***/
  5991. #if JUCE_WINDOWS
  5992. #include <winsock2.h>
  5993. #if JUCE_MSVC
  5994. #pragma warning (push)
  5995. #pragma warning (disable : 4127 4389 4018)
  5996. #endif
  5997. #else
  5998. #if JUCE_LINUX
  5999. #include <sys/types.h>
  6000. #include <sys/socket.h>
  6001. #include <sys/errno.h>
  6002. #include <unistd.h>
  6003. #include <netinet/in.h>
  6004. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6005. #include <CoreServices/CoreServices.h>
  6006. #endif
  6007. #include <fcntl.h>
  6008. #include <netdb.h>
  6009. #include <arpa/inet.h>
  6010. #include <netinet/tcp.h>
  6011. #endif
  6012. BEGIN_JUCE_NAMESPACE
  6013. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6014. typedef socklen_t juce_socklen_t;
  6015. #else
  6016. typedef int juce_socklen_t;
  6017. #endif
  6018. #if JUCE_WINDOWS
  6019. namespace SocketHelpers
  6020. {
  6021. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6022. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6023. }
  6024. static void initWin32Sockets()
  6025. {
  6026. static CriticalSection lock;
  6027. const ScopedLock sl (lock);
  6028. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6029. {
  6030. WSADATA wsaData;
  6031. const WORD wVersionRequested = MAKEWORD (1, 1);
  6032. WSAStartup (wVersionRequested, &wsaData);
  6033. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6034. }
  6035. }
  6036. void juce_shutdownWin32Sockets()
  6037. {
  6038. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6039. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6040. }
  6041. #endif
  6042. namespace SocketHelpers
  6043. {
  6044. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6045. {
  6046. const int sndBufSize = 65536;
  6047. const int rcvBufSize = 65536;
  6048. const int one = 1;
  6049. return handle > 0
  6050. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6051. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6052. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6053. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6054. }
  6055. static bool bindSocketToPort (const int handle, const int port) throw()
  6056. {
  6057. if (handle <= 0 || port <= 0)
  6058. return false;
  6059. struct sockaddr_in servTmpAddr;
  6060. zerostruct (servTmpAddr);
  6061. servTmpAddr.sin_family = PF_INET;
  6062. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6063. servTmpAddr.sin_port = htons ((uint16) port);
  6064. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6065. }
  6066. static int readSocket (const int handle,
  6067. void* const destBuffer, const int maxBytesToRead,
  6068. bool volatile& connected,
  6069. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6070. {
  6071. int bytesRead = 0;
  6072. while (bytesRead < maxBytesToRead)
  6073. {
  6074. int bytesThisTime;
  6075. #if JUCE_WINDOWS
  6076. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6077. #else
  6078. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6079. && errno == EINTR
  6080. && connected)
  6081. {
  6082. }
  6083. #endif
  6084. if (bytesThisTime <= 0 || ! connected)
  6085. {
  6086. if (bytesRead == 0)
  6087. bytesRead = -1;
  6088. break;
  6089. }
  6090. bytesRead += bytesThisTime;
  6091. if (! blockUntilSpecifiedAmountHasArrived)
  6092. break;
  6093. }
  6094. return bytesRead;
  6095. }
  6096. static int waitForReadiness (const int handle, const bool forReading,
  6097. const int timeoutMsecs) throw()
  6098. {
  6099. struct timeval timeout;
  6100. struct timeval* timeoutp;
  6101. if (timeoutMsecs >= 0)
  6102. {
  6103. timeout.tv_sec = timeoutMsecs / 1000;
  6104. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6105. timeoutp = &timeout;
  6106. }
  6107. else
  6108. {
  6109. timeoutp = 0;
  6110. }
  6111. fd_set rset, wset;
  6112. FD_ZERO (&rset);
  6113. FD_SET (handle, &rset);
  6114. FD_ZERO (&wset);
  6115. FD_SET (handle, &wset);
  6116. fd_set* const prset = forReading ? &rset : 0;
  6117. fd_set* const pwset = forReading ? 0 : &wset;
  6118. #if JUCE_WINDOWS
  6119. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6120. return -1;
  6121. #else
  6122. {
  6123. int result;
  6124. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6125. && errno == EINTR)
  6126. {
  6127. }
  6128. if (result < 0)
  6129. return -1;
  6130. }
  6131. #endif
  6132. {
  6133. int opt;
  6134. juce_socklen_t len = sizeof (opt);
  6135. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6136. || opt != 0)
  6137. return -1;
  6138. }
  6139. if ((forReading && FD_ISSET (handle, &rset))
  6140. || ((! forReading) && FD_ISSET (handle, &wset)))
  6141. return 1;
  6142. return 0;
  6143. }
  6144. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6145. {
  6146. #if JUCE_WINDOWS
  6147. u_long nonBlocking = shouldBlock ? 0 : 1;
  6148. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6149. return false;
  6150. #else
  6151. int socketFlags = fcntl (handle, F_GETFL, 0);
  6152. if (socketFlags == -1)
  6153. return false;
  6154. if (shouldBlock)
  6155. socketFlags &= ~O_NONBLOCK;
  6156. else
  6157. socketFlags |= O_NONBLOCK;
  6158. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6159. return false;
  6160. #endif
  6161. return true;
  6162. }
  6163. static bool connectSocket (int volatile& handle,
  6164. const bool isDatagram,
  6165. void** serverAddress,
  6166. const String& hostName,
  6167. const int portNumber,
  6168. const int timeOutMillisecs) throw()
  6169. {
  6170. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6171. if (hostEnt == 0)
  6172. return false;
  6173. struct in_addr targetAddress;
  6174. memcpy (&targetAddress.s_addr,
  6175. *(hostEnt->h_addr_list),
  6176. sizeof (targetAddress.s_addr));
  6177. struct sockaddr_in servTmpAddr;
  6178. zerostruct (servTmpAddr);
  6179. servTmpAddr.sin_family = PF_INET;
  6180. servTmpAddr.sin_addr = targetAddress;
  6181. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6182. if (handle < 0)
  6183. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6184. if (handle < 0)
  6185. return false;
  6186. if (isDatagram)
  6187. {
  6188. *serverAddress = new struct sockaddr_in();
  6189. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6190. return true;
  6191. }
  6192. setSocketBlockingState (handle, false);
  6193. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6194. if (result < 0)
  6195. {
  6196. #if JUCE_WINDOWS
  6197. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6198. #else
  6199. if (errno == EINPROGRESS)
  6200. #endif
  6201. {
  6202. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6203. {
  6204. setSocketBlockingState (handle, true);
  6205. return false;
  6206. }
  6207. }
  6208. }
  6209. setSocketBlockingState (handle, true);
  6210. resetSocketOptions (handle, false, false);
  6211. return true;
  6212. }
  6213. }
  6214. StreamingSocket::StreamingSocket()
  6215. : portNumber (0),
  6216. handle (-1),
  6217. connected (false),
  6218. isListener (false)
  6219. {
  6220. #if JUCE_WINDOWS
  6221. initWin32Sockets();
  6222. #endif
  6223. }
  6224. StreamingSocket::StreamingSocket (const String& hostName_,
  6225. const int portNumber_,
  6226. const int handle_)
  6227. : hostName (hostName_),
  6228. portNumber (portNumber_),
  6229. handle (handle_),
  6230. connected (true),
  6231. isListener (false)
  6232. {
  6233. #if JUCE_WINDOWS
  6234. initWin32Sockets();
  6235. #endif
  6236. SocketHelpers::resetSocketOptions (handle_, false, false);
  6237. }
  6238. StreamingSocket::~StreamingSocket()
  6239. {
  6240. close();
  6241. }
  6242. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6243. {
  6244. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6245. : -1;
  6246. }
  6247. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6248. {
  6249. if (isListener || ! connected)
  6250. return -1;
  6251. #if JUCE_WINDOWS
  6252. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6253. #else
  6254. int result;
  6255. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6256. && errno == EINTR)
  6257. {
  6258. }
  6259. return result;
  6260. #endif
  6261. }
  6262. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6263. const int timeoutMsecs) const
  6264. {
  6265. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6266. : -1;
  6267. }
  6268. bool StreamingSocket::bindToPort (const int port)
  6269. {
  6270. return SocketHelpers::bindSocketToPort (handle, port);
  6271. }
  6272. bool StreamingSocket::connect (const String& remoteHostName,
  6273. const int remotePortNumber,
  6274. const int timeOutMillisecs)
  6275. {
  6276. if (isListener)
  6277. {
  6278. jassertfalse; // a listener socket can't connect to another one!
  6279. return false;
  6280. }
  6281. if (connected)
  6282. close();
  6283. hostName = remoteHostName;
  6284. portNumber = remotePortNumber;
  6285. isListener = false;
  6286. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  6287. remotePortNumber, timeOutMillisecs);
  6288. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  6289. {
  6290. close();
  6291. return false;
  6292. }
  6293. return true;
  6294. }
  6295. void StreamingSocket::close()
  6296. {
  6297. #if JUCE_WINDOWS
  6298. if (handle != SOCKET_ERROR || connected)
  6299. closesocket (handle);
  6300. connected = false;
  6301. #else
  6302. if (connected)
  6303. {
  6304. connected = false;
  6305. if (isListener)
  6306. {
  6307. // need to do this to interrupt the accept() function..
  6308. StreamingSocket temp;
  6309. temp.connect ("localhost", portNumber, 1000);
  6310. }
  6311. }
  6312. if (handle != -1)
  6313. ::close (handle);
  6314. #endif
  6315. hostName = String::empty;
  6316. portNumber = 0;
  6317. handle = -1;
  6318. isListener = false;
  6319. }
  6320. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6321. {
  6322. if (connected)
  6323. close();
  6324. hostName = "listener";
  6325. portNumber = newPortNumber;
  6326. isListener = true;
  6327. struct sockaddr_in servTmpAddr;
  6328. zerostruct (servTmpAddr);
  6329. servTmpAddr.sin_family = PF_INET;
  6330. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6331. if (localHostName.isNotEmpty())
  6332. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6333. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6334. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6335. if (handle < 0)
  6336. return false;
  6337. const int reuse = 1;
  6338. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6339. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6340. || listen (handle, SOMAXCONN) < 0)
  6341. {
  6342. close();
  6343. return false;
  6344. }
  6345. connected = true;
  6346. return true;
  6347. }
  6348. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6349. {
  6350. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6351. // prepare this socket as a listener.
  6352. if (connected && isListener)
  6353. {
  6354. struct sockaddr address;
  6355. juce_socklen_t len = sizeof (sockaddr);
  6356. const int newSocket = (int) accept (handle, &address, &len);
  6357. if (newSocket >= 0 && connected)
  6358. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6359. portNumber, newSocket);
  6360. }
  6361. return 0;
  6362. }
  6363. bool StreamingSocket::isLocal() const throw()
  6364. {
  6365. return hostName == "127.0.0.1";
  6366. }
  6367. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6368. : portNumber (0),
  6369. handle (-1),
  6370. connected (true),
  6371. allowBroadcast (allowBroadcast_),
  6372. serverAddress (0)
  6373. {
  6374. #if JUCE_WINDOWS
  6375. initWin32Sockets();
  6376. #endif
  6377. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6378. bindToPort (localPortNumber);
  6379. }
  6380. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6381. const int handle_, const int localPortNumber)
  6382. : hostName (hostName_),
  6383. portNumber (portNumber_),
  6384. handle (handle_),
  6385. connected (true),
  6386. allowBroadcast (false),
  6387. serverAddress (0)
  6388. {
  6389. #if JUCE_WINDOWS
  6390. initWin32Sockets();
  6391. #endif
  6392. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  6393. bindToPort (localPortNumber);
  6394. }
  6395. DatagramSocket::~DatagramSocket()
  6396. {
  6397. close();
  6398. delete ((struct sockaddr_in*) serverAddress);
  6399. serverAddress = 0;
  6400. }
  6401. void DatagramSocket::close()
  6402. {
  6403. #if JUCE_WINDOWS
  6404. closesocket (handle);
  6405. connected = false;
  6406. #else
  6407. connected = false;
  6408. ::close (handle);
  6409. #endif
  6410. hostName = String::empty;
  6411. portNumber = 0;
  6412. handle = -1;
  6413. }
  6414. bool DatagramSocket::bindToPort (const int port)
  6415. {
  6416. return SocketHelpers::bindSocketToPort (handle, port);
  6417. }
  6418. bool DatagramSocket::connect (const String& remoteHostName,
  6419. const int remotePortNumber,
  6420. const int timeOutMillisecs)
  6421. {
  6422. if (connected)
  6423. close();
  6424. hostName = remoteHostName;
  6425. portNumber = remotePortNumber;
  6426. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  6427. remoteHostName, remotePortNumber,
  6428. timeOutMillisecs);
  6429. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  6430. {
  6431. close();
  6432. return false;
  6433. }
  6434. return true;
  6435. }
  6436. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6437. {
  6438. struct sockaddr address;
  6439. juce_socklen_t len = sizeof (sockaddr);
  6440. while (waitUntilReady (true, -1) == 1)
  6441. {
  6442. char buf[1];
  6443. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6444. {
  6445. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6446. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6447. -1, -1);
  6448. }
  6449. }
  6450. return 0;
  6451. }
  6452. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6453. const int timeoutMsecs) const
  6454. {
  6455. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6456. : -1;
  6457. }
  6458. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6459. {
  6460. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6461. : -1;
  6462. }
  6463. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6464. {
  6465. // You need to call connect() first to set the server address..
  6466. jassert (serverAddress != 0 && connected);
  6467. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6468. numBytesToWrite, 0,
  6469. (const struct sockaddr*) serverAddress,
  6470. sizeof (struct sockaddr_in))
  6471. : -1;
  6472. }
  6473. bool DatagramSocket::isLocal() const throw()
  6474. {
  6475. return hostName == "127.0.0.1";
  6476. }
  6477. #if JUCE_MSVC
  6478. #pragma warning (pop)
  6479. #endif
  6480. END_JUCE_NAMESPACE
  6481. /*** End of inlined file: juce_Socket.cpp ***/
  6482. /*** Start of inlined file: juce_URL.cpp ***/
  6483. BEGIN_JUCE_NAMESPACE
  6484. URL::URL()
  6485. {
  6486. }
  6487. URL::URL (const String& url_)
  6488. : url (url_)
  6489. {
  6490. int i = url.indexOfChar ('?');
  6491. if (i >= 0)
  6492. {
  6493. do
  6494. {
  6495. const int nextAmp = url.indexOfChar (i + 1, '&');
  6496. const int equalsPos = url.indexOfChar (i + 1, '=');
  6497. if (equalsPos > i + 1)
  6498. {
  6499. if (nextAmp < 0)
  6500. {
  6501. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6502. removeEscapeChars (url.substring (equalsPos + 1)));
  6503. }
  6504. else if (nextAmp > 0 && equalsPos < nextAmp)
  6505. {
  6506. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6507. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6508. }
  6509. }
  6510. i = nextAmp;
  6511. }
  6512. while (i >= 0);
  6513. url = url.upToFirstOccurrenceOf ("?", false, false);
  6514. }
  6515. }
  6516. URL::URL (const URL& other)
  6517. : url (other.url),
  6518. postData (other.postData),
  6519. parameters (other.parameters),
  6520. filesToUpload (other.filesToUpload),
  6521. mimeTypes (other.mimeTypes)
  6522. {
  6523. }
  6524. URL& URL::operator= (const URL& other)
  6525. {
  6526. url = other.url;
  6527. postData = other.postData;
  6528. parameters = other.parameters;
  6529. filesToUpload = other.filesToUpload;
  6530. mimeTypes = other.mimeTypes;
  6531. return *this;
  6532. }
  6533. URL::~URL()
  6534. {
  6535. }
  6536. static const String getMangledParameters (const StringPairArray& parameters)
  6537. {
  6538. String p;
  6539. for (int i = 0; i < parameters.size(); ++i)
  6540. {
  6541. if (i > 0)
  6542. p += '&';
  6543. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6544. << '='
  6545. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6546. }
  6547. return p;
  6548. }
  6549. const String URL::toString (const bool includeGetParameters) const
  6550. {
  6551. if (includeGetParameters && parameters.size() > 0)
  6552. return url + "?" + getMangledParameters (parameters);
  6553. else
  6554. return url;
  6555. }
  6556. bool URL::isWellFormed() const
  6557. {
  6558. //xxx TODO
  6559. return url.isNotEmpty();
  6560. }
  6561. static int findStartOfDomain (const String& url)
  6562. {
  6563. int i = 0;
  6564. while (CharacterFunctions::isLetterOrDigit (url[i])
  6565. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6566. ++i;
  6567. return url[i] == ':' ? i + 1 : 0;
  6568. }
  6569. const String URL::getDomain() const
  6570. {
  6571. int start = findStartOfDomain (url);
  6572. while (url[start] == '/')
  6573. ++start;
  6574. const int end1 = url.indexOfChar (start, '/');
  6575. const int end2 = url.indexOfChar (start, ':');
  6576. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6577. : jmin (end1, end2);
  6578. return url.substring (start, end);
  6579. }
  6580. const String URL::getSubPath() const
  6581. {
  6582. int start = findStartOfDomain (url);
  6583. while (url[start] == '/')
  6584. ++start;
  6585. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6586. return startOfPath <= 0 ? String::empty
  6587. : url.substring (startOfPath);
  6588. }
  6589. const String URL::getScheme() const
  6590. {
  6591. return url.substring (0, findStartOfDomain (url) - 1);
  6592. }
  6593. const URL URL::withNewSubPath (const String& newPath) const
  6594. {
  6595. int start = findStartOfDomain (url);
  6596. while (url[start] == '/')
  6597. ++start;
  6598. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6599. URL u (*this);
  6600. if (startOfPath > 0)
  6601. u.url = url.substring (0, startOfPath);
  6602. if (! u.url.endsWithChar ('/'))
  6603. u.url << '/';
  6604. if (newPath.startsWithChar ('/'))
  6605. u.url << newPath.substring (1);
  6606. else
  6607. u.url << newPath;
  6608. return u;
  6609. }
  6610. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6611. {
  6612. if (possibleURL.startsWithIgnoreCase ("http:")
  6613. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6614. return true;
  6615. if (possibleURL.startsWithIgnoreCase ("file:")
  6616. || possibleURL.containsChar ('@')
  6617. || possibleURL.endsWithChar ('.')
  6618. || (! possibleURL.containsChar ('.')))
  6619. return false;
  6620. if (possibleURL.startsWithIgnoreCase ("www.")
  6621. && possibleURL.substring (5).containsChar ('.'))
  6622. return true;
  6623. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6624. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6625. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6626. return true;
  6627. return false;
  6628. }
  6629. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6630. {
  6631. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6632. return atSign > 0
  6633. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6634. && (! possibleEmailAddress.endsWithChar ('.'));
  6635. }
  6636. void* juce_openInternetFile (const String& url,
  6637. const String& headers,
  6638. const MemoryBlock& optionalPostData,
  6639. const bool isPost,
  6640. URL::OpenStreamProgressCallback* callback,
  6641. void* callbackContext,
  6642. int timeOutMs);
  6643. void juce_closeInternetFile (void* handle);
  6644. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6645. int juce_seekInInternetFile (void* handle, int newPosition);
  6646. int64 juce_getInternetFileContentLength (void* handle);
  6647. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6648. class WebInputStream : public InputStream
  6649. {
  6650. public:
  6651. WebInputStream (const URL& url,
  6652. const bool isPost_,
  6653. URL::OpenStreamProgressCallback* const progressCallback_,
  6654. void* const progressCallbackContext_,
  6655. const String& extraHeaders,
  6656. const int timeOutMs_,
  6657. StringPairArray* const responseHeaders)
  6658. : position (0),
  6659. finished (false),
  6660. isPost (isPost_),
  6661. progressCallback (progressCallback_),
  6662. progressCallbackContext (progressCallbackContext_),
  6663. timeOutMs (timeOutMs_)
  6664. {
  6665. server = url.toString (! isPost);
  6666. if (isPost_)
  6667. createHeadersAndPostData (url);
  6668. headers += extraHeaders;
  6669. if (! headers.endsWithChar ('\n'))
  6670. headers << "\r\n";
  6671. handle = juce_openInternetFile (server, headers, postData, isPost,
  6672. progressCallback_, progressCallbackContext_,
  6673. timeOutMs);
  6674. if (responseHeaders != 0)
  6675. juce_getInternetFileHeaders (handle, *responseHeaders);
  6676. }
  6677. ~WebInputStream()
  6678. {
  6679. juce_closeInternetFile (handle);
  6680. }
  6681. bool isError() const { return handle == 0; }
  6682. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6683. bool isExhausted() { return finished; }
  6684. int64 getPosition() { return position; }
  6685. int read (void* dest, int bytes)
  6686. {
  6687. if (finished || isError())
  6688. {
  6689. return 0;
  6690. }
  6691. else
  6692. {
  6693. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6694. position += bytesRead;
  6695. if (bytesRead == 0)
  6696. finished = true;
  6697. return bytesRead;
  6698. }
  6699. }
  6700. bool setPosition (int64 wantedPos)
  6701. {
  6702. if (wantedPos != position)
  6703. {
  6704. finished = false;
  6705. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6706. if (actualPos == wantedPos)
  6707. {
  6708. position = wantedPos;
  6709. }
  6710. else
  6711. {
  6712. if (wantedPos < position)
  6713. {
  6714. juce_closeInternetFile (handle);
  6715. position = 0;
  6716. finished = false;
  6717. handle = juce_openInternetFile (server, headers, postData, isPost,
  6718. progressCallback, progressCallbackContext,
  6719. timeOutMs);
  6720. }
  6721. skipNextBytes (wantedPos - position);
  6722. }
  6723. }
  6724. return true;
  6725. }
  6726. juce_UseDebuggingNewOperator
  6727. private:
  6728. String server, headers;
  6729. MemoryBlock postData;
  6730. int64 position;
  6731. bool finished;
  6732. const bool isPost;
  6733. void* handle;
  6734. URL::OpenStreamProgressCallback* const progressCallback;
  6735. void* const progressCallbackContext;
  6736. const int timeOutMs;
  6737. void createHeadersAndPostData (const URL& url)
  6738. {
  6739. MemoryOutputStream data (postData, false);
  6740. if (url.getFilesToUpload().size() > 0)
  6741. {
  6742. // need to upload some files, so do it as multi-part...
  6743. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6744. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6745. data << "--" << boundary;
  6746. int i;
  6747. for (i = 0; i < url.getParameters().size(); ++i)
  6748. {
  6749. data << "\r\nContent-Disposition: form-data; name=\""
  6750. << url.getParameters().getAllKeys() [i]
  6751. << "\"\r\n\r\n"
  6752. << url.getParameters().getAllValues() [i]
  6753. << "\r\n--"
  6754. << boundary;
  6755. }
  6756. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6757. {
  6758. const File file (url.getFilesToUpload().getAllValues() [i]);
  6759. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6760. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6761. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6762. const String mimeType (url.getMimeTypesOfUploadFiles()
  6763. .getValue (paramName, String::empty));
  6764. if (mimeType.isNotEmpty())
  6765. data << "Content-Type: " << mimeType << "\r\n";
  6766. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6767. << file << "\r\n--" << boundary;
  6768. }
  6769. data << "--\r\n";
  6770. data.flush();
  6771. }
  6772. else
  6773. {
  6774. data << getMangledParameters (url.getParameters())
  6775. << url.getPostData();
  6776. data.flush();
  6777. // just a short text attachment, so use simple url encoding..
  6778. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6779. + String ((unsigned int) postData.getSize())
  6780. + "\r\n";
  6781. }
  6782. }
  6783. WebInputStream (const WebInputStream&);
  6784. WebInputStream& operator= (const WebInputStream&);
  6785. };
  6786. InputStream* URL::createInputStream (const bool usePostCommand,
  6787. OpenStreamProgressCallback* const progressCallback,
  6788. void* const progressCallbackContext,
  6789. const String& extraHeaders,
  6790. const int timeOutMs,
  6791. StringPairArray* const responseHeaders) const
  6792. {
  6793. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6794. progressCallback, progressCallbackContext,
  6795. extraHeaders, timeOutMs, responseHeaders));
  6796. return wi->isError() ? 0 : wi.release();
  6797. }
  6798. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6799. const bool usePostCommand) const
  6800. {
  6801. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6802. if (in != 0)
  6803. {
  6804. in->readIntoMemoryBlock (destData);
  6805. return true;
  6806. }
  6807. return false;
  6808. }
  6809. const String URL::readEntireTextStream (const bool usePostCommand) const
  6810. {
  6811. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6812. if (in != 0)
  6813. return in->readEntireStreamAsString();
  6814. return String::empty;
  6815. }
  6816. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6817. {
  6818. XmlDocument doc (readEntireTextStream (usePostCommand));
  6819. return doc.getDocumentElement();
  6820. }
  6821. const URL URL::withParameter (const String& parameterName,
  6822. const String& parameterValue) const
  6823. {
  6824. URL u (*this);
  6825. u.parameters.set (parameterName, parameterValue);
  6826. return u;
  6827. }
  6828. const URL URL::withFileToUpload (const String& parameterName,
  6829. const File& fileToUpload,
  6830. const String& mimeType) const
  6831. {
  6832. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6833. URL u (*this);
  6834. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6835. u.mimeTypes.set (parameterName, mimeType);
  6836. return u;
  6837. }
  6838. const URL URL::withPOSTData (const String& postData_) const
  6839. {
  6840. URL u (*this);
  6841. u.postData = postData_;
  6842. return u;
  6843. }
  6844. const StringPairArray& URL::getParameters() const
  6845. {
  6846. return parameters;
  6847. }
  6848. const StringPairArray& URL::getFilesToUpload() const
  6849. {
  6850. return filesToUpload;
  6851. }
  6852. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6853. {
  6854. return mimeTypes;
  6855. }
  6856. const String URL::removeEscapeChars (const String& s)
  6857. {
  6858. String result (s.replaceCharacter ('+', ' '));
  6859. int nextPercent = 0;
  6860. for (;;)
  6861. {
  6862. nextPercent = result.indexOfChar (nextPercent, '%');
  6863. if (nextPercent < 0)
  6864. break;
  6865. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6866. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6867. ++nextPercent;
  6868. }
  6869. return result;
  6870. }
  6871. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6872. {
  6873. String result;
  6874. result.preallocateStorage (s.length() + 8);
  6875. const char* utf8 = s.toUTF8();
  6876. const char* legalChars = isParameter ? "_-.*!'()"
  6877. : "_-$.*!'(),";
  6878. while (*utf8 != 0)
  6879. {
  6880. const char c = *utf8++;
  6881. if (CharacterFunctions::isLetterOrDigit (c)
  6882. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6883. {
  6884. result << c;
  6885. }
  6886. else
  6887. {
  6888. const int v = (int) (uint8) c;
  6889. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6890. }
  6891. }
  6892. return result;
  6893. }
  6894. bool URL::launchInDefaultBrowser() const
  6895. {
  6896. String u (toString (true));
  6897. if (u.containsChar ('@') && ! u.containsChar (':'))
  6898. u = "mailto:" + u;
  6899. return PlatformUtilities::openDocument (u, String::empty);
  6900. }
  6901. END_JUCE_NAMESPACE
  6902. /*** End of inlined file: juce_URL.cpp ***/
  6903. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6904. BEGIN_JUCE_NAMESPACE
  6905. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6906. const int bufferSize_,
  6907. const bool deleteSourceWhenDestroyed)
  6908. : source (source_),
  6909. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6910. bufferSize (jmax (256, bufferSize_)),
  6911. position (source_->getPosition()),
  6912. lastReadPos (0),
  6913. bufferOverlap (128)
  6914. {
  6915. const int sourceSize = (int) source_->getTotalLength();
  6916. if (sourceSize >= 0)
  6917. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6918. bufferStart = position;
  6919. buffer.malloc (bufferSize);
  6920. }
  6921. BufferedInputStream::~BufferedInputStream()
  6922. {
  6923. }
  6924. int64 BufferedInputStream::getTotalLength()
  6925. {
  6926. return source->getTotalLength();
  6927. }
  6928. int64 BufferedInputStream::getPosition()
  6929. {
  6930. return position;
  6931. }
  6932. bool BufferedInputStream::setPosition (int64 newPosition)
  6933. {
  6934. position = jmax ((int64) 0, newPosition);
  6935. return true;
  6936. }
  6937. bool BufferedInputStream::isExhausted()
  6938. {
  6939. return (position >= lastReadPos)
  6940. && source->isExhausted();
  6941. }
  6942. void BufferedInputStream::ensureBuffered()
  6943. {
  6944. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6945. if (position < bufferStart || position >= bufferEndOverlap)
  6946. {
  6947. int bytesRead;
  6948. if (position < lastReadPos
  6949. && position >= bufferEndOverlap
  6950. && position >= bufferStart)
  6951. {
  6952. const int bytesToKeep = (int) (lastReadPos - position);
  6953. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6954. bufferStart = position;
  6955. bytesRead = source->read (buffer + bytesToKeep,
  6956. bufferSize - bytesToKeep);
  6957. lastReadPos += bytesRead;
  6958. bytesRead += bytesToKeep;
  6959. }
  6960. else
  6961. {
  6962. bufferStart = position;
  6963. source->setPosition (bufferStart);
  6964. bytesRead = source->read (buffer, bufferSize);
  6965. lastReadPos = bufferStart + bytesRead;
  6966. }
  6967. while (bytesRead < bufferSize)
  6968. buffer [bytesRead++] = 0;
  6969. }
  6970. }
  6971. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6972. {
  6973. if (position >= bufferStart
  6974. && position + maxBytesToRead <= lastReadPos)
  6975. {
  6976. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6977. position += maxBytesToRead;
  6978. return maxBytesToRead;
  6979. }
  6980. else
  6981. {
  6982. if (position < bufferStart || position >= lastReadPos)
  6983. ensureBuffered();
  6984. int bytesRead = 0;
  6985. while (maxBytesToRead > 0)
  6986. {
  6987. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6988. if (bytesAvailable > 0)
  6989. {
  6990. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6991. maxBytesToRead -= bytesAvailable;
  6992. bytesRead += bytesAvailable;
  6993. position += bytesAvailable;
  6994. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6995. }
  6996. const int64 oldLastReadPos = lastReadPos;
  6997. ensureBuffered();
  6998. if (oldLastReadPos == lastReadPos)
  6999. break; // if ensureBuffered() failed to read any more data, bail out
  7000. if (isExhausted())
  7001. break;
  7002. }
  7003. return bytesRead;
  7004. }
  7005. }
  7006. const String BufferedInputStream::readString()
  7007. {
  7008. if (position >= bufferStart
  7009. && position < lastReadPos)
  7010. {
  7011. const int maxChars = (int) (lastReadPos - position);
  7012. const char* const src = buffer + (int) (position - bufferStart);
  7013. for (int i = 0; i < maxChars; ++i)
  7014. {
  7015. if (src[i] == 0)
  7016. {
  7017. position += i + 1;
  7018. return String::fromUTF8 (src, i);
  7019. }
  7020. }
  7021. }
  7022. return InputStream::readString();
  7023. }
  7024. END_JUCE_NAMESPACE
  7025. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7026. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7027. BEGIN_JUCE_NAMESPACE
  7028. FileInputSource::FileInputSource (const File& file_)
  7029. : file (file_)
  7030. {
  7031. }
  7032. FileInputSource::~FileInputSource()
  7033. {
  7034. }
  7035. InputStream* FileInputSource::createInputStream()
  7036. {
  7037. return file.createInputStream();
  7038. }
  7039. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7040. {
  7041. return file.getSiblingFile (relatedItemPath).createInputStream();
  7042. }
  7043. int64 FileInputSource::hashCode() const
  7044. {
  7045. return file.hashCode();
  7046. }
  7047. END_JUCE_NAMESPACE
  7048. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7049. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7050. BEGIN_JUCE_NAMESPACE
  7051. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7052. const size_t sourceDataSize,
  7053. const bool keepInternalCopy)
  7054. : data (static_cast <const char*> (sourceData)),
  7055. dataSize (sourceDataSize),
  7056. position (0)
  7057. {
  7058. if (keepInternalCopy)
  7059. {
  7060. internalCopy.append (data, sourceDataSize);
  7061. data = static_cast <const char*> (internalCopy.getData());
  7062. }
  7063. }
  7064. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7065. const bool keepInternalCopy)
  7066. : data (static_cast <const char*> (sourceData.getData())),
  7067. dataSize (sourceData.getSize()),
  7068. position (0)
  7069. {
  7070. if (keepInternalCopy)
  7071. {
  7072. internalCopy = sourceData;
  7073. data = static_cast <const char*> (internalCopy.getData());
  7074. }
  7075. }
  7076. MemoryInputStream::~MemoryInputStream()
  7077. {
  7078. }
  7079. int64 MemoryInputStream::getTotalLength()
  7080. {
  7081. return dataSize;
  7082. }
  7083. int MemoryInputStream::read (void* const buffer, const int howMany)
  7084. {
  7085. jassert (howMany >= 0);
  7086. const int num = jmin (howMany, (int) (dataSize - position));
  7087. memcpy (buffer, data + position, num);
  7088. position += num;
  7089. return (int) num;
  7090. }
  7091. bool MemoryInputStream::isExhausted()
  7092. {
  7093. return (position >= dataSize);
  7094. }
  7095. bool MemoryInputStream::setPosition (const int64 pos)
  7096. {
  7097. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7098. return true;
  7099. }
  7100. int64 MemoryInputStream::getPosition()
  7101. {
  7102. return position;
  7103. }
  7104. END_JUCE_NAMESPACE
  7105. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7106. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7107. BEGIN_JUCE_NAMESPACE
  7108. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7109. : data (internalBlock),
  7110. position (0),
  7111. size (0)
  7112. {
  7113. internalBlock.setSize (initialSize, false);
  7114. }
  7115. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7116. const bool appendToExistingBlockContent)
  7117. : data (memoryBlockToWriteTo),
  7118. position (0),
  7119. size (0)
  7120. {
  7121. if (appendToExistingBlockContent)
  7122. position = size = memoryBlockToWriteTo.getSize();
  7123. }
  7124. MemoryOutputStream::~MemoryOutputStream()
  7125. {
  7126. flush();
  7127. }
  7128. void MemoryOutputStream::flush()
  7129. {
  7130. if (&data != &internalBlock)
  7131. data.setSize (size, false);
  7132. }
  7133. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7134. {
  7135. data.ensureSize (bytesToPreallocate + 1);
  7136. }
  7137. void MemoryOutputStream::reset() throw()
  7138. {
  7139. position = 0;
  7140. size = 0;
  7141. }
  7142. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7143. {
  7144. if (howMany > 0)
  7145. {
  7146. const size_t storageNeeded = position + howMany;
  7147. if (storageNeeded >= data.getSize())
  7148. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7149. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7150. position += howMany;
  7151. size = jmax (size, position);
  7152. }
  7153. return true;
  7154. }
  7155. const void* MemoryOutputStream::getData() const throw()
  7156. {
  7157. void* const d = data.getData();
  7158. if (data.getSize() > size)
  7159. static_cast <char*> (d) [size] = 0;
  7160. return d;
  7161. }
  7162. bool MemoryOutputStream::setPosition (int64 newPosition)
  7163. {
  7164. if (newPosition <= (int64) size)
  7165. {
  7166. // ok to seek backwards
  7167. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7168. return true;
  7169. }
  7170. else
  7171. {
  7172. // trying to make it bigger isn't a good thing to do..
  7173. return false;
  7174. }
  7175. }
  7176. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  7177. {
  7178. // before writing from an input, see if we can preallocate to make it more efficient..
  7179. int64 availableData = source.getTotalLength() - source.getPosition();
  7180. if (availableData > 0)
  7181. {
  7182. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  7183. availableData = maxNumBytesToWrite;
  7184. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  7185. }
  7186. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  7187. }
  7188. const String MemoryOutputStream::toUTF8() const
  7189. {
  7190. return String (static_cast <const char*> (getData()), getDataSize());
  7191. }
  7192. const String MemoryOutputStream::toString() const
  7193. {
  7194. return String::createStringFromData (getData(), getDataSize());
  7195. }
  7196. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  7197. {
  7198. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  7199. return stream;
  7200. }
  7201. END_JUCE_NAMESPACE
  7202. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7203. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7204. BEGIN_JUCE_NAMESPACE
  7205. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7206. const int64 startPositionInSourceStream_,
  7207. const int64 lengthOfSourceStream_,
  7208. const bool deleteSourceWhenDestroyed)
  7209. : source (sourceStream),
  7210. startPositionInSourceStream (startPositionInSourceStream_),
  7211. lengthOfSourceStream (lengthOfSourceStream_)
  7212. {
  7213. if (deleteSourceWhenDestroyed)
  7214. sourceToDelete = source;
  7215. setPosition (0);
  7216. }
  7217. SubregionStream::~SubregionStream()
  7218. {
  7219. }
  7220. int64 SubregionStream::getTotalLength()
  7221. {
  7222. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7223. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7224. : srcLen;
  7225. }
  7226. int64 SubregionStream::getPosition()
  7227. {
  7228. return source->getPosition() - startPositionInSourceStream;
  7229. }
  7230. bool SubregionStream::setPosition (int64 newPosition)
  7231. {
  7232. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7233. }
  7234. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7235. {
  7236. if (lengthOfSourceStream < 0)
  7237. {
  7238. return source->read (destBuffer, maxBytesToRead);
  7239. }
  7240. else
  7241. {
  7242. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7243. if (maxBytesToRead <= 0)
  7244. return 0;
  7245. return source->read (destBuffer, maxBytesToRead);
  7246. }
  7247. }
  7248. bool SubregionStream::isExhausted()
  7249. {
  7250. if (lengthOfSourceStream >= 0)
  7251. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7252. else
  7253. return source->isExhausted();
  7254. }
  7255. END_JUCE_NAMESPACE
  7256. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7257. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7258. BEGIN_JUCE_NAMESPACE
  7259. PerformanceCounter::PerformanceCounter (const String& name_,
  7260. int runsPerPrintout,
  7261. const File& loggingFile)
  7262. : name (name_),
  7263. numRuns (0),
  7264. runsPerPrint (runsPerPrintout),
  7265. totalTime (0),
  7266. outputFile (loggingFile)
  7267. {
  7268. if (outputFile != File::nonexistent)
  7269. {
  7270. String s ("**** Counter for \"");
  7271. s << name_ << "\" started at: "
  7272. << Time::getCurrentTime().toString (true, true)
  7273. << "\r\n";
  7274. outputFile.appendText (s, false, false);
  7275. }
  7276. }
  7277. PerformanceCounter::~PerformanceCounter()
  7278. {
  7279. printStatistics();
  7280. }
  7281. void PerformanceCounter::start()
  7282. {
  7283. started = Time::getHighResolutionTicks();
  7284. }
  7285. void PerformanceCounter::stop()
  7286. {
  7287. const int64 now = Time::getHighResolutionTicks();
  7288. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7289. if (++numRuns == runsPerPrint)
  7290. printStatistics();
  7291. }
  7292. void PerformanceCounter::printStatistics()
  7293. {
  7294. if (numRuns > 0)
  7295. {
  7296. String s ("Performance count for \"");
  7297. s << name << "\" - average over " << numRuns << " run(s) = ";
  7298. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7299. if (micros > 10000)
  7300. s << (micros/1000) << " millisecs";
  7301. else
  7302. s << micros << " microsecs";
  7303. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7304. Logger::outputDebugString (s);
  7305. s << "\r\n";
  7306. if (outputFile != File::nonexistent)
  7307. outputFile.appendText (s, false, false);
  7308. numRuns = 0;
  7309. totalTime = 0;
  7310. }
  7311. }
  7312. END_JUCE_NAMESPACE
  7313. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7314. /*** Start of inlined file: juce_Uuid.cpp ***/
  7315. BEGIN_JUCE_NAMESPACE
  7316. Uuid::Uuid()
  7317. {
  7318. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7319. // to make it very very unlikely that two UUIDs will ever be the same..
  7320. static int64 macAddresses[2];
  7321. static bool hasCheckedMacAddresses = false;
  7322. if (! hasCheckedMacAddresses)
  7323. {
  7324. hasCheckedMacAddresses = true;
  7325. SystemStats::getMACAddresses (macAddresses, 2);
  7326. }
  7327. value.asInt64[0] = macAddresses[0];
  7328. value.asInt64[1] = macAddresses[1];
  7329. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7330. // whose seed will carry over between calls to this method.
  7331. Random r (macAddresses[0] ^ macAddresses[1]
  7332. ^ Random::getSystemRandom().nextInt64());
  7333. for (int i = 4; --i >= 0;)
  7334. {
  7335. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7336. value.asInt[i] ^= r.nextInt();
  7337. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7338. }
  7339. }
  7340. Uuid::~Uuid() throw()
  7341. {
  7342. }
  7343. Uuid::Uuid (const Uuid& other)
  7344. : value (other.value)
  7345. {
  7346. }
  7347. Uuid& Uuid::operator= (const Uuid& other)
  7348. {
  7349. value = other.value;
  7350. return *this;
  7351. }
  7352. bool Uuid::operator== (const Uuid& other) const
  7353. {
  7354. return value.asInt64[0] == other.value.asInt64[0]
  7355. && value.asInt64[1] == other.value.asInt64[1];
  7356. }
  7357. bool Uuid::operator!= (const Uuid& other) const
  7358. {
  7359. return ! operator== (other);
  7360. }
  7361. bool Uuid::isNull() const throw()
  7362. {
  7363. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7364. }
  7365. const String Uuid::toString() const
  7366. {
  7367. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7368. }
  7369. Uuid::Uuid (const String& uuidString)
  7370. {
  7371. operator= (uuidString);
  7372. }
  7373. Uuid& Uuid::operator= (const String& uuidString)
  7374. {
  7375. MemoryBlock mb;
  7376. mb.loadFromHexString (uuidString);
  7377. mb.ensureSize (sizeof (value.asBytes), true);
  7378. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7379. return *this;
  7380. }
  7381. Uuid::Uuid (const uint8* const rawData)
  7382. {
  7383. operator= (rawData);
  7384. }
  7385. Uuid& Uuid::operator= (const uint8* const rawData)
  7386. {
  7387. if (rawData != 0)
  7388. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7389. else
  7390. zeromem (value.asBytes, sizeof (value.asBytes));
  7391. return *this;
  7392. }
  7393. END_JUCE_NAMESPACE
  7394. /*** End of inlined file: juce_Uuid.cpp ***/
  7395. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7396. BEGIN_JUCE_NAMESPACE
  7397. class ZipFile::ZipEntryInfo
  7398. {
  7399. public:
  7400. ZipFile::ZipEntry entry;
  7401. int streamOffset;
  7402. int compressedSize;
  7403. bool compressed;
  7404. };
  7405. class ZipFile::ZipInputStream : public InputStream
  7406. {
  7407. public:
  7408. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7409. : file (file_),
  7410. zipEntryInfo (zei),
  7411. pos (0),
  7412. headerSize (0),
  7413. inputStream (0)
  7414. {
  7415. inputStream = file_.inputStream;
  7416. if (file_.inputSource != 0)
  7417. {
  7418. inputStream = file.inputSource->createInputStream();
  7419. }
  7420. else
  7421. {
  7422. #if JUCE_DEBUG
  7423. file_.numOpenStreams++;
  7424. #endif
  7425. }
  7426. char buffer [30];
  7427. if (inputStream != 0
  7428. && inputStream->setPosition (zei.streamOffset)
  7429. && inputStream->read (buffer, 30) == 30
  7430. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7431. {
  7432. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7433. + ByteOrder::littleEndianShort (buffer + 28);
  7434. }
  7435. }
  7436. ~ZipInputStream()
  7437. {
  7438. #if JUCE_DEBUG
  7439. if (inputStream != 0 && inputStream == file.inputStream)
  7440. file.numOpenStreams--;
  7441. #endif
  7442. if (inputStream != file.inputStream)
  7443. delete inputStream;
  7444. }
  7445. int64 getTotalLength()
  7446. {
  7447. return zipEntryInfo.compressedSize;
  7448. }
  7449. int read (void* buffer, int howMany)
  7450. {
  7451. if (headerSize <= 0)
  7452. return 0;
  7453. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7454. if (inputStream == 0)
  7455. return 0;
  7456. int num;
  7457. if (inputStream == file.inputStream)
  7458. {
  7459. const ScopedLock sl (file.lock);
  7460. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7461. num = inputStream->read (buffer, howMany);
  7462. }
  7463. else
  7464. {
  7465. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7466. num = inputStream->read (buffer, howMany);
  7467. }
  7468. pos += num;
  7469. return num;
  7470. }
  7471. bool isExhausted()
  7472. {
  7473. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7474. }
  7475. int64 getPosition()
  7476. {
  7477. return pos;
  7478. }
  7479. bool setPosition (int64 newPos)
  7480. {
  7481. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7482. return true;
  7483. }
  7484. private:
  7485. ZipFile& file;
  7486. ZipEntryInfo zipEntryInfo;
  7487. int64 pos;
  7488. int headerSize;
  7489. InputStream* inputStream;
  7490. ZipInputStream (const ZipInputStream&);
  7491. ZipInputStream& operator= (const ZipInputStream&);
  7492. };
  7493. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  7494. : inputStream (source_)
  7495. #if JUCE_DEBUG
  7496. , numOpenStreams (0)
  7497. #endif
  7498. {
  7499. if (deleteStreamWhenDestroyed)
  7500. streamToDelete = inputStream;
  7501. init();
  7502. }
  7503. ZipFile::ZipFile (const File& file)
  7504. : inputStream (0)
  7505. #if JUCE_DEBUG
  7506. , numOpenStreams (0)
  7507. #endif
  7508. {
  7509. inputSource = new FileInputSource (file);
  7510. init();
  7511. }
  7512. ZipFile::ZipFile (InputSource* const inputSource_)
  7513. : inputStream (0),
  7514. inputSource (inputSource_)
  7515. #if JUCE_DEBUG
  7516. , numOpenStreams (0)
  7517. #endif
  7518. {
  7519. init();
  7520. }
  7521. ZipFile::~ZipFile()
  7522. {
  7523. #if JUCE_DEBUG
  7524. entries.clear();
  7525. // If you hit this assertion, it means you've created a stream to read
  7526. // one of the items in the zipfile, but you've forgotten to delete that
  7527. // stream object before deleting the file.. Streams can't be kept open
  7528. // after the file is deleted because they need to share the input
  7529. // stream that the file uses to read itself.
  7530. jassert (numOpenStreams == 0);
  7531. #endif
  7532. }
  7533. int ZipFile::getNumEntries() const throw()
  7534. {
  7535. return entries.size();
  7536. }
  7537. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7538. {
  7539. ZipEntryInfo* const zei = entries [index];
  7540. return zei != 0 ? &(zei->entry) : 0;
  7541. }
  7542. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7543. {
  7544. for (int i = 0; i < entries.size(); ++i)
  7545. if (entries.getUnchecked (i)->entry.filename == fileName)
  7546. return i;
  7547. return -1;
  7548. }
  7549. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7550. {
  7551. return getEntry (getIndexOfFileName (fileName));
  7552. }
  7553. InputStream* ZipFile::createStreamForEntry (const int index)
  7554. {
  7555. ZipEntryInfo* const zei = entries[index];
  7556. InputStream* stream = 0;
  7557. if (zei != 0)
  7558. {
  7559. stream = new ZipInputStream (*this, *zei);
  7560. if (zei->compressed)
  7561. {
  7562. stream = new GZIPDecompressorInputStream (stream, true, true,
  7563. zei->entry.uncompressedSize);
  7564. // (much faster to unzip in big blocks using a buffer..)
  7565. stream = new BufferedInputStream (stream, 32768, true);
  7566. }
  7567. }
  7568. return stream;
  7569. }
  7570. class ZipFile::ZipFilenameComparator
  7571. {
  7572. public:
  7573. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7574. {
  7575. return first->entry.filename.compare (second->entry.filename);
  7576. }
  7577. };
  7578. void ZipFile::sortEntriesByFilename()
  7579. {
  7580. ZipFilenameComparator sorter;
  7581. entries.sort (sorter);
  7582. }
  7583. void ZipFile::init()
  7584. {
  7585. ScopedPointer <InputStream> toDelete;
  7586. InputStream* in = inputStream;
  7587. if (inputSource != 0)
  7588. {
  7589. in = inputSource->createInputStream();
  7590. toDelete = in;
  7591. }
  7592. if (in != 0)
  7593. {
  7594. int numEntries = 0;
  7595. int pos = findEndOfZipEntryTable (in, numEntries);
  7596. if (pos >= 0 && pos < in->getTotalLength())
  7597. {
  7598. const int size = (int) (in->getTotalLength() - pos);
  7599. in->setPosition (pos);
  7600. MemoryBlock headerData;
  7601. if (in->readIntoMemoryBlock (headerData, size) == size)
  7602. {
  7603. pos = 0;
  7604. for (int i = 0; i < numEntries; ++i)
  7605. {
  7606. if (pos + 46 > size)
  7607. break;
  7608. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7609. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7610. if (pos + 46 + fileNameLen > size)
  7611. break;
  7612. ZipEntryInfo* const zei = new ZipEntryInfo();
  7613. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7614. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7615. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7616. const int year = 1980 + (date >> 9);
  7617. const int month = ((date >> 5) & 15) - 1;
  7618. const int day = date & 31;
  7619. const int hours = time >> 11;
  7620. const int minutes = (time >> 5) & 63;
  7621. const int seconds = (time & 31) << 1;
  7622. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7623. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7624. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7625. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7626. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7627. entries.add (zei);
  7628. pos += 46 + fileNameLen
  7629. + ByteOrder::littleEndianShort (buffer + 30)
  7630. + ByteOrder::littleEndianShort (buffer + 32);
  7631. }
  7632. }
  7633. }
  7634. }
  7635. }
  7636. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7637. {
  7638. BufferedInputStream in (input, 8192, false);
  7639. in.setPosition (in.getTotalLength());
  7640. int64 pos = in.getPosition();
  7641. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7642. char buffer [32];
  7643. zeromem (buffer, sizeof (buffer));
  7644. while (pos > lowestPos)
  7645. {
  7646. in.setPosition (pos - 22);
  7647. pos = in.getPosition();
  7648. memcpy (buffer + 22, buffer, 4);
  7649. if (in.read (buffer, 22) != 22)
  7650. return 0;
  7651. for (int i = 0; i < 22; ++i)
  7652. {
  7653. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7654. {
  7655. in.setPosition (pos + i);
  7656. in.read (buffer, 22);
  7657. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7658. return ByteOrder::littleEndianInt (buffer + 16);
  7659. }
  7660. }
  7661. }
  7662. return 0;
  7663. }
  7664. void ZipFile::uncompressTo (const File& targetDirectory,
  7665. const bool shouldOverwriteFiles)
  7666. {
  7667. for (int i = 0; i < entries.size(); ++i)
  7668. {
  7669. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7670. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7671. if (zei.filename.endsWithChar ('/'))
  7672. {
  7673. targetFile.createDirectory(); // (entry is a directory, not a file)
  7674. }
  7675. else
  7676. {
  7677. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7678. if (in != 0)
  7679. {
  7680. if (shouldOverwriteFiles)
  7681. targetFile.deleteFile();
  7682. if ((! targetFile.exists())
  7683. && targetFile.getParentDirectory().createDirectory())
  7684. {
  7685. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7686. if (out != 0)
  7687. {
  7688. out->writeFromInputStream (*in, -1);
  7689. out = 0;
  7690. targetFile.setCreationTime (zei.fileTime);
  7691. targetFile.setLastModificationTime (zei.fileTime);
  7692. targetFile.setLastAccessTime (zei.fileTime);
  7693. }
  7694. }
  7695. }
  7696. }
  7697. }
  7698. }
  7699. END_JUCE_NAMESPACE
  7700. /*** End of inlined file: juce_ZipFile.cpp ***/
  7701. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7702. #if JUCE_MSVC
  7703. #pragma warning (push)
  7704. #pragma warning (disable: 4514 4996)
  7705. #endif
  7706. #include <cwctype>
  7707. #include <cctype>
  7708. #include <ctime>
  7709. BEGIN_JUCE_NAMESPACE
  7710. int CharacterFunctions::length (const char* const s) throw()
  7711. {
  7712. return (int) strlen (s);
  7713. }
  7714. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7715. {
  7716. return (int) wcslen (s);
  7717. }
  7718. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7719. {
  7720. strncpy (dest, src, maxChars);
  7721. }
  7722. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7723. {
  7724. wcsncpy (dest, src, maxChars);
  7725. }
  7726. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7727. {
  7728. mbstowcs (dest, src, maxChars);
  7729. }
  7730. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7731. {
  7732. wcstombs (dest, src, maxChars);
  7733. }
  7734. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7735. {
  7736. return (int) wcstombs (0, src, 0);
  7737. }
  7738. void CharacterFunctions::append (char* dest, const char* src) throw()
  7739. {
  7740. strcat (dest, src);
  7741. }
  7742. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7743. {
  7744. wcscat (dest, src);
  7745. }
  7746. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7747. {
  7748. return strcmp (s1, s2);
  7749. }
  7750. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7751. {
  7752. jassert (s1 != 0 && s2 != 0);
  7753. return wcscmp (s1, s2);
  7754. }
  7755. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7756. {
  7757. jassert (s1 != 0 && s2 != 0);
  7758. return strncmp (s1, s2, maxChars);
  7759. }
  7760. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7761. {
  7762. jassert (s1 != 0 && s2 != 0);
  7763. return wcsncmp (s1, s2, maxChars);
  7764. }
  7765. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7766. {
  7767. jassert (s1 != 0 && s2 != 0);
  7768. for (;;)
  7769. {
  7770. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7771. if (diff != 0)
  7772. return diff;
  7773. else if (*s1 == 0)
  7774. break;
  7775. ++s1;
  7776. ++s2;
  7777. }
  7778. return 0;
  7779. }
  7780. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7781. {
  7782. return -compare (s2, s1);
  7783. }
  7784. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7785. {
  7786. jassert (s1 != 0 && s2 != 0);
  7787. #if JUCE_WINDOWS
  7788. return stricmp (s1, s2);
  7789. #else
  7790. return strcasecmp (s1, s2);
  7791. #endif
  7792. }
  7793. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7794. {
  7795. jassert (s1 != 0 && s2 != 0);
  7796. #if JUCE_WINDOWS
  7797. return _wcsicmp (s1, s2);
  7798. #else
  7799. for (;;)
  7800. {
  7801. if (*s1 != *s2)
  7802. {
  7803. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7804. if (diff != 0)
  7805. return diff < 0 ? -1 : 1;
  7806. }
  7807. else if (*s1 == 0)
  7808. break;
  7809. ++s1;
  7810. ++s2;
  7811. }
  7812. return 0;
  7813. #endif
  7814. }
  7815. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7816. {
  7817. jassert (s1 != 0 && s2 != 0);
  7818. for (;;)
  7819. {
  7820. if (*s1 != *s2)
  7821. {
  7822. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7823. if (diff != 0)
  7824. return diff < 0 ? -1 : 1;
  7825. }
  7826. else if (*s1 == 0)
  7827. break;
  7828. ++s1;
  7829. ++s2;
  7830. }
  7831. return 0;
  7832. }
  7833. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7834. {
  7835. jassert (s1 != 0 && s2 != 0);
  7836. #if JUCE_WINDOWS
  7837. return strnicmp (s1, s2, maxChars);
  7838. #else
  7839. return strncasecmp (s1, s2, maxChars);
  7840. #endif
  7841. }
  7842. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7843. {
  7844. jassert (s1 != 0 && s2 != 0);
  7845. #if JUCE_WINDOWS
  7846. return _wcsnicmp (s1, s2, maxChars);
  7847. #else
  7848. while (--maxChars >= 0)
  7849. {
  7850. if (*s1 != *s2)
  7851. {
  7852. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7853. if (diff != 0)
  7854. return diff < 0 ? -1 : 1;
  7855. }
  7856. else if (*s1 == 0)
  7857. break;
  7858. ++s1;
  7859. ++s2;
  7860. }
  7861. return 0;
  7862. #endif
  7863. }
  7864. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7865. {
  7866. return strstr (haystack, needle);
  7867. }
  7868. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7869. {
  7870. return wcsstr (haystack, needle);
  7871. }
  7872. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7873. {
  7874. if (haystack != 0)
  7875. {
  7876. int i = 0;
  7877. if (ignoreCase)
  7878. {
  7879. const char n1 = toLowerCase (needle);
  7880. const char n2 = toUpperCase (needle);
  7881. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7882. {
  7883. while (haystack[i] != 0)
  7884. {
  7885. if (haystack[i] == n1 || haystack[i] == n2)
  7886. return i;
  7887. ++i;
  7888. }
  7889. return -1;
  7890. }
  7891. jassert (n1 == needle);
  7892. }
  7893. while (haystack[i] != 0)
  7894. {
  7895. if (haystack[i] == needle)
  7896. return i;
  7897. ++i;
  7898. }
  7899. }
  7900. return -1;
  7901. }
  7902. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7903. {
  7904. if (haystack != 0)
  7905. {
  7906. int i = 0;
  7907. if (ignoreCase)
  7908. {
  7909. const juce_wchar n1 = toLowerCase (needle);
  7910. const juce_wchar n2 = toUpperCase (needle);
  7911. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7912. {
  7913. while (haystack[i] != 0)
  7914. {
  7915. if (haystack[i] == n1 || haystack[i] == n2)
  7916. return i;
  7917. ++i;
  7918. }
  7919. return -1;
  7920. }
  7921. jassert (n1 == needle);
  7922. }
  7923. while (haystack[i] != 0)
  7924. {
  7925. if (haystack[i] == needle)
  7926. return i;
  7927. ++i;
  7928. }
  7929. }
  7930. return -1;
  7931. }
  7932. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7933. {
  7934. jassert (haystack != 0);
  7935. int i = 0;
  7936. while (haystack[i] != 0)
  7937. {
  7938. if (haystack[i] == needle)
  7939. return i;
  7940. ++i;
  7941. }
  7942. return -1;
  7943. }
  7944. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7945. {
  7946. jassert (haystack != 0);
  7947. int i = 0;
  7948. while (haystack[i] != 0)
  7949. {
  7950. if (haystack[i] == needle)
  7951. return i;
  7952. ++i;
  7953. }
  7954. return -1;
  7955. }
  7956. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7957. {
  7958. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7959. }
  7960. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7961. {
  7962. if (allowedChars == 0)
  7963. return 0;
  7964. int i = 0;
  7965. for (;;)
  7966. {
  7967. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7968. break;
  7969. ++i;
  7970. }
  7971. return i;
  7972. }
  7973. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7974. {
  7975. return (int) strftime (dest, maxChars, format, tm);
  7976. }
  7977. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7978. {
  7979. return (int) wcsftime (dest, maxChars, format, tm);
  7980. }
  7981. int CharacterFunctions::getIntValue (const char* const s) throw()
  7982. {
  7983. return atoi (s);
  7984. }
  7985. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7986. {
  7987. #if JUCE_WINDOWS
  7988. return _wtoi (s);
  7989. #else
  7990. int v = 0;
  7991. while (isWhitespace (*s))
  7992. ++s;
  7993. const bool isNeg = *s == '-';
  7994. if (isNeg)
  7995. ++s;
  7996. for (;;)
  7997. {
  7998. const wchar_t c = *s++;
  7999. if (c >= '0' && c <= '9')
  8000. v = v * 10 + (int) (c - '0');
  8001. else
  8002. break;
  8003. }
  8004. return isNeg ? -v : v;
  8005. #endif
  8006. }
  8007. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8008. {
  8009. #if JUCE_LINUX
  8010. return atoll (s);
  8011. #elif JUCE_WINDOWS
  8012. return _atoi64 (s);
  8013. #else
  8014. int64 v = 0;
  8015. while (isWhitespace (*s))
  8016. ++s;
  8017. const bool isNeg = *s == '-';
  8018. if (isNeg)
  8019. ++s;
  8020. for (;;)
  8021. {
  8022. const char c = *s++;
  8023. if (c >= '0' && c <= '9')
  8024. v = v * 10 + (int64) (c - '0');
  8025. else
  8026. break;
  8027. }
  8028. return isNeg ? -v : v;
  8029. #endif
  8030. }
  8031. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8032. {
  8033. #if JUCE_WINDOWS
  8034. return _wtoi64 (s);
  8035. #else
  8036. int64 v = 0;
  8037. while (isWhitespace (*s))
  8038. ++s;
  8039. const bool isNeg = *s == '-';
  8040. if (isNeg)
  8041. ++s;
  8042. for (;;)
  8043. {
  8044. const juce_wchar c = *s++;
  8045. if (c >= '0' && c <= '9')
  8046. v = v * 10 + (int64) (c - '0');
  8047. else
  8048. break;
  8049. }
  8050. return isNeg ? -v : v;
  8051. #endif
  8052. }
  8053. static double juce_mulexp10 (const double value, int exponent) throw()
  8054. {
  8055. if (exponent == 0)
  8056. return value;
  8057. if (value == 0)
  8058. return 0;
  8059. const bool negative = (exponent < 0);
  8060. if (negative)
  8061. exponent = -exponent;
  8062. double result = 1.0, power = 10.0;
  8063. for (int bit = 1; exponent != 0; bit <<= 1)
  8064. {
  8065. if ((exponent & bit) != 0)
  8066. {
  8067. exponent ^= bit;
  8068. result *= power;
  8069. if (exponent == 0)
  8070. break;
  8071. }
  8072. power *= power;
  8073. }
  8074. return negative ? (value / result) : (value * result);
  8075. }
  8076. template <class CharType>
  8077. double juce_atof (const CharType* const original) throw()
  8078. {
  8079. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8080. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8081. int exponent = 0, decPointIndex = 0, digit = 0;
  8082. int lastDigit = 0, numSignificantDigits = 0;
  8083. bool isNegative = false, digitsFound = false;
  8084. const int maxSignificantDigits = 15 + 2;
  8085. const CharType* s = original;
  8086. while (CharacterFunctions::isWhitespace (*s))
  8087. ++s;
  8088. switch (*s)
  8089. {
  8090. case '-': isNegative = true; // fall-through..
  8091. case '+': ++s;
  8092. }
  8093. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8094. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8095. for (;;)
  8096. {
  8097. if (CharacterFunctions::isDigit (*s))
  8098. {
  8099. lastDigit = digit;
  8100. digit = *s++ - '0';
  8101. digitsFound = true;
  8102. if (decPointIndex != 0)
  8103. exponentAdjustment[1]++;
  8104. if (numSignificantDigits == 0 && digit == 0)
  8105. continue;
  8106. if (++numSignificantDigits > maxSignificantDigits)
  8107. {
  8108. if (digit > 5)
  8109. ++accumulator [decPointIndex];
  8110. else if (digit == 5 && (lastDigit & 1) != 0)
  8111. ++accumulator [decPointIndex];
  8112. if (decPointIndex > 0)
  8113. exponentAdjustment[1]--;
  8114. else
  8115. exponentAdjustment[0]++;
  8116. while (CharacterFunctions::isDigit (*s))
  8117. {
  8118. ++s;
  8119. if (decPointIndex == 0)
  8120. exponentAdjustment[0]++;
  8121. }
  8122. }
  8123. else
  8124. {
  8125. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8126. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8127. {
  8128. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8129. + accumulator [decPointIndex];
  8130. accumulator [decPointIndex] = 0;
  8131. exponentAccumulator [decPointIndex] = 0;
  8132. }
  8133. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8134. exponentAccumulator [decPointIndex]++;
  8135. }
  8136. }
  8137. else if (decPointIndex == 0 && *s == '.')
  8138. {
  8139. ++s;
  8140. decPointIndex = 1;
  8141. if (numSignificantDigits > maxSignificantDigits)
  8142. {
  8143. while (CharacterFunctions::isDigit (*s))
  8144. ++s;
  8145. break;
  8146. }
  8147. }
  8148. else
  8149. {
  8150. break;
  8151. }
  8152. }
  8153. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8154. if (decPointIndex != 0)
  8155. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8156. if ((*s == 'e' || *s == 'E') && digitsFound)
  8157. {
  8158. bool negativeExponent = false;
  8159. switch (*++s)
  8160. {
  8161. case '-': negativeExponent = true; // fall-through..
  8162. case '+': ++s;
  8163. }
  8164. while (CharacterFunctions::isDigit (*s))
  8165. exponent = (exponent * 10) + (*s++ - '0');
  8166. if (negativeExponent)
  8167. exponent = -exponent;
  8168. }
  8169. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8170. if (decPointIndex != 0)
  8171. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8172. return isNegative ? -r : r;
  8173. }
  8174. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8175. {
  8176. return juce_atof <char> (s);
  8177. }
  8178. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8179. {
  8180. return juce_atof <juce_wchar> (s);
  8181. }
  8182. char CharacterFunctions::toUpperCase (const char character) throw()
  8183. {
  8184. return (char) toupper (character);
  8185. }
  8186. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8187. {
  8188. return towupper (character);
  8189. }
  8190. void CharacterFunctions::toUpperCase (char* s) throw()
  8191. {
  8192. #if JUCE_WINDOWS
  8193. strupr (s);
  8194. #else
  8195. while (*s != 0)
  8196. {
  8197. *s = toUpperCase (*s);
  8198. ++s;
  8199. }
  8200. #endif
  8201. }
  8202. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8203. {
  8204. #if JUCE_WINDOWS
  8205. _wcsupr (s);
  8206. #else
  8207. while (*s != 0)
  8208. {
  8209. *s = toUpperCase (*s);
  8210. ++s;
  8211. }
  8212. #endif
  8213. }
  8214. bool CharacterFunctions::isUpperCase (const char character) throw()
  8215. {
  8216. return isupper (character) != 0;
  8217. }
  8218. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8219. {
  8220. #if JUCE_WINDOWS
  8221. return iswupper (character) != 0;
  8222. #else
  8223. return toLowerCase (character) != character;
  8224. #endif
  8225. }
  8226. char CharacterFunctions::toLowerCase (const char character) throw()
  8227. {
  8228. return (char) tolower (character);
  8229. }
  8230. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8231. {
  8232. return towlower (character);
  8233. }
  8234. void CharacterFunctions::toLowerCase (char* s) throw()
  8235. {
  8236. #if JUCE_WINDOWS
  8237. strlwr (s);
  8238. #else
  8239. while (*s != 0)
  8240. {
  8241. *s = toLowerCase (*s);
  8242. ++s;
  8243. }
  8244. #endif
  8245. }
  8246. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8247. {
  8248. #if JUCE_WINDOWS
  8249. _wcslwr (s);
  8250. #else
  8251. while (*s != 0)
  8252. {
  8253. *s = toLowerCase (*s);
  8254. ++s;
  8255. }
  8256. #endif
  8257. }
  8258. bool CharacterFunctions::isLowerCase (const char character) throw()
  8259. {
  8260. return islower (character) != 0;
  8261. }
  8262. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8263. {
  8264. #if JUCE_WINDOWS
  8265. return iswlower (character) != 0;
  8266. #else
  8267. return toUpperCase (character) != character;
  8268. #endif
  8269. }
  8270. bool CharacterFunctions::isWhitespace (const char character) throw()
  8271. {
  8272. return character == ' ' || (character <= 13 && character >= 9);
  8273. }
  8274. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8275. {
  8276. return iswspace (character) != 0;
  8277. }
  8278. bool CharacterFunctions::isDigit (const char character) throw()
  8279. {
  8280. return (character >= '0' && character <= '9');
  8281. }
  8282. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8283. {
  8284. return iswdigit (character) != 0;
  8285. }
  8286. bool CharacterFunctions::isLetter (const char character) throw()
  8287. {
  8288. return (character >= 'a' && character <= 'z')
  8289. || (character >= 'A' && character <= 'Z');
  8290. }
  8291. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8292. {
  8293. return iswalpha (character) != 0;
  8294. }
  8295. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8296. {
  8297. return (character >= 'a' && character <= 'z')
  8298. || (character >= 'A' && character <= 'Z')
  8299. || (character >= '0' && character <= '9');
  8300. }
  8301. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8302. {
  8303. return iswalnum (character) != 0;
  8304. }
  8305. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8306. {
  8307. unsigned int d = digit - '0';
  8308. if (d < (unsigned int) 10)
  8309. return (int) d;
  8310. d += (unsigned int) ('0' - 'a');
  8311. if (d < (unsigned int) 6)
  8312. return (int) d + 10;
  8313. d += (unsigned int) ('a' - 'A');
  8314. if (d < (unsigned int) 6)
  8315. return (int) d + 10;
  8316. return -1;
  8317. }
  8318. #if JUCE_MSVC
  8319. #pragma warning (pop)
  8320. #endif
  8321. END_JUCE_NAMESPACE
  8322. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8323. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8324. BEGIN_JUCE_NAMESPACE
  8325. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8326. {
  8327. loadFromText (fileContents);
  8328. }
  8329. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8330. {
  8331. loadFromText (fileToLoad.loadFileAsString());
  8332. }
  8333. LocalisedStrings::~LocalisedStrings()
  8334. {
  8335. }
  8336. const String LocalisedStrings::translate (const String& text) const
  8337. {
  8338. return translations.getValue (text, text);
  8339. }
  8340. static int findCloseQuote (const String& text, int startPos)
  8341. {
  8342. juce_wchar lastChar = 0;
  8343. for (;;)
  8344. {
  8345. const juce_wchar c = text [startPos];
  8346. if (c == 0 || (c == '"' && lastChar != '\\'))
  8347. break;
  8348. lastChar = c;
  8349. ++startPos;
  8350. }
  8351. return startPos;
  8352. }
  8353. static const String unescapeString (const String& s)
  8354. {
  8355. return s.replace ("\\\"", "\"")
  8356. .replace ("\\\'", "\'")
  8357. .replace ("\\t", "\t")
  8358. .replace ("\\r", "\r")
  8359. .replace ("\\n", "\n");
  8360. }
  8361. void LocalisedStrings::loadFromText (const String& fileContents)
  8362. {
  8363. StringArray lines;
  8364. lines.addLines (fileContents);
  8365. for (int i = 0; i < lines.size(); ++i)
  8366. {
  8367. String line (lines[i].trim());
  8368. if (line.startsWithChar ('"'))
  8369. {
  8370. int closeQuote = findCloseQuote (line, 1);
  8371. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8372. if (originalText.isNotEmpty())
  8373. {
  8374. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8375. closeQuote = findCloseQuote (line, openingQuote + 1);
  8376. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8377. if (newText.isNotEmpty())
  8378. translations.set (originalText, newText);
  8379. }
  8380. }
  8381. else if (line.startsWithIgnoreCase ("language:"))
  8382. {
  8383. languageName = line.substring (9).trim();
  8384. }
  8385. else if (line.startsWithIgnoreCase ("countries:"))
  8386. {
  8387. countryCodes.addTokens (line.substring (10).trim(), true);
  8388. countryCodes.trim();
  8389. countryCodes.removeEmptyStrings();
  8390. }
  8391. }
  8392. }
  8393. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8394. {
  8395. translations.setIgnoresCase (shouldIgnoreCase);
  8396. }
  8397. static CriticalSection currentMappingsLock;
  8398. static LocalisedStrings* currentMappings = 0;
  8399. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8400. {
  8401. const ScopedLock sl (currentMappingsLock);
  8402. delete currentMappings;
  8403. currentMappings = newTranslations;
  8404. }
  8405. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8406. {
  8407. return currentMappings;
  8408. }
  8409. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8410. {
  8411. const ScopedLock sl (currentMappingsLock);
  8412. if (currentMappings != 0)
  8413. return currentMappings->translate (text);
  8414. return text;
  8415. }
  8416. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8417. {
  8418. return translateWithCurrentMappings (String (text));
  8419. }
  8420. END_JUCE_NAMESPACE
  8421. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8422. /*** Start of inlined file: juce_String.cpp ***/
  8423. #if JUCE_MSVC
  8424. #pragma warning (push)
  8425. #pragma warning (disable: 4514)
  8426. #endif
  8427. #include <locale>
  8428. BEGIN_JUCE_NAMESPACE
  8429. #if JUCE_MSVC
  8430. #pragma warning (pop)
  8431. #endif
  8432. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8433. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8434. #endif
  8435. class StringHolder
  8436. {
  8437. public:
  8438. StringHolder()
  8439. : refCount (0x3fffffff), allocatedNumChars (0)
  8440. {
  8441. text[0] = 0;
  8442. }
  8443. static juce_wchar* createUninitialised (const size_t numChars)
  8444. {
  8445. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8446. s->refCount.value = 0;
  8447. s->allocatedNumChars = numChars;
  8448. return &(s->text[0]);
  8449. }
  8450. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8451. {
  8452. juce_wchar* const dest = createUninitialised (numChars);
  8453. copyChars (dest, src, numChars);
  8454. return dest;
  8455. }
  8456. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8457. {
  8458. juce_wchar* const dest = createUninitialised (numChars);
  8459. CharacterFunctions::copy (dest, src, (int) numChars);
  8460. dest [numChars] = 0;
  8461. return dest;
  8462. }
  8463. static inline juce_wchar* getEmpty() throw()
  8464. {
  8465. return &(empty.text[0]);
  8466. }
  8467. static void retain (juce_wchar* const text) throw()
  8468. {
  8469. ++(bufferFromText (text)->refCount);
  8470. }
  8471. static inline void release (StringHolder* const b) throw()
  8472. {
  8473. if (--(b->refCount) == -1 && b != &empty)
  8474. delete[] reinterpret_cast <char*> (b);
  8475. }
  8476. static void release (juce_wchar* const text) throw()
  8477. {
  8478. release (bufferFromText (text));
  8479. }
  8480. static juce_wchar* makeUnique (juce_wchar* const text)
  8481. {
  8482. StringHolder* const b = bufferFromText (text);
  8483. if (b->refCount.get() <= 0)
  8484. return text;
  8485. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8486. release (b);
  8487. return newText;
  8488. }
  8489. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8490. {
  8491. StringHolder* const b = bufferFromText (text);
  8492. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8493. return text;
  8494. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8495. copyChars (newText, text, b->allocatedNumChars);
  8496. release (b);
  8497. return newText;
  8498. }
  8499. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8500. {
  8501. return bufferFromText (text)->allocatedNumChars;
  8502. }
  8503. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8504. {
  8505. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8506. dest [numChars] = 0;
  8507. }
  8508. Atomic<int> refCount;
  8509. size_t allocatedNumChars;
  8510. juce_wchar text[1];
  8511. static StringHolder empty;
  8512. private:
  8513. static inline StringHolder* bufferFromText (void* const text) throw()
  8514. {
  8515. // (Can't use offsetof() here because of warnings about this not being a POD)
  8516. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8517. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8518. }
  8519. };
  8520. StringHolder StringHolder::empty;
  8521. const String String::empty;
  8522. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8523. {
  8524. jassert (t[numChars] == 0); // must have a null terminator
  8525. text = StringHolder::createCopy (t, numChars);
  8526. }
  8527. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8528. {
  8529. if (numExtraChars > 0)
  8530. {
  8531. const int oldLen = length();
  8532. const int newTotalLen = oldLen + numExtraChars;
  8533. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8534. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8535. }
  8536. }
  8537. void String::preallocateStorage (const size_t numChars)
  8538. {
  8539. text = StringHolder::makeUniqueWithSize (text, numChars);
  8540. }
  8541. String::String() throw()
  8542. : text (StringHolder::getEmpty())
  8543. {
  8544. }
  8545. String::~String() throw()
  8546. {
  8547. StringHolder::release (text);
  8548. }
  8549. String::String (const String& other) throw()
  8550. : text (other.text)
  8551. {
  8552. StringHolder::retain (text);
  8553. }
  8554. void String::swapWith (String& other) throw()
  8555. {
  8556. swapVariables (text, other.text);
  8557. }
  8558. String& String::operator= (const String& other) throw()
  8559. {
  8560. juce_wchar* const newText = other.text;
  8561. StringHolder::retain (newText);
  8562. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8563. return *this;
  8564. }
  8565. String::String (const size_t numChars, const int /*dummyVariable*/)
  8566. : text (StringHolder::createUninitialised (numChars))
  8567. {
  8568. }
  8569. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8570. {
  8571. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8572. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8573. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8574. }
  8575. String::String (const char* const t)
  8576. {
  8577. if (t != 0 && *t != 0)
  8578. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8579. else
  8580. text = StringHolder::getEmpty();
  8581. }
  8582. String::String (const juce_wchar* const t)
  8583. {
  8584. if (t != 0 && *t != 0)
  8585. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8586. else
  8587. text = StringHolder::getEmpty();
  8588. }
  8589. String::String (const char* const t, const size_t maxChars)
  8590. {
  8591. int i;
  8592. for (i = 0; (size_t) i < maxChars; ++i)
  8593. if (t[i] == 0)
  8594. break;
  8595. if (i > 0)
  8596. text = StringHolder::createCopy (t, i);
  8597. else
  8598. text = StringHolder::getEmpty();
  8599. }
  8600. String::String (const juce_wchar* const t, const size_t maxChars)
  8601. {
  8602. int i;
  8603. for (i = 0; (size_t) i < maxChars; ++i)
  8604. if (t[i] == 0)
  8605. break;
  8606. if (i > 0)
  8607. text = StringHolder::createCopy (t, i);
  8608. else
  8609. text = StringHolder::getEmpty();
  8610. }
  8611. const String String::charToString (const juce_wchar character)
  8612. {
  8613. String result ((size_t) 1, (int) 0);
  8614. result.text[0] = character;
  8615. result.text[1] = 0;
  8616. return result;
  8617. }
  8618. namespace NumberToStringConverters
  8619. {
  8620. // pass in a pointer to the END of a buffer..
  8621. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8622. {
  8623. *--t = 0;
  8624. int64 v = (n >= 0) ? n : -n;
  8625. do
  8626. {
  8627. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8628. v /= 10;
  8629. } while (v > 0);
  8630. if (n < 0)
  8631. *--t = '-';
  8632. return t;
  8633. }
  8634. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8635. {
  8636. *--t = 0;
  8637. do
  8638. {
  8639. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8640. v /= 10;
  8641. } while (v > 0);
  8642. return t;
  8643. }
  8644. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8645. {
  8646. if (n == (int) 0x80000000) // (would cause an overflow)
  8647. return int64ToString (t, n);
  8648. *--t = 0;
  8649. int v = abs (n);
  8650. do
  8651. {
  8652. *--t = (juce_wchar) ('0' + (v % 10));
  8653. v /= 10;
  8654. } while (v > 0);
  8655. if (n < 0)
  8656. *--t = '-';
  8657. return t;
  8658. }
  8659. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8660. {
  8661. *--t = 0;
  8662. do
  8663. {
  8664. *--t = (juce_wchar) ('0' + (v % 10));
  8665. v /= 10;
  8666. } while (v > 0);
  8667. return t;
  8668. }
  8669. static juce_wchar getDecimalPoint()
  8670. {
  8671. #if JUCE_WINDOWS && _MSC_VER < 1400
  8672. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8673. #else
  8674. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8675. #endif
  8676. return dp;
  8677. }
  8678. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8679. {
  8680. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8681. {
  8682. juce_wchar* const end = buffer + numChars;
  8683. juce_wchar* t = end;
  8684. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8685. *--t = (juce_wchar) 0;
  8686. while (numDecPlaces >= 0 || v > 0)
  8687. {
  8688. if (numDecPlaces == 0)
  8689. *--t = getDecimalPoint();
  8690. *--t = (juce_wchar) ('0' + (v % 10));
  8691. v /= 10;
  8692. --numDecPlaces;
  8693. }
  8694. if (n < 0)
  8695. *--t = '-';
  8696. len = end - t - 1;
  8697. return t;
  8698. }
  8699. else
  8700. {
  8701. #if JUCE_WINDOWS
  8702. #if _MSC_VER <= 1400
  8703. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8704. #else
  8705. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8706. #endif
  8707. #else
  8708. len = swprintf (buffer, numChars, L"%.9g", n);
  8709. #endif
  8710. return buffer;
  8711. }
  8712. }
  8713. }
  8714. String::String (const int number)
  8715. {
  8716. juce_wchar buffer [16];
  8717. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8718. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8719. createInternal (start, end - start - 1);
  8720. }
  8721. String::String (const unsigned int number)
  8722. {
  8723. juce_wchar buffer [16];
  8724. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8725. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8726. createInternal (start, end - start - 1);
  8727. }
  8728. String::String (const short number)
  8729. {
  8730. juce_wchar buffer [16];
  8731. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8732. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8733. createInternal (start, end - start - 1);
  8734. }
  8735. String::String (const unsigned short number)
  8736. {
  8737. juce_wchar buffer [16];
  8738. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8739. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8740. createInternal (start, end - start - 1);
  8741. }
  8742. String::String (const int64 number)
  8743. {
  8744. juce_wchar buffer [32];
  8745. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8746. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8747. createInternal (start, end - start - 1);
  8748. }
  8749. String::String (const uint64 number)
  8750. {
  8751. juce_wchar buffer [32];
  8752. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8753. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8754. createInternal (start, end - start - 1);
  8755. }
  8756. String::String (const float number, const int numberOfDecimalPlaces)
  8757. {
  8758. juce_wchar buffer [48];
  8759. size_t len;
  8760. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8761. createInternal (start, len);
  8762. }
  8763. String::String (const double number, const int numberOfDecimalPlaces)
  8764. {
  8765. juce_wchar buffer [48];
  8766. size_t len;
  8767. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8768. createInternal (start, len);
  8769. }
  8770. int String::length() const throw()
  8771. {
  8772. return CharacterFunctions::length (text);
  8773. }
  8774. int String::hashCode() const throw()
  8775. {
  8776. const juce_wchar* t = text;
  8777. int result = 0;
  8778. while (*t != (juce_wchar) 0)
  8779. result = 31 * result + *t++;
  8780. return result;
  8781. }
  8782. int64 String::hashCode64() const throw()
  8783. {
  8784. const juce_wchar* t = text;
  8785. int64 result = 0;
  8786. while (*t != (juce_wchar) 0)
  8787. result = 101 * result + *t++;
  8788. return result;
  8789. }
  8790. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  8791. {
  8792. return string1.compare (string2) == 0;
  8793. }
  8794. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  8795. {
  8796. return string1.compare (string2) == 0;
  8797. }
  8798. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  8799. {
  8800. return string1.compare (string2) == 0;
  8801. }
  8802. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  8803. {
  8804. return string1.compare (string2) != 0;
  8805. }
  8806. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  8807. {
  8808. return string1.compare (string2) != 0;
  8809. }
  8810. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  8811. {
  8812. return string1.compare (string2) != 0;
  8813. }
  8814. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  8815. {
  8816. return string1.compare (string2) > 0;
  8817. }
  8818. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  8819. {
  8820. return string1.compare (string2) < 0;
  8821. }
  8822. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  8823. {
  8824. return string1.compare (string2) >= 0;
  8825. }
  8826. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  8827. {
  8828. return string1.compare (string2) <= 0;
  8829. }
  8830. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8831. {
  8832. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8833. : isEmpty();
  8834. }
  8835. bool String::equalsIgnoreCase (const char* t) const throw()
  8836. {
  8837. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8838. : isEmpty();
  8839. }
  8840. bool String::equalsIgnoreCase (const String& other) const throw()
  8841. {
  8842. return text == other.text
  8843. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8844. }
  8845. int String::compare (const String& other) const throw()
  8846. {
  8847. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8848. }
  8849. int String::compare (const char* other) const throw()
  8850. {
  8851. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8852. }
  8853. int String::compare (const juce_wchar* other) const throw()
  8854. {
  8855. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8856. }
  8857. int String::compareIgnoreCase (const String& other) const throw()
  8858. {
  8859. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8860. }
  8861. int String::compareLexicographically (const String& other) const throw()
  8862. {
  8863. const juce_wchar* s1 = text;
  8864. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8865. ++s1;
  8866. const juce_wchar* s2 = other.text;
  8867. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8868. ++s2;
  8869. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8870. }
  8871. String& String::operator+= (const juce_wchar* const t)
  8872. {
  8873. if (t != 0)
  8874. appendInternal (t, CharacterFunctions::length (t));
  8875. return *this;
  8876. }
  8877. String& String::operator+= (const String& other)
  8878. {
  8879. if (isEmpty())
  8880. operator= (other);
  8881. else
  8882. appendInternal (other.text, other.length());
  8883. return *this;
  8884. }
  8885. String& String::operator+= (const char ch)
  8886. {
  8887. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8888. return operator+= (static_cast <const juce_wchar*> (asString));
  8889. }
  8890. String& String::operator+= (const juce_wchar ch)
  8891. {
  8892. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8893. return operator+= (static_cast <const juce_wchar*> (asString));
  8894. }
  8895. String& String::operator+= (const int number)
  8896. {
  8897. juce_wchar buffer [16];
  8898. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8899. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8900. appendInternal (start, (int) (end - start));
  8901. return *this;
  8902. }
  8903. String& String::operator+= (const unsigned int number)
  8904. {
  8905. juce_wchar buffer [16];
  8906. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8907. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8908. appendInternal (start, (int) (end - start));
  8909. return *this;
  8910. }
  8911. void String::append (const juce_wchar* const other, const int howMany)
  8912. {
  8913. if (howMany > 0)
  8914. {
  8915. int i;
  8916. for (i = 0; i < howMany; ++i)
  8917. if (other[i] == 0)
  8918. break;
  8919. appendInternal (other, i);
  8920. }
  8921. }
  8922. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  8923. {
  8924. String s (string1);
  8925. return s += string2;
  8926. }
  8927. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  8928. {
  8929. String s (string1);
  8930. return s += string2;
  8931. }
  8932. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  8933. {
  8934. return String::charToString (string1) + string2;
  8935. }
  8936. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  8937. {
  8938. return String::charToString (string1) + string2;
  8939. }
  8940. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  8941. {
  8942. return string1 += string2;
  8943. }
  8944. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  8945. {
  8946. return string1 += string2;
  8947. }
  8948. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  8949. {
  8950. return string1 += string2;
  8951. }
  8952. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  8953. {
  8954. return string1 += string2;
  8955. }
  8956. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  8957. {
  8958. return string1 += string2;
  8959. }
  8960. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  8961. {
  8962. return string1 += characterToAppend;
  8963. }
  8964. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  8965. {
  8966. return string1 += characterToAppend;
  8967. }
  8968. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  8969. {
  8970. return string1 += string2;
  8971. }
  8972. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  8973. {
  8974. return string1 += string2;
  8975. }
  8976. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  8977. {
  8978. return string1 += string2;
  8979. }
  8980. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  8981. {
  8982. return string1 += (int) number;
  8983. }
  8984. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  8985. {
  8986. return string1 += number;
  8987. }
  8988. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  8989. {
  8990. return string1 += number;
  8991. }
  8992. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  8993. {
  8994. return string1 += (int) number;
  8995. }
  8996. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  8997. {
  8998. return string1 += (unsigned int) number;
  8999. }
  9000. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9001. {
  9002. return string1 += String (number);
  9003. }
  9004. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9005. {
  9006. return string1 += String (number);
  9007. }
  9008. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9009. {
  9010. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9011. // if lots of large, persistent strings were to be written to streams).
  9012. const int numBytes = text.getNumBytesAsUTF8();
  9013. HeapBlock<char> temp (numBytes + 1);
  9014. text.copyToUTF8 (temp, numBytes + 1);
  9015. stream.write (temp, numBytes);
  9016. return stream;
  9017. }
  9018. int String::indexOfChar (const juce_wchar character) const throw()
  9019. {
  9020. const juce_wchar* t = text;
  9021. for (;;)
  9022. {
  9023. if (*t == character)
  9024. return (int) (t - text);
  9025. if (*t++ == 0)
  9026. return -1;
  9027. }
  9028. }
  9029. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9030. {
  9031. for (int i = length(); --i >= 0;)
  9032. if (text[i] == character)
  9033. return i;
  9034. return -1;
  9035. }
  9036. int String::indexOf (const String& t) const throw()
  9037. {
  9038. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9039. return r == 0 ? -1 : (int) (r - text);
  9040. }
  9041. int String::indexOfChar (const int startIndex,
  9042. const juce_wchar character) const throw()
  9043. {
  9044. if (startIndex > 0 && startIndex >= length())
  9045. return -1;
  9046. const juce_wchar* t = text + jmax (0, startIndex);
  9047. for (;;)
  9048. {
  9049. if (*t == character)
  9050. return (int) (t - text);
  9051. if (*t == 0)
  9052. return -1;
  9053. ++t;
  9054. }
  9055. }
  9056. int String::indexOfAnyOf (const String& charactersToLookFor,
  9057. const int startIndex,
  9058. const bool ignoreCase) const throw()
  9059. {
  9060. if (startIndex > 0 && startIndex >= length())
  9061. return -1;
  9062. const juce_wchar* t = text + jmax (0, startIndex);
  9063. while (*t != 0)
  9064. {
  9065. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9066. return (int) (t - text);
  9067. ++t;
  9068. }
  9069. return -1;
  9070. }
  9071. int String::indexOf (const int startIndex, const String& other) const throw()
  9072. {
  9073. if (startIndex > 0 && startIndex >= length())
  9074. return -1;
  9075. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9076. return found == 0 ? -1 : (int) (found - text);
  9077. }
  9078. int String::indexOfIgnoreCase (const String& other) const throw()
  9079. {
  9080. if (other.isNotEmpty())
  9081. {
  9082. const int len = other.length();
  9083. const int end = length() - len;
  9084. for (int i = 0; i <= end; ++i)
  9085. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9086. return i;
  9087. }
  9088. return -1;
  9089. }
  9090. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9091. {
  9092. if (other.isNotEmpty())
  9093. {
  9094. const int len = other.length();
  9095. const int end = length() - len;
  9096. for (int i = jmax (0, startIndex); i <= end; ++i)
  9097. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9098. return i;
  9099. }
  9100. return -1;
  9101. }
  9102. int String::lastIndexOf (const String& other) const throw()
  9103. {
  9104. if (other.isNotEmpty())
  9105. {
  9106. const int len = other.length();
  9107. int i = length() - len;
  9108. if (i >= 0)
  9109. {
  9110. const juce_wchar* n = text + i;
  9111. while (i >= 0)
  9112. {
  9113. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9114. return i;
  9115. --i;
  9116. }
  9117. }
  9118. }
  9119. return -1;
  9120. }
  9121. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9122. {
  9123. if (other.isNotEmpty())
  9124. {
  9125. const int len = other.length();
  9126. int i = length() - len;
  9127. if (i >= 0)
  9128. {
  9129. const juce_wchar* n = text + i;
  9130. while (i >= 0)
  9131. {
  9132. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9133. return i;
  9134. --i;
  9135. }
  9136. }
  9137. }
  9138. return -1;
  9139. }
  9140. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9141. {
  9142. for (int i = length(); --i >= 0;)
  9143. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9144. return i;
  9145. return -1;
  9146. }
  9147. bool String::contains (const String& other) const throw()
  9148. {
  9149. return indexOf (other) >= 0;
  9150. }
  9151. bool String::containsChar (const juce_wchar character) const throw()
  9152. {
  9153. const juce_wchar* t = text;
  9154. for (;;)
  9155. {
  9156. if (*t == 0)
  9157. return false;
  9158. if (*t == character)
  9159. return true;
  9160. ++t;
  9161. }
  9162. }
  9163. bool String::containsIgnoreCase (const String& t) const throw()
  9164. {
  9165. return indexOfIgnoreCase (t) >= 0;
  9166. }
  9167. int String::indexOfWholeWord (const String& word) const throw()
  9168. {
  9169. if (word.isNotEmpty())
  9170. {
  9171. const int wordLen = word.length();
  9172. const int end = length() - wordLen;
  9173. const juce_wchar* t = text;
  9174. for (int i = 0; i <= end; ++i)
  9175. {
  9176. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9177. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9178. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9179. {
  9180. return i;
  9181. }
  9182. ++t;
  9183. }
  9184. }
  9185. return -1;
  9186. }
  9187. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9188. {
  9189. if (word.isNotEmpty())
  9190. {
  9191. const int wordLen = word.length();
  9192. const int end = length() - wordLen;
  9193. const juce_wchar* t = text;
  9194. for (int i = 0; i <= end; ++i)
  9195. {
  9196. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9197. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9198. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9199. {
  9200. return i;
  9201. }
  9202. ++t;
  9203. }
  9204. }
  9205. return -1;
  9206. }
  9207. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9208. {
  9209. return indexOfWholeWord (wordToLookFor) >= 0;
  9210. }
  9211. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9212. {
  9213. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9214. }
  9215. static int indexOfMatch (const juce_wchar* const wildcard,
  9216. const juce_wchar* const test,
  9217. const bool ignoreCase) throw()
  9218. {
  9219. int start = 0;
  9220. while (test [start] != 0)
  9221. {
  9222. int i = 0;
  9223. for (;;)
  9224. {
  9225. const juce_wchar wc = wildcard [i];
  9226. const juce_wchar c = test [i + start];
  9227. if (wc == c
  9228. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9229. || (wc == '?' && c != 0))
  9230. {
  9231. if (wc == 0)
  9232. return start;
  9233. ++i;
  9234. }
  9235. else
  9236. {
  9237. if (wc == '*' && (wildcard [i + 1] == 0
  9238. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9239. {
  9240. return start;
  9241. }
  9242. break;
  9243. }
  9244. }
  9245. ++start;
  9246. }
  9247. return -1;
  9248. }
  9249. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9250. {
  9251. int i = 0;
  9252. for (;;)
  9253. {
  9254. const juce_wchar wc = wildcard.text [i];
  9255. const juce_wchar c = text [i];
  9256. if (wc == c
  9257. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9258. || (wc == '?' && c != 0))
  9259. {
  9260. if (wc == 0)
  9261. return true;
  9262. ++i;
  9263. }
  9264. else
  9265. {
  9266. return wc == '*' && (wildcard [i + 1] == 0
  9267. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9268. }
  9269. }
  9270. }
  9271. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9272. {
  9273. const int len = stringToRepeat.length();
  9274. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9275. juce_wchar* n = result.text;
  9276. *n = 0;
  9277. while (--numberOfTimesToRepeat >= 0)
  9278. {
  9279. StringHolder::copyChars (n, stringToRepeat.text, len);
  9280. n += len;
  9281. }
  9282. return result;
  9283. }
  9284. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9285. {
  9286. jassert (padCharacter != 0);
  9287. const int len = length();
  9288. if (len >= minimumLength || padCharacter == 0)
  9289. return *this;
  9290. String result ((size_t) minimumLength + 1, (int) 0);
  9291. juce_wchar* n = result.text;
  9292. minimumLength -= len;
  9293. while (--minimumLength >= 0)
  9294. *n++ = padCharacter;
  9295. StringHolder::copyChars (n, text, len);
  9296. return result;
  9297. }
  9298. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9299. {
  9300. jassert (padCharacter != 0);
  9301. const int len = length();
  9302. if (len >= minimumLength || padCharacter == 0)
  9303. return *this;
  9304. String result (*this, (size_t) minimumLength);
  9305. juce_wchar* n = result.text + len;
  9306. minimumLength -= len;
  9307. while (--minimumLength >= 0)
  9308. *n++ = padCharacter;
  9309. *n = 0;
  9310. return result;
  9311. }
  9312. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9313. {
  9314. if (index < 0)
  9315. {
  9316. // a negative index to replace from?
  9317. jassertfalse;
  9318. index = 0;
  9319. }
  9320. if (numCharsToReplace < 0)
  9321. {
  9322. // replacing a negative number of characters?
  9323. numCharsToReplace = 0;
  9324. jassertfalse;
  9325. }
  9326. const int len = length();
  9327. if (index + numCharsToReplace > len)
  9328. {
  9329. if (index > len)
  9330. {
  9331. // replacing beyond the end of the string?
  9332. index = len;
  9333. jassertfalse;
  9334. }
  9335. numCharsToReplace = len - index;
  9336. }
  9337. const int newStringLen = stringToInsert.length();
  9338. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9339. if (newTotalLen <= 0)
  9340. return String::empty;
  9341. String result ((size_t) newTotalLen, (int) 0);
  9342. StringHolder::copyChars (result.text, text, index);
  9343. if (newStringLen > 0)
  9344. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9345. const int endStringLen = newTotalLen - (index + newStringLen);
  9346. if (endStringLen > 0)
  9347. StringHolder::copyChars (result.text + (index + newStringLen),
  9348. text + (index + numCharsToReplace),
  9349. endStringLen);
  9350. return result;
  9351. }
  9352. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9353. {
  9354. const int stringToReplaceLen = stringToReplace.length();
  9355. const int stringToInsertLen = stringToInsert.length();
  9356. int i = 0;
  9357. String result (*this);
  9358. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9359. : result.indexOf (i, stringToReplace))) >= 0)
  9360. {
  9361. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9362. i += stringToInsertLen;
  9363. }
  9364. return result;
  9365. }
  9366. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9367. {
  9368. const int index = indexOfChar (charToReplace);
  9369. if (index < 0)
  9370. return *this;
  9371. String result (*this, size_t());
  9372. juce_wchar* t = result.text + index;
  9373. while (*t != 0)
  9374. {
  9375. if (*t == charToReplace)
  9376. *t = charToInsert;
  9377. ++t;
  9378. }
  9379. return result;
  9380. }
  9381. const String String::replaceCharacters (const String& charactersToReplace,
  9382. const String& charactersToInsertInstead) const
  9383. {
  9384. String result (*this, size_t());
  9385. juce_wchar* t = result.text;
  9386. const int len2 = charactersToInsertInstead.length();
  9387. // the two strings passed in are supposed to be the same length!
  9388. jassert (len2 == charactersToReplace.length());
  9389. while (*t != 0)
  9390. {
  9391. const int index = charactersToReplace.indexOfChar (*t);
  9392. if (((unsigned int) index) < (unsigned int) len2)
  9393. *t = charactersToInsertInstead [index];
  9394. ++t;
  9395. }
  9396. return result;
  9397. }
  9398. bool String::startsWith (const String& other) const throw()
  9399. {
  9400. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9401. }
  9402. bool String::startsWithIgnoreCase (const String& other) const throw()
  9403. {
  9404. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9405. }
  9406. bool String::startsWithChar (const juce_wchar character) const throw()
  9407. {
  9408. jassert (character != 0); // strings can't contain a null character!
  9409. return text[0] == character;
  9410. }
  9411. bool String::endsWithChar (const juce_wchar character) const throw()
  9412. {
  9413. jassert (character != 0); // strings can't contain a null character!
  9414. return text[0] != 0
  9415. && text [length() - 1] == character;
  9416. }
  9417. bool String::endsWith (const String& other) const throw()
  9418. {
  9419. const int thisLen = length();
  9420. const int otherLen = other.length();
  9421. return thisLen >= otherLen
  9422. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9423. }
  9424. bool String::endsWithIgnoreCase (const String& other) const throw()
  9425. {
  9426. const int thisLen = length();
  9427. const int otherLen = other.length();
  9428. return thisLen >= otherLen
  9429. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9430. }
  9431. const String String::toUpperCase() const
  9432. {
  9433. String result (*this, size_t());
  9434. CharacterFunctions::toUpperCase (result.text);
  9435. return result;
  9436. }
  9437. const String String::toLowerCase() const
  9438. {
  9439. String result (*this, size_t());
  9440. CharacterFunctions::toLowerCase (result.text);
  9441. return result;
  9442. }
  9443. juce_wchar& String::operator[] (const int index)
  9444. {
  9445. jassert (((unsigned int) index) <= (unsigned int) length());
  9446. text = StringHolder::makeUnique (text);
  9447. return text [index];
  9448. }
  9449. juce_wchar String::getLastCharacter() const throw()
  9450. {
  9451. return isEmpty() ? juce_wchar() : text [length() - 1];
  9452. }
  9453. const String String::substring (int start, int end) const
  9454. {
  9455. if (start < 0)
  9456. start = 0;
  9457. else if (end <= start)
  9458. return empty;
  9459. int len = 0;
  9460. while (len <= end && text [len] != 0)
  9461. ++len;
  9462. if (end >= len)
  9463. {
  9464. if (start == 0)
  9465. return *this;
  9466. end = len;
  9467. }
  9468. return String (text + start, end - start);
  9469. }
  9470. const String String::substring (const int start) const
  9471. {
  9472. if (start <= 0)
  9473. return *this;
  9474. const int len = length();
  9475. if (start >= len)
  9476. return empty;
  9477. return String (text + start, len - start);
  9478. }
  9479. const String String::dropLastCharacters (const int numberToDrop) const
  9480. {
  9481. return String (text, jmax (0, length() - numberToDrop));
  9482. }
  9483. const String String::getLastCharacters (const int numCharacters) const
  9484. {
  9485. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9486. }
  9487. const String String::fromFirstOccurrenceOf (const String& sub,
  9488. const bool includeSubString,
  9489. const bool ignoreCase) const
  9490. {
  9491. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9492. : indexOf (sub);
  9493. if (i < 0)
  9494. return empty;
  9495. return substring (includeSubString ? i : i + sub.length());
  9496. }
  9497. const String String::fromLastOccurrenceOf (const String& sub,
  9498. const bool includeSubString,
  9499. const bool ignoreCase) const
  9500. {
  9501. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9502. : lastIndexOf (sub);
  9503. if (i < 0)
  9504. return *this;
  9505. return substring (includeSubString ? i : i + sub.length());
  9506. }
  9507. const String String::upToFirstOccurrenceOf (const String& sub,
  9508. const bool includeSubString,
  9509. const bool ignoreCase) const
  9510. {
  9511. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9512. : indexOf (sub);
  9513. if (i < 0)
  9514. return *this;
  9515. return substring (0, includeSubString ? i + sub.length() : i);
  9516. }
  9517. const String String::upToLastOccurrenceOf (const String& sub,
  9518. const bool includeSubString,
  9519. const bool ignoreCase) const
  9520. {
  9521. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9522. : lastIndexOf (sub);
  9523. if (i < 0)
  9524. return *this;
  9525. return substring (0, includeSubString ? i + sub.length() : i);
  9526. }
  9527. bool String::isQuotedString() const
  9528. {
  9529. const String trimmed (trimStart());
  9530. return trimmed[0] == '"'
  9531. || trimmed[0] == '\'';
  9532. }
  9533. const String String::unquoted() const
  9534. {
  9535. String s (*this);
  9536. if (s.text[0] == '"' || s.text[0] == '\'')
  9537. s = s.substring (1);
  9538. const int lastCharIndex = s.length() - 1;
  9539. if (lastCharIndex >= 0
  9540. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9541. s [lastCharIndex] = 0;
  9542. return s;
  9543. }
  9544. const String String::quoted (const juce_wchar quoteCharacter) const
  9545. {
  9546. if (isEmpty())
  9547. return charToString (quoteCharacter) + quoteCharacter;
  9548. String t (*this);
  9549. if (! t.startsWithChar (quoteCharacter))
  9550. t = charToString (quoteCharacter) + t;
  9551. if (! t.endsWithChar (quoteCharacter))
  9552. t += quoteCharacter;
  9553. return t;
  9554. }
  9555. const String String::trim() const
  9556. {
  9557. if (isEmpty())
  9558. return empty;
  9559. int start = 0;
  9560. while (CharacterFunctions::isWhitespace (text [start]))
  9561. ++start;
  9562. const int len = length();
  9563. int end = len - 1;
  9564. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9565. --end;
  9566. ++end;
  9567. if (end <= start)
  9568. return empty;
  9569. else if (start > 0 || end < len)
  9570. return String (text + start, end - start);
  9571. return *this;
  9572. }
  9573. const String String::trimStart() const
  9574. {
  9575. if (isEmpty())
  9576. return empty;
  9577. const juce_wchar* t = text;
  9578. while (CharacterFunctions::isWhitespace (*t))
  9579. ++t;
  9580. if (t == text)
  9581. return *this;
  9582. return String (t);
  9583. }
  9584. const String String::trimEnd() const
  9585. {
  9586. if (isEmpty())
  9587. return empty;
  9588. const juce_wchar* endT = text + (length() - 1);
  9589. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9590. --endT;
  9591. return String (text, (int) (++endT - text));
  9592. }
  9593. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9594. {
  9595. const juce_wchar* t = text;
  9596. while (charactersToTrim.containsChar (*t))
  9597. ++t;
  9598. return t == text ? *this : String (t);
  9599. }
  9600. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9601. {
  9602. if (isEmpty())
  9603. return empty;
  9604. const int len = length();
  9605. const juce_wchar* endT = text + (len - 1);
  9606. int numToRemove = 0;
  9607. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9608. {
  9609. ++numToRemove;
  9610. --endT;
  9611. }
  9612. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9613. }
  9614. const String String::retainCharacters (const String& charactersToRetain) const
  9615. {
  9616. if (isEmpty())
  9617. return empty;
  9618. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9619. juce_wchar* dst = result.text;
  9620. const juce_wchar* src = text;
  9621. while (*src != 0)
  9622. {
  9623. if (charactersToRetain.containsChar (*src))
  9624. *dst++ = *src;
  9625. ++src;
  9626. }
  9627. *dst = 0;
  9628. return result;
  9629. }
  9630. const String String::removeCharacters (const String& charactersToRemove) const
  9631. {
  9632. if (isEmpty())
  9633. return empty;
  9634. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9635. juce_wchar* dst = result.text;
  9636. const juce_wchar* src = text;
  9637. while (*src != 0)
  9638. {
  9639. if (! charactersToRemove.containsChar (*src))
  9640. *dst++ = *src;
  9641. ++src;
  9642. }
  9643. *dst = 0;
  9644. return result;
  9645. }
  9646. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9647. {
  9648. int i = 0;
  9649. for (;;)
  9650. {
  9651. if (! permittedCharacters.containsChar (text[i]))
  9652. break;
  9653. ++i;
  9654. }
  9655. return substring (0, i);
  9656. }
  9657. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9658. {
  9659. const juce_wchar* const t = text;
  9660. int i = 0;
  9661. while (t[i] != 0)
  9662. {
  9663. if (charactersToStopAt.containsChar (t[i]))
  9664. return String (text, i);
  9665. ++i;
  9666. }
  9667. return empty;
  9668. }
  9669. bool String::containsOnly (const String& chars) const throw()
  9670. {
  9671. const juce_wchar* t = text;
  9672. while (*t != 0)
  9673. if (! chars.containsChar (*t++))
  9674. return false;
  9675. return true;
  9676. }
  9677. bool String::containsAnyOf (const String& chars) const throw()
  9678. {
  9679. const juce_wchar* t = text;
  9680. while (*t != 0)
  9681. if (chars.containsChar (*t++))
  9682. return true;
  9683. return false;
  9684. }
  9685. bool String::containsNonWhitespaceChars() const throw()
  9686. {
  9687. const juce_wchar* t = text;
  9688. while (*t != 0)
  9689. if (! CharacterFunctions::isWhitespace (*t++))
  9690. return true;
  9691. return false;
  9692. }
  9693. const String String::formatted (const juce_wchar* const pf, ... )
  9694. {
  9695. jassert (pf != 0);
  9696. va_list args;
  9697. va_start (args, pf);
  9698. size_t bufferSize = 256;
  9699. String result (bufferSize, (int) 0);
  9700. result.text[0] = 0;
  9701. for (;;)
  9702. {
  9703. #if JUCE_LINUX && JUCE_64BIT
  9704. va_list tempArgs;
  9705. va_copy (tempArgs, args);
  9706. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9707. va_end (tempArgs);
  9708. #elif JUCE_WINDOWS
  9709. #if JUCE_MSVC
  9710. #pragma warning (push)
  9711. #pragma warning (disable: 4996)
  9712. #endif
  9713. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9714. #if JUCE_MSVC
  9715. #pragma warning (pop)
  9716. #endif
  9717. #else
  9718. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9719. #endif
  9720. if (num > 0)
  9721. return result;
  9722. bufferSize += 256;
  9723. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9724. break; // returns -1 because of an error rather than because it needs more space.
  9725. result.preallocateStorage (bufferSize);
  9726. }
  9727. return empty;
  9728. }
  9729. int String::getIntValue() const throw()
  9730. {
  9731. return CharacterFunctions::getIntValue (text);
  9732. }
  9733. int String::getTrailingIntValue() const throw()
  9734. {
  9735. int n = 0;
  9736. int mult = 1;
  9737. const juce_wchar* t = text + length();
  9738. while (--t >= text)
  9739. {
  9740. const juce_wchar c = *t;
  9741. if (! CharacterFunctions::isDigit (c))
  9742. {
  9743. if (c == '-')
  9744. n = -n;
  9745. break;
  9746. }
  9747. n += mult * (c - '0');
  9748. mult *= 10;
  9749. }
  9750. return n;
  9751. }
  9752. int64 String::getLargeIntValue() const throw()
  9753. {
  9754. return CharacterFunctions::getInt64Value (text);
  9755. }
  9756. float String::getFloatValue() const throw()
  9757. {
  9758. return (float) CharacterFunctions::getDoubleValue (text);
  9759. }
  9760. double String::getDoubleValue() const throw()
  9761. {
  9762. return CharacterFunctions::getDoubleValue (text);
  9763. }
  9764. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9765. const String String::toHexString (const int number)
  9766. {
  9767. juce_wchar buffer[32];
  9768. juce_wchar* const end = buffer + 32;
  9769. juce_wchar* t = end;
  9770. *--t = 0;
  9771. unsigned int v = (unsigned int) number;
  9772. do
  9773. {
  9774. *--t = hexDigits [v & 15];
  9775. v >>= 4;
  9776. } while (v != 0);
  9777. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9778. }
  9779. const String String::toHexString (const int64 number)
  9780. {
  9781. juce_wchar buffer[32];
  9782. juce_wchar* const end = buffer + 32;
  9783. juce_wchar* t = end;
  9784. *--t = 0;
  9785. uint64 v = (uint64) number;
  9786. do
  9787. {
  9788. *--t = hexDigits [(int) (v & 15)];
  9789. v >>= 4;
  9790. } while (v != 0);
  9791. return String (t, (int) (((char*) end) - (char*) t));
  9792. }
  9793. const String String::toHexString (const short number)
  9794. {
  9795. return toHexString ((int) (unsigned short) number);
  9796. }
  9797. const String String::toHexString (const unsigned char* data,
  9798. const int size,
  9799. const int groupSize)
  9800. {
  9801. if (size <= 0)
  9802. return empty;
  9803. int numChars = (size * 2) + 2;
  9804. if (groupSize > 0)
  9805. numChars += size / groupSize;
  9806. String s ((size_t) numChars, (int) 0);
  9807. juce_wchar* d = s.text;
  9808. for (int i = 0; i < size; ++i)
  9809. {
  9810. *d++ = hexDigits [(*data) >> 4];
  9811. *d++ = hexDigits [(*data) & 0xf];
  9812. ++data;
  9813. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9814. *d++ = ' ';
  9815. }
  9816. *d = 0;
  9817. return s;
  9818. }
  9819. int String::getHexValue32() const throw()
  9820. {
  9821. int result = 0;
  9822. const juce_wchar* c = text;
  9823. for (;;)
  9824. {
  9825. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9826. if (hexValue >= 0)
  9827. result = (result << 4) | hexValue;
  9828. else if (*c == 0)
  9829. break;
  9830. ++c;
  9831. }
  9832. return result;
  9833. }
  9834. int64 String::getHexValue64() const throw()
  9835. {
  9836. int64 result = 0;
  9837. const juce_wchar* c = text;
  9838. for (;;)
  9839. {
  9840. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9841. if (hexValue >= 0)
  9842. result = (result << 4) | hexValue;
  9843. else if (*c == 0)
  9844. break;
  9845. ++c;
  9846. }
  9847. return result;
  9848. }
  9849. const String String::createStringFromData (const void* const data_, const int size)
  9850. {
  9851. const char* const data = static_cast <const char*> (data_);
  9852. if (size <= 0 || data == 0)
  9853. {
  9854. return empty;
  9855. }
  9856. else if (size < 2)
  9857. {
  9858. return charToString (data[0]);
  9859. }
  9860. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9861. || (data[0] == (char)-1 && data[1] == (char)-2))
  9862. {
  9863. // assume it's 16-bit unicode
  9864. const bool bigEndian = (data[0] == (char)-2);
  9865. const int numChars = size / 2 - 1;
  9866. String result;
  9867. result.preallocateStorage (numChars + 2);
  9868. const uint16* const src = (const uint16*) (data + 2);
  9869. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9870. if (bigEndian)
  9871. {
  9872. for (int i = 0; i < numChars; ++i)
  9873. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9874. }
  9875. else
  9876. {
  9877. for (int i = 0; i < numChars; ++i)
  9878. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9879. }
  9880. dst [numChars] = 0;
  9881. return result;
  9882. }
  9883. else
  9884. {
  9885. return String::fromUTF8 (data, size);
  9886. }
  9887. }
  9888. const char* String::toUTF8() const
  9889. {
  9890. if (isEmpty())
  9891. {
  9892. return reinterpret_cast <const char*> (text);
  9893. }
  9894. else
  9895. {
  9896. const int currentLen = length() + 1;
  9897. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9898. String* const mutableThis = const_cast <String*> (this);
  9899. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9900. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9901. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  9902. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  9903. #endif
  9904. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9905. return otherCopy;
  9906. }
  9907. }
  9908. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9909. {
  9910. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9911. int num = 0, index = 0;
  9912. for (;;)
  9913. {
  9914. const uint32 c = (uint32) text [index++];
  9915. if (c >= 0x80)
  9916. {
  9917. int numExtraBytes = 1;
  9918. if (c >= 0x800)
  9919. {
  9920. ++numExtraBytes;
  9921. if (c >= 0x10000)
  9922. {
  9923. ++numExtraBytes;
  9924. if (c >= 0x200000)
  9925. {
  9926. ++numExtraBytes;
  9927. if (c >= 0x4000000)
  9928. ++numExtraBytes;
  9929. }
  9930. }
  9931. }
  9932. if (buffer != 0)
  9933. {
  9934. if (num + numExtraBytes >= maxBufferSizeBytes)
  9935. {
  9936. buffer [num++] = 0;
  9937. break;
  9938. }
  9939. else
  9940. {
  9941. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9942. while (--numExtraBytes >= 0)
  9943. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9944. }
  9945. }
  9946. else
  9947. {
  9948. num += numExtraBytes + 1;
  9949. }
  9950. }
  9951. else
  9952. {
  9953. if (buffer != 0)
  9954. {
  9955. if (num + 1 >= maxBufferSizeBytes)
  9956. {
  9957. buffer [num++] = 0;
  9958. break;
  9959. }
  9960. buffer [num] = (uint8) c;
  9961. }
  9962. ++num;
  9963. }
  9964. if (c == 0)
  9965. break;
  9966. }
  9967. return num;
  9968. }
  9969. int String::getNumBytesAsUTF8() const throw()
  9970. {
  9971. int num = 0;
  9972. const juce_wchar* t = text;
  9973. for (;;)
  9974. {
  9975. const uint32 c = (uint32) *t;
  9976. if (c >= 0x80)
  9977. {
  9978. ++num;
  9979. if (c >= 0x800)
  9980. {
  9981. ++num;
  9982. if (c >= 0x10000)
  9983. {
  9984. ++num;
  9985. if (c >= 0x200000)
  9986. {
  9987. ++num;
  9988. if (c >= 0x4000000)
  9989. ++num;
  9990. }
  9991. }
  9992. }
  9993. }
  9994. else if (c == 0)
  9995. break;
  9996. ++num;
  9997. ++t;
  9998. }
  9999. return num;
  10000. }
  10001. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10002. {
  10003. if (buffer == 0)
  10004. return empty;
  10005. if (bufferSizeBytes < 0)
  10006. bufferSizeBytes = std::numeric_limits<int>::max();
  10007. size_t numBytes;
  10008. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10009. if (buffer [numBytes] == 0)
  10010. break;
  10011. String result ((size_t) numBytes + 1, (int) 0);
  10012. juce_wchar* dest = result.text;
  10013. size_t i = 0;
  10014. while (i < numBytes)
  10015. {
  10016. const char c = buffer [i++];
  10017. if (c < 0)
  10018. {
  10019. unsigned int mask = 0x7f;
  10020. int bit = 0x40;
  10021. int numExtraValues = 0;
  10022. while (bit != 0 && (c & bit) != 0)
  10023. {
  10024. bit >>= 1;
  10025. mask >>= 1;
  10026. ++numExtraValues;
  10027. }
  10028. int n = (mask & (unsigned char) c);
  10029. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10030. {
  10031. const char nextByte = buffer[i];
  10032. if ((nextByte & 0xc0) != 0x80)
  10033. break;
  10034. n <<= 6;
  10035. n |= (nextByte & 0x3f);
  10036. ++i;
  10037. }
  10038. *dest++ = (juce_wchar) n;
  10039. }
  10040. else
  10041. {
  10042. *dest++ = (juce_wchar) c;
  10043. }
  10044. }
  10045. *dest = 0;
  10046. return result;
  10047. }
  10048. const char* String::toCString() const
  10049. {
  10050. if (isEmpty())
  10051. {
  10052. return reinterpret_cast <const char*> (text);
  10053. }
  10054. else
  10055. {
  10056. const int len = length();
  10057. String* const mutableThis = const_cast <String*> (this);
  10058. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10059. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10060. CharacterFunctions::copy (otherCopy, text, len);
  10061. otherCopy [len] = 0;
  10062. return otherCopy;
  10063. }
  10064. }
  10065. #if JUCE_MSVC
  10066. #pragma warning (push)
  10067. #pragma warning (disable: 4514 4996)
  10068. #endif
  10069. int String::getNumBytesAsCString() const throw()
  10070. {
  10071. return (int) wcstombs (0, text, 0);
  10072. }
  10073. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10074. {
  10075. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10076. if (destBuffer != 0 && numBytes >= 0)
  10077. destBuffer [numBytes] = 0;
  10078. return numBytes;
  10079. }
  10080. #if JUCE_MSVC
  10081. #pragma warning (pop)
  10082. #endif
  10083. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10084. {
  10085. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10086. }
  10087. String::Concatenator::Concatenator (String& stringToAppendTo)
  10088. : result (stringToAppendTo),
  10089. nextIndex (stringToAppendTo.length())
  10090. {
  10091. }
  10092. String::Concatenator::~Concatenator()
  10093. {
  10094. }
  10095. void String::Concatenator::append (const String& s)
  10096. {
  10097. const int len = s.length();
  10098. if (len > 0)
  10099. {
  10100. result.preallocateStorage (nextIndex + len);
  10101. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10102. nextIndex += len;
  10103. }
  10104. }
  10105. END_JUCE_NAMESPACE
  10106. /*** End of inlined file: juce_String.cpp ***/
  10107. /*** Start of inlined file: juce_StringArray.cpp ***/
  10108. BEGIN_JUCE_NAMESPACE
  10109. StringArray::StringArray() throw()
  10110. {
  10111. }
  10112. StringArray::StringArray (const StringArray& other)
  10113. : strings (other.strings)
  10114. {
  10115. }
  10116. StringArray::StringArray (const String& firstValue)
  10117. {
  10118. strings.add (firstValue);
  10119. }
  10120. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10121. const int numberOfStrings)
  10122. {
  10123. for (int i = 0; i < numberOfStrings; ++i)
  10124. strings.add (initialStrings [i]);
  10125. }
  10126. StringArray::StringArray (const char* const* const initialStrings,
  10127. const int numberOfStrings)
  10128. {
  10129. for (int i = 0; i < numberOfStrings; ++i)
  10130. strings.add (initialStrings [i]);
  10131. }
  10132. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10133. {
  10134. int i = 0;
  10135. while (initialStrings[i] != 0)
  10136. strings.add (initialStrings [i++]);
  10137. }
  10138. StringArray::StringArray (const char* const* const initialStrings)
  10139. {
  10140. int i = 0;
  10141. while (initialStrings[i] != 0)
  10142. strings.add (initialStrings [i++]);
  10143. }
  10144. StringArray& StringArray::operator= (const StringArray& other)
  10145. {
  10146. strings = other.strings;
  10147. return *this;
  10148. }
  10149. StringArray::~StringArray()
  10150. {
  10151. }
  10152. bool StringArray::operator== (const StringArray& other) const throw()
  10153. {
  10154. if (other.size() != size())
  10155. return false;
  10156. for (int i = size(); --i >= 0;)
  10157. if (other.strings.getReference(i) != strings.getReference(i))
  10158. return false;
  10159. return true;
  10160. }
  10161. bool StringArray::operator!= (const StringArray& other) const throw()
  10162. {
  10163. return ! operator== (other);
  10164. }
  10165. void StringArray::clear()
  10166. {
  10167. strings.clear();
  10168. }
  10169. const String& StringArray::operator[] (const int index) const throw()
  10170. {
  10171. if (((unsigned int) index) < (unsigned int) strings.size())
  10172. return strings.getReference (index);
  10173. return String::empty;
  10174. }
  10175. String& StringArray::getReference (const int index) throw()
  10176. {
  10177. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10178. return strings.getReference (index);
  10179. }
  10180. void StringArray::add (const String& newString)
  10181. {
  10182. strings.add (newString);
  10183. }
  10184. void StringArray::insert (const int index, const String& newString)
  10185. {
  10186. strings.insert (index, newString);
  10187. }
  10188. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10189. {
  10190. if (! contains (newString, ignoreCase))
  10191. add (newString);
  10192. }
  10193. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10194. {
  10195. if (startIndex < 0)
  10196. {
  10197. jassertfalse;
  10198. startIndex = 0;
  10199. }
  10200. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10201. numElementsToAdd = otherArray.size() - startIndex;
  10202. while (--numElementsToAdd >= 0)
  10203. strings.add (otherArray.strings.getReference (startIndex++));
  10204. }
  10205. void StringArray::set (const int index, const String& newString)
  10206. {
  10207. strings.set (index, newString);
  10208. }
  10209. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10210. {
  10211. if (ignoreCase)
  10212. {
  10213. for (int i = size(); --i >= 0;)
  10214. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10215. return true;
  10216. }
  10217. else
  10218. {
  10219. for (int i = size(); --i >= 0;)
  10220. if (stringToLookFor == strings.getReference(i))
  10221. return true;
  10222. }
  10223. return false;
  10224. }
  10225. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10226. {
  10227. if (i < 0)
  10228. i = 0;
  10229. const int numElements = size();
  10230. if (ignoreCase)
  10231. {
  10232. while (i < numElements)
  10233. {
  10234. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10235. return i;
  10236. ++i;
  10237. }
  10238. }
  10239. else
  10240. {
  10241. while (i < numElements)
  10242. {
  10243. if (stringToLookFor == strings.getReference (i))
  10244. return i;
  10245. ++i;
  10246. }
  10247. }
  10248. return -1;
  10249. }
  10250. void StringArray::remove (const int index)
  10251. {
  10252. strings.remove (index);
  10253. }
  10254. void StringArray::removeString (const String& stringToRemove,
  10255. const bool ignoreCase)
  10256. {
  10257. if (ignoreCase)
  10258. {
  10259. for (int i = size(); --i >= 0;)
  10260. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10261. strings.remove (i);
  10262. }
  10263. else
  10264. {
  10265. for (int i = size(); --i >= 0;)
  10266. if (stringToRemove == strings.getReference (i))
  10267. strings.remove (i);
  10268. }
  10269. }
  10270. void StringArray::removeRange (int startIndex, int numberToRemove)
  10271. {
  10272. strings.removeRange (startIndex, numberToRemove);
  10273. }
  10274. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10275. {
  10276. if (removeWhitespaceStrings)
  10277. {
  10278. for (int i = size(); --i >= 0;)
  10279. if (! strings.getReference(i).containsNonWhitespaceChars())
  10280. strings.remove (i);
  10281. }
  10282. else
  10283. {
  10284. for (int i = size(); --i >= 0;)
  10285. if (strings.getReference(i).isEmpty())
  10286. strings.remove (i);
  10287. }
  10288. }
  10289. void StringArray::trim()
  10290. {
  10291. for (int i = size(); --i >= 0;)
  10292. {
  10293. String& s = strings.getReference(i);
  10294. s = s.trim();
  10295. }
  10296. }
  10297. class InternalStringArrayComparator_CaseSensitive
  10298. {
  10299. public:
  10300. static int compareElements (String& first, String& second) { return first.compare (second); }
  10301. };
  10302. class InternalStringArrayComparator_CaseInsensitive
  10303. {
  10304. public:
  10305. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10306. };
  10307. void StringArray::sort (const bool ignoreCase)
  10308. {
  10309. if (ignoreCase)
  10310. {
  10311. InternalStringArrayComparator_CaseInsensitive comp;
  10312. strings.sort (comp);
  10313. }
  10314. else
  10315. {
  10316. InternalStringArrayComparator_CaseSensitive comp;
  10317. strings.sort (comp);
  10318. }
  10319. }
  10320. void StringArray::move (const int currentIndex, int newIndex) throw()
  10321. {
  10322. strings.move (currentIndex, newIndex);
  10323. }
  10324. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10325. {
  10326. const int last = (numberToJoin < 0) ? size()
  10327. : jmin (size(), start + numberToJoin);
  10328. if (start < 0)
  10329. start = 0;
  10330. if (start >= last)
  10331. return String::empty;
  10332. if (start == last - 1)
  10333. return strings.getReference (start);
  10334. const int separatorLen = separator.length();
  10335. int charsNeeded = separatorLen * (last - start - 1);
  10336. for (int i = start; i < last; ++i)
  10337. charsNeeded += strings.getReference(i).length();
  10338. String result;
  10339. result.preallocateStorage (charsNeeded);
  10340. juce_wchar* dest = result;
  10341. while (start < last)
  10342. {
  10343. const String& s = strings.getReference (start);
  10344. const int len = s.length();
  10345. if (len > 0)
  10346. {
  10347. s.copyToUnicode (dest, len);
  10348. dest += len;
  10349. }
  10350. if (++start < last && separatorLen > 0)
  10351. {
  10352. separator.copyToUnicode (dest, separatorLen);
  10353. dest += separatorLen;
  10354. }
  10355. }
  10356. *dest = 0;
  10357. return result;
  10358. }
  10359. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10360. {
  10361. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10362. }
  10363. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10364. {
  10365. int num = 0;
  10366. if (text.isNotEmpty())
  10367. {
  10368. bool insideQuotes = false;
  10369. juce_wchar currentQuoteChar = 0;
  10370. int i = 0;
  10371. int tokenStart = 0;
  10372. for (;;)
  10373. {
  10374. const juce_wchar c = text[i];
  10375. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10376. if (! isBreak)
  10377. {
  10378. if (quoteCharacters.containsChar (c))
  10379. {
  10380. if (insideQuotes)
  10381. {
  10382. // only break out of quotes-mode if we find a matching quote to the
  10383. // one that we opened with..
  10384. if (currentQuoteChar == c)
  10385. insideQuotes = false;
  10386. }
  10387. else
  10388. {
  10389. insideQuotes = true;
  10390. currentQuoteChar = c;
  10391. }
  10392. }
  10393. }
  10394. else
  10395. {
  10396. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10397. ++num;
  10398. tokenStart = i + 1;
  10399. }
  10400. if (c == 0)
  10401. break;
  10402. ++i;
  10403. }
  10404. }
  10405. return num;
  10406. }
  10407. int StringArray::addLines (const String& sourceText)
  10408. {
  10409. int numLines = 0;
  10410. const juce_wchar* text = sourceText;
  10411. while (*text != 0)
  10412. {
  10413. const juce_wchar* const startOfLine = text;
  10414. while (*text != 0)
  10415. {
  10416. if (*text == '\r')
  10417. {
  10418. ++text;
  10419. if (*text == '\n')
  10420. ++text;
  10421. break;
  10422. }
  10423. if (*text == '\n')
  10424. {
  10425. ++text;
  10426. break;
  10427. }
  10428. ++text;
  10429. }
  10430. const juce_wchar* endOfLine = text;
  10431. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10432. --endOfLine;
  10433. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10434. --endOfLine;
  10435. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10436. ++numLines;
  10437. }
  10438. return numLines;
  10439. }
  10440. void StringArray::removeDuplicates (const bool ignoreCase)
  10441. {
  10442. for (int i = 0; i < size() - 1; ++i)
  10443. {
  10444. const String s (strings.getReference(i));
  10445. int nextIndex = i + 1;
  10446. for (;;)
  10447. {
  10448. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10449. if (nextIndex < 0)
  10450. break;
  10451. strings.remove (nextIndex);
  10452. }
  10453. }
  10454. }
  10455. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10456. const bool appendNumberToFirstInstance,
  10457. const juce_wchar* preNumberString,
  10458. const juce_wchar* postNumberString)
  10459. {
  10460. if (preNumberString == 0)
  10461. preNumberString = L" (";
  10462. if (postNumberString == 0)
  10463. postNumberString = L")";
  10464. for (int i = 0; i < size() - 1; ++i)
  10465. {
  10466. String& s = strings.getReference(i);
  10467. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10468. if (nextIndex >= 0)
  10469. {
  10470. const String original (s);
  10471. int number = 0;
  10472. if (appendNumberToFirstInstance)
  10473. s = original + preNumberString + String (++number) + postNumberString;
  10474. else
  10475. ++number;
  10476. while (nextIndex >= 0)
  10477. {
  10478. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10479. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10480. }
  10481. }
  10482. }
  10483. }
  10484. void StringArray::minimiseStorageOverheads()
  10485. {
  10486. strings.minimiseStorageOverheads();
  10487. }
  10488. END_JUCE_NAMESPACE
  10489. /*** End of inlined file: juce_StringArray.cpp ***/
  10490. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10491. BEGIN_JUCE_NAMESPACE
  10492. StringPairArray::StringPairArray (const bool ignoreCase_)
  10493. : ignoreCase (ignoreCase_)
  10494. {
  10495. }
  10496. StringPairArray::StringPairArray (const StringPairArray& other)
  10497. : keys (other.keys),
  10498. values (other.values),
  10499. ignoreCase (other.ignoreCase)
  10500. {
  10501. }
  10502. StringPairArray::~StringPairArray()
  10503. {
  10504. }
  10505. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10506. {
  10507. keys = other.keys;
  10508. values = other.values;
  10509. return *this;
  10510. }
  10511. bool StringPairArray::operator== (const StringPairArray& other) const
  10512. {
  10513. for (int i = keys.size(); --i >= 0;)
  10514. if (other [keys[i]] != values[i])
  10515. return false;
  10516. return true;
  10517. }
  10518. bool StringPairArray::operator!= (const StringPairArray& other) const
  10519. {
  10520. return ! operator== (other);
  10521. }
  10522. const String& StringPairArray::operator[] (const String& key) const
  10523. {
  10524. return values [keys.indexOf (key, ignoreCase)];
  10525. }
  10526. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10527. {
  10528. const int i = keys.indexOf (key, ignoreCase);
  10529. if (i >= 0)
  10530. return values[i];
  10531. return defaultReturnValue;
  10532. }
  10533. void StringPairArray::set (const String& key, const String& value)
  10534. {
  10535. const int i = keys.indexOf (key, ignoreCase);
  10536. if (i >= 0)
  10537. {
  10538. values.set (i, value);
  10539. }
  10540. else
  10541. {
  10542. keys.add (key);
  10543. values.add (value);
  10544. }
  10545. }
  10546. void StringPairArray::addArray (const StringPairArray& other)
  10547. {
  10548. for (int i = 0; i < other.size(); ++i)
  10549. set (other.keys[i], other.values[i]);
  10550. }
  10551. void StringPairArray::clear()
  10552. {
  10553. keys.clear();
  10554. values.clear();
  10555. }
  10556. void StringPairArray::remove (const String& key)
  10557. {
  10558. remove (keys.indexOf (key, ignoreCase));
  10559. }
  10560. void StringPairArray::remove (const int index)
  10561. {
  10562. keys.remove (index);
  10563. values.remove (index);
  10564. }
  10565. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10566. {
  10567. ignoreCase = shouldIgnoreCase;
  10568. }
  10569. const String StringPairArray::getDescription() const
  10570. {
  10571. String s;
  10572. for (int i = 0; i < keys.size(); ++i)
  10573. {
  10574. s << keys[i] << " = " << values[i];
  10575. if (i < keys.size())
  10576. s << ", ";
  10577. }
  10578. return s;
  10579. }
  10580. void StringPairArray::minimiseStorageOverheads()
  10581. {
  10582. keys.minimiseStorageOverheads();
  10583. values.minimiseStorageOverheads();
  10584. }
  10585. END_JUCE_NAMESPACE
  10586. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10587. /*** Start of inlined file: juce_StringPool.cpp ***/
  10588. BEGIN_JUCE_NAMESPACE
  10589. StringPool::StringPool() throw() {}
  10590. StringPool::~StringPool() {}
  10591. template <class StringType>
  10592. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10593. {
  10594. int start = 0;
  10595. int end = strings.size();
  10596. for (;;)
  10597. {
  10598. if (start >= end)
  10599. {
  10600. jassert (start <= end);
  10601. strings.insert (start, newString);
  10602. return strings.getReference (start);
  10603. }
  10604. else
  10605. {
  10606. const String& startString = strings.getReference (start);
  10607. if (startString == newString)
  10608. return startString;
  10609. const int halfway = (start + end) >> 1;
  10610. if (halfway == start)
  10611. {
  10612. if (startString.compare (newString) < 0)
  10613. ++start;
  10614. strings.insert (start, newString);
  10615. return strings.getReference (start);
  10616. }
  10617. const int comp = strings.getReference (halfway).compare (newString);
  10618. if (comp == 0)
  10619. return strings.getReference (halfway);
  10620. else if (comp < 0)
  10621. start = halfway;
  10622. else
  10623. end = halfway;
  10624. }
  10625. }
  10626. }
  10627. const juce_wchar* StringPool::getPooledString (const String& s)
  10628. {
  10629. if (s.isEmpty())
  10630. return String::empty;
  10631. return getPooledStringFromArray (strings, s);
  10632. }
  10633. const juce_wchar* StringPool::getPooledString (const char* const s)
  10634. {
  10635. if (s == 0 || *s == 0)
  10636. return String::empty;
  10637. return getPooledStringFromArray (strings, s);
  10638. }
  10639. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10640. {
  10641. if (s == 0 || *s == 0)
  10642. return String::empty;
  10643. return getPooledStringFromArray (strings, s);
  10644. }
  10645. int StringPool::size() const throw()
  10646. {
  10647. return strings.size();
  10648. }
  10649. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10650. {
  10651. return strings [index];
  10652. }
  10653. END_JUCE_NAMESPACE
  10654. /*** End of inlined file: juce_StringPool.cpp ***/
  10655. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10656. BEGIN_JUCE_NAMESPACE
  10657. XmlDocument::XmlDocument (const String& documentText)
  10658. : originalText (documentText),
  10659. ignoreEmptyTextElements (true)
  10660. {
  10661. }
  10662. XmlDocument::XmlDocument (const File& file)
  10663. : ignoreEmptyTextElements (true)
  10664. {
  10665. inputSource = new FileInputSource (file);
  10666. }
  10667. XmlDocument::~XmlDocument()
  10668. {
  10669. }
  10670. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10671. {
  10672. inputSource = newSource;
  10673. }
  10674. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10675. {
  10676. ignoreEmptyTextElements = shouldBeIgnored;
  10677. }
  10678. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10679. {
  10680. return CharacterFunctions::isLetterOrDigit (c)
  10681. || c == '_' || c == '-' || c == ':' || c == '.';
  10682. }
  10683. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10684. {
  10685. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10686. : isXmlIdentifierCharSlow (c);
  10687. }
  10688. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10689. {
  10690. String textToParse (originalText);
  10691. if (textToParse.isEmpty() && inputSource != 0)
  10692. {
  10693. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10694. if (in != 0)
  10695. {
  10696. MemoryOutputStream data;
  10697. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  10698. textToParse = data.toString();
  10699. if (! onlyReadOuterDocumentElement)
  10700. originalText = textToParse;
  10701. }
  10702. }
  10703. input = textToParse;
  10704. lastError = String::empty;
  10705. errorOccurred = false;
  10706. outOfData = false;
  10707. needToLoadDTD = true;
  10708. for (int i = 0; i < 128; ++i)
  10709. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10710. if (textToParse.isEmpty())
  10711. {
  10712. lastError = "not enough input";
  10713. }
  10714. else
  10715. {
  10716. skipHeader();
  10717. if (input != 0)
  10718. {
  10719. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10720. if (! errorOccurred)
  10721. return result.release();
  10722. }
  10723. else
  10724. {
  10725. lastError = "incorrect xml header";
  10726. }
  10727. }
  10728. return 0;
  10729. }
  10730. const String& XmlDocument::getLastParseError() const throw()
  10731. {
  10732. return lastError;
  10733. }
  10734. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10735. {
  10736. lastError = desc;
  10737. errorOccurred = ! carryOn;
  10738. }
  10739. const String XmlDocument::getFileContents (const String& filename) const
  10740. {
  10741. if (inputSource != 0)
  10742. {
  10743. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10744. if (in != 0)
  10745. return in->readEntireStreamAsString();
  10746. }
  10747. return String::empty;
  10748. }
  10749. juce_wchar XmlDocument::readNextChar() throw()
  10750. {
  10751. if (*input != 0)
  10752. {
  10753. return *input++;
  10754. }
  10755. else
  10756. {
  10757. outOfData = true;
  10758. return 0;
  10759. }
  10760. }
  10761. int XmlDocument::findNextTokenLength() throw()
  10762. {
  10763. int len = 0;
  10764. juce_wchar c = *input;
  10765. while (isXmlIdentifierChar (c))
  10766. c = input [++len];
  10767. return len;
  10768. }
  10769. void XmlDocument::skipHeader()
  10770. {
  10771. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10772. if (found != 0)
  10773. {
  10774. input = found;
  10775. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10776. if (input == 0)
  10777. return;
  10778. input += 2;
  10779. }
  10780. skipNextWhiteSpace();
  10781. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10782. if (docType == 0)
  10783. return;
  10784. input = docType + 9;
  10785. int n = 1;
  10786. while (n > 0)
  10787. {
  10788. const juce_wchar c = readNextChar();
  10789. if (outOfData)
  10790. return;
  10791. if (c == '<')
  10792. ++n;
  10793. else if (c == '>')
  10794. --n;
  10795. }
  10796. docType += 9;
  10797. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10798. }
  10799. void XmlDocument::skipNextWhiteSpace()
  10800. {
  10801. for (;;)
  10802. {
  10803. juce_wchar c = *input;
  10804. while (CharacterFunctions::isWhitespace (c))
  10805. c = *++input;
  10806. if (c == 0)
  10807. {
  10808. outOfData = true;
  10809. break;
  10810. }
  10811. else if (c == '<')
  10812. {
  10813. if (input[1] == '!'
  10814. && input[2] == '-'
  10815. && input[3] == '-')
  10816. {
  10817. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10818. if (closeComment == 0)
  10819. {
  10820. outOfData = true;
  10821. break;
  10822. }
  10823. input = closeComment + 3;
  10824. continue;
  10825. }
  10826. else if (input[1] == '?')
  10827. {
  10828. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10829. if (closeBracket == 0)
  10830. {
  10831. outOfData = true;
  10832. break;
  10833. }
  10834. input = closeBracket + 2;
  10835. continue;
  10836. }
  10837. }
  10838. break;
  10839. }
  10840. }
  10841. void XmlDocument::readQuotedString (String& result)
  10842. {
  10843. const juce_wchar quote = readNextChar();
  10844. while (! outOfData)
  10845. {
  10846. const juce_wchar c = readNextChar();
  10847. if (c == quote)
  10848. break;
  10849. if (c == '&')
  10850. {
  10851. --input;
  10852. readEntity (result);
  10853. }
  10854. else
  10855. {
  10856. --input;
  10857. const juce_wchar* const start = input;
  10858. for (;;)
  10859. {
  10860. const juce_wchar character = *input;
  10861. if (character == quote)
  10862. {
  10863. result.append (start, (int) (input - start));
  10864. ++input;
  10865. return;
  10866. }
  10867. else if (character == '&')
  10868. {
  10869. result.append (start, (int) (input - start));
  10870. break;
  10871. }
  10872. else if (character == 0)
  10873. {
  10874. outOfData = true;
  10875. setLastError ("unmatched quotes", false);
  10876. break;
  10877. }
  10878. ++input;
  10879. }
  10880. }
  10881. }
  10882. }
  10883. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10884. {
  10885. XmlElement* node = 0;
  10886. skipNextWhiteSpace();
  10887. if (outOfData)
  10888. return 0;
  10889. input = CharacterFunctions::find (input, JUCE_T("<"));
  10890. if (input != 0)
  10891. {
  10892. ++input;
  10893. int tagLen = findNextTokenLength();
  10894. if (tagLen == 0)
  10895. {
  10896. // no tag name - but allow for a gap after the '<' before giving an error
  10897. skipNextWhiteSpace();
  10898. tagLen = findNextTokenLength();
  10899. if (tagLen == 0)
  10900. {
  10901. setLastError ("tag name missing", false);
  10902. return node;
  10903. }
  10904. }
  10905. node = new XmlElement (String (input, tagLen));
  10906. input += tagLen;
  10907. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10908. // look for attributes
  10909. for (;;)
  10910. {
  10911. skipNextWhiteSpace();
  10912. const juce_wchar c = *input;
  10913. // empty tag..
  10914. if (c == '/' && input[1] == '>')
  10915. {
  10916. input += 2;
  10917. break;
  10918. }
  10919. // parse the guts of the element..
  10920. if (c == '>')
  10921. {
  10922. ++input;
  10923. skipNextWhiteSpace();
  10924. if (alsoParseSubElements)
  10925. readChildElements (node);
  10926. break;
  10927. }
  10928. // get an attribute..
  10929. if (isXmlIdentifierChar (c))
  10930. {
  10931. const int attNameLen = findNextTokenLength();
  10932. if (attNameLen > 0)
  10933. {
  10934. const juce_wchar* attNameStart = input;
  10935. input += attNameLen;
  10936. skipNextWhiteSpace();
  10937. if (readNextChar() == '=')
  10938. {
  10939. skipNextWhiteSpace();
  10940. const juce_wchar nextChar = *input;
  10941. if (nextChar == '"' || nextChar == '\'')
  10942. {
  10943. XmlElement::XmlAttributeNode* const newAtt
  10944. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10945. String::empty);
  10946. readQuotedString (newAtt->value);
  10947. if (lastAttribute == 0)
  10948. node->attributes = newAtt;
  10949. else
  10950. lastAttribute->next = newAtt;
  10951. lastAttribute = newAtt;
  10952. continue;
  10953. }
  10954. }
  10955. }
  10956. }
  10957. else
  10958. {
  10959. if (! outOfData)
  10960. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10961. }
  10962. break;
  10963. }
  10964. }
  10965. return node;
  10966. }
  10967. void XmlDocument::readChildElements (XmlElement* parent)
  10968. {
  10969. XmlElement* lastChildNode = 0;
  10970. for (;;)
  10971. {
  10972. skipNextWhiteSpace();
  10973. if (outOfData)
  10974. {
  10975. setLastError ("unmatched tags", false);
  10976. break;
  10977. }
  10978. if (*input == '<')
  10979. {
  10980. if (input[1] == '/')
  10981. {
  10982. // our close tag..
  10983. input = CharacterFunctions::find (input, JUCE_T(">"));
  10984. ++input;
  10985. break;
  10986. }
  10987. else if (input[1] == '!'
  10988. && input[2] == '['
  10989. && input[3] == 'C'
  10990. && input[4] == 'D'
  10991. && input[5] == 'A'
  10992. && input[6] == 'T'
  10993. && input[7] == 'A'
  10994. && input[8] == '[')
  10995. {
  10996. input += 9;
  10997. const juce_wchar* const inputStart = input;
  10998. int len = 0;
  10999. for (;;)
  11000. {
  11001. if (*input == 0)
  11002. {
  11003. setLastError ("unterminated CDATA section", false);
  11004. outOfData = true;
  11005. break;
  11006. }
  11007. else if (input[0] == ']'
  11008. && input[1] == ']'
  11009. && input[2] == '>')
  11010. {
  11011. input += 3;
  11012. break;
  11013. }
  11014. ++input;
  11015. ++len;
  11016. }
  11017. XmlElement* const e = new XmlElement ((int) 0);
  11018. e->setText (String (inputStart, len));
  11019. if (lastChildNode != 0)
  11020. lastChildNode->nextElement = e;
  11021. else
  11022. parent->addChildElement (e);
  11023. lastChildNode = e;
  11024. }
  11025. else
  11026. {
  11027. // this is some other element, so parse and add it..
  11028. XmlElement* const n = readNextElement (true);
  11029. if (n != 0)
  11030. {
  11031. if (lastChildNode == 0)
  11032. parent->addChildElement (n);
  11033. else
  11034. lastChildNode->nextElement = n;
  11035. lastChildNode = n;
  11036. }
  11037. else
  11038. {
  11039. return;
  11040. }
  11041. }
  11042. }
  11043. else
  11044. {
  11045. // read character block..
  11046. XmlElement* const e = new XmlElement ((int)0);
  11047. if (lastChildNode != 0)
  11048. lastChildNode->nextElement = e;
  11049. else
  11050. parent->addChildElement (e);
  11051. lastChildNode = e;
  11052. String textElementContent;
  11053. for (;;)
  11054. {
  11055. const juce_wchar c = *input;
  11056. if (c == '<')
  11057. break;
  11058. if (c == 0)
  11059. {
  11060. setLastError ("unmatched tags", false);
  11061. outOfData = true;
  11062. return;
  11063. }
  11064. if (c == '&')
  11065. {
  11066. String entity;
  11067. readEntity (entity);
  11068. if (entity.startsWithChar ('<') && entity [1] != 0)
  11069. {
  11070. const juce_wchar* const oldInput = input;
  11071. const bool oldOutOfData = outOfData;
  11072. input = entity;
  11073. outOfData = false;
  11074. for (;;)
  11075. {
  11076. XmlElement* const n = readNextElement (true);
  11077. if (n == 0)
  11078. break;
  11079. if (lastChildNode == 0)
  11080. parent->addChildElement (n);
  11081. else
  11082. lastChildNode->nextElement = n;
  11083. lastChildNode = n;
  11084. }
  11085. input = oldInput;
  11086. outOfData = oldOutOfData;
  11087. }
  11088. else
  11089. {
  11090. textElementContent += entity;
  11091. }
  11092. }
  11093. else
  11094. {
  11095. const juce_wchar* start = input;
  11096. int len = 0;
  11097. for (;;)
  11098. {
  11099. const juce_wchar nextChar = *input;
  11100. if (nextChar == '<' || nextChar == '&')
  11101. {
  11102. break;
  11103. }
  11104. else if (nextChar == 0)
  11105. {
  11106. setLastError ("unmatched tags", false);
  11107. outOfData = true;
  11108. return;
  11109. }
  11110. ++input;
  11111. ++len;
  11112. }
  11113. textElementContent.append (start, len);
  11114. }
  11115. }
  11116. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11117. : textElementContent.isNotEmpty())
  11118. e->setText (textElementContent);
  11119. }
  11120. }
  11121. }
  11122. void XmlDocument::readEntity (String& result)
  11123. {
  11124. // skip over the ampersand
  11125. ++input;
  11126. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11127. {
  11128. input += 4;
  11129. result += '&';
  11130. }
  11131. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11132. {
  11133. input += 5;
  11134. result += '"';
  11135. }
  11136. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11137. {
  11138. input += 5;
  11139. result += '\'';
  11140. }
  11141. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11142. {
  11143. input += 3;
  11144. result += '<';
  11145. }
  11146. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11147. {
  11148. input += 3;
  11149. result += '>';
  11150. }
  11151. else if (*input == '#')
  11152. {
  11153. int charCode = 0;
  11154. ++input;
  11155. if (*input == 'x' || *input == 'X')
  11156. {
  11157. ++input;
  11158. int numChars = 0;
  11159. while (input[0] != ';')
  11160. {
  11161. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11162. if (hexValue < 0 || ++numChars > 8)
  11163. {
  11164. setLastError ("illegal escape sequence", true);
  11165. break;
  11166. }
  11167. charCode = (charCode << 4) | hexValue;
  11168. ++input;
  11169. }
  11170. ++input;
  11171. }
  11172. else if (input[0] >= '0' && input[0] <= '9')
  11173. {
  11174. int numChars = 0;
  11175. while (input[0] != ';')
  11176. {
  11177. if (++numChars > 12)
  11178. {
  11179. setLastError ("illegal escape sequence", true);
  11180. break;
  11181. }
  11182. charCode = charCode * 10 + (input[0] - '0');
  11183. ++input;
  11184. }
  11185. ++input;
  11186. }
  11187. else
  11188. {
  11189. setLastError ("illegal escape sequence", true);
  11190. result += '&';
  11191. return;
  11192. }
  11193. result << (juce_wchar) charCode;
  11194. }
  11195. else
  11196. {
  11197. const juce_wchar* const entityNameStart = input;
  11198. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11199. if (closingSemiColon == 0)
  11200. {
  11201. outOfData = true;
  11202. result += '&';
  11203. }
  11204. else
  11205. {
  11206. input = closingSemiColon + 1;
  11207. result += expandExternalEntity (String (entityNameStart,
  11208. (int) (closingSemiColon - entityNameStart)));
  11209. }
  11210. }
  11211. }
  11212. const String XmlDocument::expandEntity (const String& ent)
  11213. {
  11214. if (ent.equalsIgnoreCase ("amp"))
  11215. return String::charToString ('&');
  11216. if (ent.equalsIgnoreCase ("quot"))
  11217. return String::charToString ('"');
  11218. if (ent.equalsIgnoreCase ("apos"))
  11219. return String::charToString ('\'');
  11220. if (ent.equalsIgnoreCase ("lt"))
  11221. return String::charToString ('<');
  11222. if (ent.equalsIgnoreCase ("gt"))
  11223. return String::charToString ('>');
  11224. if (ent[0] == '#')
  11225. {
  11226. if (ent[1] == 'x' || ent[1] == 'X')
  11227. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11228. if (ent[1] >= '0' && ent[1] <= '9')
  11229. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11230. setLastError ("illegal escape sequence", false);
  11231. return String::charToString ('&');
  11232. }
  11233. return expandExternalEntity (ent);
  11234. }
  11235. const String XmlDocument::expandExternalEntity (const String& entity)
  11236. {
  11237. if (needToLoadDTD)
  11238. {
  11239. if (dtdText.isNotEmpty())
  11240. {
  11241. dtdText = dtdText.trimCharactersAtEnd (">");
  11242. tokenisedDTD.addTokens (dtdText, true);
  11243. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11244. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11245. {
  11246. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11247. tokenisedDTD.clear();
  11248. tokenisedDTD.addTokens (getFileContents (fn), true);
  11249. }
  11250. else
  11251. {
  11252. tokenisedDTD.clear();
  11253. const int openBracket = dtdText.indexOfChar ('[');
  11254. if (openBracket > 0)
  11255. {
  11256. const int closeBracket = dtdText.lastIndexOfChar (']');
  11257. if (closeBracket > openBracket)
  11258. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11259. closeBracket), true);
  11260. }
  11261. }
  11262. for (int i = tokenisedDTD.size(); --i >= 0;)
  11263. {
  11264. if (tokenisedDTD[i].startsWithChar ('%')
  11265. && tokenisedDTD[i].endsWithChar (';'))
  11266. {
  11267. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11268. StringArray newToks;
  11269. newToks.addTokens (parsed, true);
  11270. tokenisedDTD.remove (i);
  11271. for (int j = newToks.size(); --j >= 0;)
  11272. tokenisedDTD.insert (i, newToks[j]);
  11273. }
  11274. }
  11275. }
  11276. needToLoadDTD = false;
  11277. }
  11278. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11279. {
  11280. if (tokenisedDTD[i] == entity)
  11281. {
  11282. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11283. {
  11284. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11285. // check for sub-entities..
  11286. int ampersand = ent.indexOfChar ('&');
  11287. while (ampersand >= 0)
  11288. {
  11289. const int semiColon = ent.indexOf (i + 1, ";");
  11290. if (semiColon < 0)
  11291. {
  11292. setLastError ("entity without terminating semi-colon", false);
  11293. break;
  11294. }
  11295. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11296. ent = ent.substring (0, ampersand)
  11297. + resolved
  11298. + ent.substring (semiColon + 1);
  11299. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11300. }
  11301. return ent;
  11302. }
  11303. }
  11304. }
  11305. setLastError ("unknown entity", true);
  11306. return entity;
  11307. }
  11308. const String XmlDocument::getParameterEntity (const String& entity)
  11309. {
  11310. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11311. {
  11312. if (tokenisedDTD[i] == entity)
  11313. {
  11314. if (tokenisedDTD [i - 1] == "%"
  11315. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11316. {
  11317. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11318. if (ent.equalsIgnoreCase ("system"))
  11319. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11320. else
  11321. return ent.trim().unquoted();
  11322. }
  11323. }
  11324. }
  11325. return entity;
  11326. }
  11327. END_JUCE_NAMESPACE
  11328. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11329. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11330. BEGIN_JUCE_NAMESPACE
  11331. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11332. : name (other.name),
  11333. value (other.value),
  11334. next (0)
  11335. {
  11336. }
  11337. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11338. : name (name_),
  11339. value (value_),
  11340. next (0)
  11341. {
  11342. }
  11343. XmlElement::XmlElement (const String& tagName_) throw()
  11344. : tagName (tagName_),
  11345. firstChildElement (0),
  11346. nextElement (0),
  11347. attributes (0)
  11348. {
  11349. // the tag name mustn't be empty, or it'll look like a text element!
  11350. jassert (tagName_.containsNonWhitespaceChars())
  11351. // The tag can't contain spaces or other characters that would create invalid XML!
  11352. jassert (! tagName_.containsAnyOf (" <>/&"));
  11353. }
  11354. XmlElement::XmlElement (int /*dummy*/) throw()
  11355. : firstChildElement (0),
  11356. nextElement (0),
  11357. attributes (0)
  11358. {
  11359. }
  11360. XmlElement::XmlElement (const XmlElement& other)
  11361. : tagName (other.tagName),
  11362. firstChildElement (0),
  11363. nextElement (0),
  11364. attributes (0)
  11365. {
  11366. copyChildrenAndAttributesFrom (other);
  11367. }
  11368. XmlElement& XmlElement::operator= (const XmlElement& other)
  11369. {
  11370. if (this != &other)
  11371. {
  11372. removeAllAttributes();
  11373. deleteAllChildElements();
  11374. tagName = other.tagName;
  11375. copyChildrenAndAttributesFrom (other);
  11376. }
  11377. return *this;
  11378. }
  11379. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11380. {
  11381. XmlElement* child = other.firstChildElement;
  11382. XmlElement* lastChild = 0;
  11383. while (child != 0)
  11384. {
  11385. XmlElement* const copiedChild = new XmlElement (*child);
  11386. if (lastChild != 0)
  11387. lastChild->nextElement = copiedChild;
  11388. else
  11389. firstChildElement = copiedChild;
  11390. lastChild = copiedChild;
  11391. child = child->nextElement;
  11392. }
  11393. const XmlAttributeNode* att = other.attributes;
  11394. XmlAttributeNode* lastAtt = 0;
  11395. while (att != 0)
  11396. {
  11397. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11398. if (lastAtt != 0)
  11399. lastAtt->next = newAtt;
  11400. else
  11401. attributes = newAtt;
  11402. lastAtt = newAtt;
  11403. att = att->next;
  11404. }
  11405. }
  11406. XmlElement::~XmlElement() throw()
  11407. {
  11408. XmlElement* child = firstChildElement;
  11409. while (child != 0)
  11410. {
  11411. XmlElement* const nextChild = child->nextElement;
  11412. delete child;
  11413. child = nextChild;
  11414. }
  11415. XmlAttributeNode* att = attributes;
  11416. while (att != 0)
  11417. {
  11418. XmlAttributeNode* const nextAtt = att->next;
  11419. delete att;
  11420. att = nextAtt;
  11421. }
  11422. }
  11423. namespace XmlOutputFunctions
  11424. {
  11425. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11426. {
  11427. if ((character >= 'a' && character <= 'z')
  11428. || (character >= 'A' && character <= 'Z')
  11429. || (character >= '0' && character <= '9'))
  11430. return true;
  11431. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  11432. do
  11433. {
  11434. if (((juce_wchar) (uint8) *t) == character)
  11435. return true;
  11436. }
  11437. while (*++t != 0);
  11438. return false;
  11439. }
  11440. static void generateLegalCharConstants()
  11441. {
  11442. uint8 n[32];
  11443. zerostruct (n);
  11444. for (int i = 0; i < 256; ++i)
  11445. if (isLegalXmlCharSlow (i))
  11446. n[i >> 3] |= (1 << (i & 7));
  11447. String s;
  11448. for (int i = 0; i < 32; ++i)
  11449. s << (int) n[i] << ", ";
  11450. DBG (s);
  11451. }*/
  11452. static bool isLegalXmlChar (const uint32 c) throw()
  11453. {
  11454. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  11455. return c < sizeof (legalChars) * 8
  11456. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11457. }
  11458. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11459. {
  11460. const juce_wchar* t = text;
  11461. for (;;)
  11462. {
  11463. const juce_wchar character = *t++;
  11464. if (character == 0)
  11465. {
  11466. break;
  11467. }
  11468. else if (isLegalXmlChar ((uint32) character))
  11469. {
  11470. outputStream << (char) character;
  11471. }
  11472. else
  11473. {
  11474. switch (character)
  11475. {
  11476. case '&': outputStream << "&amp;"; break;
  11477. case '"': outputStream << "&quot;"; break;
  11478. case '>': outputStream << "&gt;"; break;
  11479. case '<': outputStream << "&lt;"; break;
  11480. case '\n':
  11481. if (changeNewLines)
  11482. outputStream << "&#10;";
  11483. else
  11484. outputStream << (char) character;
  11485. break;
  11486. case '\r':
  11487. if (changeNewLines)
  11488. outputStream << "&#13;";
  11489. else
  11490. outputStream << (char) character;
  11491. break;
  11492. default:
  11493. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11494. break;
  11495. }
  11496. }
  11497. }
  11498. }
  11499. static void writeSpaces (OutputStream& out, int numSpaces)
  11500. {
  11501. if (numSpaces > 0)
  11502. {
  11503. const char* const blanks = " ";
  11504. const int blankSize = (int) sizeof (blanks) - 1;
  11505. while (numSpaces > blankSize)
  11506. {
  11507. out.write (blanks, blankSize);
  11508. numSpaces -= blankSize;
  11509. }
  11510. out.write (blanks, numSpaces);
  11511. }
  11512. }
  11513. }
  11514. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11515. const int indentationLevel,
  11516. const int lineWrapLength) const
  11517. {
  11518. using namespace XmlOutputFunctions;
  11519. writeSpaces (outputStream, indentationLevel);
  11520. if (! isTextElement())
  11521. {
  11522. outputStream.writeByte ('<');
  11523. outputStream << tagName;
  11524. const int attIndent = indentationLevel + tagName.length() + 1;
  11525. int lineLen = 0;
  11526. const XmlAttributeNode* att = attributes;
  11527. while (att != 0)
  11528. {
  11529. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11530. {
  11531. outputStream.write ("\r\n", 2);
  11532. writeSpaces (outputStream, attIndent);
  11533. lineLen = 0;
  11534. }
  11535. const int64 startPos = outputStream.getPosition();
  11536. outputStream.writeByte (' ');
  11537. outputStream << att->name;
  11538. outputStream.write ("=\"", 2);
  11539. escapeIllegalXmlChars (outputStream, att->value, true);
  11540. outputStream.writeByte ('"');
  11541. lineLen += (int) (outputStream.getPosition() - startPos);
  11542. att = att->next;
  11543. }
  11544. if (firstChildElement != 0)
  11545. {
  11546. XmlElement* child = firstChildElement;
  11547. if (child->nextElement == 0 && child->isTextElement())
  11548. {
  11549. outputStream.writeByte ('>');
  11550. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11551. }
  11552. else
  11553. {
  11554. if (indentationLevel >= 0)
  11555. outputStream.write (">\r\n", 3);
  11556. else
  11557. outputStream.writeByte ('>');
  11558. bool lastWasTextNode = false;
  11559. while (child != 0)
  11560. {
  11561. if (child->isTextElement())
  11562. {
  11563. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11564. writeSpaces (outputStream, indentationLevel + 2);
  11565. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11566. lastWasTextNode = true;
  11567. }
  11568. else
  11569. {
  11570. if (indentationLevel >= 0)
  11571. {
  11572. if (lastWasTextNode)
  11573. outputStream.write ("\r\n", 2);
  11574. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11575. }
  11576. else
  11577. {
  11578. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11579. }
  11580. lastWasTextNode = false;
  11581. }
  11582. child = child->nextElement;
  11583. }
  11584. if (indentationLevel >= 0)
  11585. {
  11586. if (lastWasTextNode)
  11587. outputStream.write ("\r\n", 2);
  11588. writeSpaces (outputStream, indentationLevel);
  11589. }
  11590. }
  11591. outputStream.write ("</", 2);
  11592. outputStream << tagName;
  11593. if (indentationLevel >= 0)
  11594. outputStream.write (">\r\n", 3);
  11595. else
  11596. outputStream.writeByte ('>');
  11597. }
  11598. else
  11599. {
  11600. if (indentationLevel >= 0)
  11601. outputStream.write ("/>\r\n", 4);
  11602. else
  11603. outputStream.write ("/>", 2);
  11604. }
  11605. }
  11606. else
  11607. {
  11608. if (indentationLevel >= 0)
  11609. writeSpaces (outputStream, indentationLevel + 2);
  11610. escapeIllegalXmlChars (outputStream, getText(), false);
  11611. }
  11612. }
  11613. const String XmlElement::createDocument (const String& dtdToUse,
  11614. const bool allOnOneLine,
  11615. const bool includeXmlHeader,
  11616. const String& encodingType,
  11617. const int lineWrapLength) const
  11618. {
  11619. MemoryOutputStream mem (2048);
  11620. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11621. return mem.toUTF8();
  11622. }
  11623. void XmlElement::writeToStream (OutputStream& output,
  11624. const String& dtdToUse,
  11625. const bool allOnOneLine,
  11626. const bool includeXmlHeader,
  11627. const String& encodingType,
  11628. const int lineWrapLength) const
  11629. {
  11630. if (includeXmlHeader)
  11631. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11632. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11633. if (dtdToUse.isNotEmpty())
  11634. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11635. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11636. }
  11637. bool XmlElement::writeToFile (const File& file,
  11638. const String& dtdToUse,
  11639. const String& encodingType,
  11640. const int lineWrapLength) const
  11641. {
  11642. if (file.hasWriteAccess())
  11643. {
  11644. TemporaryFile tempFile (file);
  11645. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11646. if (out != 0)
  11647. {
  11648. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11649. out = 0;
  11650. return tempFile.overwriteTargetFileWithTemporary();
  11651. }
  11652. }
  11653. return false;
  11654. }
  11655. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11656. {
  11657. #if JUCE_DEBUG
  11658. // if debugging, check that the case is actually the same, because
  11659. // valid xml is case-sensitive, and although this lets it pass, it's
  11660. // better not to..
  11661. if (tagName.equalsIgnoreCase (tagNameWanted))
  11662. {
  11663. jassert (tagName == tagNameWanted);
  11664. return true;
  11665. }
  11666. else
  11667. {
  11668. return false;
  11669. }
  11670. #else
  11671. return tagName.equalsIgnoreCase (tagNameWanted);
  11672. #endif
  11673. }
  11674. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11675. {
  11676. XmlElement* e = nextElement;
  11677. while (e != 0 && ! e->hasTagName (requiredTagName))
  11678. e = e->nextElement;
  11679. return e;
  11680. }
  11681. int XmlElement::getNumAttributes() const throw()
  11682. {
  11683. const XmlAttributeNode* att = attributes;
  11684. int count = 0;
  11685. while (att != 0)
  11686. {
  11687. att = att->next;
  11688. ++count;
  11689. }
  11690. return count;
  11691. }
  11692. const String& XmlElement::getAttributeName (const int index) const throw()
  11693. {
  11694. const XmlAttributeNode* att = attributes;
  11695. int count = 0;
  11696. while (att != 0)
  11697. {
  11698. if (count == index)
  11699. return att->name;
  11700. att = att->next;
  11701. ++count;
  11702. }
  11703. return String::empty;
  11704. }
  11705. const String& XmlElement::getAttributeValue (const int index) const throw()
  11706. {
  11707. const XmlAttributeNode* att = attributes;
  11708. int count = 0;
  11709. while (att != 0)
  11710. {
  11711. if (count == index)
  11712. return att->value;
  11713. att = att->next;
  11714. ++count;
  11715. }
  11716. return String::empty;
  11717. }
  11718. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11719. {
  11720. const XmlAttributeNode* att = attributes;
  11721. while (att != 0)
  11722. {
  11723. if (att->name.equalsIgnoreCase (attributeName))
  11724. return true;
  11725. att = att->next;
  11726. }
  11727. return false;
  11728. }
  11729. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11730. {
  11731. const XmlAttributeNode* att = attributes;
  11732. while (att != 0)
  11733. {
  11734. if (att->name.equalsIgnoreCase (attributeName))
  11735. return att->value;
  11736. att = att->next;
  11737. }
  11738. return String::empty;
  11739. }
  11740. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11741. {
  11742. const XmlAttributeNode* att = attributes;
  11743. while (att != 0)
  11744. {
  11745. if (att->name.equalsIgnoreCase (attributeName))
  11746. return att->value;
  11747. att = att->next;
  11748. }
  11749. return defaultReturnValue;
  11750. }
  11751. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11752. {
  11753. const XmlAttributeNode* att = attributes;
  11754. while (att != 0)
  11755. {
  11756. if (att->name.equalsIgnoreCase (attributeName))
  11757. return att->value.getIntValue();
  11758. att = att->next;
  11759. }
  11760. return defaultReturnValue;
  11761. }
  11762. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11763. {
  11764. const XmlAttributeNode* att = attributes;
  11765. while (att != 0)
  11766. {
  11767. if (att->name.equalsIgnoreCase (attributeName))
  11768. return att->value.getDoubleValue();
  11769. att = att->next;
  11770. }
  11771. return defaultReturnValue;
  11772. }
  11773. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11774. {
  11775. const XmlAttributeNode* att = attributes;
  11776. while (att != 0)
  11777. {
  11778. if (att->name.equalsIgnoreCase (attributeName))
  11779. {
  11780. juce_wchar firstChar = att->value[0];
  11781. if (CharacterFunctions::isWhitespace (firstChar))
  11782. firstChar = att->value.trimStart() [0];
  11783. return firstChar == '1'
  11784. || firstChar == 't'
  11785. || firstChar == 'y'
  11786. || firstChar == 'T'
  11787. || firstChar == 'Y';
  11788. }
  11789. att = att->next;
  11790. }
  11791. return defaultReturnValue;
  11792. }
  11793. bool XmlElement::compareAttribute (const String& attributeName,
  11794. const String& stringToCompareAgainst,
  11795. const bool ignoreCase) const throw()
  11796. {
  11797. const XmlAttributeNode* att = attributes;
  11798. while (att != 0)
  11799. {
  11800. if (att->name.equalsIgnoreCase (attributeName))
  11801. {
  11802. if (ignoreCase)
  11803. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11804. else
  11805. return att->value == stringToCompareAgainst;
  11806. }
  11807. att = att->next;
  11808. }
  11809. return false;
  11810. }
  11811. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11812. {
  11813. #if JUCE_DEBUG
  11814. // check the identifier being passed in is legal..
  11815. const juce_wchar* t = attributeName;
  11816. while (*t != 0)
  11817. {
  11818. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11819. || *t == '_'
  11820. || *t == '-'
  11821. || *t == ':');
  11822. ++t;
  11823. }
  11824. #endif
  11825. if (attributes == 0)
  11826. {
  11827. attributes = new XmlAttributeNode (attributeName, value);
  11828. }
  11829. else
  11830. {
  11831. XmlAttributeNode* att = attributes;
  11832. for (;;)
  11833. {
  11834. if (att->name.equalsIgnoreCase (attributeName))
  11835. {
  11836. att->value = value;
  11837. break;
  11838. }
  11839. else if (att->next == 0)
  11840. {
  11841. att->next = new XmlAttributeNode (attributeName, value);
  11842. break;
  11843. }
  11844. att = att->next;
  11845. }
  11846. }
  11847. }
  11848. void XmlElement::setAttribute (const String& attributeName, const int number)
  11849. {
  11850. setAttribute (attributeName, String (number));
  11851. }
  11852. void XmlElement::setAttribute (const String& attributeName, const double number)
  11853. {
  11854. setAttribute (attributeName, String (number));
  11855. }
  11856. void XmlElement::removeAttribute (const String& attributeName) throw()
  11857. {
  11858. XmlAttributeNode* att = attributes;
  11859. XmlAttributeNode* lastAtt = 0;
  11860. while (att != 0)
  11861. {
  11862. if (att->name.equalsIgnoreCase (attributeName))
  11863. {
  11864. if (lastAtt == 0)
  11865. attributes = att->next;
  11866. else
  11867. lastAtt->next = att->next;
  11868. delete att;
  11869. break;
  11870. }
  11871. lastAtt = att;
  11872. att = att->next;
  11873. }
  11874. }
  11875. void XmlElement::removeAllAttributes() throw()
  11876. {
  11877. while (attributes != 0)
  11878. {
  11879. XmlAttributeNode* const nextAtt = attributes->next;
  11880. delete attributes;
  11881. attributes = nextAtt;
  11882. }
  11883. }
  11884. int XmlElement::getNumChildElements() const throw()
  11885. {
  11886. int count = 0;
  11887. const XmlElement* child = firstChildElement;
  11888. while (child != 0)
  11889. {
  11890. ++count;
  11891. child = child->nextElement;
  11892. }
  11893. return count;
  11894. }
  11895. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11896. {
  11897. int count = 0;
  11898. XmlElement* child = firstChildElement;
  11899. while (child != 0 && count < index)
  11900. {
  11901. child = child->nextElement;
  11902. ++count;
  11903. }
  11904. return child;
  11905. }
  11906. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11907. {
  11908. XmlElement* child = firstChildElement;
  11909. while (child != 0)
  11910. {
  11911. if (child->hasTagName (childName))
  11912. break;
  11913. child = child->nextElement;
  11914. }
  11915. return child;
  11916. }
  11917. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11918. {
  11919. if (newNode != 0)
  11920. {
  11921. if (firstChildElement == 0)
  11922. {
  11923. firstChildElement = newNode;
  11924. }
  11925. else
  11926. {
  11927. XmlElement* child = firstChildElement;
  11928. while (child->nextElement != 0)
  11929. child = child->nextElement;
  11930. child->nextElement = newNode;
  11931. // if this is non-zero, then something's probably
  11932. // gone wrong..
  11933. jassert (newNode->nextElement == 0);
  11934. }
  11935. }
  11936. }
  11937. void XmlElement::insertChildElement (XmlElement* const newNode,
  11938. int indexToInsertAt) throw()
  11939. {
  11940. if (newNode != 0)
  11941. {
  11942. removeChildElement (newNode, false);
  11943. if (indexToInsertAt == 0)
  11944. {
  11945. newNode->nextElement = firstChildElement;
  11946. firstChildElement = newNode;
  11947. }
  11948. else
  11949. {
  11950. if (firstChildElement == 0)
  11951. {
  11952. firstChildElement = newNode;
  11953. }
  11954. else
  11955. {
  11956. if (indexToInsertAt < 0)
  11957. indexToInsertAt = std::numeric_limits<int>::max();
  11958. XmlElement* child = firstChildElement;
  11959. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11960. child = child->nextElement;
  11961. newNode->nextElement = child->nextElement;
  11962. child->nextElement = newNode;
  11963. }
  11964. }
  11965. }
  11966. }
  11967. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11968. {
  11969. XmlElement* const newElement = new XmlElement (childTagName);
  11970. addChildElement (newElement);
  11971. return newElement;
  11972. }
  11973. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11974. XmlElement* const newNode) throw()
  11975. {
  11976. if (newNode != 0)
  11977. {
  11978. XmlElement* child = firstChildElement;
  11979. XmlElement* previousNode = 0;
  11980. while (child != 0)
  11981. {
  11982. if (child == currentChildElement)
  11983. {
  11984. if (child != newNode)
  11985. {
  11986. if (previousNode == 0)
  11987. firstChildElement = newNode;
  11988. else
  11989. previousNode->nextElement = newNode;
  11990. newNode->nextElement = child->nextElement;
  11991. delete child;
  11992. }
  11993. return true;
  11994. }
  11995. previousNode = child;
  11996. child = child->nextElement;
  11997. }
  11998. }
  11999. return false;
  12000. }
  12001. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12002. const bool shouldDeleteTheChild) throw()
  12003. {
  12004. if (childToRemove != 0)
  12005. {
  12006. if (firstChildElement == childToRemove)
  12007. {
  12008. firstChildElement = childToRemove->nextElement;
  12009. childToRemove->nextElement = 0;
  12010. }
  12011. else
  12012. {
  12013. XmlElement* child = firstChildElement;
  12014. XmlElement* last = 0;
  12015. while (child != 0)
  12016. {
  12017. if (child == childToRemove)
  12018. {
  12019. if (last == 0)
  12020. firstChildElement = child->nextElement;
  12021. else
  12022. last->nextElement = child->nextElement;
  12023. childToRemove->nextElement = 0;
  12024. break;
  12025. }
  12026. last = child;
  12027. child = child->nextElement;
  12028. }
  12029. }
  12030. if (shouldDeleteTheChild)
  12031. delete childToRemove;
  12032. }
  12033. }
  12034. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12035. const bool ignoreOrderOfAttributes) const throw()
  12036. {
  12037. if (this != other)
  12038. {
  12039. if (other == 0 || tagName != other->tagName)
  12040. {
  12041. return false;
  12042. }
  12043. if (ignoreOrderOfAttributes)
  12044. {
  12045. int totalAtts = 0;
  12046. const XmlAttributeNode* att = attributes;
  12047. while (att != 0)
  12048. {
  12049. if (! other->compareAttribute (att->name, att->value))
  12050. return false;
  12051. att = att->next;
  12052. ++totalAtts;
  12053. }
  12054. if (totalAtts != other->getNumAttributes())
  12055. return false;
  12056. }
  12057. else
  12058. {
  12059. const XmlAttributeNode* thisAtt = attributes;
  12060. const XmlAttributeNode* otherAtt = other->attributes;
  12061. for (;;)
  12062. {
  12063. if (thisAtt == 0 || otherAtt == 0)
  12064. {
  12065. if (thisAtt == otherAtt) // both 0, so it's a match
  12066. break;
  12067. return false;
  12068. }
  12069. if (thisAtt->name != otherAtt->name
  12070. || thisAtt->value != otherAtt->value)
  12071. {
  12072. return false;
  12073. }
  12074. thisAtt = thisAtt->next;
  12075. otherAtt = otherAtt->next;
  12076. }
  12077. }
  12078. const XmlElement* thisChild = firstChildElement;
  12079. const XmlElement* otherChild = other->firstChildElement;
  12080. for (;;)
  12081. {
  12082. if (thisChild == 0 || otherChild == 0)
  12083. {
  12084. if (thisChild == otherChild) // both 0, so it's a match
  12085. break;
  12086. return false;
  12087. }
  12088. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12089. return false;
  12090. thisChild = thisChild->nextElement;
  12091. otherChild = otherChild->nextElement;
  12092. }
  12093. }
  12094. return true;
  12095. }
  12096. void XmlElement::deleteAllChildElements() throw()
  12097. {
  12098. while (firstChildElement != 0)
  12099. {
  12100. XmlElement* const nextChild = firstChildElement->nextElement;
  12101. delete firstChildElement;
  12102. firstChildElement = nextChild;
  12103. }
  12104. }
  12105. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12106. {
  12107. XmlElement* child = firstChildElement;
  12108. while (child != 0)
  12109. {
  12110. if (child->hasTagName (name))
  12111. {
  12112. XmlElement* const nextChild = child->nextElement;
  12113. removeChildElement (child, true);
  12114. child = nextChild;
  12115. }
  12116. else
  12117. {
  12118. child = child->nextElement;
  12119. }
  12120. }
  12121. }
  12122. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12123. {
  12124. const XmlElement* child = firstChildElement;
  12125. while (child != 0)
  12126. {
  12127. if (child == possibleChild)
  12128. return true;
  12129. child = child->nextElement;
  12130. }
  12131. return false;
  12132. }
  12133. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12134. {
  12135. if (this == elementToLookFor || elementToLookFor == 0)
  12136. return 0;
  12137. XmlElement* child = firstChildElement;
  12138. while (child != 0)
  12139. {
  12140. if (elementToLookFor == child)
  12141. return this;
  12142. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12143. if (found != 0)
  12144. return found;
  12145. child = child->nextElement;
  12146. }
  12147. return 0;
  12148. }
  12149. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12150. {
  12151. XmlElement* e = firstChildElement;
  12152. while (e != 0)
  12153. {
  12154. *elems++ = e;
  12155. e = e->nextElement;
  12156. }
  12157. }
  12158. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12159. {
  12160. XmlElement* e = firstChildElement = elems[0];
  12161. for (int i = 1; i < num; ++i)
  12162. {
  12163. e->nextElement = elems[i];
  12164. e = e->nextElement;
  12165. }
  12166. e->nextElement = 0;
  12167. }
  12168. bool XmlElement::isTextElement() const throw()
  12169. {
  12170. return tagName.isEmpty();
  12171. }
  12172. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12173. const String& XmlElement::getText() const throw()
  12174. {
  12175. jassert (isTextElement()); // you're trying to get the text from an element that
  12176. // isn't actually a text element.. If this contains text sub-nodes, you
  12177. // probably want to use getAllSubText instead.
  12178. return getStringAttribute (juce_xmltextContentAttributeName);
  12179. }
  12180. void XmlElement::setText (const String& newText)
  12181. {
  12182. if (isTextElement())
  12183. setAttribute (juce_xmltextContentAttributeName, newText);
  12184. else
  12185. jassertfalse; // you can only change the text in a text element, not a normal one.
  12186. }
  12187. const String XmlElement::getAllSubText() const
  12188. {
  12189. String result;
  12190. String::Concatenator concatenator (result);
  12191. const XmlElement* child = firstChildElement;
  12192. while (child != 0)
  12193. {
  12194. if (child->isTextElement())
  12195. concatenator.append (child->getText());
  12196. child = child->nextElement;
  12197. }
  12198. return result;
  12199. }
  12200. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12201. const String& defaultReturnValue) const
  12202. {
  12203. const XmlElement* const child = getChildByName (childTagName);
  12204. if (child != 0)
  12205. return child->getAllSubText();
  12206. return defaultReturnValue;
  12207. }
  12208. XmlElement* XmlElement::createTextElement (const String& text)
  12209. {
  12210. XmlElement* const e = new XmlElement ((int) 0);
  12211. e->setAttribute (juce_xmltextContentAttributeName, text);
  12212. return e;
  12213. }
  12214. void XmlElement::addTextElement (const String& text)
  12215. {
  12216. addChildElement (createTextElement (text));
  12217. }
  12218. void XmlElement::deleteAllTextElements() throw()
  12219. {
  12220. XmlElement* child = firstChildElement;
  12221. while (child != 0)
  12222. {
  12223. XmlElement* const next = child->nextElement;
  12224. if (child->isTextElement())
  12225. removeChildElement (child, true);
  12226. child = next;
  12227. }
  12228. }
  12229. END_JUCE_NAMESPACE
  12230. /*** End of inlined file: juce_XmlElement.cpp ***/
  12231. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12232. BEGIN_JUCE_NAMESPACE
  12233. ReadWriteLock::ReadWriteLock() throw()
  12234. : numWaitingWriters (0),
  12235. numWriters (0),
  12236. writerThreadId (0)
  12237. {
  12238. }
  12239. ReadWriteLock::~ReadWriteLock() throw()
  12240. {
  12241. jassert (readerThreads.size() == 0);
  12242. jassert (numWriters == 0);
  12243. }
  12244. void ReadWriteLock::enterRead() const throw()
  12245. {
  12246. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12247. const ScopedLock sl (accessLock);
  12248. for (;;)
  12249. {
  12250. jassert (readerThreads.size() % 2 == 0);
  12251. int i;
  12252. for (i = 0; i < readerThreads.size(); i += 2)
  12253. if (readerThreads.getUnchecked(i) == threadId)
  12254. break;
  12255. if (i < readerThreads.size()
  12256. || numWriters + numWaitingWriters == 0
  12257. || (threadId == writerThreadId && numWriters > 0))
  12258. {
  12259. if (i < readerThreads.size())
  12260. {
  12261. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12262. }
  12263. else
  12264. {
  12265. readerThreads.add (threadId);
  12266. readerThreads.add ((Thread::ThreadID) 1);
  12267. }
  12268. return;
  12269. }
  12270. const ScopedUnlock ul (accessLock);
  12271. waitEvent.wait (100);
  12272. }
  12273. }
  12274. void ReadWriteLock::exitRead() const throw()
  12275. {
  12276. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12277. const ScopedLock sl (accessLock);
  12278. for (int i = 0; i < readerThreads.size(); i += 2)
  12279. {
  12280. if (readerThreads.getUnchecked(i) == threadId)
  12281. {
  12282. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12283. if (newCount == 0)
  12284. {
  12285. readerThreads.removeRange (i, 2);
  12286. waitEvent.signal();
  12287. }
  12288. else
  12289. {
  12290. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12291. }
  12292. return;
  12293. }
  12294. }
  12295. jassertfalse; // unlocking a lock that wasn't locked..
  12296. }
  12297. void ReadWriteLock::enterWrite() const throw()
  12298. {
  12299. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12300. const ScopedLock sl (accessLock);
  12301. for (;;)
  12302. {
  12303. if (readerThreads.size() + numWriters == 0
  12304. || threadId == writerThreadId
  12305. || (readerThreads.size() == 2
  12306. && readerThreads.getUnchecked(0) == threadId))
  12307. {
  12308. writerThreadId = threadId;
  12309. ++numWriters;
  12310. break;
  12311. }
  12312. ++numWaitingWriters;
  12313. accessLock.exit();
  12314. waitEvent.wait (100);
  12315. accessLock.enter();
  12316. --numWaitingWriters;
  12317. }
  12318. }
  12319. bool ReadWriteLock::tryEnterWrite() const throw()
  12320. {
  12321. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12322. const ScopedLock sl (accessLock);
  12323. if (readerThreads.size() + numWriters == 0
  12324. || threadId == writerThreadId
  12325. || (readerThreads.size() == 2
  12326. && readerThreads.getUnchecked(0) == threadId))
  12327. {
  12328. writerThreadId = threadId;
  12329. ++numWriters;
  12330. return true;
  12331. }
  12332. return false;
  12333. }
  12334. void ReadWriteLock::exitWrite() const throw()
  12335. {
  12336. const ScopedLock sl (accessLock);
  12337. // check this thread actually had the lock..
  12338. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12339. if (--numWriters == 0)
  12340. {
  12341. writerThreadId = 0;
  12342. waitEvent.signal();
  12343. }
  12344. }
  12345. END_JUCE_NAMESPACE
  12346. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12347. /*** Start of inlined file: juce_Thread.cpp ***/
  12348. BEGIN_JUCE_NAMESPACE
  12349. // these functions are implemented in the platform-specific code.
  12350. void* juce_createThread (void* userData);
  12351. void juce_killThread (void* handle);
  12352. bool juce_setThreadPriority (void* handle, int priority);
  12353. void juce_setCurrentThreadName (const String& name);
  12354. #if JUCE_WINDOWS
  12355. void juce_CloseThreadHandle (void* handle);
  12356. #endif
  12357. void Thread::threadEntryPoint (Thread* const thread)
  12358. {
  12359. {
  12360. const ScopedLock sl (runningThreadsLock);
  12361. runningThreads.add (thread);
  12362. }
  12363. JUCE_TRY
  12364. {
  12365. thread->threadId_ = Thread::getCurrentThreadId();
  12366. if (thread->threadName_.isNotEmpty())
  12367. juce_setCurrentThreadName (thread->threadName_);
  12368. if (thread->startSuspensionEvent_.wait (10000))
  12369. {
  12370. if (thread->affinityMask_ != 0)
  12371. setCurrentThreadAffinityMask (thread->affinityMask_);
  12372. thread->run();
  12373. }
  12374. }
  12375. JUCE_CATCH_ALL_ASSERT
  12376. {
  12377. const ScopedLock sl (runningThreadsLock);
  12378. jassert (runningThreads.contains (thread));
  12379. runningThreads.removeValue (thread);
  12380. }
  12381. #if JUCE_WINDOWS
  12382. juce_CloseThreadHandle (thread->threadHandle_);
  12383. #endif
  12384. thread->threadHandle_ = 0;
  12385. thread->threadId_ = 0;
  12386. }
  12387. // used to wrap the incoming call from the platform-specific code
  12388. void JUCE_API juce_threadEntryPoint (void* userData)
  12389. {
  12390. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12391. }
  12392. Thread::Thread (const String& threadName)
  12393. : threadName_ (threadName),
  12394. threadHandle_ (0),
  12395. threadPriority_ (5),
  12396. threadId_ (0),
  12397. affinityMask_ (0),
  12398. threadShouldExit_ (false)
  12399. {
  12400. }
  12401. Thread::~Thread()
  12402. {
  12403. stopThread (100);
  12404. }
  12405. void Thread::startThread()
  12406. {
  12407. const ScopedLock sl (startStopLock);
  12408. threadShouldExit_ = false;
  12409. if (threadHandle_ == 0)
  12410. {
  12411. threadHandle_ = juce_createThread (this);
  12412. juce_setThreadPriority (threadHandle_, threadPriority_);
  12413. startSuspensionEvent_.signal();
  12414. }
  12415. }
  12416. void Thread::startThread (const int priority)
  12417. {
  12418. const ScopedLock sl (startStopLock);
  12419. if (threadHandle_ == 0)
  12420. {
  12421. threadPriority_ = priority;
  12422. startThread();
  12423. }
  12424. else
  12425. {
  12426. setPriority (priority);
  12427. }
  12428. }
  12429. bool Thread::isThreadRunning() const
  12430. {
  12431. return threadHandle_ != 0;
  12432. }
  12433. void Thread::signalThreadShouldExit()
  12434. {
  12435. threadShouldExit_ = true;
  12436. }
  12437. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12438. {
  12439. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12440. jassert (getThreadId() != getCurrentThreadId());
  12441. const int sleepMsPerIteration = 5;
  12442. int count = timeOutMilliseconds / sleepMsPerIteration;
  12443. while (isThreadRunning())
  12444. {
  12445. if (timeOutMilliseconds > 0 && --count < 0)
  12446. return false;
  12447. sleep (sleepMsPerIteration);
  12448. }
  12449. return true;
  12450. }
  12451. void Thread::stopThread (const int timeOutMilliseconds)
  12452. {
  12453. // agh! You can't stop the thread that's calling this method! How on earth
  12454. // would that work??
  12455. jassert (getCurrentThreadId() != getThreadId());
  12456. const ScopedLock sl (startStopLock);
  12457. if (isThreadRunning())
  12458. {
  12459. signalThreadShouldExit();
  12460. notify();
  12461. if (timeOutMilliseconds != 0)
  12462. waitForThreadToExit (timeOutMilliseconds);
  12463. if (isThreadRunning())
  12464. {
  12465. // very bad karma if this point is reached, as
  12466. // there are bound to be locks and events left in
  12467. // silly states when a thread is killed by force..
  12468. jassertfalse;
  12469. Logger::writeToLog ("!! killing thread by force !!");
  12470. juce_killThread (threadHandle_);
  12471. threadHandle_ = 0;
  12472. threadId_ = 0;
  12473. const ScopedLock sl2 (runningThreadsLock);
  12474. runningThreads.removeValue (this);
  12475. }
  12476. }
  12477. }
  12478. bool Thread::setPriority (const int priority)
  12479. {
  12480. const ScopedLock sl (startStopLock);
  12481. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12482. if (worked)
  12483. threadPriority_ = priority;
  12484. return worked;
  12485. }
  12486. bool Thread::setCurrentThreadPriority (const int priority)
  12487. {
  12488. return juce_setThreadPriority (0, priority);
  12489. }
  12490. void Thread::setAffinityMask (const uint32 affinityMask)
  12491. {
  12492. affinityMask_ = affinityMask;
  12493. }
  12494. bool Thread::wait (const int timeOutMilliseconds) const
  12495. {
  12496. return defaultEvent_.wait (timeOutMilliseconds);
  12497. }
  12498. void Thread::notify() const
  12499. {
  12500. defaultEvent_.signal();
  12501. }
  12502. int Thread::getNumRunningThreads()
  12503. {
  12504. return runningThreads.size();
  12505. }
  12506. Thread* Thread::getCurrentThread()
  12507. {
  12508. const ThreadID thisId = getCurrentThreadId();
  12509. const ScopedLock sl (runningThreadsLock);
  12510. for (int i = runningThreads.size(); --i >= 0;)
  12511. {
  12512. Thread* const t = runningThreads.getUnchecked(i);
  12513. if (t->threadId_ == thisId)
  12514. return t;
  12515. }
  12516. return 0;
  12517. }
  12518. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12519. {
  12520. {
  12521. const ScopedLock sl (runningThreadsLock);
  12522. for (int i = runningThreads.size(); --i >= 0;)
  12523. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12524. }
  12525. for (;;)
  12526. {
  12527. Thread* firstThread;
  12528. {
  12529. const ScopedLock sl (runningThreadsLock);
  12530. firstThread = runningThreads.getFirst();
  12531. }
  12532. if (firstThread == 0)
  12533. break;
  12534. firstThread->stopThread (timeOutMilliseconds);
  12535. }
  12536. }
  12537. Array<Thread*> Thread::runningThreads;
  12538. CriticalSection Thread::runningThreadsLock;
  12539. END_JUCE_NAMESPACE
  12540. /*** End of inlined file: juce_Thread.cpp ***/
  12541. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12542. BEGIN_JUCE_NAMESPACE
  12543. ThreadPoolJob::ThreadPoolJob (const String& name)
  12544. : jobName (name),
  12545. pool (0),
  12546. shouldStop (false),
  12547. isActive (false),
  12548. shouldBeDeleted (false)
  12549. {
  12550. }
  12551. ThreadPoolJob::~ThreadPoolJob()
  12552. {
  12553. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12554. // to remove it first!
  12555. jassert (pool == 0 || ! pool->contains (this));
  12556. }
  12557. const String ThreadPoolJob::getJobName() const
  12558. {
  12559. return jobName;
  12560. }
  12561. void ThreadPoolJob::setJobName (const String& newName)
  12562. {
  12563. jobName = newName;
  12564. }
  12565. void ThreadPoolJob::signalJobShouldExit()
  12566. {
  12567. shouldStop = true;
  12568. }
  12569. class ThreadPool::ThreadPoolThread : public Thread
  12570. {
  12571. public:
  12572. ThreadPoolThread (ThreadPool& pool_)
  12573. : Thread ("Pool"),
  12574. pool (pool_),
  12575. busy (false)
  12576. {
  12577. }
  12578. ~ThreadPoolThread()
  12579. {
  12580. }
  12581. void run()
  12582. {
  12583. while (! threadShouldExit())
  12584. {
  12585. if (! pool.runNextJob())
  12586. wait (500);
  12587. }
  12588. }
  12589. private:
  12590. ThreadPool& pool;
  12591. bool volatile busy;
  12592. ThreadPoolThread (const ThreadPoolThread&);
  12593. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12594. };
  12595. ThreadPool::ThreadPool (const int numThreads,
  12596. const bool startThreadsOnlyWhenNeeded,
  12597. const int stopThreadsWhenNotUsedTimeoutMs)
  12598. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12599. priority (5)
  12600. {
  12601. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12602. for (int i = jmax (1, numThreads); --i >= 0;)
  12603. threads.add (new ThreadPoolThread (*this));
  12604. if (! startThreadsOnlyWhenNeeded)
  12605. for (int i = threads.size(); --i >= 0;)
  12606. threads.getUnchecked(i)->startThread (priority);
  12607. }
  12608. ThreadPool::~ThreadPool()
  12609. {
  12610. removeAllJobs (true, 4000);
  12611. int i;
  12612. for (i = threads.size(); --i >= 0;)
  12613. threads.getUnchecked(i)->signalThreadShouldExit();
  12614. for (i = threads.size(); --i >= 0;)
  12615. threads.getUnchecked(i)->stopThread (500);
  12616. }
  12617. void ThreadPool::addJob (ThreadPoolJob* const job)
  12618. {
  12619. jassert (job != 0);
  12620. jassert (job->pool == 0);
  12621. if (job->pool == 0)
  12622. {
  12623. job->pool = this;
  12624. job->shouldStop = false;
  12625. job->isActive = false;
  12626. {
  12627. const ScopedLock sl (lock);
  12628. jobs.add (job);
  12629. int numRunning = 0;
  12630. for (int i = threads.size(); --i >= 0;)
  12631. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12632. ++numRunning;
  12633. if (numRunning < threads.size())
  12634. {
  12635. bool startedOne = false;
  12636. int n = 1000;
  12637. while (--n >= 0 && ! startedOne)
  12638. {
  12639. for (int i = threads.size(); --i >= 0;)
  12640. {
  12641. if (! threads.getUnchecked(i)->isThreadRunning())
  12642. {
  12643. threads.getUnchecked(i)->startThread (priority);
  12644. startedOne = true;
  12645. break;
  12646. }
  12647. }
  12648. if (! startedOne)
  12649. Thread::sleep (2);
  12650. }
  12651. }
  12652. }
  12653. for (int i = threads.size(); --i >= 0;)
  12654. threads.getUnchecked(i)->notify();
  12655. }
  12656. }
  12657. int ThreadPool::getNumJobs() const
  12658. {
  12659. return jobs.size();
  12660. }
  12661. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12662. {
  12663. const ScopedLock sl (lock);
  12664. return jobs [index];
  12665. }
  12666. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12667. {
  12668. const ScopedLock sl (lock);
  12669. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12670. }
  12671. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12672. {
  12673. const ScopedLock sl (lock);
  12674. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12675. }
  12676. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12677. const int timeOutMs) const
  12678. {
  12679. if (job != 0)
  12680. {
  12681. const uint32 start = Time::getMillisecondCounter();
  12682. while (contains (job))
  12683. {
  12684. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12685. return false;
  12686. jobFinishedSignal.wait (2);
  12687. }
  12688. }
  12689. return true;
  12690. }
  12691. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12692. const bool interruptIfRunning,
  12693. const int timeOutMs)
  12694. {
  12695. bool dontWait = true;
  12696. if (job != 0)
  12697. {
  12698. const ScopedLock sl (lock);
  12699. if (jobs.contains (job))
  12700. {
  12701. if (job->isActive)
  12702. {
  12703. if (interruptIfRunning)
  12704. job->signalJobShouldExit();
  12705. dontWait = false;
  12706. }
  12707. else
  12708. {
  12709. jobs.removeValue (job);
  12710. job->pool = 0;
  12711. }
  12712. }
  12713. }
  12714. return dontWait || waitForJobToFinish (job, timeOutMs);
  12715. }
  12716. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12717. const int timeOutMs,
  12718. const bool deleteInactiveJobs,
  12719. ThreadPool::JobSelector* selectedJobsToRemove)
  12720. {
  12721. Array <ThreadPoolJob*> jobsToWaitFor;
  12722. {
  12723. const ScopedLock sl (lock);
  12724. for (int i = jobs.size(); --i >= 0;)
  12725. {
  12726. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12727. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12728. {
  12729. if (job->isActive)
  12730. {
  12731. jobsToWaitFor.add (job);
  12732. if (interruptRunningJobs)
  12733. job->signalJobShouldExit();
  12734. }
  12735. else
  12736. {
  12737. jobs.remove (i);
  12738. if (deleteInactiveJobs)
  12739. delete job;
  12740. else
  12741. job->pool = 0;
  12742. }
  12743. }
  12744. }
  12745. }
  12746. const uint32 start = Time::getMillisecondCounter();
  12747. for (;;)
  12748. {
  12749. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12750. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12751. jobsToWaitFor.remove (i);
  12752. if (jobsToWaitFor.size() == 0)
  12753. break;
  12754. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12755. return false;
  12756. jobFinishedSignal.wait (20);
  12757. }
  12758. return true;
  12759. }
  12760. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12761. {
  12762. StringArray s;
  12763. const ScopedLock sl (lock);
  12764. for (int i = 0; i < jobs.size(); ++i)
  12765. {
  12766. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12767. if (job->isActive || ! onlyReturnActiveJobs)
  12768. s.add (job->getJobName());
  12769. }
  12770. return s;
  12771. }
  12772. bool ThreadPool::setThreadPriorities (const int newPriority)
  12773. {
  12774. bool ok = true;
  12775. if (priority != newPriority)
  12776. {
  12777. priority = newPriority;
  12778. for (int i = threads.size(); --i >= 0;)
  12779. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12780. ok = false;
  12781. }
  12782. return ok;
  12783. }
  12784. bool ThreadPool::runNextJob()
  12785. {
  12786. ThreadPoolJob* job = 0;
  12787. {
  12788. const ScopedLock sl (lock);
  12789. for (int i = 0; i < jobs.size(); ++i)
  12790. {
  12791. job = jobs[i];
  12792. if (job != 0 && ! (job->isActive || job->shouldStop))
  12793. break;
  12794. job = 0;
  12795. }
  12796. if (job != 0)
  12797. job->isActive = true;
  12798. }
  12799. if (job != 0)
  12800. {
  12801. JUCE_TRY
  12802. {
  12803. ThreadPoolJob::JobStatus result = job->runJob();
  12804. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12805. const ScopedLock sl (lock);
  12806. if (jobs.contains (job))
  12807. {
  12808. job->isActive = false;
  12809. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12810. {
  12811. job->pool = 0;
  12812. job->shouldStop = true;
  12813. jobs.removeValue (job);
  12814. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12815. delete job;
  12816. jobFinishedSignal.signal();
  12817. }
  12818. else
  12819. {
  12820. // move the job to the end of the queue if it wants another go
  12821. jobs.move (jobs.indexOf (job), -1);
  12822. }
  12823. }
  12824. }
  12825. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12826. catch (...)
  12827. {
  12828. const ScopedLock sl (lock);
  12829. jobs.removeValue (job);
  12830. }
  12831. #endif
  12832. }
  12833. else
  12834. {
  12835. if (threadStopTimeout > 0
  12836. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12837. {
  12838. const ScopedLock sl (lock);
  12839. if (jobs.size() == 0)
  12840. for (int i = threads.size(); --i >= 0;)
  12841. threads.getUnchecked(i)->signalThreadShouldExit();
  12842. }
  12843. else
  12844. {
  12845. return false;
  12846. }
  12847. }
  12848. return true;
  12849. }
  12850. END_JUCE_NAMESPACE
  12851. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12852. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12853. BEGIN_JUCE_NAMESPACE
  12854. TimeSliceThread::TimeSliceThread (const String& threadName)
  12855. : Thread (threadName),
  12856. index (0),
  12857. clientBeingCalled (0),
  12858. clientsChanged (false)
  12859. {
  12860. }
  12861. TimeSliceThread::~TimeSliceThread()
  12862. {
  12863. stopThread (2000);
  12864. }
  12865. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12866. {
  12867. const ScopedLock sl (listLock);
  12868. clients.addIfNotAlreadyThere (client);
  12869. clientsChanged = true;
  12870. notify();
  12871. }
  12872. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12873. {
  12874. const ScopedLock sl1 (listLock);
  12875. clientsChanged = true;
  12876. // if there's a chance we're in the middle of calling this client, we need to
  12877. // also lock the outer lock..
  12878. if (clientBeingCalled == client)
  12879. {
  12880. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12881. const ScopedLock sl2 (callbackLock);
  12882. const ScopedLock sl3 (listLock);
  12883. clients.removeValue (client);
  12884. }
  12885. else
  12886. {
  12887. clients.removeValue (client);
  12888. }
  12889. }
  12890. int TimeSliceThread::getNumClients() const
  12891. {
  12892. return clients.size();
  12893. }
  12894. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12895. {
  12896. const ScopedLock sl (listLock);
  12897. return clients [i];
  12898. }
  12899. void TimeSliceThread::run()
  12900. {
  12901. int numCallsSinceBusy = 0;
  12902. while (! threadShouldExit())
  12903. {
  12904. int timeToWait = 500;
  12905. {
  12906. const ScopedLock sl (callbackLock);
  12907. {
  12908. const ScopedLock sl2 (listLock);
  12909. if (clients.size() > 0)
  12910. {
  12911. index = (index + 1) % clients.size();
  12912. clientBeingCalled = clients [index];
  12913. }
  12914. else
  12915. {
  12916. index = 0;
  12917. clientBeingCalled = 0;
  12918. }
  12919. if (clientsChanged)
  12920. {
  12921. clientsChanged = false;
  12922. numCallsSinceBusy = 0;
  12923. }
  12924. }
  12925. if (clientBeingCalled != 0)
  12926. {
  12927. if (clientBeingCalled->useTimeSlice())
  12928. numCallsSinceBusy = 0;
  12929. else
  12930. ++numCallsSinceBusy;
  12931. if (numCallsSinceBusy >= clients.size())
  12932. timeToWait = 500;
  12933. else if (index == 0)
  12934. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12935. else
  12936. timeToWait = 0;
  12937. }
  12938. }
  12939. if (timeToWait > 0)
  12940. wait (timeToWait);
  12941. }
  12942. }
  12943. END_JUCE_NAMESPACE
  12944. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12945. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12946. BEGIN_JUCE_NAMESPACE
  12947. DeletedAtShutdown::DeletedAtShutdown()
  12948. {
  12949. const ScopedLock sl (getLock());
  12950. getObjects().add (this);
  12951. }
  12952. DeletedAtShutdown::~DeletedAtShutdown()
  12953. {
  12954. const ScopedLock sl (getLock());
  12955. getObjects().removeValue (this);
  12956. }
  12957. void DeletedAtShutdown::deleteAll()
  12958. {
  12959. // make a local copy of the array, so it can't get into a loop if something
  12960. // creates another DeletedAtShutdown object during its destructor.
  12961. Array <DeletedAtShutdown*> localCopy;
  12962. {
  12963. const ScopedLock sl (getLock());
  12964. localCopy = getObjects();
  12965. }
  12966. for (int i = localCopy.size(); --i >= 0;)
  12967. {
  12968. JUCE_TRY
  12969. {
  12970. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12971. // double-check that it's not already been deleted during another object's destructor.
  12972. {
  12973. const ScopedLock sl (getLock());
  12974. if (! getObjects().contains (deletee))
  12975. deletee = 0;
  12976. }
  12977. delete deletee;
  12978. }
  12979. JUCE_CATCH_EXCEPTION
  12980. }
  12981. // if no objects got re-created during shutdown, this should have been emptied by their
  12982. // destructors
  12983. jassert (getObjects().size() == 0);
  12984. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12985. }
  12986. CriticalSection& DeletedAtShutdown::getLock()
  12987. {
  12988. static CriticalSection lock;
  12989. return lock;
  12990. }
  12991. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12992. {
  12993. static Array <DeletedAtShutdown*> objects;
  12994. return objects;
  12995. }
  12996. END_JUCE_NAMESPACE
  12997. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12998. #endif
  12999. #if JUCE_BUILD_MISC
  13000. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13001. BEGIN_JUCE_NAMESPACE
  13002. class ValueTree::SetPropertyAction : public UndoableAction
  13003. {
  13004. public:
  13005. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13006. const var& newValue_, const var& oldValue_,
  13007. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13008. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13009. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13010. {
  13011. }
  13012. ~SetPropertyAction() {}
  13013. bool perform()
  13014. {
  13015. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13016. if (isDeletingProperty)
  13017. target->removeProperty (name, 0);
  13018. else
  13019. target->setProperty (name, newValue, 0);
  13020. return true;
  13021. }
  13022. bool undo()
  13023. {
  13024. if (isAddingNewProperty)
  13025. target->removeProperty (name, 0);
  13026. else
  13027. target->setProperty (name, oldValue, 0);
  13028. return true;
  13029. }
  13030. int getSizeInUnits()
  13031. {
  13032. return (int) sizeof (*this); //xxx should be more accurate
  13033. }
  13034. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13035. {
  13036. if (! (isAddingNewProperty || isDeletingProperty))
  13037. {
  13038. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13039. if (next != 0 && next->target == target && next->name == name
  13040. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13041. {
  13042. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13043. }
  13044. }
  13045. return 0;
  13046. }
  13047. private:
  13048. const SharedObjectPtr target;
  13049. const Identifier name;
  13050. const var newValue;
  13051. var oldValue;
  13052. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13053. SetPropertyAction (const SetPropertyAction&);
  13054. SetPropertyAction& operator= (const SetPropertyAction&);
  13055. };
  13056. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13057. {
  13058. public:
  13059. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13060. const SharedObjectPtr& newChild_)
  13061. : target (target_),
  13062. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13063. childIndex (childIndex_),
  13064. isDeleting (newChild_ == 0)
  13065. {
  13066. jassert (child != 0);
  13067. }
  13068. ~AddOrRemoveChildAction() {}
  13069. bool perform()
  13070. {
  13071. if (isDeleting)
  13072. target->removeChild (childIndex, 0);
  13073. else
  13074. target->addChild (child, childIndex, 0);
  13075. return true;
  13076. }
  13077. bool undo()
  13078. {
  13079. if (isDeleting)
  13080. {
  13081. target->addChild (child, childIndex, 0);
  13082. }
  13083. else
  13084. {
  13085. // If you hit this, it seems that your object's state is getting confused - probably
  13086. // because you've interleaved some undoable and non-undoable operations?
  13087. jassert (childIndex < target->children.size());
  13088. target->removeChild (childIndex, 0);
  13089. }
  13090. return true;
  13091. }
  13092. int getSizeInUnits()
  13093. {
  13094. return (int) sizeof (*this); //xxx should be more accurate
  13095. }
  13096. private:
  13097. const SharedObjectPtr target, child;
  13098. const int childIndex;
  13099. const bool isDeleting;
  13100. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13101. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13102. };
  13103. class ValueTree::MoveChildAction : public UndoableAction
  13104. {
  13105. public:
  13106. MoveChildAction (const SharedObjectPtr& parent_,
  13107. const int startIndex_, const int endIndex_)
  13108. : parent (parent_),
  13109. startIndex (startIndex_),
  13110. endIndex (endIndex_)
  13111. {
  13112. }
  13113. ~MoveChildAction() {}
  13114. bool perform()
  13115. {
  13116. parent->moveChild (startIndex, endIndex, 0);
  13117. return true;
  13118. }
  13119. bool undo()
  13120. {
  13121. parent->moveChild (endIndex, startIndex, 0);
  13122. return true;
  13123. }
  13124. int getSizeInUnits()
  13125. {
  13126. return (int) sizeof (*this); //xxx should be more accurate
  13127. }
  13128. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13129. {
  13130. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13131. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13132. return new MoveChildAction (parent, startIndex, next->endIndex);
  13133. return 0;
  13134. }
  13135. private:
  13136. const SharedObjectPtr parent;
  13137. const int startIndex, endIndex;
  13138. MoveChildAction (const MoveChildAction&);
  13139. MoveChildAction& operator= (const MoveChildAction&);
  13140. };
  13141. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13142. : type (type_), parent (0)
  13143. {
  13144. }
  13145. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13146. : type (other.type), properties (other.properties), parent (0)
  13147. {
  13148. for (int i = 0; i < other.children.size(); ++i)
  13149. {
  13150. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13151. child->parent = this;
  13152. children.add (child);
  13153. }
  13154. }
  13155. ValueTree::SharedObject::~SharedObject()
  13156. {
  13157. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13158. for (int i = children.size(); --i >= 0;)
  13159. {
  13160. const SharedObjectPtr c (children.getUnchecked(i));
  13161. c->parent = 0;
  13162. children.remove (i);
  13163. c->sendParentChangeMessage();
  13164. }
  13165. }
  13166. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13167. {
  13168. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13169. {
  13170. ValueTree* const v = valueTreesWithListeners[i];
  13171. if (v != 0)
  13172. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13173. }
  13174. }
  13175. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13176. {
  13177. ValueTree tree (this);
  13178. ValueTree::SharedObject* t = this;
  13179. while (t != 0)
  13180. {
  13181. t->sendPropertyChangeMessage (tree, property);
  13182. t = t->parent;
  13183. }
  13184. }
  13185. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13186. {
  13187. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13188. {
  13189. ValueTree* const v = valueTreesWithListeners[i];
  13190. if (v != 0)
  13191. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13192. }
  13193. }
  13194. void ValueTree::SharedObject::sendChildChangeMessage()
  13195. {
  13196. ValueTree tree (this);
  13197. ValueTree::SharedObject* t = this;
  13198. while (t != 0)
  13199. {
  13200. t->sendChildChangeMessage (tree);
  13201. t = t->parent;
  13202. }
  13203. }
  13204. void ValueTree::SharedObject::sendParentChangeMessage()
  13205. {
  13206. ValueTree tree (this);
  13207. int i;
  13208. for (i = children.size(); --i >= 0;)
  13209. {
  13210. SharedObject* const t = children[i];
  13211. if (t != 0)
  13212. t->sendParentChangeMessage();
  13213. }
  13214. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13215. {
  13216. ValueTree* const v = valueTreesWithListeners[i];
  13217. if (v != 0)
  13218. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13219. }
  13220. }
  13221. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13222. {
  13223. return properties [name];
  13224. }
  13225. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13226. {
  13227. return properties.getWithDefault (name, defaultReturnValue);
  13228. }
  13229. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13230. {
  13231. if (undoManager == 0)
  13232. {
  13233. if (properties.set (name, newValue))
  13234. sendPropertyChangeMessage (name);
  13235. }
  13236. else
  13237. {
  13238. var* const existingValue = properties.getItem (name);
  13239. if (existingValue != 0)
  13240. {
  13241. if (*existingValue != newValue)
  13242. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13243. }
  13244. else
  13245. {
  13246. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13247. }
  13248. }
  13249. }
  13250. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13251. {
  13252. return properties.contains (name);
  13253. }
  13254. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13255. {
  13256. if (undoManager == 0)
  13257. {
  13258. if (properties.remove (name))
  13259. sendPropertyChangeMessage (name);
  13260. }
  13261. else
  13262. {
  13263. if (properties.contains (name))
  13264. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13265. }
  13266. }
  13267. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13268. {
  13269. if (undoManager == 0)
  13270. {
  13271. while (properties.size() > 0)
  13272. {
  13273. const Identifier name (properties.getName (properties.size() - 1));
  13274. properties.remove (name);
  13275. sendPropertyChangeMessage (name);
  13276. }
  13277. }
  13278. else
  13279. {
  13280. for (int i = properties.size(); --i >= 0;)
  13281. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13282. }
  13283. }
  13284. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13285. {
  13286. for (int i = 0; i < children.size(); ++i)
  13287. if (children.getUnchecked(i)->type == typeToMatch)
  13288. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13289. return ValueTree::invalid;
  13290. }
  13291. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13292. {
  13293. for (int i = 0; i < children.size(); ++i)
  13294. if (children.getUnchecked(i)->type == typeToMatch)
  13295. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13296. SharedObject* const newObject = new SharedObject (typeToMatch);
  13297. addChild (newObject, -1, undoManager);
  13298. return ValueTree (newObject);
  13299. }
  13300. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13301. {
  13302. for (int i = 0; i < children.size(); ++i)
  13303. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13304. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13305. return ValueTree::invalid;
  13306. }
  13307. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13308. {
  13309. const SharedObject* p = parent;
  13310. while (p != 0)
  13311. {
  13312. if (p == possibleParent)
  13313. return true;
  13314. p = p->parent;
  13315. }
  13316. return false;
  13317. }
  13318. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13319. {
  13320. return children.indexOf (child.object);
  13321. }
  13322. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13323. {
  13324. if (child != 0 && child->parent != this)
  13325. {
  13326. if (child != this && ! isAChildOf (child))
  13327. {
  13328. // You should always make sure that a child is removed from its previous parent before
  13329. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13330. // undomanager should be used when removing it from its current parent..
  13331. jassert (child->parent == 0);
  13332. if (child->parent != 0)
  13333. {
  13334. jassert (child->parent->children.indexOf (child) >= 0);
  13335. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13336. }
  13337. if (undoManager == 0)
  13338. {
  13339. children.insert (index, child);
  13340. child->parent = this;
  13341. sendChildChangeMessage();
  13342. child->sendParentChangeMessage();
  13343. }
  13344. else
  13345. {
  13346. if (index < 0)
  13347. index = children.size();
  13348. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13349. }
  13350. }
  13351. else
  13352. {
  13353. // You're attempting to create a recursive loop! A node
  13354. // can't be a child of one of its own children!
  13355. jassertfalse;
  13356. }
  13357. }
  13358. }
  13359. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13360. {
  13361. const SharedObjectPtr child (children [childIndex]);
  13362. if (child != 0)
  13363. {
  13364. if (undoManager == 0)
  13365. {
  13366. children.remove (childIndex);
  13367. child->parent = 0;
  13368. sendChildChangeMessage();
  13369. child->sendParentChangeMessage();
  13370. }
  13371. else
  13372. {
  13373. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13374. }
  13375. }
  13376. }
  13377. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13378. {
  13379. while (children.size() > 0)
  13380. removeChild (children.size() - 1, undoManager);
  13381. }
  13382. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13383. {
  13384. // The source index must be a valid index!
  13385. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13386. if (currentIndex != newIndex
  13387. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13388. {
  13389. if (undoManager == 0)
  13390. {
  13391. children.move (currentIndex, newIndex);
  13392. sendChildChangeMessage();
  13393. }
  13394. else
  13395. {
  13396. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13397. newIndex = children.size() - 1;
  13398. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13399. }
  13400. }
  13401. }
  13402. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13403. {
  13404. if (type != other.type
  13405. || properties.size() != other.properties.size()
  13406. || children.size() != other.children.size()
  13407. || properties != other.properties)
  13408. return false;
  13409. for (int i = 0; i < children.size(); ++i)
  13410. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13411. return false;
  13412. return true;
  13413. }
  13414. ValueTree::ValueTree() throw()
  13415. : object (0)
  13416. {
  13417. }
  13418. const ValueTree ValueTree::invalid;
  13419. ValueTree::ValueTree (const Identifier& type_)
  13420. : object (new ValueTree::SharedObject (type_))
  13421. {
  13422. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13423. }
  13424. ValueTree::ValueTree (SharedObject* const object_)
  13425. : object (object_)
  13426. {
  13427. }
  13428. ValueTree::ValueTree (const ValueTree& other)
  13429. : object (other.object)
  13430. {
  13431. }
  13432. ValueTree& ValueTree::operator= (const ValueTree& other)
  13433. {
  13434. if (listeners.size() > 0)
  13435. {
  13436. if (object != 0)
  13437. object->valueTreesWithListeners.removeValue (this);
  13438. if (other.object != 0)
  13439. other.object->valueTreesWithListeners.add (this);
  13440. }
  13441. object = other.object;
  13442. return *this;
  13443. }
  13444. ValueTree::~ValueTree()
  13445. {
  13446. if (listeners.size() > 0 && object != 0)
  13447. object->valueTreesWithListeners.removeValue (this);
  13448. }
  13449. bool ValueTree::operator== (const ValueTree& other) const throw()
  13450. {
  13451. return object == other.object;
  13452. }
  13453. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13454. {
  13455. return object != other.object;
  13456. }
  13457. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13458. {
  13459. return object == other.object
  13460. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13461. }
  13462. ValueTree ValueTree::createCopy() const
  13463. {
  13464. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13465. }
  13466. bool ValueTree::hasType (const Identifier& typeName) const
  13467. {
  13468. return object != 0 && object->type == typeName;
  13469. }
  13470. const Identifier ValueTree::getType() const
  13471. {
  13472. return object != 0 ? object->type : Identifier();
  13473. }
  13474. ValueTree ValueTree::getParent() const
  13475. {
  13476. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13477. }
  13478. ValueTree ValueTree::getSibling (const int delta) const
  13479. {
  13480. if (object == 0 || object->parent == 0)
  13481. return invalid;
  13482. const int index = object->parent->indexOf (*this) + delta;
  13483. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  13484. }
  13485. const var& ValueTree::operator[] (const Identifier& name) const
  13486. {
  13487. return object == 0 ? var::null : object->getProperty (name);
  13488. }
  13489. const var& ValueTree::getProperty (const Identifier& name) const
  13490. {
  13491. return object == 0 ? var::null : object->getProperty (name);
  13492. }
  13493. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13494. {
  13495. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13496. }
  13497. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13498. {
  13499. jassert (name.toString().isNotEmpty());
  13500. if (object != 0 && name.toString().isNotEmpty())
  13501. object->setProperty (name, newValue, undoManager);
  13502. }
  13503. bool ValueTree::hasProperty (const Identifier& name) const
  13504. {
  13505. return object != 0 && object->hasProperty (name);
  13506. }
  13507. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13508. {
  13509. if (object != 0)
  13510. object->removeProperty (name, undoManager);
  13511. }
  13512. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13513. {
  13514. if (object != 0)
  13515. object->removeAllProperties (undoManager);
  13516. }
  13517. int ValueTree::getNumProperties() const
  13518. {
  13519. return object == 0 ? 0 : object->properties.size();
  13520. }
  13521. const Identifier ValueTree::getPropertyName (const int index) const
  13522. {
  13523. return object == 0 ? Identifier()
  13524. : object->properties.getName (index);
  13525. }
  13526. class ValueTreePropertyValueSource : public Value::ValueSource,
  13527. public ValueTree::Listener
  13528. {
  13529. public:
  13530. ValueTreePropertyValueSource (const ValueTree& tree_,
  13531. const Identifier& property_,
  13532. UndoManager* const undoManager_)
  13533. : tree (tree_),
  13534. property (property_),
  13535. undoManager (undoManager_)
  13536. {
  13537. tree.addListener (this);
  13538. }
  13539. ~ValueTreePropertyValueSource()
  13540. {
  13541. tree.removeListener (this);
  13542. }
  13543. const var getValue() const
  13544. {
  13545. return tree [property];
  13546. }
  13547. void setValue (const var& newValue)
  13548. {
  13549. tree.setProperty (property, newValue, undoManager);
  13550. }
  13551. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13552. {
  13553. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13554. sendChangeMessage (false);
  13555. }
  13556. void valueTreeChildrenChanged (ValueTree&) {}
  13557. void valueTreeParentChanged (ValueTree&) {}
  13558. private:
  13559. ValueTree tree;
  13560. const Identifier property;
  13561. UndoManager* const undoManager;
  13562. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13563. };
  13564. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13565. {
  13566. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13567. }
  13568. int ValueTree::getNumChildren() const
  13569. {
  13570. return object == 0 ? 0 : object->children.size();
  13571. }
  13572. ValueTree ValueTree::getChild (int index) const
  13573. {
  13574. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13575. }
  13576. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13577. {
  13578. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13579. }
  13580. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13581. {
  13582. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13583. }
  13584. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13585. {
  13586. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13587. }
  13588. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13589. {
  13590. return object != 0 && object->isAChildOf (possibleParent.object);
  13591. }
  13592. int ValueTree::indexOf (const ValueTree& child) const
  13593. {
  13594. return object != 0 ? object->indexOf (child) : -1;
  13595. }
  13596. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13597. {
  13598. if (object != 0)
  13599. object->addChild (child.object, index, undoManager);
  13600. }
  13601. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13602. {
  13603. if (object != 0)
  13604. object->removeChild (childIndex, undoManager);
  13605. }
  13606. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13607. {
  13608. if (object != 0)
  13609. object->removeChild (object->children.indexOf (child.object), undoManager);
  13610. }
  13611. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13612. {
  13613. if (object != 0)
  13614. object->removeAllChildren (undoManager);
  13615. }
  13616. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13617. {
  13618. if (object != 0)
  13619. object->moveChild (currentIndex, newIndex, undoManager);
  13620. }
  13621. void ValueTree::addListener (Listener* listener)
  13622. {
  13623. if (listener != 0)
  13624. {
  13625. if (listeners.size() == 0 && object != 0)
  13626. object->valueTreesWithListeners.add (this);
  13627. listeners.add (listener);
  13628. }
  13629. }
  13630. void ValueTree::removeListener (Listener* listener)
  13631. {
  13632. listeners.remove (listener);
  13633. if (listeners.size() == 0 && object != 0)
  13634. object->valueTreesWithListeners.removeValue (this);
  13635. }
  13636. XmlElement* ValueTree::SharedObject::createXml() const
  13637. {
  13638. XmlElement* xml = new XmlElement (type.toString());
  13639. int i;
  13640. for (i = 0; i < properties.size(); ++i)
  13641. {
  13642. Identifier name (properties.getName(i));
  13643. const var& v = properties [name];
  13644. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13645. xml->setAttribute (name.toString(), v.toString());
  13646. }
  13647. for (i = 0; i < children.size(); ++i)
  13648. xml->addChildElement (children.getUnchecked(i)->createXml());
  13649. return xml;
  13650. }
  13651. XmlElement* ValueTree::createXml() const
  13652. {
  13653. return object != 0 ? object->createXml() : 0;
  13654. }
  13655. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13656. {
  13657. ValueTree v (xml.getTagName());
  13658. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13659. for (int i = 0; i < numAtts; ++i)
  13660. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13661. forEachXmlChildElement (xml, e)
  13662. {
  13663. v.addChild (fromXml (*e), -1, 0);
  13664. }
  13665. return v;
  13666. }
  13667. void ValueTree::writeToStream (OutputStream& output)
  13668. {
  13669. output.writeString (getType().toString());
  13670. const int numProps = getNumProperties();
  13671. output.writeCompressedInt (numProps);
  13672. int i;
  13673. for (i = 0; i < numProps; ++i)
  13674. {
  13675. const Identifier name (getPropertyName(i));
  13676. output.writeString (name.toString());
  13677. getProperty(name).writeToStream (output);
  13678. }
  13679. const int numChildren = getNumChildren();
  13680. output.writeCompressedInt (numChildren);
  13681. for (i = 0; i < numChildren; ++i)
  13682. getChild (i).writeToStream (output);
  13683. }
  13684. ValueTree ValueTree::readFromStream (InputStream& input)
  13685. {
  13686. const String type (input.readString());
  13687. if (type.isEmpty())
  13688. return ValueTree::invalid;
  13689. ValueTree v (type);
  13690. const int numProps = input.readCompressedInt();
  13691. if (numProps < 0)
  13692. {
  13693. jassertfalse; // trying to read corrupted data!
  13694. return v;
  13695. }
  13696. int i;
  13697. for (i = 0; i < numProps; ++i)
  13698. {
  13699. const String name (input.readString());
  13700. jassert (name.isNotEmpty());
  13701. const var value (var::readFromStream (input));
  13702. v.setProperty (name, value, 0);
  13703. }
  13704. const int numChildren = input.readCompressedInt();
  13705. for (i = 0; i < numChildren; ++i)
  13706. v.addChild (readFromStream (input), -1, 0);
  13707. return v;
  13708. }
  13709. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13710. {
  13711. MemoryInputStream in (data, numBytes, false);
  13712. return readFromStream (in);
  13713. }
  13714. END_JUCE_NAMESPACE
  13715. /*** End of inlined file: juce_ValueTree.cpp ***/
  13716. /*** Start of inlined file: juce_Value.cpp ***/
  13717. BEGIN_JUCE_NAMESPACE
  13718. Value::ValueSource::ValueSource()
  13719. {
  13720. }
  13721. Value::ValueSource::~ValueSource()
  13722. {
  13723. }
  13724. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13725. {
  13726. if (synchronous)
  13727. {
  13728. for (int i = valuesWithListeners.size(); --i >= 0;)
  13729. {
  13730. Value* const v = valuesWithListeners[i];
  13731. if (v != 0)
  13732. v->callListeners();
  13733. }
  13734. }
  13735. else
  13736. {
  13737. triggerAsyncUpdate();
  13738. }
  13739. }
  13740. void Value::ValueSource::handleAsyncUpdate()
  13741. {
  13742. sendChangeMessage (true);
  13743. }
  13744. class SimpleValueSource : public Value::ValueSource
  13745. {
  13746. public:
  13747. SimpleValueSource()
  13748. {
  13749. }
  13750. SimpleValueSource (const var& initialValue)
  13751. : value (initialValue)
  13752. {
  13753. }
  13754. ~SimpleValueSource()
  13755. {
  13756. }
  13757. const var getValue() const
  13758. {
  13759. return value;
  13760. }
  13761. void setValue (const var& newValue)
  13762. {
  13763. if (newValue != value)
  13764. {
  13765. value = newValue;
  13766. sendChangeMessage (false);
  13767. }
  13768. }
  13769. private:
  13770. var value;
  13771. SimpleValueSource (const SimpleValueSource&);
  13772. SimpleValueSource& operator= (const SimpleValueSource&);
  13773. };
  13774. Value::Value()
  13775. : value (new SimpleValueSource())
  13776. {
  13777. }
  13778. Value::Value (ValueSource* const value_)
  13779. : value (value_)
  13780. {
  13781. jassert (value_ != 0);
  13782. }
  13783. Value::Value (const var& initialValue)
  13784. : value (new SimpleValueSource (initialValue))
  13785. {
  13786. }
  13787. Value::Value (const Value& other)
  13788. : value (other.value)
  13789. {
  13790. }
  13791. Value& Value::operator= (const Value& other)
  13792. {
  13793. value = other.value;
  13794. return *this;
  13795. }
  13796. Value::~Value()
  13797. {
  13798. if (listeners.size() > 0)
  13799. value->valuesWithListeners.removeValue (this);
  13800. }
  13801. const var Value::getValue() const
  13802. {
  13803. return value->getValue();
  13804. }
  13805. Value::operator const var() const
  13806. {
  13807. return getValue();
  13808. }
  13809. void Value::setValue (const var& newValue)
  13810. {
  13811. value->setValue (newValue);
  13812. }
  13813. const String Value::toString() const
  13814. {
  13815. return value->getValue().toString();
  13816. }
  13817. Value& Value::operator= (const var& newValue)
  13818. {
  13819. value->setValue (newValue);
  13820. return *this;
  13821. }
  13822. void Value::referTo (const Value& valueToReferTo)
  13823. {
  13824. if (valueToReferTo.value != value)
  13825. {
  13826. if (listeners.size() > 0)
  13827. {
  13828. value->valuesWithListeners.removeValue (this);
  13829. valueToReferTo.value->valuesWithListeners.add (this);
  13830. }
  13831. value = valueToReferTo.value;
  13832. callListeners();
  13833. }
  13834. }
  13835. bool Value::refersToSameSourceAs (const Value& other) const
  13836. {
  13837. return value == other.value;
  13838. }
  13839. bool Value::operator== (const Value& other) const
  13840. {
  13841. return value == other.value || value->getValue() == other.getValue();
  13842. }
  13843. bool Value::operator!= (const Value& other) const
  13844. {
  13845. return value != other.value && value->getValue() != other.getValue();
  13846. }
  13847. void Value::addListener (Listener* const listener)
  13848. {
  13849. if (listener != 0)
  13850. {
  13851. if (listeners.size() == 0)
  13852. value->valuesWithListeners.add (this);
  13853. listeners.add (listener);
  13854. }
  13855. }
  13856. void Value::removeListener (Listener* const listener)
  13857. {
  13858. listeners.remove (listener);
  13859. if (listeners.size() == 0)
  13860. value->valuesWithListeners.removeValue (this);
  13861. }
  13862. void Value::callListeners()
  13863. {
  13864. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13865. listeners.call (&Value::Listener::valueChanged, v);
  13866. }
  13867. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13868. {
  13869. return stream << value.toString();
  13870. }
  13871. END_JUCE_NAMESPACE
  13872. /*** End of inlined file: juce_Value.cpp ***/
  13873. /*** Start of inlined file: juce_Application.cpp ***/
  13874. BEGIN_JUCE_NAMESPACE
  13875. #if JUCE_MAC
  13876. extern void juce_initialiseMacMainMenu();
  13877. #endif
  13878. JUCEApplication::JUCEApplication()
  13879. : appReturnValue (0),
  13880. stillInitialising (true)
  13881. {
  13882. jassert (isStandaloneApp() && appInstance == 0);
  13883. appInstance = this;
  13884. }
  13885. JUCEApplication::~JUCEApplication()
  13886. {
  13887. if (appLock != 0)
  13888. {
  13889. appLock->exit();
  13890. appLock = 0;
  13891. }
  13892. jassert (appInstance == this);
  13893. appInstance = 0;
  13894. }
  13895. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  13896. JUCEApplication* JUCEApplication::appInstance = 0;
  13897. bool JUCEApplication::moreThanOneInstanceAllowed()
  13898. {
  13899. return true;
  13900. }
  13901. void JUCEApplication::anotherInstanceStarted (const String&)
  13902. {
  13903. }
  13904. void JUCEApplication::systemRequestedQuit()
  13905. {
  13906. quit();
  13907. }
  13908. void JUCEApplication::quit()
  13909. {
  13910. MessageManager::getInstance()->stopDispatchLoop();
  13911. }
  13912. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13913. {
  13914. appReturnValue = newReturnValue;
  13915. }
  13916. void JUCEApplication::actionListenerCallback (const String& message)
  13917. {
  13918. if (message.startsWith (getApplicationName() + "/"))
  13919. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13920. }
  13921. void JUCEApplication::unhandledException (const std::exception*,
  13922. const String&,
  13923. const int)
  13924. {
  13925. jassertfalse;
  13926. }
  13927. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13928. const char* const sourceFile,
  13929. const int lineNumber)
  13930. {
  13931. if (appInstance != 0)
  13932. appInstance->unhandledException (e, sourceFile, lineNumber);
  13933. }
  13934. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13935. {
  13936. return 0;
  13937. }
  13938. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13939. {
  13940. commands.add (StandardApplicationCommandIDs::quit);
  13941. }
  13942. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13943. {
  13944. if (commandID == StandardApplicationCommandIDs::quit)
  13945. {
  13946. result.setInfo (TRANS("Quit"),
  13947. TRANS("Quits the application"),
  13948. "Application",
  13949. 0);
  13950. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13951. }
  13952. }
  13953. bool JUCEApplication::perform (const InvocationInfo& info)
  13954. {
  13955. if (info.commandID == StandardApplicationCommandIDs::quit)
  13956. {
  13957. systemRequestedQuit();
  13958. return true;
  13959. }
  13960. return false;
  13961. }
  13962. bool JUCEApplication::initialiseApp (const String& commandLine)
  13963. {
  13964. commandLineParameters = commandLine.trim();
  13965. #if ! JUCE_IOS
  13966. jassert (appLock == 0); // initialiseApp must only be called once!
  13967. if (! moreThanOneInstanceAllowed())
  13968. {
  13969. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13970. if (! appLock->enter(0))
  13971. {
  13972. appLock = 0;
  13973. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13974. DBG ("Another instance is running - quitting...");
  13975. return false;
  13976. }
  13977. }
  13978. #endif
  13979. // let the app do its setting-up..
  13980. initialise (commandLineParameters);
  13981. #if JUCE_MAC
  13982. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  13983. #endif
  13984. // register for broadcast new app messages
  13985. MessageManager::getInstance()->registerBroadcastListener (this);
  13986. stillInitialising = false;
  13987. return true;
  13988. }
  13989. int JUCEApplication::shutdownApp()
  13990. {
  13991. jassert (appInstance == this);
  13992. MessageManager::getInstance()->deregisterBroadcastListener (this);
  13993. JUCE_TRY
  13994. {
  13995. // give the app a chance to clean up..
  13996. shutdown();
  13997. }
  13998. JUCE_CATCH_EXCEPTION
  13999. return getApplicationReturnValue();
  14000. }
  14001. int JUCEApplication::main (const String& commandLine)
  14002. {
  14003. ScopedJuceInitialiser_GUI libraryInitialiser;
  14004. jassert (createInstance != 0);
  14005. const ScopedPointer<JUCEApplication> app (createInstance());
  14006. if (! app->initialiseApp (commandLine))
  14007. return 0;
  14008. JUCE_TRY
  14009. {
  14010. // loop until a quit message is received..
  14011. MessageManager::getInstance()->runDispatchLoop();
  14012. }
  14013. JUCE_CATCH_EXCEPTION
  14014. return app->shutdownApp();
  14015. }
  14016. #if JUCE_IOS
  14017. extern int juce_iOSMain (int argc, const char* argv[]);
  14018. #endif
  14019. #if ! JUCE_WINDOWS
  14020. extern const char* juce_Argv0;
  14021. #endif
  14022. int JUCEApplication::main (int argc, const char* argv[])
  14023. {
  14024. JUCE_AUTORELEASEPOOL
  14025. #if ! JUCE_WINDOWS
  14026. jassert (createInstance != 0);
  14027. juce_Argv0 = argv[0];
  14028. #endif
  14029. #if JUCE_IOS
  14030. return juce_iOSMain (argc, argv);
  14031. #else
  14032. String cmd;
  14033. for (int i = 1; i < argc; ++i)
  14034. cmd << argv[i] << ' ';
  14035. return JUCEApplication::main (cmd);
  14036. #endif
  14037. }
  14038. END_JUCE_NAMESPACE
  14039. /*** End of inlined file: juce_Application.cpp ***/
  14040. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14041. BEGIN_JUCE_NAMESPACE
  14042. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14043. : commandID (commandID_),
  14044. flags (0)
  14045. {
  14046. }
  14047. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14048. const String& description_,
  14049. const String& categoryName_,
  14050. const int flags_) throw()
  14051. {
  14052. shortName = shortName_;
  14053. description = description_;
  14054. categoryName = categoryName_;
  14055. flags = flags_;
  14056. }
  14057. void ApplicationCommandInfo::setActive (const bool b) throw()
  14058. {
  14059. if (b)
  14060. flags &= ~isDisabled;
  14061. else
  14062. flags |= isDisabled;
  14063. }
  14064. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14065. {
  14066. if (b)
  14067. flags |= isTicked;
  14068. else
  14069. flags &= ~isTicked;
  14070. }
  14071. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14072. {
  14073. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14074. }
  14075. END_JUCE_NAMESPACE
  14076. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14077. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14078. BEGIN_JUCE_NAMESPACE
  14079. ApplicationCommandManager::ApplicationCommandManager()
  14080. : firstTarget (0)
  14081. {
  14082. keyMappings = new KeyPressMappingSet (this);
  14083. Desktop::getInstance().addFocusChangeListener (this);
  14084. }
  14085. ApplicationCommandManager::~ApplicationCommandManager()
  14086. {
  14087. Desktop::getInstance().removeFocusChangeListener (this);
  14088. keyMappings = 0;
  14089. }
  14090. void ApplicationCommandManager::clearCommands()
  14091. {
  14092. commands.clear();
  14093. keyMappings->clearAllKeyPresses();
  14094. triggerAsyncUpdate();
  14095. }
  14096. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14097. {
  14098. // zero isn't a valid command ID!
  14099. jassert (newCommand.commandID != 0);
  14100. // the name isn't optional!
  14101. jassert (newCommand.shortName.isNotEmpty());
  14102. if (getCommandForID (newCommand.commandID) == 0)
  14103. {
  14104. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14105. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14106. commands.add (newInfo);
  14107. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14108. triggerAsyncUpdate();
  14109. }
  14110. else
  14111. {
  14112. // trying to re-register the same command with different parameters?
  14113. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14114. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14115. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14116. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14117. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14118. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14119. }
  14120. }
  14121. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14122. {
  14123. if (target != 0)
  14124. {
  14125. Array <CommandID> commandIDs;
  14126. target->getAllCommands (commandIDs);
  14127. for (int i = 0; i < commandIDs.size(); ++i)
  14128. {
  14129. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14130. target->getCommandInfo (info.commandID, info);
  14131. registerCommand (info);
  14132. }
  14133. }
  14134. }
  14135. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14136. {
  14137. for (int i = commands.size(); --i >= 0;)
  14138. {
  14139. if (commands.getUnchecked (i)->commandID == commandID)
  14140. {
  14141. commands.remove (i);
  14142. triggerAsyncUpdate();
  14143. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14144. for (int j = keys.size(); --j >= 0;)
  14145. keyMappings->removeKeyPress (keys.getReference (j));
  14146. }
  14147. }
  14148. }
  14149. void ApplicationCommandManager::commandStatusChanged()
  14150. {
  14151. triggerAsyncUpdate();
  14152. }
  14153. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14154. {
  14155. for (int i = commands.size(); --i >= 0;)
  14156. if (commands.getUnchecked(i)->commandID == commandID)
  14157. return commands.getUnchecked(i);
  14158. return 0;
  14159. }
  14160. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14161. {
  14162. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14163. return (ci != 0) ? ci->shortName : String::empty;
  14164. }
  14165. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14166. {
  14167. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14168. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14169. : String::empty;
  14170. }
  14171. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14172. {
  14173. StringArray s;
  14174. for (int i = 0; i < commands.size(); ++i)
  14175. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14176. return s;
  14177. }
  14178. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14179. {
  14180. Array <CommandID> results;
  14181. for (int i = 0; i < commands.size(); ++i)
  14182. if (commands.getUnchecked(i)->categoryName == categoryName)
  14183. results.add (commands.getUnchecked(i)->commandID);
  14184. return results;
  14185. }
  14186. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14187. {
  14188. ApplicationCommandTarget::InvocationInfo info (commandID);
  14189. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14190. return invoke (info, asynchronously);
  14191. }
  14192. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14193. {
  14194. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14195. // manager first..
  14196. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14197. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14198. if (target == 0)
  14199. return false;
  14200. ApplicationCommandInfo commandInfo (0);
  14201. target->getCommandInfo (info_.commandID, commandInfo);
  14202. ApplicationCommandTarget::InvocationInfo info (info_);
  14203. info.commandFlags = commandInfo.flags;
  14204. sendListenerInvokeCallback (info);
  14205. const bool ok = target->invoke (info, asynchronously);
  14206. commandStatusChanged();
  14207. return ok;
  14208. }
  14209. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14210. {
  14211. return firstTarget != 0 ? firstTarget
  14212. : findDefaultComponentTarget();
  14213. }
  14214. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14215. {
  14216. firstTarget = newTarget;
  14217. }
  14218. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14219. ApplicationCommandInfo& upToDateInfo)
  14220. {
  14221. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14222. if (target == 0)
  14223. target = JUCEApplication::getInstance();
  14224. if (target != 0)
  14225. target = target->getTargetForCommand (commandID);
  14226. if (target != 0)
  14227. target->getCommandInfo (commandID, upToDateInfo);
  14228. return target;
  14229. }
  14230. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14231. {
  14232. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14233. if (target == 0 && c != 0)
  14234. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14235. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14236. return target;
  14237. }
  14238. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14239. {
  14240. Component* c = Component::getCurrentlyFocusedComponent();
  14241. if (c == 0)
  14242. {
  14243. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14244. if (activeWindow != 0)
  14245. {
  14246. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14247. if (c == 0)
  14248. c = activeWindow;
  14249. }
  14250. }
  14251. if (c == 0 && Process::isForegroundProcess())
  14252. {
  14253. // getting a bit desperate now - try all desktop comps..
  14254. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14255. {
  14256. ApplicationCommandTarget* const target
  14257. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14258. ->getPeer()->getLastFocusedSubcomponent());
  14259. if (target != 0)
  14260. return target;
  14261. }
  14262. }
  14263. if (c != 0)
  14264. {
  14265. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14266. // if we're focused on a ResizableWindow, chances are that it's the content
  14267. // component that really should get the event. And if not, the event will
  14268. // still be passed up to the top level window anyway, so let's send it to the
  14269. // content comp.
  14270. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14271. c = resizableWindow->getContentComponent();
  14272. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14273. if (target != 0)
  14274. return target;
  14275. }
  14276. return JUCEApplication::getInstance();
  14277. }
  14278. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14279. {
  14280. listeners.add (listener);
  14281. }
  14282. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14283. {
  14284. listeners.remove (listener);
  14285. }
  14286. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14287. {
  14288. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14289. }
  14290. void ApplicationCommandManager::handleAsyncUpdate()
  14291. {
  14292. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14293. }
  14294. void ApplicationCommandManager::globalFocusChanged (Component*)
  14295. {
  14296. commandStatusChanged();
  14297. }
  14298. END_JUCE_NAMESPACE
  14299. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14300. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14301. BEGIN_JUCE_NAMESPACE
  14302. ApplicationCommandTarget::ApplicationCommandTarget()
  14303. {
  14304. }
  14305. ApplicationCommandTarget::~ApplicationCommandTarget()
  14306. {
  14307. messageInvoker = 0;
  14308. }
  14309. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14310. {
  14311. if (isCommandActive (info.commandID))
  14312. {
  14313. if (async)
  14314. {
  14315. if (messageInvoker == 0)
  14316. messageInvoker = new CommandTargetMessageInvoker (this);
  14317. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14318. return true;
  14319. }
  14320. else
  14321. {
  14322. const bool success = perform (info);
  14323. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14324. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14325. // returns the command's info.
  14326. return success;
  14327. }
  14328. }
  14329. return false;
  14330. }
  14331. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14332. {
  14333. Component* c = dynamic_cast <Component*> (this);
  14334. if (c != 0)
  14335. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14336. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14337. return 0;
  14338. }
  14339. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14340. {
  14341. ApplicationCommandTarget* target = this;
  14342. int depth = 0;
  14343. while (target != 0)
  14344. {
  14345. Array <CommandID> commandIDs;
  14346. target->getAllCommands (commandIDs);
  14347. if (commandIDs.contains (commandID))
  14348. return target;
  14349. target = target->getNextCommandTarget();
  14350. ++depth;
  14351. jassert (depth < 100); // could be a recursive command chain??
  14352. jassert (target != this); // definitely a recursive command chain!
  14353. if (depth > 100 || target == this)
  14354. break;
  14355. }
  14356. if (target == 0)
  14357. {
  14358. target = JUCEApplication::getInstance();
  14359. if (target != 0)
  14360. {
  14361. Array <CommandID> commandIDs;
  14362. target->getAllCommands (commandIDs);
  14363. if (commandIDs.contains (commandID))
  14364. return target;
  14365. }
  14366. }
  14367. return 0;
  14368. }
  14369. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14370. {
  14371. ApplicationCommandInfo info (commandID);
  14372. info.flags = ApplicationCommandInfo::isDisabled;
  14373. getCommandInfo (commandID, info);
  14374. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14375. }
  14376. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14377. {
  14378. ApplicationCommandTarget* target = this;
  14379. int depth = 0;
  14380. while (target != 0)
  14381. {
  14382. if (target->tryToInvoke (info, async))
  14383. return true;
  14384. target = target->getNextCommandTarget();
  14385. ++depth;
  14386. jassert (depth < 100); // could be a recursive command chain??
  14387. jassert (target != this); // definitely a recursive command chain!
  14388. if (depth > 100 || target == this)
  14389. break;
  14390. }
  14391. if (target == 0)
  14392. {
  14393. target = JUCEApplication::getInstance();
  14394. if (target != 0)
  14395. return target->tryToInvoke (info, async);
  14396. }
  14397. return false;
  14398. }
  14399. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14400. {
  14401. ApplicationCommandTarget::InvocationInfo info (commandID);
  14402. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14403. return invoke (info, asynchronously);
  14404. }
  14405. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14406. : commandID (commandID_),
  14407. commandFlags (0),
  14408. invocationMethod (direct),
  14409. originatingComponent (0),
  14410. isKeyDown (false),
  14411. millisecsSinceKeyPressed (0)
  14412. {
  14413. }
  14414. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14415. : owner (owner_)
  14416. {
  14417. }
  14418. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14419. {
  14420. }
  14421. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14422. {
  14423. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14424. owner->tryToInvoke (*info, false);
  14425. }
  14426. END_JUCE_NAMESPACE
  14427. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14428. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14429. BEGIN_JUCE_NAMESPACE
  14430. juce_ImplementSingleton (ApplicationProperties)
  14431. ApplicationProperties::ApplicationProperties() throw()
  14432. : msBeforeSaving (3000),
  14433. options (PropertiesFile::storeAsBinary),
  14434. commonSettingsAreReadOnly (0)
  14435. {
  14436. }
  14437. ApplicationProperties::~ApplicationProperties()
  14438. {
  14439. closeFiles();
  14440. clearSingletonInstance();
  14441. }
  14442. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14443. const String& fileNameSuffix,
  14444. const String& folderName_,
  14445. const int millisecondsBeforeSaving,
  14446. const int propertiesFileOptions) throw()
  14447. {
  14448. appName = applicationName;
  14449. fileSuffix = fileNameSuffix;
  14450. folderName = folderName_;
  14451. msBeforeSaving = millisecondsBeforeSaving;
  14452. options = propertiesFileOptions;
  14453. }
  14454. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14455. const bool testCommonSettings,
  14456. const bool showWarningDialogOnFailure)
  14457. {
  14458. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14459. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14460. if (! (userOk && commonOk))
  14461. {
  14462. if (showWarningDialogOnFailure)
  14463. {
  14464. String filenames;
  14465. if (userProps != 0 && ! userOk)
  14466. filenames << '\n' << userProps->getFile().getFullPathName();
  14467. if (commonProps != 0 && ! commonOk)
  14468. filenames << '\n' << commonProps->getFile().getFullPathName();
  14469. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14470. appName + TRANS(" - Unable to save settings"),
  14471. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14472. + appName + TRANS(" needs to be able to write to the following files:\n")
  14473. + filenames
  14474. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14475. }
  14476. return false;
  14477. }
  14478. return true;
  14479. }
  14480. void ApplicationProperties::openFiles() throw()
  14481. {
  14482. // You need to call setStorageParameters() before trying to get hold of the
  14483. // properties!
  14484. jassert (appName.isNotEmpty());
  14485. if (appName.isNotEmpty())
  14486. {
  14487. if (userProps == 0)
  14488. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14489. false, msBeforeSaving, options);
  14490. if (commonProps == 0)
  14491. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14492. true, msBeforeSaving, options);
  14493. userProps->setFallbackPropertySet (commonProps);
  14494. }
  14495. }
  14496. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14497. {
  14498. if (userProps == 0)
  14499. openFiles();
  14500. return userProps;
  14501. }
  14502. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14503. {
  14504. if (commonProps == 0)
  14505. openFiles();
  14506. if (returnUserPropsIfReadOnly)
  14507. {
  14508. if (commonSettingsAreReadOnly == 0)
  14509. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14510. if (commonSettingsAreReadOnly > 0)
  14511. return userProps;
  14512. }
  14513. return commonProps;
  14514. }
  14515. bool ApplicationProperties::saveIfNeeded()
  14516. {
  14517. return (userProps == 0 || userProps->saveIfNeeded())
  14518. && (commonProps == 0 || commonProps->saveIfNeeded());
  14519. }
  14520. void ApplicationProperties::closeFiles()
  14521. {
  14522. userProps = 0;
  14523. commonProps = 0;
  14524. }
  14525. END_JUCE_NAMESPACE
  14526. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14527. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14528. BEGIN_JUCE_NAMESPACE
  14529. namespace PropertyFileConstants
  14530. {
  14531. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14532. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14533. static const char* const fileTag = "PROPERTIES";
  14534. static const char* const valueTag = "VALUE";
  14535. static const char* const nameAttribute = "name";
  14536. static const char* const valueAttribute = "val";
  14537. }
  14538. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14539. const int options_, InterProcessLock* const processLock_)
  14540. : PropertySet (ignoreCaseOfKeyNames),
  14541. file (f),
  14542. timerInterval (millisecondsBeforeSaving),
  14543. options (options_),
  14544. loadedOk (false),
  14545. needsWriting (false),
  14546. processLock (processLock_)
  14547. {
  14548. // You need to correctly specify just one storage format for the file
  14549. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14550. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14551. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14552. ProcessScopedLock pl (createProcessLock());
  14553. if (pl != 0 && ! pl->isLocked())
  14554. return; // locking failure..
  14555. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14556. if (fileStream != 0)
  14557. {
  14558. int magicNumber = fileStream->readInt();
  14559. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14560. {
  14561. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14562. magicNumber = PropertyFileConstants::magicNumber;
  14563. }
  14564. if (magicNumber == PropertyFileConstants::magicNumber)
  14565. {
  14566. loadedOk = true;
  14567. BufferedInputStream in (fileStream.release(), 2048, true);
  14568. int numValues = in.readInt();
  14569. while (--numValues >= 0 && ! in.isExhausted())
  14570. {
  14571. const String key (in.readString());
  14572. const String value (in.readString());
  14573. jassert (key.isNotEmpty());
  14574. if (key.isNotEmpty())
  14575. getAllProperties().set (key, value);
  14576. }
  14577. }
  14578. else
  14579. {
  14580. // Not a binary props file - let's see if it's XML..
  14581. fileStream = 0;
  14582. XmlDocument parser (f);
  14583. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14584. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14585. {
  14586. doc = parser.getDocumentElement();
  14587. if (doc != 0)
  14588. {
  14589. loadedOk = true;
  14590. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14591. {
  14592. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14593. if (name.isNotEmpty())
  14594. {
  14595. getAllProperties().set (name,
  14596. e->getFirstChildElement() != 0
  14597. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14598. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14599. }
  14600. }
  14601. }
  14602. else
  14603. {
  14604. // must be a pretty broken XML file we're trying to parse here,
  14605. // or a sign that this object needs an InterProcessLock,
  14606. // or just a failure reading the file. This last reason is why
  14607. // we don't jassertfalse here.
  14608. }
  14609. }
  14610. }
  14611. }
  14612. else
  14613. {
  14614. loadedOk = ! f.exists();
  14615. }
  14616. }
  14617. PropertiesFile::~PropertiesFile()
  14618. {
  14619. if (! saveIfNeeded())
  14620. jassertfalse;
  14621. }
  14622. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14623. {
  14624. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14625. }
  14626. bool PropertiesFile::saveIfNeeded()
  14627. {
  14628. const ScopedLock sl (getLock());
  14629. return (! needsWriting) || save();
  14630. }
  14631. bool PropertiesFile::needsToBeSaved() const
  14632. {
  14633. const ScopedLock sl (getLock());
  14634. return needsWriting;
  14635. }
  14636. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14637. {
  14638. const ScopedLock sl (getLock());
  14639. needsWriting = needsToBeSaved_;
  14640. }
  14641. bool PropertiesFile::save()
  14642. {
  14643. const ScopedLock sl (getLock());
  14644. stopTimer();
  14645. if (file == File::nonexistent
  14646. || file.isDirectory()
  14647. || ! file.getParentDirectory().createDirectory())
  14648. return false;
  14649. if ((options & storeAsXML) != 0)
  14650. {
  14651. XmlElement doc (PropertyFileConstants::fileTag);
  14652. for (int i = 0; i < getAllProperties().size(); ++i)
  14653. {
  14654. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14655. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14656. // if the value seems to contain xml, store it as such..
  14657. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14658. XmlElement* const childElement = xmlContent.getDocumentElement();
  14659. if (childElement != 0)
  14660. e->addChildElement (childElement);
  14661. else
  14662. e->setAttribute (PropertyFileConstants::valueAttribute,
  14663. getAllProperties().getAllValues() [i]);
  14664. }
  14665. ProcessScopedLock pl (createProcessLock());
  14666. if (pl != 0 && ! pl->isLocked())
  14667. return false; // locking failure..
  14668. if (doc.writeToFile (file, String::empty))
  14669. {
  14670. needsWriting = false;
  14671. return true;
  14672. }
  14673. }
  14674. else
  14675. {
  14676. ProcessScopedLock pl (createProcessLock());
  14677. if (pl != 0 && ! pl->isLocked())
  14678. return false; // locking failure..
  14679. TemporaryFile tempFile (file);
  14680. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14681. if (out != 0)
  14682. {
  14683. if ((options & storeAsCompressedBinary) != 0)
  14684. {
  14685. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14686. out->flush();
  14687. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14688. }
  14689. else
  14690. {
  14691. // have you set up the storage option flags correctly?
  14692. jassert ((options & storeAsBinary) != 0);
  14693. out->writeInt (PropertyFileConstants::magicNumber);
  14694. }
  14695. const int numProperties = getAllProperties().size();
  14696. out->writeInt (numProperties);
  14697. for (int i = 0; i < numProperties; ++i)
  14698. {
  14699. out->writeString (getAllProperties().getAllKeys() [i]);
  14700. out->writeString (getAllProperties().getAllValues() [i]);
  14701. }
  14702. out = 0;
  14703. if (tempFile.overwriteTargetFileWithTemporary())
  14704. {
  14705. needsWriting = false;
  14706. return true;
  14707. }
  14708. }
  14709. }
  14710. return false;
  14711. }
  14712. void PropertiesFile::timerCallback()
  14713. {
  14714. saveIfNeeded();
  14715. }
  14716. void PropertiesFile::propertyChanged()
  14717. {
  14718. sendChangeMessage (this);
  14719. needsWriting = true;
  14720. if (timerInterval > 0)
  14721. startTimer (timerInterval);
  14722. else if (timerInterval == 0)
  14723. saveIfNeeded();
  14724. }
  14725. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14726. const String& fileNameSuffix,
  14727. const String& folderName,
  14728. const bool commonToAllUsers)
  14729. {
  14730. // mustn't have illegal characters in this name..
  14731. jassert (applicationName == File::createLegalFileName (applicationName));
  14732. #if JUCE_MAC || JUCE_IOS
  14733. File dir (commonToAllUsers ? "/Library/Preferences"
  14734. : "~/Library/Preferences");
  14735. if (folderName.isNotEmpty())
  14736. dir = dir.getChildFile (folderName);
  14737. #endif
  14738. #ifdef JUCE_LINUX
  14739. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14740. + (folderName.isNotEmpty() ? folderName
  14741. : ("." + applicationName)));
  14742. #endif
  14743. #if JUCE_WINDOWS
  14744. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14745. : File::userApplicationDataDirectory));
  14746. if (dir == File::nonexistent)
  14747. return File::nonexistent;
  14748. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14749. : applicationName);
  14750. #endif
  14751. return dir.getChildFile (applicationName)
  14752. .withFileExtension (fileNameSuffix);
  14753. }
  14754. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14755. const String& fileNameSuffix,
  14756. const String& folderName,
  14757. const bool commonToAllUsers,
  14758. const int millisecondsBeforeSaving,
  14759. const int propertiesFileOptions,
  14760. InterProcessLock* processLock_)
  14761. {
  14762. const File file (getDefaultAppSettingsFile (applicationName,
  14763. fileNameSuffix,
  14764. folderName,
  14765. commonToAllUsers));
  14766. jassert (file != File::nonexistent);
  14767. if (file == File::nonexistent)
  14768. return 0;
  14769. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14770. }
  14771. END_JUCE_NAMESPACE
  14772. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14773. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14774. BEGIN_JUCE_NAMESPACE
  14775. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14776. const String& fileWildcard_,
  14777. const String& openFileDialogTitle_,
  14778. const String& saveFileDialogTitle_)
  14779. : changedSinceSave (false),
  14780. fileExtension (fileExtension_),
  14781. fileWildcard (fileWildcard_),
  14782. openFileDialogTitle (openFileDialogTitle_),
  14783. saveFileDialogTitle (saveFileDialogTitle_)
  14784. {
  14785. }
  14786. FileBasedDocument::~FileBasedDocument()
  14787. {
  14788. }
  14789. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14790. {
  14791. if (changedSinceSave != hasChanged)
  14792. {
  14793. changedSinceSave = hasChanged;
  14794. sendChangeMessage (this);
  14795. }
  14796. }
  14797. void FileBasedDocument::changed()
  14798. {
  14799. changedSinceSave = true;
  14800. sendChangeMessage (this);
  14801. }
  14802. void FileBasedDocument::setFile (const File& newFile)
  14803. {
  14804. if (documentFile != newFile)
  14805. {
  14806. documentFile = newFile;
  14807. changed();
  14808. }
  14809. }
  14810. bool FileBasedDocument::loadFrom (const File& newFile,
  14811. const bool showMessageOnFailure)
  14812. {
  14813. MouseCursor::showWaitCursor();
  14814. const File oldFile (documentFile);
  14815. documentFile = newFile;
  14816. String error;
  14817. if (newFile.existsAsFile())
  14818. {
  14819. error = loadDocument (newFile);
  14820. if (error.isEmpty())
  14821. {
  14822. setChangedFlag (false);
  14823. MouseCursor::hideWaitCursor();
  14824. setLastDocumentOpened (newFile);
  14825. return true;
  14826. }
  14827. }
  14828. else
  14829. {
  14830. error = "The file doesn't exist";
  14831. }
  14832. documentFile = oldFile;
  14833. MouseCursor::hideWaitCursor();
  14834. if (showMessageOnFailure)
  14835. {
  14836. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14837. TRANS("Failed to open file..."),
  14838. TRANS("There was an error while trying to load the file:\n\n")
  14839. + newFile.getFullPathName()
  14840. + "\n\n"
  14841. + error);
  14842. }
  14843. return false;
  14844. }
  14845. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14846. {
  14847. FileChooser fc (openFileDialogTitle,
  14848. getLastDocumentOpened(),
  14849. fileWildcard);
  14850. if (fc.browseForFileToOpen())
  14851. return loadFrom (fc.getResult(), showMessageOnFailure);
  14852. return false;
  14853. }
  14854. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14855. const bool showMessageOnFailure)
  14856. {
  14857. return saveAs (documentFile,
  14858. false,
  14859. askUserForFileIfNotSpecified,
  14860. showMessageOnFailure);
  14861. }
  14862. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14863. const bool warnAboutOverwritingExistingFiles,
  14864. const bool askUserForFileIfNotSpecified,
  14865. const bool showMessageOnFailure)
  14866. {
  14867. if (newFile == File::nonexistent)
  14868. {
  14869. if (askUserForFileIfNotSpecified)
  14870. {
  14871. return saveAsInteractive (true);
  14872. }
  14873. else
  14874. {
  14875. // can't save to an unspecified file
  14876. jassertfalse;
  14877. return failedToWriteToFile;
  14878. }
  14879. }
  14880. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14881. {
  14882. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14883. TRANS("File already exists"),
  14884. TRANS("There's already a file called:\n\n")
  14885. + newFile.getFullPathName()
  14886. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14887. TRANS("overwrite"),
  14888. TRANS("cancel")))
  14889. {
  14890. return userCancelledSave;
  14891. }
  14892. }
  14893. MouseCursor::showWaitCursor();
  14894. const File oldFile (documentFile);
  14895. documentFile = newFile;
  14896. String error (saveDocument (newFile));
  14897. if (error.isEmpty())
  14898. {
  14899. setChangedFlag (false);
  14900. MouseCursor::hideWaitCursor();
  14901. return savedOk;
  14902. }
  14903. documentFile = oldFile;
  14904. MouseCursor::hideWaitCursor();
  14905. if (showMessageOnFailure)
  14906. {
  14907. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14908. TRANS("Error writing to file..."),
  14909. TRANS("An error occurred while trying to save \"")
  14910. + getDocumentTitle()
  14911. + TRANS("\" to the file:\n\n")
  14912. + newFile.getFullPathName()
  14913. + "\n\n"
  14914. + error);
  14915. }
  14916. return failedToWriteToFile;
  14917. }
  14918. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14919. {
  14920. if (! hasChangedSinceSaved())
  14921. return savedOk;
  14922. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14923. TRANS("Closing document..."),
  14924. TRANS("Do you want to save the changes to \"")
  14925. + getDocumentTitle() + "\"?",
  14926. TRANS("save"),
  14927. TRANS("discard changes"),
  14928. TRANS("cancel"));
  14929. if (r == 1)
  14930. {
  14931. // save changes
  14932. return save (true, true);
  14933. }
  14934. else if (r == 2)
  14935. {
  14936. // discard changes
  14937. return savedOk;
  14938. }
  14939. return userCancelledSave;
  14940. }
  14941. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14942. {
  14943. File f;
  14944. if (documentFile.existsAsFile())
  14945. f = documentFile;
  14946. else
  14947. f = getLastDocumentOpened();
  14948. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14949. if (legalFilename.isEmpty())
  14950. legalFilename = "unnamed";
  14951. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14952. f = f.getSiblingFile (legalFilename);
  14953. else
  14954. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14955. f = f.withFileExtension (fileExtension)
  14956. .getNonexistentSibling (true);
  14957. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14958. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14959. {
  14960. setLastDocumentOpened (fc.getResult());
  14961. File chosen (fc.getResult());
  14962. if (chosen.getFileExtension().isEmpty())
  14963. {
  14964. chosen = chosen.withFileExtension (fileExtension);
  14965. if (chosen.exists())
  14966. {
  14967. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14968. TRANS("File already exists"),
  14969. TRANS("There's already a file called:")
  14970. + "\n\n" + chosen.getFullPathName()
  14971. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14972. TRANS("overwrite"),
  14973. TRANS("cancel")))
  14974. {
  14975. return userCancelledSave;
  14976. }
  14977. }
  14978. }
  14979. return saveAs (chosen, false, false, true);
  14980. }
  14981. return userCancelledSave;
  14982. }
  14983. END_JUCE_NAMESPACE
  14984. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14985. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14986. BEGIN_JUCE_NAMESPACE
  14987. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14988. : maxNumberOfItems (10)
  14989. {
  14990. }
  14991. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14992. {
  14993. }
  14994. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14995. {
  14996. maxNumberOfItems = jmax (1, newMaxNumber);
  14997. while (getNumFiles() > maxNumberOfItems)
  14998. files.remove (getNumFiles() - 1);
  14999. }
  15000. int RecentlyOpenedFilesList::getNumFiles() const
  15001. {
  15002. return files.size();
  15003. }
  15004. const File RecentlyOpenedFilesList::getFile (const int index) const
  15005. {
  15006. return File (files [index]);
  15007. }
  15008. void RecentlyOpenedFilesList::clear()
  15009. {
  15010. files.clear();
  15011. }
  15012. void RecentlyOpenedFilesList::addFile (const File& file)
  15013. {
  15014. const String path (file.getFullPathName());
  15015. files.removeString (path, true);
  15016. files.insert (0, path);
  15017. setMaxNumberOfItems (maxNumberOfItems);
  15018. }
  15019. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15020. {
  15021. for (int i = getNumFiles(); --i >= 0;)
  15022. if (! getFile(i).exists())
  15023. files.remove (i);
  15024. }
  15025. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15026. const int baseItemId,
  15027. const bool showFullPaths,
  15028. const bool dontAddNonExistentFiles,
  15029. const File** filesToAvoid)
  15030. {
  15031. int num = 0;
  15032. for (int i = 0; i < getNumFiles(); ++i)
  15033. {
  15034. const File f (getFile(i));
  15035. if ((! dontAddNonExistentFiles) || f.exists())
  15036. {
  15037. bool needsAvoiding = false;
  15038. if (filesToAvoid != 0)
  15039. {
  15040. const File** avoid = filesToAvoid;
  15041. while (*avoid != 0)
  15042. {
  15043. if (f == **avoid)
  15044. {
  15045. needsAvoiding = true;
  15046. break;
  15047. }
  15048. ++avoid;
  15049. }
  15050. }
  15051. if (! needsAvoiding)
  15052. {
  15053. menuToAddTo.addItem (baseItemId + i,
  15054. showFullPaths ? f.getFullPathName()
  15055. : f.getFileName());
  15056. ++num;
  15057. }
  15058. }
  15059. }
  15060. return num;
  15061. }
  15062. const String RecentlyOpenedFilesList::toString() const
  15063. {
  15064. return files.joinIntoString ("\n");
  15065. }
  15066. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15067. {
  15068. clear();
  15069. files.addLines (stringifiedVersion);
  15070. setMaxNumberOfItems (maxNumberOfItems);
  15071. }
  15072. END_JUCE_NAMESPACE
  15073. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15074. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15075. BEGIN_JUCE_NAMESPACE
  15076. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15077. const int minimumTransactions)
  15078. : totalUnitsStored (0),
  15079. nextIndex (0),
  15080. newTransaction (true),
  15081. reentrancyCheck (false)
  15082. {
  15083. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15084. minimumTransactions);
  15085. }
  15086. UndoManager::~UndoManager()
  15087. {
  15088. clearUndoHistory();
  15089. }
  15090. void UndoManager::clearUndoHistory()
  15091. {
  15092. transactions.clear();
  15093. transactionNames.clear();
  15094. totalUnitsStored = 0;
  15095. nextIndex = 0;
  15096. sendChangeMessage (this);
  15097. }
  15098. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15099. {
  15100. return totalUnitsStored;
  15101. }
  15102. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15103. const int minimumTransactions)
  15104. {
  15105. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15106. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15107. }
  15108. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15109. {
  15110. if (command_ != 0)
  15111. {
  15112. ScopedPointer<UndoableAction> command (command_);
  15113. if (actionName.isNotEmpty())
  15114. currentTransactionName = actionName;
  15115. if (reentrancyCheck)
  15116. {
  15117. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15118. // undo() methods, or else these actions won't actually get done.
  15119. return false;
  15120. }
  15121. else if (command->perform())
  15122. {
  15123. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15124. if (commandSet != 0 && ! newTransaction)
  15125. {
  15126. UndoableAction* lastAction = commandSet->getLast();
  15127. if (lastAction != 0)
  15128. {
  15129. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15130. if (coalescedAction != 0)
  15131. {
  15132. command = coalescedAction;
  15133. totalUnitsStored -= lastAction->getSizeInUnits();
  15134. commandSet->removeLast();
  15135. }
  15136. }
  15137. }
  15138. else
  15139. {
  15140. commandSet = new OwnedArray<UndoableAction>();
  15141. transactions.insert (nextIndex, commandSet);
  15142. transactionNames.insert (nextIndex, currentTransactionName);
  15143. ++nextIndex;
  15144. }
  15145. totalUnitsStored += command->getSizeInUnits();
  15146. commandSet->add (command.release());
  15147. newTransaction = false;
  15148. while (nextIndex < transactions.size())
  15149. {
  15150. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15151. for (int i = lastSet->size(); --i >= 0;)
  15152. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15153. transactions.removeLast();
  15154. transactionNames.remove (transactionNames.size() - 1);
  15155. }
  15156. while (nextIndex > 0
  15157. && totalUnitsStored > maxNumUnitsToKeep
  15158. && transactions.size() > minimumTransactionsToKeep)
  15159. {
  15160. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15161. for (int i = firstSet->size(); --i >= 0;)
  15162. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15163. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15164. transactions.remove (0);
  15165. transactionNames.remove (0);
  15166. --nextIndex;
  15167. }
  15168. sendChangeMessage (this);
  15169. return true;
  15170. }
  15171. }
  15172. return false;
  15173. }
  15174. void UndoManager::beginNewTransaction (const String& actionName)
  15175. {
  15176. newTransaction = true;
  15177. currentTransactionName = actionName;
  15178. }
  15179. void UndoManager::setCurrentTransactionName (const String& newName)
  15180. {
  15181. currentTransactionName = newName;
  15182. }
  15183. bool UndoManager::canUndo() const
  15184. {
  15185. return nextIndex > 0;
  15186. }
  15187. bool UndoManager::canRedo() const
  15188. {
  15189. return nextIndex < transactions.size();
  15190. }
  15191. const String UndoManager::getUndoDescription() const
  15192. {
  15193. return transactionNames [nextIndex - 1];
  15194. }
  15195. const String UndoManager::getRedoDescription() const
  15196. {
  15197. return transactionNames [nextIndex];
  15198. }
  15199. bool UndoManager::undo()
  15200. {
  15201. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15202. if (commandSet == 0)
  15203. return false;
  15204. reentrancyCheck = true;
  15205. bool failed = false;
  15206. for (int i = commandSet->size(); --i >= 0;)
  15207. {
  15208. if (! commandSet->getUnchecked(i)->undo())
  15209. {
  15210. jassertfalse;
  15211. failed = true;
  15212. break;
  15213. }
  15214. }
  15215. reentrancyCheck = false;
  15216. if (failed)
  15217. clearUndoHistory();
  15218. else
  15219. --nextIndex;
  15220. beginNewTransaction();
  15221. sendChangeMessage (this);
  15222. return true;
  15223. }
  15224. bool UndoManager::redo()
  15225. {
  15226. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15227. if (commandSet == 0)
  15228. return false;
  15229. reentrancyCheck = true;
  15230. bool failed = false;
  15231. for (int i = 0; i < commandSet->size(); ++i)
  15232. {
  15233. if (! commandSet->getUnchecked(i)->perform())
  15234. {
  15235. jassertfalse;
  15236. failed = true;
  15237. break;
  15238. }
  15239. }
  15240. reentrancyCheck = false;
  15241. if (failed)
  15242. clearUndoHistory();
  15243. else
  15244. ++nextIndex;
  15245. beginNewTransaction();
  15246. sendChangeMessage (this);
  15247. return true;
  15248. }
  15249. bool UndoManager::undoCurrentTransactionOnly()
  15250. {
  15251. return newTransaction ? false : undo();
  15252. }
  15253. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15254. {
  15255. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15256. if (commandSet != 0 && ! newTransaction)
  15257. {
  15258. for (int i = 0; i < commandSet->size(); ++i)
  15259. actionsFound.add (commandSet->getUnchecked(i));
  15260. }
  15261. }
  15262. int UndoManager::getNumActionsInCurrentTransaction() const
  15263. {
  15264. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15265. if (commandSet != 0 && ! newTransaction)
  15266. return commandSet->size();
  15267. return 0;
  15268. }
  15269. END_JUCE_NAMESPACE
  15270. /*** End of inlined file: juce_UndoManager.cpp ***/
  15271. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15272. BEGIN_JUCE_NAMESPACE
  15273. static const char* const aiffFormatName = "AIFF file";
  15274. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15275. class AiffAudioFormatReader : public AudioFormatReader
  15276. {
  15277. public:
  15278. int bytesPerFrame;
  15279. int64 dataChunkStart;
  15280. bool littleEndian;
  15281. AiffAudioFormatReader (InputStream* in)
  15282. : AudioFormatReader (in, TRANS (aiffFormatName))
  15283. {
  15284. if (input->readInt() == chunkName ("FORM"))
  15285. {
  15286. const int len = input->readIntBigEndian();
  15287. const int64 end = input->getPosition() + len;
  15288. const int nextType = input->readInt();
  15289. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15290. {
  15291. bool hasGotVer = false;
  15292. bool hasGotData = false;
  15293. bool hasGotType = false;
  15294. while (input->getPosition() < end)
  15295. {
  15296. const int type = input->readInt();
  15297. const uint32 length = (uint32) input->readIntBigEndian();
  15298. const int64 chunkEnd = input->getPosition() + length;
  15299. if (type == chunkName ("FVER"))
  15300. {
  15301. hasGotVer = true;
  15302. const int ver = input->readIntBigEndian();
  15303. if (ver != 0 && ver != (int)0xa2805140)
  15304. break;
  15305. }
  15306. else if (type == chunkName ("COMM"))
  15307. {
  15308. hasGotType = true;
  15309. numChannels = (unsigned int)input->readShortBigEndian();
  15310. lengthInSamples = input->readIntBigEndian();
  15311. bitsPerSample = input->readShortBigEndian();
  15312. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15313. unsigned char sampleRateBytes[10];
  15314. input->read (sampleRateBytes, 10);
  15315. const int byte0 = sampleRateBytes[0];
  15316. if ((byte0 & 0x80) != 0
  15317. || byte0 <= 0x3F || byte0 > 0x40
  15318. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15319. break;
  15320. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15321. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15322. sampleRate = (int) sampRate;
  15323. if (length <= 18)
  15324. {
  15325. // some types don't have a chunk large enough to include a compression
  15326. // type, so assume it's just big-endian pcm
  15327. littleEndian = false;
  15328. }
  15329. else
  15330. {
  15331. const int compType = input->readInt();
  15332. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15333. {
  15334. littleEndian = false;
  15335. }
  15336. else if (compType == chunkName ("sowt"))
  15337. {
  15338. littleEndian = true;
  15339. }
  15340. else
  15341. {
  15342. sampleRate = 0;
  15343. break;
  15344. }
  15345. }
  15346. }
  15347. else if (type == chunkName ("SSND"))
  15348. {
  15349. hasGotData = true;
  15350. const int offset = input->readIntBigEndian();
  15351. dataChunkStart = input->getPosition() + 4 + offset;
  15352. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15353. }
  15354. else if ((hasGotVer && hasGotData && hasGotType)
  15355. || chunkEnd < input->getPosition()
  15356. || input->isExhausted())
  15357. {
  15358. break;
  15359. }
  15360. input->setPosition (chunkEnd);
  15361. }
  15362. }
  15363. }
  15364. }
  15365. ~AiffAudioFormatReader()
  15366. {
  15367. }
  15368. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15369. int64 startSampleInFile, int numSamples)
  15370. {
  15371. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15372. if (samplesAvailable < numSamples)
  15373. {
  15374. for (int i = numDestChannels; --i >= 0;)
  15375. if (destSamples[i] != 0)
  15376. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15377. numSamples = (int) samplesAvailable;
  15378. }
  15379. if (numSamples <= 0)
  15380. return true;
  15381. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15382. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15383. char tempBuffer [tempBufSize];
  15384. while (numSamples > 0)
  15385. {
  15386. int* left = destSamples[0];
  15387. if (left != 0)
  15388. left += startOffsetInDestBuffer;
  15389. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15390. if (right != 0)
  15391. right += startOffsetInDestBuffer;
  15392. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15393. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15394. if (bytesRead < numThisTime * bytesPerFrame)
  15395. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15396. if (bitsPerSample == 16)
  15397. {
  15398. if (littleEndian)
  15399. {
  15400. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15401. if (numChannels > 1)
  15402. {
  15403. if (left == 0)
  15404. {
  15405. for (int i = numThisTime; --i >= 0;)
  15406. {
  15407. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15408. ++src;
  15409. }
  15410. }
  15411. else if (right == 0)
  15412. {
  15413. for (int i = numThisTime; --i >= 0;)
  15414. {
  15415. ++src;
  15416. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15417. }
  15418. }
  15419. else
  15420. {
  15421. for (int i = numThisTime; --i >= 0;)
  15422. {
  15423. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15424. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15425. }
  15426. }
  15427. }
  15428. else
  15429. {
  15430. for (int i = numThisTime; --i >= 0;)
  15431. {
  15432. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15433. }
  15434. }
  15435. }
  15436. else
  15437. {
  15438. const char* src = tempBuffer;
  15439. if (numChannels > 1)
  15440. {
  15441. if (left == 0)
  15442. {
  15443. for (int i = numThisTime; --i >= 0;)
  15444. {
  15445. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15446. src += 4;
  15447. }
  15448. }
  15449. else if (right == 0)
  15450. {
  15451. for (int i = numThisTime; --i >= 0;)
  15452. {
  15453. src += 2;
  15454. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15455. src += 2;
  15456. }
  15457. }
  15458. else
  15459. {
  15460. for (int i = numThisTime; --i >= 0;)
  15461. {
  15462. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15463. src += 2;
  15464. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15465. src += 2;
  15466. }
  15467. }
  15468. }
  15469. else
  15470. {
  15471. for (int i = numThisTime; --i >= 0;)
  15472. {
  15473. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15474. src += 2;
  15475. }
  15476. }
  15477. }
  15478. }
  15479. else if (bitsPerSample == 24)
  15480. {
  15481. const char* src = (const char*)tempBuffer;
  15482. if (littleEndian)
  15483. {
  15484. if (numChannels > 1)
  15485. {
  15486. if (left == 0)
  15487. {
  15488. for (int i = numThisTime; --i >= 0;)
  15489. {
  15490. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15491. src += 6;
  15492. }
  15493. }
  15494. else if (right == 0)
  15495. {
  15496. for (int i = numThisTime; --i >= 0;)
  15497. {
  15498. src += 3;
  15499. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15500. src += 3;
  15501. }
  15502. }
  15503. else
  15504. {
  15505. for (int i = numThisTime; --i >= 0;)
  15506. {
  15507. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15508. src += 3;
  15509. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15510. src += 3;
  15511. }
  15512. }
  15513. }
  15514. else
  15515. {
  15516. for (int i = numThisTime; --i >= 0;)
  15517. {
  15518. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15519. src += 3;
  15520. }
  15521. }
  15522. }
  15523. else
  15524. {
  15525. if (numChannels > 1)
  15526. {
  15527. if (left == 0)
  15528. {
  15529. for (int i = numThisTime; --i >= 0;)
  15530. {
  15531. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15532. src += 6;
  15533. }
  15534. }
  15535. else if (right == 0)
  15536. {
  15537. for (int i = numThisTime; --i >= 0;)
  15538. {
  15539. src += 3;
  15540. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15541. src += 3;
  15542. }
  15543. }
  15544. else
  15545. {
  15546. for (int i = numThisTime; --i >= 0;)
  15547. {
  15548. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15549. src += 3;
  15550. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15551. src += 3;
  15552. }
  15553. }
  15554. }
  15555. else
  15556. {
  15557. for (int i = numThisTime; --i >= 0;)
  15558. {
  15559. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15560. src += 3;
  15561. }
  15562. }
  15563. }
  15564. }
  15565. else if (bitsPerSample == 32)
  15566. {
  15567. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15568. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15569. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15570. if (littleEndian)
  15571. {
  15572. if (numChannels > 1)
  15573. {
  15574. if (l == 0)
  15575. {
  15576. for (int i = numThisTime; --i >= 0;)
  15577. {
  15578. ++src;
  15579. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15580. }
  15581. }
  15582. else if (r == 0)
  15583. {
  15584. for (int i = numThisTime; --i >= 0;)
  15585. {
  15586. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15587. ++src;
  15588. }
  15589. }
  15590. else
  15591. {
  15592. for (int i = numThisTime; --i >= 0;)
  15593. {
  15594. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15595. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15596. }
  15597. }
  15598. }
  15599. else
  15600. {
  15601. for (int i = numThisTime; --i >= 0;)
  15602. {
  15603. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15604. }
  15605. }
  15606. }
  15607. else
  15608. {
  15609. if (numChannels > 1)
  15610. {
  15611. if (l == 0)
  15612. {
  15613. for (int i = numThisTime; --i >= 0;)
  15614. {
  15615. ++src;
  15616. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15617. }
  15618. }
  15619. else if (r == 0)
  15620. {
  15621. for (int i = numThisTime; --i >= 0;)
  15622. {
  15623. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15624. ++src;
  15625. }
  15626. }
  15627. else
  15628. {
  15629. for (int i = numThisTime; --i >= 0;)
  15630. {
  15631. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15632. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15633. }
  15634. }
  15635. }
  15636. else
  15637. {
  15638. for (int i = numThisTime; --i >= 0;)
  15639. {
  15640. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15641. }
  15642. }
  15643. }
  15644. left = reinterpret_cast <int*> (l);
  15645. right = reinterpret_cast <int*> (r);
  15646. }
  15647. else if (bitsPerSample == 8)
  15648. {
  15649. const char* src = tempBuffer;
  15650. if (numChannels > 1)
  15651. {
  15652. if (left == 0)
  15653. {
  15654. for (int i = numThisTime; --i >= 0;)
  15655. {
  15656. *right++ = ((int) *src++) << 24;
  15657. ++src;
  15658. }
  15659. }
  15660. else if (right == 0)
  15661. {
  15662. for (int i = numThisTime; --i >= 0;)
  15663. {
  15664. ++src;
  15665. *left++ = ((int) *src++) << 24;
  15666. }
  15667. }
  15668. else
  15669. {
  15670. for (int i = numThisTime; --i >= 0;)
  15671. {
  15672. *left++ = ((int) *src++) << 24;
  15673. *right++ = ((int) *src++) << 24;
  15674. }
  15675. }
  15676. }
  15677. else
  15678. {
  15679. for (int i = numThisTime; --i >= 0;)
  15680. {
  15681. *left++ = ((int) *src++) << 24;
  15682. }
  15683. }
  15684. }
  15685. startOffsetInDestBuffer += numThisTime;
  15686. numSamples -= numThisTime;
  15687. }
  15688. if (numSamples > 0)
  15689. {
  15690. for (int i = numDestChannels; --i >= 0;)
  15691. if (destSamples[i] != 0)
  15692. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15693. sizeof (int) * numSamples);
  15694. }
  15695. return true;
  15696. }
  15697. juce_UseDebuggingNewOperator
  15698. private:
  15699. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15700. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15701. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15702. };
  15703. class AiffAudioFormatWriter : public AudioFormatWriter
  15704. {
  15705. MemoryBlock tempBlock;
  15706. uint32 lengthInSamples, bytesWritten;
  15707. int64 headerPosition;
  15708. bool writeFailed;
  15709. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15710. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15711. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15712. void writeHeader()
  15713. {
  15714. const bool couldSeekOk = output->setPosition (headerPosition);
  15715. (void) couldSeekOk;
  15716. // if this fails, you've given it an output stream that can't seek! It needs
  15717. // to be able to seek back to write the header
  15718. jassert (couldSeekOk);
  15719. const int headerLen = 54;
  15720. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15721. audioBytes += (audioBytes & 1);
  15722. output->writeInt (chunkName ("FORM"));
  15723. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15724. output->writeInt (chunkName ("AIFF"));
  15725. output->writeInt (chunkName ("COMM"));
  15726. output->writeIntBigEndian (18);
  15727. output->writeShortBigEndian ((short) numChannels);
  15728. output->writeIntBigEndian (lengthInSamples);
  15729. output->writeShortBigEndian ((short) bitsPerSample);
  15730. uint8 sampleRateBytes[10];
  15731. zeromem (sampleRateBytes, 10);
  15732. if (sampleRate <= 1)
  15733. {
  15734. sampleRateBytes[0] = 0x3f;
  15735. sampleRateBytes[1] = 0xff;
  15736. sampleRateBytes[2] = 0x80;
  15737. }
  15738. else
  15739. {
  15740. int mask = 0x40000000;
  15741. sampleRateBytes[0] = 0x40;
  15742. if (sampleRate >= mask)
  15743. {
  15744. jassertfalse;
  15745. sampleRateBytes[1] = 0x1d;
  15746. }
  15747. else
  15748. {
  15749. int n = (int) sampleRate;
  15750. int i;
  15751. for (i = 0; i <= 32 ; ++i)
  15752. {
  15753. if ((n & mask) != 0)
  15754. break;
  15755. mask >>= 1;
  15756. }
  15757. n = n << (i + 1);
  15758. sampleRateBytes[1] = (uint8) (29 - i);
  15759. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15760. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15761. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15762. sampleRateBytes[5] = (uint8) (n & 0xff);
  15763. }
  15764. }
  15765. output->write (sampleRateBytes, 10);
  15766. output->writeInt (chunkName ("SSND"));
  15767. output->writeIntBigEndian (audioBytes + 8);
  15768. output->writeInt (0);
  15769. output->writeInt (0);
  15770. jassert (output->getPosition() == headerLen);
  15771. }
  15772. public:
  15773. AiffAudioFormatWriter (OutputStream* out,
  15774. const double sampleRate_,
  15775. const unsigned int chans,
  15776. const int bits)
  15777. : AudioFormatWriter (out,
  15778. TRANS (aiffFormatName),
  15779. sampleRate_,
  15780. chans,
  15781. bits),
  15782. lengthInSamples (0),
  15783. bytesWritten (0),
  15784. writeFailed (false)
  15785. {
  15786. headerPosition = out->getPosition();
  15787. writeHeader();
  15788. }
  15789. ~AiffAudioFormatWriter()
  15790. {
  15791. if ((bytesWritten & 1) != 0)
  15792. output->writeByte (0);
  15793. writeHeader();
  15794. }
  15795. bool write (const int** data, int numSamples)
  15796. {
  15797. if (writeFailed)
  15798. return false;
  15799. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15800. tempBlock.ensureSize (bytes, false);
  15801. char* buffer = static_cast <char*> (tempBlock.getData());
  15802. const int* left = data[0];
  15803. const int* right = data[1];
  15804. if (right == 0)
  15805. right = left;
  15806. if (bitsPerSample == 16)
  15807. {
  15808. short* b = reinterpret_cast <short*> (buffer);
  15809. if (numChannels > 1)
  15810. {
  15811. for (int i = numSamples; --i >= 0;)
  15812. {
  15813. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15814. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15815. }
  15816. }
  15817. else
  15818. {
  15819. for (int i = numSamples; --i >= 0;)
  15820. {
  15821. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15822. }
  15823. }
  15824. }
  15825. else if (bitsPerSample == 24)
  15826. {
  15827. char* b = buffer;
  15828. if (numChannels > 1)
  15829. {
  15830. for (int i = numSamples; --i >= 0;)
  15831. {
  15832. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15833. b += 3;
  15834. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15835. b += 3;
  15836. }
  15837. }
  15838. else
  15839. {
  15840. for (int i = numSamples; --i >= 0;)
  15841. {
  15842. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15843. b += 3;
  15844. }
  15845. }
  15846. }
  15847. else if (bitsPerSample == 32)
  15848. {
  15849. uint32* b = reinterpret_cast <uint32*> (buffer);
  15850. if (numChannels > 1)
  15851. {
  15852. for (int i = numSamples; --i >= 0;)
  15853. {
  15854. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15855. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15856. }
  15857. }
  15858. else
  15859. {
  15860. for (int i = numSamples; --i >= 0;)
  15861. {
  15862. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15863. }
  15864. }
  15865. }
  15866. else if (bitsPerSample == 8)
  15867. {
  15868. char* b = buffer;
  15869. if (numChannels > 1)
  15870. {
  15871. for (int i = numSamples; --i >= 0;)
  15872. {
  15873. *b++ = (char) (*left++ >> 24);
  15874. *b++ = (char) (*right++ >> 24);
  15875. }
  15876. }
  15877. else
  15878. {
  15879. for (int i = numSamples; --i >= 0;)
  15880. {
  15881. *b++ = (char) (*left++ >> 24);
  15882. }
  15883. }
  15884. }
  15885. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15886. || ! output->write (buffer, bytes))
  15887. {
  15888. // failed to write to disk, so let's try writing the header.
  15889. // If it's just run out of disk space, then if it does manage
  15890. // to write the header, we'll still have a useable file..
  15891. writeHeader();
  15892. writeFailed = true;
  15893. return false;
  15894. }
  15895. else
  15896. {
  15897. bytesWritten += bytes;
  15898. lengthInSamples += numSamples;
  15899. return true;
  15900. }
  15901. }
  15902. juce_UseDebuggingNewOperator
  15903. };
  15904. AiffAudioFormat::AiffAudioFormat()
  15905. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15906. {
  15907. }
  15908. AiffAudioFormat::~AiffAudioFormat()
  15909. {
  15910. }
  15911. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15912. {
  15913. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15914. return Array <int> (rates);
  15915. }
  15916. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15917. {
  15918. const int depths[] = { 8, 16, 24, 0 };
  15919. return Array <int> (depths);
  15920. }
  15921. bool AiffAudioFormat::canDoStereo()
  15922. {
  15923. return true;
  15924. }
  15925. bool AiffAudioFormat::canDoMono()
  15926. {
  15927. return true;
  15928. }
  15929. #if JUCE_MAC
  15930. bool AiffAudioFormat::canHandleFile (const File& f)
  15931. {
  15932. if (AudioFormat::canHandleFile (f))
  15933. return true;
  15934. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15935. return type == 'AIFF' || type == 'AIFC'
  15936. || type == 'aiff' || type == 'aifc';
  15937. }
  15938. #endif
  15939. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15940. const bool deleteStreamIfOpeningFails)
  15941. {
  15942. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15943. if (w->sampleRate != 0)
  15944. return w.release();
  15945. if (! deleteStreamIfOpeningFails)
  15946. w->input = 0;
  15947. return 0;
  15948. }
  15949. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15950. double sampleRate,
  15951. unsigned int chans,
  15952. int bitsPerSample,
  15953. const StringPairArray& /*metadataValues*/,
  15954. int /*qualityOptionIndex*/)
  15955. {
  15956. if (getPossibleBitDepths().contains (bitsPerSample))
  15957. {
  15958. return new AiffAudioFormatWriter (out,
  15959. sampleRate,
  15960. chans,
  15961. bitsPerSample);
  15962. }
  15963. return 0;
  15964. }
  15965. END_JUCE_NAMESPACE
  15966. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15967. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15968. BEGIN_JUCE_NAMESPACE
  15969. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15970. const String& formatName_)
  15971. : sampleRate (0),
  15972. bitsPerSample (0),
  15973. lengthInSamples (0),
  15974. numChannels (0),
  15975. usesFloatingPointData (false),
  15976. input (in),
  15977. formatName (formatName_)
  15978. {
  15979. }
  15980. AudioFormatReader::~AudioFormatReader()
  15981. {
  15982. delete input;
  15983. }
  15984. bool AudioFormatReader::read (int** destSamples,
  15985. int numDestChannels,
  15986. int64 startSampleInSource,
  15987. int numSamplesToRead,
  15988. const bool fillLeftoverChannelsWithCopies)
  15989. {
  15990. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15991. int startOffsetInDestBuffer = 0;
  15992. if (startSampleInSource < 0)
  15993. {
  15994. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15995. for (int i = numDestChannels; --i >= 0;)
  15996. if (destSamples[i] != 0)
  15997. zeromem (destSamples[i], sizeof (int) * silence);
  15998. startOffsetInDestBuffer += silence;
  15999. numSamplesToRead -= silence;
  16000. startSampleInSource = 0;
  16001. }
  16002. if (numSamplesToRead <= 0)
  16003. return true;
  16004. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16005. startSampleInSource, numSamplesToRead))
  16006. return false;
  16007. if (numDestChannels > (int) numChannels)
  16008. {
  16009. if (fillLeftoverChannelsWithCopies)
  16010. {
  16011. int* lastFullChannel = destSamples[0];
  16012. for (int i = (int) numChannels; --i > 0;)
  16013. {
  16014. if (destSamples[i] != 0)
  16015. {
  16016. lastFullChannel = destSamples[i];
  16017. break;
  16018. }
  16019. }
  16020. if (lastFullChannel != 0)
  16021. for (int i = numChannels; i < numDestChannels; ++i)
  16022. if (destSamples[i] != 0)
  16023. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16024. }
  16025. else
  16026. {
  16027. for (int i = numChannels; i < numDestChannels; ++i)
  16028. if (destSamples[i] != 0)
  16029. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16030. }
  16031. }
  16032. return true;
  16033. }
  16034. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16035. {
  16036. float mn = buffer[0];
  16037. float mx = mn;
  16038. for (int i = 1; i < num; ++i)
  16039. {
  16040. const float s = buffer[i];
  16041. if (s > mx) mx = s;
  16042. if (s < mn) mn = s;
  16043. }
  16044. maxVal = mx;
  16045. minVal = mn;
  16046. }
  16047. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16048. int64 numSamples,
  16049. float& lowestLeft, float& highestLeft,
  16050. float& lowestRight, float& highestRight)
  16051. {
  16052. if (numSamples <= 0)
  16053. {
  16054. lowestLeft = 0;
  16055. lowestRight = 0;
  16056. highestLeft = 0;
  16057. highestRight = 0;
  16058. return;
  16059. }
  16060. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16061. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16062. int* tempBuffer[3];
  16063. tempBuffer[0] = (int*) tempSpace.getData();
  16064. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16065. tempBuffer[2] = 0;
  16066. if (usesFloatingPointData)
  16067. {
  16068. float lmin = 1.0e6f;
  16069. float lmax = -lmin;
  16070. float rmin = lmin;
  16071. float rmax = lmax;
  16072. while (numSamples > 0)
  16073. {
  16074. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16075. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16076. numSamples -= numToDo;
  16077. startSampleInFile += numToDo;
  16078. float bufmin, bufmax;
  16079. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16080. lmin = jmin (lmin, bufmin);
  16081. lmax = jmax (lmax, bufmax);
  16082. if (numChannels > 1)
  16083. {
  16084. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16085. rmin = jmin (rmin, bufmin);
  16086. rmax = jmax (rmax, bufmax);
  16087. }
  16088. }
  16089. if (numChannels <= 1)
  16090. {
  16091. rmax = lmax;
  16092. rmin = lmin;
  16093. }
  16094. lowestLeft = lmin;
  16095. highestLeft = lmax;
  16096. lowestRight = rmin;
  16097. highestRight = rmax;
  16098. }
  16099. else
  16100. {
  16101. int lmax = std::numeric_limits<int>::min();
  16102. int lmin = std::numeric_limits<int>::max();
  16103. int rmax = std::numeric_limits<int>::min();
  16104. int rmin = std::numeric_limits<int>::max();
  16105. while (numSamples > 0)
  16106. {
  16107. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16108. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16109. numSamples -= numToDo;
  16110. startSampleInFile += numToDo;
  16111. for (int j = numChannels; --j >= 0;)
  16112. {
  16113. int bufMax = std::numeric_limits<int>::min();
  16114. int bufMin = std::numeric_limits<int>::max();
  16115. const int* const b = tempBuffer[j];
  16116. for (int i = 0; i < numToDo; ++i)
  16117. {
  16118. const int samp = b[i];
  16119. if (samp < bufMin)
  16120. bufMin = samp;
  16121. if (samp > bufMax)
  16122. bufMax = samp;
  16123. }
  16124. if (j == 0)
  16125. {
  16126. lmax = jmax (lmax, bufMax);
  16127. lmin = jmin (lmin, bufMin);
  16128. }
  16129. else
  16130. {
  16131. rmax = jmax (rmax, bufMax);
  16132. rmin = jmin (rmin, bufMin);
  16133. }
  16134. }
  16135. }
  16136. if (numChannels <= 1)
  16137. {
  16138. rmax = lmax;
  16139. rmin = lmin;
  16140. }
  16141. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16142. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16143. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16144. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16145. }
  16146. }
  16147. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16148. int64 numSamplesToSearch,
  16149. const double magnitudeRangeMinimum,
  16150. const double magnitudeRangeMaximum,
  16151. const int minimumConsecutiveSamples)
  16152. {
  16153. if (numSamplesToSearch == 0)
  16154. return -1;
  16155. const int bufferSize = 4096;
  16156. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16157. int* tempBuffer[3];
  16158. tempBuffer[0] = (int*) tempSpace.getData();
  16159. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16160. tempBuffer[2] = 0;
  16161. int consecutive = 0;
  16162. int64 firstMatchPos = -1;
  16163. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16164. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16165. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16166. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16167. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16168. while (numSamplesToSearch != 0)
  16169. {
  16170. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16171. int64 bufferStart = startSample;
  16172. if (numSamplesToSearch < 0)
  16173. bufferStart -= numThisTime;
  16174. if (bufferStart >= (int) lengthInSamples)
  16175. break;
  16176. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16177. int num = numThisTime;
  16178. while (--num >= 0)
  16179. {
  16180. if (numSamplesToSearch < 0)
  16181. --startSample;
  16182. bool matches = false;
  16183. const int index = (int) (startSample - bufferStart);
  16184. if (usesFloatingPointData)
  16185. {
  16186. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16187. if (sample1 >= magnitudeRangeMinimum
  16188. && sample1 <= magnitudeRangeMaximum)
  16189. {
  16190. matches = true;
  16191. }
  16192. else if (numChannels > 1)
  16193. {
  16194. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16195. matches = (sample2 >= magnitudeRangeMinimum
  16196. && sample2 <= magnitudeRangeMaximum);
  16197. }
  16198. }
  16199. else
  16200. {
  16201. const int sample1 = abs (tempBuffer[0] [index]);
  16202. if (sample1 >= intMagnitudeRangeMinimum
  16203. && sample1 <= intMagnitudeRangeMaximum)
  16204. {
  16205. matches = true;
  16206. }
  16207. else if (numChannels > 1)
  16208. {
  16209. const int sample2 = abs (tempBuffer[1][index]);
  16210. matches = (sample2 >= intMagnitudeRangeMinimum
  16211. && sample2 <= intMagnitudeRangeMaximum);
  16212. }
  16213. }
  16214. if (matches)
  16215. {
  16216. if (firstMatchPos < 0)
  16217. firstMatchPos = startSample;
  16218. if (++consecutive >= minimumConsecutiveSamples)
  16219. {
  16220. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16221. return -1;
  16222. return firstMatchPos;
  16223. }
  16224. }
  16225. else
  16226. {
  16227. consecutive = 0;
  16228. firstMatchPos = -1;
  16229. }
  16230. if (numSamplesToSearch > 0)
  16231. ++startSample;
  16232. }
  16233. if (numSamplesToSearch > 0)
  16234. numSamplesToSearch -= numThisTime;
  16235. else
  16236. numSamplesToSearch += numThisTime;
  16237. }
  16238. return -1;
  16239. }
  16240. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16241. const String& formatName_,
  16242. const double rate,
  16243. const unsigned int numChannels_,
  16244. const unsigned int bitsPerSample_)
  16245. : sampleRate (rate),
  16246. numChannels (numChannels_),
  16247. bitsPerSample (bitsPerSample_),
  16248. usesFloatingPointData (false),
  16249. output (out),
  16250. formatName (formatName_)
  16251. {
  16252. }
  16253. AudioFormatWriter::~AudioFormatWriter()
  16254. {
  16255. delete output;
  16256. }
  16257. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16258. int64 startSample,
  16259. int64 numSamplesToRead)
  16260. {
  16261. const int bufferSize = 16384;
  16262. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16263. int* buffers [128];
  16264. zerostruct (buffers);
  16265. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16266. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16267. if (numSamplesToRead < 0)
  16268. numSamplesToRead = reader.lengthInSamples;
  16269. while (numSamplesToRead > 0)
  16270. {
  16271. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16272. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16273. return false;
  16274. if (reader.usesFloatingPointData != isFloatingPoint())
  16275. {
  16276. int** bufferChan = buffers;
  16277. while (*bufferChan != 0)
  16278. {
  16279. int* b = *bufferChan++;
  16280. if (isFloatingPoint())
  16281. {
  16282. // int -> float
  16283. const double factor = 1.0 / std::numeric_limits<int>::max();
  16284. for (int i = 0; i < numToDo; ++i)
  16285. ((float*) b)[i] = (float) (factor * b[i]);
  16286. }
  16287. else
  16288. {
  16289. // float -> int
  16290. for (int i = 0; i < numToDo; ++i)
  16291. {
  16292. const double samp = *(const float*) b;
  16293. if (samp <= -1.0)
  16294. *b++ = std::numeric_limits<int>::min();
  16295. else if (samp >= 1.0)
  16296. *b++ = std::numeric_limits<int>::max();
  16297. else
  16298. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16299. }
  16300. }
  16301. }
  16302. }
  16303. if (! write ((const int**) buffers, numToDo))
  16304. return false;
  16305. numSamplesToRead -= numToDo;
  16306. startSample += numToDo;
  16307. }
  16308. return true;
  16309. }
  16310. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16311. int numSamplesToRead,
  16312. const int samplesPerBlock)
  16313. {
  16314. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16315. int* buffers [128];
  16316. zerostruct (buffers);
  16317. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16318. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16319. while (numSamplesToRead > 0)
  16320. {
  16321. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16322. AudioSourceChannelInfo info;
  16323. info.buffer = &tempBuffer;
  16324. info.startSample = 0;
  16325. info.numSamples = numToDo;
  16326. info.clearActiveBufferRegion();
  16327. source.getNextAudioBlock (info);
  16328. if (! isFloatingPoint())
  16329. {
  16330. int** bufferChan = buffers;
  16331. while (*bufferChan != 0)
  16332. {
  16333. int* b = *bufferChan++;
  16334. // float -> int
  16335. for (int j = numToDo; --j >= 0;)
  16336. {
  16337. const double samp = *(const float*) b;
  16338. if (samp <= -1.0)
  16339. *b++ = std::numeric_limits<int>::min();
  16340. else if (samp >= 1.0)
  16341. *b++ = std::numeric_limits<int>::max();
  16342. else
  16343. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16344. }
  16345. }
  16346. }
  16347. if (! write ((const int**) buffers, numToDo))
  16348. return false;
  16349. numSamplesToRead -= numToDo;
  16350. }
  16351. return true;
  16352. }
  16353. AudioFormat::AudioFormat (const String& name,
  16354. const StringArray& extensions)
  16355. : formatName (name),
  16356. fileExtensions (extensions)
  16357. {
  16358. }
  16359. AudioFormat::~AudioFormat()
  16360. {
  16361. }
  16362. const String& AudioFormat::getFormatName() const
  16363. {
  16364. return formatName;
  16365. }
  16366. const StringArray& AudioFormat::getFileExtensions() const
  16367. {
  16368. return fileExtensions;
  16369. }
  16370. bool AudioFormat::canHandleFile (const File& f)
  16371. {
  16372. for (int i = 0; i < fileExtensions.size(); ++i)
  16373. if (f.hasFileExtension (fileExtensions[i]))
  16374. return true;
  16375. return false;
  16376. }
  16377. bool AudioFormat::isCompressed()
  16378. {
  16379. return false;
  16380. }
  16381. const StringArray AudioFormat::getQualityOptions()
  16382. {
  16383. return StringArray();
  16384. }
  16385. END_JUCE_NAMESPACE
  16386. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16387. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16388. BEGIN_JUCE_NAMESPACE
  16389. AudioFormatManager::AudioFormatManager()
  16390. : defaultFormatIndex (0)
  16391. {
  16392. }
  16393. AudioFormatManager::~AudioFormatManager()
  16394. {
  16395. clearFormats();
  16396. clearSingletonInstance();
  16397. }
  16398. juce_ImplementSingleton (AudioFormatManager);
  16399. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16400. const bool makeThisTheDefaultFormat)
  16401. {
  16402. jassert (newFormat != 0);
  16403. if (newFormat != 0)
  16404. {
  16405. #if JUCE_DEBUG
  16406. for (int i = getNumKnownFormats(); --i >= 0;)
  16407. {
  16408. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16409. {
  16410. jassertfalse; // trying to add the same format twice!
  16411. }
  16412. }
  16413. #endif
  16414. if (makeThisTheDefaultFormat)
  16415. defaultFormatIndex = getNumKnownFormats();
  16416. knownFormats.add (newFormat);
  16417. }
  16418. }
  16419. void AudioFormatManager::registerBasicFormats()
  16420. {
  16421. #if JUCE_MAC
  16422. registerFormat (new AiffAudioFormat(), true);
  16423. registerFormat (new WavAudioFormat(), false);
  16424. #else
  16425. registerFormat (new WavAudioFormat(), true);
  16426. registerFormat (new AiffAudioFormat(), false);
  16427. #endif
  16428. #if JUCE_USE_FLAC
  16429. registerFormat (new FlacAudioFormat(), false);
  16430. #endif
  16431. #if JUCE_USE_OGGVORBIS
  16432. registerFormat (new OggVorbisAudioFormat(), false);
  16433. #endif
  16434. }
  16435. void AudioFormatManager::clearFormats()
  16436. {
  16437. knownFormats.clear();
  16438. defaultFormatIndex = 0;
  16439. }
  16440. int AudioFormatManager::getNumKnownFormats() const
  16441. {
  16442. return knownFormats.size();
  16443. }
  16444. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16445. {
  16446. return knownFormats [index];
  16447. }
  16448. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16449. {
  16450. return getKnownFormat (defaultFormatIndex);
  16451. }
  16452. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16453. {
  16454. String e (fileExtension);
  16455. if (! e.startsWithChar ('.'))
  16456. e = "." + e;
  16457. for (int i = 0; i < getNumKnownFormats(); ++i)
  16458. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16459. return getKnownFormat(i);
  16460. return 0;
  16461. }
  16462. const String AudioFormatManager::getWildcardForAllFormats() const
  16463. {
  16464. StringArray allExtensions;
  16465. int i;
  16466. for (i = 0; i < getNumKnownFormats(); ++i)
  16467. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16468. allExtensions.trim();
  16469. allExtensions.removeEmptyStrings();
  16470. String s;
  16471. for (i = 0; i < allExtensions.size(); ++i)
  16472. {
  16473. s << '*';
  16474. if (! allExtensions[i].startsWithChar ('.'))
  16475. s << '.';
  16476. s << allExtensions[i];
  16477. if (i < allExtensions.size() - 1)
  16478. s << ';';
  16479. }
  16480. return s;
  16481. }
  16482. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16483. {
  16484. // you need to actually register some formats before the manager can
  16485. // use them to open a file!
  16486. jassert (getNumKnownFormats() > 0);
  16487. for (int i = 0; i < getNumKnownFormats(); ++i)
  16488. {
  16489. AudioFormat* const af = getKnownFormat(i);
  16490. if (af->canHandleFile (file))
  16491. {
  16492. InputStream* const in = file.createInputStream();
  16493. if (in != 0)
  16494. {
  16495. AudioFormatReader* const r = af->createReaderFor (in, true);
  16496. if (r != 0)
  16497. return r;
  16498. }
  16499. }
  16500. }
  16501. return 0;
  16502. }
  16503. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16504. {
  16505. // you need to actually register some formats before the manager can
  16506. // use them to open a file!
  16507. jassert (getNumKnownFormats() > 0);
  16508. ScopedPointer <InputStream> in (audioFileStream);
  16509. if (in != 0)
  16510. {
  16511. const int64 originalStreamPos = in->getPosition();
  16512. for (int i = 0; i < getNumKnownFormats(); ++i)
  16513. {
  16514. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16515. if (r != 0)
  16516. {
  16517. in.release();
  16518. return r;
  16519. }
  16520. in->setPosition (originalStreamPos);
  16521. // the stream that is passed-in must be capable of being repositioned so
  16522. // that all the formats can have a go at opening it.
  16523. jassert (in->getPosition() == originalStreamPos);
  16524. }
  16525. }
  16526. return 0;
  16527. }
  16528. END_JUCE_NAMESPACE
  16529. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16530. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16531. BEGIN_JUCE_NAMESPACE
  16532. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16533. const int64 startSample_,
  16534. const int64 length_,
  16535. const bool deleteSourceWhenDeleted_)
  16536. : AudioFormatReader (0, source_->getFormatName()),
  16537. source (source_),
  16538. startSample (startSample_),
  16539. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16540. {
  16541. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16542. sampleRate = source->sampleRate;
  16543. bitsPerSample = source->bitsPerSample;
  16544. lengthInSamples = length;
  16545. numChannels = source->numChannels;
  16546. usesFloatingPointData = source->usesFloatingPointData;
  16547. }
  16548. AudioSubsectionReader::~AudioSubsectionReader()
  16549. {
  16550. if (deleteSourceWhenDeleted)
  16551. delete source;
  16552. }
  16553. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16554. int64 startSampleInFile, int numSamples)
  16555. {
  16556. if (startSampleInFile + numSamples > length)
  16557. {
  16558. for (int i = numDestChannels; --i >= 0;)
  16559. if (destSamples[i] != 0)
  16560. zeromem (destSamples[i], sizeof (int) * numSamples);
  16561. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16562. if (numSamples <= 0)
  16563. return true;
  16564. }
  16565. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16566. startSampleInFile + startSample, numSamples);
  16567. }
  16568. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16569. int64 numSamples,
  16570. float& lowestLeft,
  16571. float& highestLeft,
  16572. float& lowestRight,
  16573. float& highestRight)
  16574. {
  16575. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16576. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16577. source->readMaxLevels (startSampleInFile + startSample,
  16578. numSamples,
  16579. lowestLeft,
  16580. highestLeft,
  16581. lowestRight,
  16582. highestRight);
  16583. }
  16584. END_JUCE_NAMESPACE
  16585. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16586. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16587. BEGIN_JUCE_NAMESPACE
  16588. const int timeBeforeDeletingReader = 2000;
  16589. struct AudioThumbnailDataFormat
  16590. {
  16591. char thumbnailMagic[4];
  16592. int samplesPerThumbSample;
  16593. int64 totalSamples; // source samples
  16594. int64 numFinishedSamples; // source samples
  16595. int numThumbnailSamples;
  16596. int numChannels;
  16597. int sampleRate;
  16598. char future[16];
  16599. char data[1];
  16600. void swapEndiannessIfNeeded() throw()
  16601. {
  16602. #if JUCE_BIG_ENDIAN
  16603. flip (samplesPerThumbSample);
  16604. flip (totalSamples);
  16605. flip (numFinishedSamples);
  16606. flip (numThumbnailSamples);
  16607. flip (numChannels);
  16608. flip (sampleRate);
  16609. #endif
  16610. }
  16611. private:
  16612. #if JUCE_BIG_ENDIAN
  16613. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16614. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16615. #endif
  16616. };
  16617. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16618. AudioFormatManager& formatManagerToUse_,
  16619. AudioThumbnailCache& cacheToUse)
  16620. : formatManagerToUse (formatManagerToUse_),
  16621. cache (cacheToUse),
  16622. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16623. {
  16624. clear();
  16625. }
  16626. AudioThumbnail::~AudioThumbnail()
  16627. {
  16628. cache.removeThumbnail (this);
  16629. const ScopedLock sl (readerLock);
  16630. reader = 0;
  16631. }
  16632. void AudioThumbnail::setSource (InputSource* const newSource)
  16633. {
  16634. cache.removeThumbnail (this);
  16635. timerCallback(); // stops the timer and deletes the reader
  16636. source = newSource;
  16637. clear();
  16638. if (newSource != 0
  16639. && ! (cache.loadThumb (*this, newSource->hashCode())
  16640. && isFullyLoaded()))
  16641. {
  16642. {
  16643. const ScopedLock sl (readerLock);
  16644. reader = createReader();
  16645. }
  16646. if (reader != 0)
  16647. {
  16648. initialiseFromAudioFile (*reader);
  16649. cache.addThumbnail (this);
  16650. }
  16651. }
  16652. sendChangeMessage (this);
  16653. }
  16654. bool AudioThumbnail::useTimeSlice()
  16655. {
  16656. const ScopedLock sl (readerLock);
  16657. if (isFullyLoaded())
  16658. {
  16659. if (reader != 0)
  16660. startTimer (timeBeforeDeletingReader);
  16661. cache.removeThumbnail (this);
  16662. return false;
  16663. }
  16664. if (reader == 0)
  16665. reader = createReader();
  16666. if (reader != 0)
  16667. {
  16668. readNextBlockFromAudioFile (*reader);
  16669. stopTimer();
  16670. sendChangeMessage (this);
  16671. const bool justFinished = isFullyLoaded();
  16672. if (justFinished)
  16673. cache.storeThumb (*this, source->hashCode());
  16674. return ! justFinished;
  16675. }
  16676. return false;
  16677. }
  16678. AudioFormatReader* AudioThumbnail::createReader() const
  16679. {
  16680. if (source != 0)
  16681. {
  16682. InputStream* const audioFileStream = source->createInputStream();
  16683. if (audioFileStream != 0)
  16684. return formatManagerToUse.createReaderFor (audioFileStream);
  16685. }
  16686. return 0;
  16687. }
  16688. void AudioThumbnail::timerCallback()
  16689. {
  16690. stopTimer();
  16691. const ScopedLock sl (readerLock);
  16692. reader = 0;
  16693. }
  16694. void AudioThumbnail::clear()
  16695. {
  16696. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16697. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16698. d->thumbnailMagic[0] = 'j';
  16699. d->thumbnailMagic[1] = 'a';
  16700. d->thumbnailMagic[2] = 't';
  16701. d->thumbnailMagic[3] = 'm';
  16702. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16703. d->totalSamples = 0;
  16704. d->numFinishedSamples = 0;
  16705. d->numThumbnailSamples = 0;
  16706. d->numChannels = 0;
  16707. d->sampleRate = 0;
  16708. numSamplesCached = 0;
  16709. cacheNeedsRefilling = true;
  16710. }
  16711. void AudioThumbnail::loadFrom (InputStream& input)
  16712. {
  16713. const ScopedLock sl (readerLock);
  16714. data.setSize (0);
  16715. input.readIntoMemoryBlock (data);
  16716. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16717. d->swapEndiannessIfNeeded();
  16718. if (! (d->thumbnailMagic[0] == 'j'
  16719. && d->thumbnailMagic[1] == 'a'
  16720. && d->thumbnailMagic[2] == 't'
  16721. && d->thumbnailMagic[3] == 'm'))
  16722. {
  16723. clear();
  16724. }
  16725. numSamplesCached = 0;
  16726. cacheNeedsRefilling = true;
  16727. }
  16728. void AudioThumbnail::saveTo (OutputStream& output) const
  16729. {
  16730. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16731. d->swapEndiannessIfNeeded();
  16732. output.write (data.getData(), (int) data.getSize());
  16733. d->swapEndiannessIfNeeded();
  16734. }
  16735. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16736. {
  16737. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16738. d->totalSamples = fileReader.lengthInSamples;
  16739. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16740. d->numFinishedSamples = 0;
  16741. d->sampleRate = roundToInt (fileReader.sampleRate);
  16742. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16743. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16744. d = (AudioThumbnailDataFormat*) data.getData();
  16745. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16746. return d->totalSamples > 0;
  16747. }
  16748. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16749. {
  16750. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16751. if (d->numFinishedSamples < d->totalSamples)
  16752. {
  16753. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16754. generateSection (fileReader,
  16755. d->numFinishedSamples,
  16756. numToDo);
  16757. d->numFinishedSamples += numToDo;
  16758. }
  16759. cacheNeedsRefilling = true;
  16760. return (d->numFinishedSamples < d->totalSamples);
  16761. }
  16762. int AudioThumbnail::getNumChannels() const throw()
  16763. {
  16764. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16765. jassert (d != 0);
  16766. return d->numChannels;
  16767. }
  16768. double AudioThumbnail::getTotalLength() const throw()
  16769. {
  16770. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16771. jassert (d != 0);
  16772. if (d->sampleRate > 0)
  16773. return d->totalSamples / (double)d->sampleRate;
  16774. else
  16775. return 0.0;
  16776. }
  16777. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16778. int64 startSample,
  16779. int numSamples)
  16780. {
  16781. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16782. jassert (d != 0);
  16783. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16784. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16785. char* l = getChannelData (0);
  16786. char* r = getChannelData (1);
  16787. for (int i = firstDataPos; i < lastDataPos; ++i)
  16788. {
  16789. const int sourceStart = i * d->samplesPerThumbSample;
  16790. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16791. float lowestLeft, highestLeft, lowestRight, highestRight;
  16792. fileReader.readMaxLevels (sourceStart,
  16793. sourceEnd - sourceStart,
  16794. lowestLeft,
  16795. highestLeft,
  16796. lowestRight,
  16797. highestRight);
  16798. int n = i * 2;
  16799. if (r != 0)
  16800. {
  16801. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16802. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16803. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16804. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16805. }
  16806. else
  16807. {
  16808. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16809. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16810. }
  16811. }
  16812. }
  16813. char* AudioThumbnail::getChannelData (int channel) const
  16814. {
  16815. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16816. jassert (d != 0);
  16817. if (channel >= 0 && channel < d->numChannels)
  16818. return d->data + (channel * 2 * d->numThumbnailSamples);
  16819. return 0;
  16820. }
  16821. bool AudioThumbnail::isFullyLoaded() const throw()
  16822. {
  16823. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16824. jassert (d != 0);
  16825. return d->numFinishedSamples >= d->totalSamples;
  16826. }
  16827. void AudioThumbnail::refillCache (const int numSamples,
  16828. double startTime,
  16829. const double timePerPixel)
  16830. {
  16831. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16832. jassert (d != 0);
  16833. if (numSamples <= 0
  16834. || timePerPixel <= 0.0
  16835. || d->sampleRate <= 0)
  16836. {
  16837. numSamplesCached = 0;
  16838. cacheNeedsRefilling = true;
  16839. return;
  16840. }
  16841. if (numSamples == numSamplesCached
  16842. && numChannelsCached == d->numChannels
  16843. && startTime == cachedStart
  16844. && timePerPixel == cachedTimePerPixel
  16845. && ! cacheNeedsRefilling)
  16846. {
  16847. return;
  16848. }
  16849. numSamplesCached = numSamples;
  16850. numChannelsCached = d->numChannels;
  16851. cachedStart = startTime;
  16852. cachedTimePerPixel = timePerPixel;
  16853. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16854. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16855. const ScopedLock sl (readerLock);
  16856. cacheNeedsRefilling = false;
  16857. if (needExtraDetail && reader == 0)
  16858. reader = createReader();
  16859. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16860. {
  16861. startTimer (timeBeforeDeletingReader);
  16862. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16863. int sample = roundToInt (startTime * d->sampleRate);
  16864. for (int i = numSamples; --i >= 0;)
  16865. {
  16866. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16867. if (sample >= 0)
  16868. {
  16869. if (sample >= reader->lengthInSamples)
  16870. break;
  16871. float lmin, lmax, rmin, rmax;
  16872. reader->readMaxLevels (sample,
  16873. jmax (1, nextSample - sample),
  16874. lmin, lmax, rmin, rmax);
  16875. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16876. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16877. if (numChannelsCached > 1)
  16878. {
  16879. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16880. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16881. }
  16882. cacheData += 2 * numChannelsCached;
  16883. }
  16884. startTime += timePerPixel;
  16885. sample = nextSample;
  16886. }
  16887. }
  16888. else
  16889. {
  16890. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16891. {
  16892. char* const channelData = getChannelData (channelNum);
  16893. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16894. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16895. startTime = cachedStart;
  16896. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16897. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16898. for (int i = numSamples; --i >= 0;)
  16899. {
  16900. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16901. if (sample >= 0 && channelData != 0)
  16902. {
  16903. char mx = -128;
  16904. char mn = 127;
  16905. while (sample <= nextSample)
  16906. {
  16907. if (sample >= numFinished)
  16908. break;
  16909. const int n = sample << 1;
  16910. const char sampMin = channelData [n];
  16911. const char sampMax = channelData [n + 1];
  16912. if (sampMin < mn)
  16913. mn = sampMin;
  16914. if (sampMax > mx)
  16915. mx = sampMax;
  16916. ++sample;
  16917. }
  16918. if (mn <= mx)
  16919. {
  16920. cacheData[0] = mn;
  16921. cacheData[1] = mx;
  16922. }
  16923. else
  16924. {
  16925. cacheData[0] = 1;
  16926. cacheData[1] = 0;
  16927. }
  16928. }
  16929. else
  16930. {
  16931. cacheData[0] = 1;
  16932. cacheData[1] = 0;
  16933. }
  16934. cacheData += numChannelsCached * 2;
  16935. startTime += timePerPixel;
  16936. sample = nextSample;
  16937. }
  16938. }
  16939. }
  16940. }
  16941. void AudioThumbnail::drawChannel (Graphics& g,
  16942. int x, int y, int w, int h,
  16943. double startTime,
  16944. double endTime,
  16945. int channelNum,
  16946. const float verticalZoomFactor)
  16947. {
  16948. refillCache (w, startTime, (endTime - startTime) / w);
  16949. if (numSamplesCached >= w
  16950. && channelNum >= 0
  16951. && channelNum < numChannelsCached)
  16952. {
  16953. const float topY = (float) y;
  16954. const float bottomY = topY + h;
  16955. const float midY = topY + h * 0.5f;
  16956. const float vscale = verticalZoomFactor * h / 256.0f;
  16957. const Rectangle<int> clip (g.getClipBounds());
  16958. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16959. w -= skipLeft;
  16960. x += skipLeft;
  16961. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16962. + (channelNum << 1)
  16963. + skipLeft * (numChannelsCached << 1);
  16964. while (--w >= 0)
  16965. {
  16966. const char mn = cacheData[0];
  16967. const char mx = cacheData[1];
  16968. cacheData += numChannelsCached << 1;
  16969. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16970. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16971. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16972. ++x;
  16973. if (x >= clip.getRight())
  16974. break;
  16975. }
  16976. }
  16977. }
  16978. END_JUCE_NAMESPACE
  16979. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16980. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16981. BEGIN_JUCE_NAMESPACE
  16982. struct ThumbnailCacheEntry
  16983. {
  16984. int64 hash;
  16985. uint32 lastUsed;
  16986. MemoryBlock data;
  16987. juce_UseDebuggingNewOperator
  16988. };
  16989. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16990. : TimeSliceThread ("thumb cache"),
  16991. maxNumThumbsToStore (maxNumThumbsToStore_)
  16992. {
  16993. startThread (2);
  16994. }
  16995. AudioThumbnailCache::~AudioThumbnailCache()
  16996. {
  16997. }
  16998. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16999. {
  17000. for (int i = thumbs.size(); --i >= 0;)
  17001. {
  17002. if (thumbs[i]->hash == hashCode)
  17003. {
  17004. MemoryInputStream in (thumbs[i]->data, false);
  17005. thumb.loadFrom (in);
  17006. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17007. return true;
  17008. }
  17009. }
  17010. return false;
  17011. }
  17012. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17013. const int64 hashCode)
  17014. {
  17015. MemoryOutputStream out;
  17016. thumb.saveTo (out);
  17017. ThumbnailCacheEntry* te = 0;
  17018. for (int i = thumbs.size(); --i >= 0;)
  17019. {
  17020. if (thumbs[i]->hash == hashCode)
  17021. {
  17022. te = thumbs[i];
  17023. break;
  17024. }
  17025. }
  17026. if (te == 0)
  17027. {
  17028. te = new ThumbnailCacheEntry();
  17029. te->hash = hashCode;
  17030. if (thumbs.size() < maxNumThumbsToStore)
  17031. {
  17032. thumbs.add (te);
  17033. }
  17034. else
  17035. {
  17036. int oldest = 0;
  17037. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17038. int i;
  17039. for (i = thumbs.size(); --i >= 0;)
  17040. if (thumbs[i]->lastUsed < oldestTime)
  17041. oldest = i;
  17042. thumbs.set (i, te);
  17043. }
  17044. }
  17045. te->lastUsed = Time::getMillisecondCounter();
  17046. te->data.setSize (0);
  17047. te->data.append (out.getData(), out.getDataSize());
  17048. }
  17049. void AudioThumbnailCache::clear()
  17050. {
  17051. thumbs.clear();
  17052. }
  17053. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17054. {
  17055. addTimeSliceClient (thumb);
  17056. }
  17057. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17058. {
  17059. removeTimeSliceClient (thumb);
  17060. }
  17061. END_JUCE_NAMESPACE
  17062. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17063. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17064. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17065. #if ! JUCE_WINDOWS
  17066. #include <QuickTime/Movies.h>
  17067. #include <QuickTime/QTML.h>
  17068. #include <QuickTime/QuickTimeComponents.h>
  17069. #include <QuickTime/MediaHandlers.h>
  17070. #include <QuickTime/ImageCodec.h>
  17071. #else
  17072. #if JUCE_MSVC
  17073. #pragma warning (push)
  17074. #pragma warning (disable : 4100)
  17075. #endif
  17076. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17077. add its header directory to your include path.
  17078. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17079. flag in juce_Config.h
  17080. */
  17081. #include <Movies.h>
  17082. #include <QTML.h>
  17083. #include <QuickTimeComponents.h>
  17084. #include <MediaHandlers.h>
  17085. #include <ImageCodec.h>
  17086. #if JUCE_MSVC
  17087. #pragma warning (pop)
  17088. #endif
  17089. #endif
  17090. BEGIN_JUCE_NAMESPACE
  17091. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17092. static const char* const quickTimeFormatName = "QuickTime file";
  17093. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17094. class QTAudioReader : public AudioFormatReader
  17095. {
  17096. public:
  17097. QTAudioReader (InputStream* const input_, const int trackNum_)
  17098. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17099. ok (false),
  17100. movie (0),
  17101. trackNum (trackNum_),
  17102. lastSampleRead (0),
  17103. lastThreadId (0),
  17104. extractor (0),
  17105. dataHandle (0)
  17106. {
  17107. bufferList.calloc (256, 1);
  17108. #if JUCE_WINDOWS
  17109. if (InitializeQTML (0) != noErr)
  17110. return;
  17111. #endif
  17112. if (EnterMovies() != noErr)
  17113. return;
  17114. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17115. if (! opened)
  17116. return;
  17117. {
  17118. const int numTracks = GetMovieTrackCount (movie);
  17119. int trackCount = 0;
  17120. for (int i = 1; i <= numTracks; ++i)
  17121. {
  17122. track = GetMovieIndTrack (movie, i);
  17123. media = GetTrackMedia (track);
  17124. OSType mediaType;
  17125. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17126. if (mediaType == SoundMediaType
  17127. && trackCount++ == trackNum_)
  17128. {
  17129. ok = true;
  17130. break;
  17131. }
  17132. }
  17133. }
  17134. if (! ok)
  17135. return;
  17136. ok = false;
  17137. lengthInSamples = GetMediaDecodeDuration (media);
  17138. usesFloatingPointData = false;
  17139. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17140. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17141. / GetMediaTimeScale (media);
  17142. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17143. unsigned long output_layout_size;
  17144. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17145. kQTPropertyClass_MovieAudioExtraction_Audio,
  17146. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17147. 0, &output_layout_size, 0);
  17148. if (err != noErr)
  17149. return;
  17150. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17151. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17152. err = MovieAudioExtractionGetProperty (extractor,
  17153. kQTPropertyClass_MovieAudioExtraction_Audio,
  17154. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17155. output_layout_size, qt_audio_channel_layout, 0);
  17156. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17157. err = MovieAudioExtractionSetProperty (extractor,
  17158. kQTPropertyClass_MovieAudioExtraction_Audio,
  17159. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17160. output_layout_size,
  17161. qt_audio_channel_layout);
  17162. err = MovieAudioExtractionGetProperty (extractor,
  17163. kQTPropertyClass_MovieAudioExtraction_Audio,
  17164. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17165. sizeof (inputStreamDesc),
  17166. &inputStreamDesc, 0);
  17167. if (err != noErr)
  17168. return;
  17169. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17170. | kAudioFormatFlagIsPacked
  17171. | kAudioFormatFlagsNativeEndian;
  17172. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17173. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17174. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17175. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17176. err = MovieAudioExtractionSetProperty (extractor,
  17177. kQTPropertyClass_MovieAudioExtraction_Audio,
  17178. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17179. sizeof (inputStreamDesc),
  17180. &inputStreamDesc);
  17181. if (err != noErr)
  17182. return;
  17183. Boolean allChannelsDiscrete = false;
  17184. err = MovieAudioExtractionSetProperty (extractor,
  17185. kQTPropertyClass_MovieAudioExtraction_Movie,
  17186. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17187. sizeof (allChannelsDiscrete),
  17188. &allChannelsDiscrete);
  17189. if (err != noErr)
  17190. return;
  17191. bufferList->mNumberBuffers = 1;
  17192. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17193. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17194. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17195. bufferList->mBuffers[0].mData = dataBuffer;
  17196. sampleRate = inputStreamDesc.mSampleRate;
  17197. bitsPerSample = 16;
  17198. numChannels = inputStreamDesc.mChannelsPerFrame;
  17199. detachThread();
  17200. ok = true;
  17201. }
  17202. ~QTAudioReader()
  17203. {
  17204. if (dataHandle != 0)
  17205. DisposeHandle (dataHandle);
  17206. if (extractor != 0)
  17207. {
  17208. MovieAudioExtractionEnd (extractor);
  17209. extractor = 0;
  17210. }
  17211. checkThreadIsAttached();
  17212. DisposeMovie (movie);
  17213. #if JUCE_MAC
  17214. ExitMoviesOnThread ();
  17215. #endif
  17216. }
  17217. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17218. int64 startSampleInFile, int numSamples)
  17219. {
  17220. checkThreadIsAttached();
  17221. while (numSamples > 0)
  17222. {
  17223. if (! loadFrame ((int) startSampleInFile))
  17224. return false;
  17225. const int numToDo = jmin (numSamples, samplesPerFrame);
  17226. for (int j = numDestChannels; --j >= 0;)
  17227. {
  17228. if (destSamples[j] != 0)
  17229. {
  17230. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17231. for (int i = 0; i < numToDo; ++i)
  17232. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17233. }
  17234. }
  17235. startOffsetInDestBuffer += numToDo;
  17236. startSampleInFile += numToDo;
  17237. numSamples -= numToDo;
  17238. }
  17239. detachThread();
  17240. return true;
  17241. }
  17242. bool loadFrame (const int sampleNum)
  17243. {
  17244. if (lastSampleRead != sampleNum)
  17245. {
  17246. TimeRecord time;
  17247. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17248. time.base = 0;
  17249. time.value.hi = 0;
  17250. time.value.lo = (UInt32) sampleNum;
  17251. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17252. kQTPropertyClass_MovieAudioExtraction_Movie,
  17253. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17254. sizeof (time), &time);
  17255. if (err != noErr)
  17256. return false;
  17257. }
  17258. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17259. UInt32 outFlags = 0;
  17260. UInt32 actualNumSamples = samplesPerFrame;
  17261. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17262. bufferList, &outFlags);
  17263. lastSampleRead = sampleNum + samplesPerFrame;
  17264. return err == noErr;
  17265. }
  17266. juce_UseDebuggingNewOperator
  17267. bool ok;
  17268. private:
  17269. Movie movie;
  17270. Media media;
  17271. Track track;
  17272. const int trackNum;
  17273. double trackUnitsPerFrame;
  17274. int samplesPerFrame;
  17275. int lastSampleRead;
  17276. Thread::ThreadID lastThreadId;
  17277. MovieAudioExtractionRef extractor;
  17278. AudioStreamBasicDescription inputStreamDesc;
  17279. HeapBlock <AudioBufferList> bufferList;
  17280. HeapBlock <char> dataBuffer;
  17281. Handle dataHandle;
  17282. void checkThreadIsAttached()
  17283. {
  17284. #if JUCE_MAC
  17285. if (Thread::getCurrentThreadId() != lastThreadId)
  17286. EnterMoviesOnThread (0);
  17287. AttachMovieToCurrentThread (movie);
  17288. #endif
  17289. }
  17290. void detachThread()
  17291. {
  17292. #if JUCE_MAC
  17293. DetachMovieFromCurrentThread (movie);
  17294. #endif
  17295. }
  17296. QTAudioReader (const QTAudioReader&);
  17297. QTAudioReader& operator= (const QTAudioReader&);
  17298. };
  17299. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17300. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17301. {
  17302. }
  17303. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17304. {
  17305. }
  17306. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17307. {
  17308. return Array<int>();
  17309. }
  17310. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17311. {
  17312. return Array<int>();
  17313. }
  17314. bool QuickTimeAudioFormat::canDoStereo()
  17315. {
  17316. return true;
  17317. }
  17318. bool QuickTimeAudioFormat::canDoMono()
  17319. {
  17320. return true;
  17321. }
  17322. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17323. const bool deleteStreamIfOpeningFails)
  17324. {
  17325. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17326. if (r->ok)
  17327. return r.release();
  17328. if (! deleteStreamIfOpeningFails)
  17329. r->input = 0;
  17330. return 0;
  17331. }
  17332. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17333. double /*sampleRateToUse*/,
  17334. unsigned int /*numberOfChannels*/,
  17335. int /*bitsPerSample*/,
  17336. const StringPairArray& /*metadataValues*/,
  17337. int /*qualityOptionIndex*/)
  17338. {
  17339. jassertfalse; // not yet implemented!
  17340. return 0;
  17341. }
  17342. END_JUCE_NAMESPACE
  17343. #endif
  17344. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17345. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17346. BEGIN_JUCE_NAMESPACE
  17347. static const char* const wavFormatName = "WAV file";
  17348. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17349. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17350. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17351. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17352. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17353. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17354. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17355. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17356. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17357. const String& originator,
  17358. const String& originatorRef,
  17359. const Time& date,
  17360. const int64 timeReferenceSamples,
  17361. const String& codingHistory)
  17362. {
  17363. StringPairArray m;
  17364. m.set (bwavDescription, description);
  17365. m.set (bwavOriginator, originator);
  17366. m.set (bwavOriginatorRef, originatorRef);
  17367. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17368. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17369. m.set (bwavTimeReference, String (timeReferenceSamples));
  17370. m.set (bwavCodingHistory, codingHistory);
  17371. return m;
  17372. }
  17373. #if JUCE_MSVC
  17374. #pragma pack (push, 1)
  17375. #define PACKED
  17376. #elif JUCE_GCC
  17377. #define PACKED __attribute__((packed))
  17378. #else
  17379. #define PACKED
  17380. #endif
  17381. struct BWAVChunk
  17382. {
  17383. char description [256];
  17384. char originator [32];
  17385. char originatorRef [32];
  17386. char originationDate [10];
  17387. char originationTime [8];
  17388. uint32 timeRefLow;
  17389. uint32 timeRefHigh;
  17390. uint16 version;
  17391. uint8 umid[64];
  17392. uint8 reserved[190];
  17393. char codingHistory[1];
  17394. void copyTo (StringPairArray& values) const
  17395. {
  17396. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17397. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17398. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17399. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17400. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17401. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17402. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17403. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17404. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17405. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17406. }
  17407. static MemoryBlock createFrom (const StringPairArray& values)
  17408. {
  17409. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17410. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17411. data.fillWith (0);
  17412. BWAVChunk* b = (BWAVChunk*) data.getData();
  17413. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17414. // as they get called in the right order..
  17415. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17416. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17417. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17418. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17419. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17420. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17421. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17422. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17423. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17424. if (b->description[0] != 0
  17425. || b->originator[0] != 0
  17426. || b->originationDate[0] != 0
  17427. || b->originationTime[0] != 0
  17428. || b->codingHistory[0] != 0
  17429. || time != 0)
  17430. {
  17431. return data;
  17432. }
  17433. return MemoryBlock();
  17434. }
  17435. } PACKED;
  17436. struct SMPLChunk
  17437. {
  17438. struct SampleLoop
  17439. {
  17440. uint32 identifier;
  17441. uint32 type;
  17442. uint32 start;
  17443. uint32 end;
  17444. uint32 fraction;
  17445. uint32 playCount;
  17446. } PACKED;
  17447. uint32 manufacturer;
  17448. uint32 product;
  17449. uint32 samplePeriod;
  17450. uint32 midiUnityNote;
  17451. uint32 midiPitchFraction;
  17452. uint32 smpteFormat;
  17453. uint32 smpteOffset;
  17454. uint32 numSampleLoops;
  17455. uint32 samplerData;
  17456. SampleLoop loops[1];
  17457. void copyTo (StringPairArray& values, const int totalSize) const
  17458. {
  17459. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17460. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17461. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17462. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17463. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17464. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17465. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17466. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17467. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17468. for (uint32 i = 0; i < numSampleLoops; ++i)
  17469. {
  17470. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17471. break;
  17472. const String prefix ("Loop" + String(i));
  17473. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17474. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17475. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17476. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17477. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17478. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17479. }
  17480. }
  17481. static MemoryBlock createFrom (const StringPairArray& values)
  17482. {
  17483. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17484. if (numLoops <= 0)
  17485. return MemoryBlock();
  17486. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17487. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17488. data.fillWith (0);
  17489. SMPLChunk* s = (SMPLChunk*) data.getData();
  17490. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17491. // as they get called in the right order..
  17492. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17493. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17494. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17495. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17496. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17497. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17498. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17499. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17500. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17501. for (int i = 0; i < numLoops; ++i)
  17502. {
  17503. const String prefix ("Loop" + String(i));
  17504. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17505. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17506. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17507. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17508. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17509. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17510. }
  17511. return data;
  17512. }
  17513. } PACKED;
  17514. struct ExtensibleWavSubFormat
  17515. {
  17516. uint32 data1;
  17517. uint16 data2;
  17518. uint16 data3;
  17519. uint8 data4[8];
  17520. } PACKED;
  17521. #if JUCE_MSVC
  17522. #pragma pack (pop)
  17523. #endif
  17524. #undef PACKED
  17525. class WavAudioFormatReader : public AudioFormatReader
  17526. {
  17527. int bytesPerFrame;
  17528. int64 dataChunkStart, dataLength;
  17529. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17530. WavAudioFormatReader (const WavAudioFormatReader&);
  17531. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17532. public:
  17533. int64 bwavChunkStart, bwavSize;
  17534. WavAudioFormatReader (InputStream* const in)
  17535. : AudioFormatReader (in, TRANS (wavFormatName)),
  17536. dataLength (0),
  17537. bwavChunkStart (0),
  17538. bwavSize (0)
  17539. {
  17540. if (input->readInt() == chunkName ("RIFF"))
  17541. {
  17542. const uint32 len = (uint32) input->readInt();
  17543. const int64 end = input->getPosition() + len;
  17544. bool hasGotType = false;
  17545. bool hasGotData = false;
  17546. if (input->readInt() == chunkName ("WAVE"))
  17547. {
  17548. while (input->getPosition() < end
  17549. && ! input->isExhausted())
  17550. {
  17551. const int chunkType = input->readInt();
  17552. uint32 length = (uint32) input->readInt();
  17553. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17554. if (chunkType == chunkName ("fmt "))
  17555. {
  17556. // read the format chunk
  17557. const unsigned short format = input->readShort();
  17558. const short numChans = input->readShort();
  17559. sampleRate = input->readInt();
  17560. const int bytesPerSec = input->readInt();
  17561. numChannels = numChans;
  17562. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17563. bitsPerSample = 8 * bytesPerFrame / numChans;
  17564. if (format == 3)
  17565. {
  17566. usesFloatingPointData = true;
  17567. }
  17568. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17569. {
  17570. if (length < 40) // too short
  17571. {
  17572. bytesPerFrame = 0;
  17573. }
  17574. else
  17575. {
  17576. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17577. ExtensibleWavSubFormat subFormat;
  17578. subFormat.data1 = input->readInt();
  17579. subFormat.data2 = input->readShort();
  17580. subFormat.data3 = input->readShort();
  17581. input->read (subFormat.data4, sizeof (subFormat.data4));
  17582. const ExtensibleWavSubFormat pcmFormat
  17583. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17584. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17585. {
  17586. const ExtensibleWavSubFormat ambisonicFormat
  17587. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17588. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17589. bytesPerFrame = 0;
  17590. }
  17591. }
  17592. }
  17593. else if (format != 1)
  17594. {
  17595. bytesPerFrame = 0;
  17596. }
  17597. hasGotType = true;
  17598. }
  17599. else if (chunkType == chunkName ("data"))
  17600. {
  17601. // get the data chunk's position
  17602. dataLength = length;
  17603. dataChunkStart = input->getPosition();
  17604. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17605. hasGotData = true;
  17606. }
  17607. else if (chunkType == chunkName ("bext"))
  17608. {
  17609. bwavChunkStart = input->getPosition();
  17610. bwavSize = length;
  17611. // Broadcast-wav extension chunk..
  17612. HeapBlock <BWAVChunk> bwav;
  17613. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17614. input->read (bwav, length);
  17615. bwav->copyTo (metadataValues);
  17616. }
  17617. else if (chunkType == chunkName ("smpl"))
  17618. {
  17619. HeapBlock <SMPLChunk> smpl;
  17620. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17621. input->read (smpl, length);
  17622. smpl->copyTo (metadataValues, length);
  17623. }
  17624. else if (chunkEnd <= input->getPosition())
  17625. {
  17626. break;
  17627. }
  17628. input->setPosition (chunkEnd);
  17629. }
  17630. }
  17631. }
  17632. }
  17633. ~WavAudioFormatReader()
  17634. {
  17635. }
  17636. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17637. int64 startSampleInFile, int numSamples)
  17638. {
  17639. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17640. if (samplesAvailable < numSamples)
  17641. {
  17642. for (int i = numDestChannels; --i >= 0;)
  17643. if (destSamples[i] != 0)
  17644. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17645. numSamples = (int) samplesAvailable;
  17646. }
  17647. if (numSamples <= 0)
  17648. return true;
  17649. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17650. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17651. char tempBuffer [tempBufSize];
  17652. while (numSamples > 0)
  17653. {
  17654. int* left = destSamples[0];
  17655. if (left != 0)
  17656. left += startOffsetInDestBuffer;
  17657. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17658. if (right != 0)
  17659. right += startOffsetInDestBuffer;
  17660. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17661. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17662. if (bytesRead < numThisTime * bytesPerFrame)
  17663. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17664. if (bitsPerSample == 16)
  17665. {
  17666. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17667. if (numChannels > 1)
  17668. {
  17669. if (left == 0)
  17670. {
  17671. for (int i = numThisTime; --i >= 0;)
  17672. {
  17673. ++src;
  17674. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17675. }
  17676. }
  17677. else if (right == 0)
  17678. {
  17679. for (int i = numThisTime; --i >= 0;)
  17680. {
  17681. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17682. ++src;
  17683. }
  17684. }
  17685. else
  17686. {
  17687. for (int i = numThisTime; --i >= 0;)
  17688. {
  17689. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17690. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17691. }
  17692. }
  17693. }
  17694. else
  17695. {
  17696. for (int i = numThisTime; --i >= 0;)
  17697. {
  17698. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17699. }
  17700. }
  17701. }
  17702. else if (bitsPerSample == 24)
  17703. {
  17704. const char* src = tempBuffer;
  17705. if (numChannels > 1)
  17706. {
  17707. if (left == 0)
  17708. {
  17709. for (int i = numThisTime; --i >= 0;)
  17710. {
  17711. src += 3;
  17712. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17713. src += 3;
  17714. }
  17715. }
  17716. else if (right == 0)
  17717. {
  17718. for (int i = numThisTime; --i >= 0;)
  17719. {
  17720. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17721. src += 6;
  17722. }
  17723. }
  17724. else
  17725. {
  17726. for (int i = 0; i < numThisTime; ++i)
  17727. {
  17728. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17729. src += 3;
  17730. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17731. src += 3;
  17732. }
  17733. }
  17734. }
  17735. else
  17736. {
  17737. for (int i = 0; i < numThisTime; ++i)
  17738. {
  17739. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17740. src += 3;
  17741. }
  17742. }
  17743. }
  17744. else if (bitsPerSample == 32)
  17745. {
  17746. const unsigned int* src = (const unsigned int*) tempBuffer;
  17747. unsigned int* l = (unsigned int*) left;
  17748. unsigned int* r = (unsigned int*) right;
  17749. if (numChannels > 1)
  17750. {
  17751. if (l == 0)
  17752. {
  17753. for (int i = numThisTime; --i >= 0;)
  17754. {
  17755. ++src;
  17756. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17757. }
  17758. }
  17759. else if (r == 0)
  17760. {
  17761. for (int i = numThisTime; --i >= 0;)
  17762. {
  17763. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17764. ++src;
  17765. }
  17766. }
  17767. else
  17768. {
  17769. for (int i = numThisTime; --i >= 0;)
  17770. {
  17771. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17772. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17773. }
  17774. }
  17775. }
  17776. else
  17777. {
  17778. for (int i = numThisTime; --i >= 0;)
  17779. {
  17780. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17781. }
  17782. }
  17783. left = (int*)l;
  17784. right = (int*)r;
  17785. }
  17786. else if (bitsPerSample == 8)
  17787. {
  17788. const unsigned char* src = (const unsigned char*) tempBuffer;
  17789. if (numChannels > 1)
  17790. {
  17791. if (left == 0)
  17792. {
  17793. for (int i = numThisTime; --i >= 0;)
  17794. {
  17795. ++src;
  17796. *right++ = ((int) *src++ - 128) << 24;
  17797. }
  17798. }
  17799. else if (right == 0)
  17800. {
  17801. for (int i = numThisTime; --i >= 0;)
  17802. {
  17803. *left++ = ((int) *src++ - 128) << 24;
  17804. ++src;
  17805. }
  17806. }
  17807. else
  17808. {
  17809. for (int i = numThisTime; --i >= 0;)
  17810. {
  17811. *left++ = ((int) *src++ - 128) << 24;
  17812. *right++ = ((int) *src++ - 128) << 24;
  17813. }
  17814. }
  17815. }
  17816. else
  17817. {
  17818. for (int i = numThisTime; --i >= 0;)
  17819. {
  17820. *left++ = ((int)*src++ - 128) << 24;
  17821. }
  17822. }
  17823. }
  17824. startOffsetInDestBuffer += numThisTime;
  17825. numSamples -= numThisTime;
  17826. }
  17827. if (numSamples > 0)
  17828. {
  17829. for (int i = numDestChannels; --i >= 0;)
  17830. if (destSamples[i] != 0)
  17831. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17832. sizeof (int) * numSamples);
  17833. }
  17834. return true;
  17835. }
  17836. juce_UseDebuggingNewOperator
  17837. };
  17838. class WavAudioFormatWriter : public AudioFormatWriter
  17839. {
  17840. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17841. uint32 lengthInSamples, bytesWritten;
  17842. int64 headerPosition;
  17843. bool writeFailed;
  17844. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17845. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17846. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17847. void writeHeader()
  17848. {
  17849. const bool seekedOk = output->setPosition (headerPosition);
  17850. (void) seekedOk;
  17851. // if this fails, you've given it an output stream that can't seek! It needs
  17852. // to be able to seek back to write the header
  17853. jassert (seekedOk);
  17854. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17855. output->writeInt (chunkName ("RIFF"));
  17856. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17857. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17858. output->writeInt (chunkName ("WAVE"));
  17859. output->writeInt (chunkName ("fmt "));
  17860. output->writeInt (16);
  17861. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17862. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17863. output->writeShort ((short) numChannels);
  17864. output->writeInt ((int) sampleRate);
  17865. output->writeInt (bytesPerFrame * (int) sampleRate);
  17866. output->writeShort ((short) bytesPerFrame);
  17867. output->writeShort ((short) bitsPerSample);
  17868. if (bwavChunk.getSize() > 0)
  17869. {
  17870. output->writeInt (chunkName ("bext"));
  17871. output->writeInt ((int) bwavChunk.getSize());
  17872. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17873. }
  17874. if (smplChunk.getSize() > 0)
  17875. {
  17876. output->writeInt (chunkName ("smpl"));
  17877. output->writeInt ((int) smplChunk.getSize());
  17878. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17879. }
  17880. output->writeInt (chunkName ("data"));
  17881. output->writeInt (lengthInSamples * bytesPerFrame);
  17882. usesFloatingPointData = (bitsPerSample == 32);
  17883. }
  17884. public:
  17885. WavAudioFormatWriter (OutputStream* const out,
  17886. const double sampleRate_,
  17887. const unsigned int numChannels_,
  17888. const int bits,
  17889. const StringPairArray& metadataValues)
  17890. : AudioFormatWriter (out,
  17891. TRANS (wavFormatName),
  17892. sampleRate_,
  17893. numChannels_,
  17894. bits),
  17895. lengthInSamples (0),
  17896. bytesWritten (0),
  17897. writeFailed (false)
  17898. {
  17899. if (metadataValues.size() > 0)
  17900. {
  17901. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17902. smplChunk = SMPLChunk::createFrom (metadataValues);
  17903. }
  17904. headerPosition = out->getPosition();
  17905. writeHeader();
  17906. }
  17907. ~WavAudioFormatWriter()
  17908. {
  17909. writeHeader();
  17910. }
  17911. bool write (const int** data, int numSamples)
  17912. {
  17913. if (writeFailed)
  17914. return false;
  17915. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17916. tempBlock.ensureSize (bytes, false);
  17917. char* buffer = static_cast <char*> (tempBlock.getData());
  17918. const int* left = data[0];
  17919. const int* right = data[1];
  17920. if (right == 0)
  17921. right = left;
  17922. if (bitsPerSample == 16)
  17923. {
  17924. short* b = (short*) buffer;
  17925. if (numChannels > 1)
  17926. {
  17927. for (int i = numSamples; --i >= 0;)
  17928. {
  17929. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17930. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17931. }
  17932. }
  17933. else
  17934. {
  17935. for (int i = numSamples; --i >= 0;)
  17936. {
  17937. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17938. }
  17939. }
  17940. }
  17941. else if (bitsPerSample == 24)
  17942. {
  17943. char* b = buffer;
  17944. if (numChannels > 1)
  17945. {
  17946. for (int i = numSamples; --i >= 0;)
  17947. {
  17948. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17949. b += 3;
  17950. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17951. b += 3;
  17952. }
  17953. }
  17954. else
  17955. {
  17956. for (int i = numSamples; --i >= 0;)
  17957. {
  17958. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17959. b += 3;
  17960. }
  17961. }
  17962. }
  17963. else if (bitsPerSample == 32)
  17964. {
  17965. unsigned int* b = (unsigned int*) buffer;
  17966. if (numChannels > 1)
  17967. {
  17968. for (int i = numSamples; --i >= 0;)
  17969. {
  17970. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17971. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17972. }
  17973. }
  17974. else
  17975. {
  17976. for (int i = numSamples; --i >= 0;)
  17977. {
  17978. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17979. }
  17980. }
  17981. }
  17982. else if (bitsPerSample == 8)
  17983. {
  17984. unsigned char* b = (unsigned char*) buffer;
  17985. if (numChannels > 1)
  17986. {
  17987. for (int i = numSamples; --i >= 0;)
  17988. {
  17989. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17990. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17991. }
  17992. }
  17993. else
  17994. {
  17995. for (int i = numSamples; --i >= 0;)
  17996. {
  17997. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17998. }
  17999. }
  18000. }
  18001. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18002. || ! output->write (buffer, bytes))
  18003. {
  18004. // failed to write to disk, so let's try writing the header.
  18005. // If it's just run out of disk space, then if it does manage
  18006. // to write the header, we'll still have a useable file..
  18007. writeHeader();
  18008. writeFailed = true;
  18009. return false;
  18010. }
  18011. else
  18012. {
  18013. bytesWritten += bytes;
  18014. lengthInSamples += numSamples;
  18015. return true;
  18016. }
  18017. }
  18018. juce_UseDebuggingNewOperator
  18019. };
  18020. WavAudioFormat::WavAudioFormat()
  18021. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18022. {
  18023. }
  18024. WavAudioFormat::~WavAudioFormat()
  18025. {
  18026. }
  18027. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18028. {
  18029. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18030. return Array <int> (rates);
  18031. }
  18032. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18033. {
  18034. const int depths[] = { 8, 16, 24, 32, 0 };
  18035. return Array <int> (depths);
  18036. }
  18037. bool WavAudioFormat::canDoStereo()
  18038. {
  18039. return true;
  18040. }
  18041. bool WavAudioFormat::canDoMono()
  18042. {
  18043. return true;
  18044. }
  18045. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18046. const bool deleteStreamIfOpeningFails)
  18047. {
  18048. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18049. if (r->sampleRate != 0)
  18050. return r.release();
  18051. if (! deleteStreamIfOpeningFails)
  18052. r->input = 0;
  18053. return 0;
  18054. }
  18055. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18056. double sampleRate,
  18057. unsigned int numChannels,
  18058. int bitsPerSample,
  18059. const StringPairArray& metadataValues,
  18060. int /*qualityOptionIndex*/)
  18061. {
  18062. if (getPossibleBitDepths().contains (bitsPerSample))
  18063. {
  18064. return new WavAudioFormatWriter (out,
  18065. sampleRate,
  18066. numChannels,
  18067. bitsPerSample,
  18068. metadataValues);
  18069. }
  18070. return 0;
  18071. }
  18072. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18073. {
  18074. TemporaryFile tempFile (file);
  18075. WavAudioFormat wav;
  18076. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18077. if (reader != 0)
  18078. {
  18079. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18080. if (outStream != 0)
  18081. {
  18082. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18083. reader->numChannels, reader->bitsPerSample,
  18084. metadata, 0));
  18085. if (writer != 0)
  18086. {
  18087. outStream.release();
  18088. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18089. writer = 0;
  18090. reader = 0;
  18091. return ok && tempFile.overwriteTargetFileWithTemporary();
  18092. }
  18093. }
  18094. }
  18095. return false;
  18096. }
  18097. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18098. {
  18099. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18100. if (reader != 0)
  18101. {
  18102. const int64 bwavPos = reader->bwavChunkStart;
  18103. const int64 bwavSize = reader->bwavSize;
  18104. reader = 0;
  18105. if (bwavSize > 0)
  18106. {
  18107. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18108. if (chunk.getSize() <= (size_t) bwavSize)
  18109. {
  18110. // the new one will fit in the space available, so write it directly..
  18111. const int64 oldSize = wavFile.getSize();
  18112. {
  18113. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18114. out->setPosition (bwavPos);
  18115. out->write (chunk.getData(), (int) chunk.getSize());
  18116. out->setPosition (oldSize);
  18117. }
  18118. jassert (wavFile.getSize() == oldSize);
  18119. return true;
  18120. }
  18121. }
  18122. }
  18123. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18124. }
  18125. END_JUCE_NAMESPACE
  18126. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18127. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18128. #if JUCE_USE_CDREADER
  18129. BEGIN_JUCE_NAMESPACE
  18130. int AudioCDReader::getNumTracks() const
  18131. {
  18132. return trackStartSamples.size() - 1;
  18133. }
  18134. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18135. {
  18136. return trackStartSamples [trackNum];
  18137. }
  18138. const Array<int>& AudioCDReader::getTrackOffsets() const
  18139. {
  18140. return trackStartSamples;
  18141. }
  18142. int AudioCDReader::getCDDBId()
  18143. {
  18144. int checksum = 0;
  18145. const int numTracks = getNumTracks();
  18146. for (int i = 0; i < numTracks; ++i)
  18147. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18148. checksum += offset % 10;
  18149. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18150. // CCLLLLTT: checksum, length, tracks
  18151. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18152. }
  18153. END_JUCE_NAMESPACE
  18154. #endif
  18155. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18156. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18157. BEGIN_JUCE_NAMESPACE
  18158. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18159. const bool deleteReaderWhenThisIsDeleted)
  18160. : reader (reader_),
  18161. deleteReader (deleteReaderWhenThisIsDeleted),
  18162. nextPlayPos (0),
  18163. looping (false)
  18164. {
  18165. jassert (reader != 0);
  18166. }
  18167. AudioFormatReaderSource::~AudioFormatReaderSource()
  18168. {
  18169. releaseResources();
  18170. if (deleteReader)
  18171. delete reader;
  18172. }
  18173. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18174. {
  18175. nextPlayPos = newPosition;
  18176. }
  18177. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18178. {
  18179. looping = shouldLoop;
  18180. }
  18181. int AudioFormatReaderSource::getNextReadPosition() const
  18182. {
  18183. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18184. : nextPlayPos;
  18185. }
  18186. int AudioFormatReaderSource::getTotalLength() const
  18187. {
  18188. return (int) reader->lengthInSamples;
  18189. }
  18190. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18191. double /*sampleRate*/)
  18192. {
  18193. }
  18194. void AudioFormatReaderSource::releaseResources()
  18195. {
  18196. }
  18197. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18198. {
  18199. if (info.numSamples > 0)
  18200. {
  18201. const int start = nextPlayPos;
  18202. if (looping)
  18203. {
  18204. const int newStart = start % (int) reader->lengthInSamples;
  18205. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18206. if (newEnd > newStart)
  18207. {
  18208. info.buffer->readFromAudioReader (reader,
  18209. info.startSample,
  18210. newEnd - newStart,
  18211. newStart,
  18212. true, true);
  18213. }
  18214. else
  18215. {
  18216. const int endSamps = (int) reader->lengthInSamples - newStart;
  18217. info.buffer->readFromAudioReader (reader,
  18218. info.startSample,
  18219. endSamps,
  18220. newStart,
  18221. true, true);
  18222. info.buffer->readFromAudioReader (reader,
  18223. info.startSample + endSamps,
  18224. newEnd,
  18225. 0,
  18226. true, true);
  18227. }
  18228. nextPlayPos = newEnd;
  18229. }
  18230. else
  18231. {
  18232. info.buffer->readFromAudioReader (reader,
  18233. info.startSample,
  18234. info.numSamples,
  18235. start,
  18236. true, true);
  18237. nextPlayPos += info.numSamples;
  18238. }
  18239. }
  18240. }
  18241. END_JUCE_NAMESPACE
  18242. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18243. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18244. BEGIN_JUCE_NAMESPACE
  18245. AudioSourcePlayer::AudioSourcePlayer()
  18246. : source (0),
  18247. sampleRate (0),
  18248. bufferSize (0),
  18249. tempBuffer (2, 8),
  18250. lastGain (1.0f),
  18251. gain (1.0f)
  18252. {
  18253. }
  18254. AudioSourcePlayer::~AudioSourcePlayer()
  18255. {
  18256. setSource (0);
  18257. }
  18258. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18259. {
  18260. if (source != newSource)
  18261. {
  18262. AudioSource* const oldSource = source;
  18263. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18264. newSource->prepareToPlay (bufferSize, sampleRate);
  18265. {
  18266. const ScopedLock sl (readLock);
  18267. source = newSource;
  18268. }
  18269. if (oldSource != 0)
  18270. oldSource->releaseResources();
  18271. }
  18272. }
  18273. void AudioSourcePlayer::setGain (const float newGain) throw()
  18274. {
  18275. gain = newGain;
  18276. }
  18277. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18278. int totalNumInputChannels,
  18279. float** outputChannelData,
  18280. int totalNumOutputChannels,
  18281. int numSamples)
  18282. {
  18283. // these should have been prepared by audioDeviceAboutToStart()...
  18284. jassert (sampleRate > 0 && bufferSize > 0);
  18285. const ScopedLock sl (readLock);
  18286. if (source != 0)
  18287. {
  18288. AudioSourceChannelInfo info;
  18289. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18290. // messy stuff needed to compact the channels down into an array
  18291. // of non-zero pointers..
  18292. for (i = 0; i < totalNumInputChannels; ++i)
  18293. {
  18294. if (inputChannelData[i] != 0)
  18295. {
  18296. inputChans [numInputs++] = inputChannelData[i];
  18297. if (numInputs >= numElementsInArray (inputChans))
  18298. break;
  18299. }
  18300. }
  18301. for (i = 0; i < totalNumOutputChannels; ++i)
  18302. {
  18303. if (outputChannelData[i] != 0)
  18304. {
  18305. outputChans [numOutputs++] = outputChannelData[i];
  18306. if (numOutputs >= numElementsInArray (outputChans))
  18307. break;
  18308. }
  18309. }
  18310. if (numInputs > numOutputs)
  18311. {
  18312. // if there aren't enough output channels for the number of
  18313. // inputs, we need to create some temporary extra ones (can't
  18314. // use the input data in case it gets written to)
  18315. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18316. false, false, true);
  18317. for (i = 0; i < numOutputs; ++i)
  18318. {
  18319. channels[numActiveChans] = outputChans[i];
  18320. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18321. ++numActiveChans;
  18322. }
  18323. for (i = numOutputs; i < numInputs; ++i)
  18324. {
  18325. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18326. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18327. ++numActiveChans;
  18328. }
  18329. }
  18330. else
  18331. {
  18332. for (i = 0; i < numInputs; ++i)
  18333. {
  18334. channels[numActiveChans] = outputChans[i];
  18335. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18336. ++numActiveChans;
  18337. }
  18338. for (i = numInputs; i < numOutputs; ++i)
  18339. {
  18340. channels[numActiveChans] = outputChans[i];
  18341. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18342. ++numActiveChans;
  18343. }
  18344. }
  18345. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18346. info.buffer = &buffer;
  18347. info.startSample = 0;
  18348. info.numSamples = numSamples;
  18349. source->getNextAudioBlock (info);
  18350. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18351. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18352. lastGain = gain;
  18353. }
  18354. else
  18355. {
  18356. for (int i = 0; i < totalNumOutputChannels; ++i)
  18357. if (outputChannelData[i] != 0)
  18358. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18359. }
  18360. }
  18361. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18362. {
  18363. sampleRate = device->getCurrentSampleRate();
  18364. bufferSize = device->getCurrentBufferSizeSamples();
  18365. zeromem (channels, sizeof (channels));
  18366. if (source != 0)
  18367. source->prepareToPlay (bufferSize, sampleRate);
  18368. }
  18369. void AudioSourcePlayer::audioDeviceStopped()
  18370. {
  18371. if (source != 0)
  18372. source->releaseResources();
  18373. sampleRate = 0.0;
  18374. bufferSize = 0;
  18375. tempBuffer.setSize (2, 8);
  18376. }
  18377. END_JUCE_NAMESPACE
  18378. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18379. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18380. BEGIN_JUCE_NAMESPACE
  18381. AudioTransportSource::AudioTransportSource()
  18382. : source (0),
  18383. resamplerSource (0),
  18384. bufferingSource (0),
  18385. positionableSource (0),
  18386. masterSource (0),
  18387. gain (1.0f),
  18388. lastGain (1.0f),
  18389. playing (false),
  18390. stopped (true),
  18391. sampleRate (44100.0),
  18392. sourceSampleRate (0.0),
  18393. blockSize (128),
  18394. readAheadBufferSize (0),
  18395. isPrepared (false),
  18396. inputStreamEOF (false)
  18397. {
  18398. }
  18399. AudioTransportSource::~AudioTransportSource()
  18400. {
  18401. setSource (0);
  18402. releaseResources();
  18403. }
  18404. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18405. int readAheadBufferSize_,
  18406. double sourceSampleRateToCorrectFor)
  18407. {
  18408. if (source == newSource)
  18409. {
  18410. if (source == 0)
  18411. return;
  18412. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18413. }
  18414. readAheadBufferSize = readAheadBufferSize_;
  18415. sourceSampleRate = sourceSampleRateToCorrectFor;
  18416. ResamplingAudioSource* newResamplerSource = 0;
  18417. BufferingAudioSource* newBufferingSource = 0;
  18418. PositionableAudioSource* newPositionableSource = 0;
  18419. AudioSource* newMasterSource = 0;
  18420. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18421. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18422. AudioSource* oldMasterSource = masterSource;
  18423. if (newSource != 0)
  18424. {
  18425. newPositionableSource = newSource;
  18426. if (readAheadBufferSize_ > 0)
  18427. newPositionableSource = newBufferingSource
  18428. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18429. newPositionableSource->setNextReadPosition (0);
  18430. if (sourceSampleRateToCorrectFor != 0)
  18431. newMasterSource = newResamplerSource
  18432. = new ResamplingAudioSource (newPositionableSource, false);
  18433. else
  18434. newMasterSource = newPositionableSource;
  18435. if (isPrepared)
  18436. {
  18437. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18438. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18439. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18440. }
  18441. }
  18442. {
  18443. const ScopedLock sl (callbackLock);
  18444. source = newSource;
  18445. resamplerSource = newResamplerSource;
  18446. bufferingSource = newBufferingSource;
  18447. masterSource = newMasterSource;
  18448. positionableSource = newPositionableSource;
  18449. playing = false;
  18450. }
  18451. if (oldMasterSource != 0)
  18452. oldMasterSource->releaseResources();
  18453. }
  18454. void AudioTransportSource::start()
  18455. {
  18456. if ((! playing) && masterSource != 0)
  18457. {
  18458. {
  18459. const ScopedLock sl (callbackLock);
  18460. playing = true;
  18461. stopped = false;
  18462. inputStreamEOF = false;
  18463. }
  18464. sendChangeMessage (this);
  18465. }
  18466. }
  18467. void AudioTransportSource::stop()
  18468. {
  18469. if (playing)
  18470. {
  18471. {
  18472. const ScopedLock sl (callbackLock);
  18473. playing = false;
  18474. }
  18475. int n = 500;
  18476. while (--n >= 0 && ! stopped)
  18477. Thread::sleep (2);
  18478. sendChangeMessage (this);
  18479. }
  18480. }
  18481. void AudioTransportSource::setPosition (double newPosition)
  18482. {
  18483. if (sampleRate > 0.0)
  18484. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18485. }
  18486. double AudioTransportSource::getCurrentPosition() const
  18487. {
  18488. if (sampleRate > 0.0)
  18489. return getNextReadPosition() / sampleRate;
  18490. else
  18491. return 0.0;
  18492. }
  18493. void AudioTransportSource::setNextReadPosition (int newPosition)
  18494. {
  18495. if (positionableSource != 0)
  18496. {
  18497. if (sampleRate > 0 && sourceSampleRate > 0)
  18498. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18499. positionableSource->setNextReadPosition (newPosition);
  18500. }
  18501. }
  18502. int AudioTransportSource::getNextReadPosition() const
  18503. {
  18504. if (positionableSource != 0)
  18505. {
  18506. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18507. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18508. }
  18509. return 0;
  18510. }
  18511. int AudioTransportSource::getTotalLength() const
  18512. {
  18513. const ScopedLock sl (callbackLock);
  18514. if (positionableSource != 0)
  18515. {
  18516. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18517. return roundToInt (positionableSource->getTotalLength() * ratio);
  18518. }
  18519. return 0;
  18520. }
  18521. bool AudioTransportSource::isLooping() const
  18522. {
  18523. const ScopedLock sl (callbackLock);
  18524. return positionableSource != 0
  18525. && positionableSource->isLooping();
  18526. }
  18527. void AudioTransportSource::setGain (const float newGain) throw()
  18528. {
  18529. gain = newGain;
  18530. }
  18531. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18532. double sampleRate_)
  18533. {
  18534. const ScopedLock sl (callbackLock);
  18535. sampleRate = sampleRate_;
  18536. blockSize = samplesPerBlockExpected;
  18537. if (masterSource != 0)
  18538. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18539. if (resamplerSource != 0 && sourceSampleRate != 0)
  18540. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18541. isPrepared = true;
  18542. }
  18543. void AudioTransportSource::releaseResources()
  18544. {
  18545. const ScopedLock sl (callbackLock);
  18546. if (masterSource != 0)
  18547. masterSource->releaseResources();
  18548. isPrepared = false;
  18549. }
  18550. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18551. {
  18552. const ScopedLock sl (callbackLock);
  18553. inputStreamEOF = false;
  18554. if (masterSource != 0 && ! stopped)
  18555. {
  18556. masterSource->getNextAudioBlock (info);
  18557. if (! playing)
  18558. {
  18559. // just stopped playing, so fade out the last block..
  18560. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18561. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18562. if (info.numSamples > 256)
  18563. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18564. }
  18565. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18566. && ! positionableSource->isLooping())
  18567. {
  18568. playing = false;
  18569. inputStreamEOF = true;
  18570. sendChangeMessage (this);
  18571. }
  18572. stopped = ! playing;
  18573. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18574. {
  18575. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18576. lastGain, gain);
  18577. }
  18578. }
  18579. else
  18580. {
  18581. info.clearActiveBufferRegion();
  18582. stopped = true;
  18583. }
  18584. lastGain = gain;
  18585. }
  18586. END_JUCE_NAMESPACE
  18587. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18588. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18589. BEGIN_JUCE_NAMESPACE
  18590. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18591. public Thread,
  18592. private Timer
  18593. {
  18594. public:
  18595. SharedBufferingAudioSourceThread()
  18596. : Thread ("Audio Buffer")
  18597. {
  18598. }
  18599. ~SharedBufferingAudioSourceThread()
  18600. {
  18601. stopThread (10000);
  18602. clearSingletonInstance();
  18603. }
  18604. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18605. void addSource (BufferingAudioSource* source)
  18606. {
  18607. const ScopedLock sl (lock);
  18608. if (! sources.contains (source))
  18609. {
  18610. sources.add (source);
  18611. startThread();
  18612. stopTimer();
  18613. }
  18614. notify();
  18615. }
  18616. void removeSource (BufferingAudioSource* source)
  18617. {
  18618. const ScopedLock sl (lock);
  18619. sources.removeValue (source);
  18620. if (sources.size() == 0)
  18621. startTimer (5000);
  18622. }
  18623. private:
  18624. Array <BufferingAudioSource*> sources;
  18625. CriticalSection lock;
  18626. void run()
  18627. {
  18628. while (! threadShouldExit())
  18629. {
  18630. bool busy = false;
  18631. for (int i = sources.size(); --i >= 0;)
  18632. {
  18633. if (threadShouldExit())
  18634. return;
  18635. const ScopedLock sl (lock);
  18636. BufferingAudioSource* const b = sources[i];
  18637. if (b != 0 && b->readNextBufferChunk())
  18638. busy = true;
  18639. }
  18640. if (! busy)
  18641. wait (500);
  18642. }
  18643. }
  18644. void timerCallback()
  18645. {
  18646. stopTimer();
  18647. if (sources.size() == 0)
  18648. deleteInstance();
  18649. }
  18650. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18651. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18652. };
  18653. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18654. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18655. const bool deleteSourceWhenDeleted_,
  18656. int numberOfSamplesToBuffer_)
  18657. : source (source_),
  18658. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18659. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18660. buffer (2, 0),
  18661. bufferValidStart (0),
  18662. bufferValidEnd (0),
  18663. nextPlayPos (0),
  18664. wasSourceLooping (false)
  18665. {
  18666. jassert (source_ != 0);
  18667. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18668. // not using a larger buffer..
  18669. }
  18670. BufferingAudioSource::~BufferingAudioSource()
  18671. {
  18672. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18673. if (thread != 0)
  18674. thread->removeSource (this);
  18675. if (deleteSourceWhenDeleted)
  18676. delete source;
  18677. }
  18678. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18679. {
  18680. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18681. sampleRate = sampleRate_;
  18682. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18683. buffer.clear();
  18684. bufferValidStart = 0;
  18685. bufferValidEnd = 0;
  18686. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18687. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18688. buffer.getNumSamples() / 2))
  18689. {
  18690. SharedBufferingAudioSourceThread::getInstance()->notify();
  18691. Thread::sleep (5);
  18692. }
  18693. }
  18694. void BufferingAudioSource::releaseResources()
  18695. {
  18696. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18697. if (thread != 0)
  18698. thread->removeSource (this);
  18699. buffer.setSize (2, 0);
  18700. source->releaseResources();
  18701. }
  18702. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18703. {
  18704. const ScopedLock sl (bufferStartPosLock);
  18705. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18706. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18707. if (validStart == validEnd)
  18708. {
  18709. // total cache miss
  18710. info.clearActiveBufferRegion();
  18711. }
  18712. else
  18713. {
  18714. if (validStart > 0)
  18715. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18716. if (validEnd < info.numSamples)
  18717. info.buffer->clear (info.startSample + validEnd,
  18718. info.numSamples - validEnd); // partial cache miss at end
  18719. if (validStart < validEnd)
  18720. {
  18721. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18722. {
  18723. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18724. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18725. if (startBufferIndex < endBufferIndex)
  18726. {
  18727. info.buffer->copyFrom (chan, info.startSample + validStart,
  18728. buffer,
  18729. chan, startBufferIndex,
  18730. validEnd - validStart);
  18731. }
  18732. else
  18733. {
  18734. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18735. info.buffer->copyFrom (chan, info.startSample + validStart,
  18736. buffer,
  18737. chan, startBufferIndex,
  18738. initialSize);
  18739. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18740. buffer,
  18741. chan, 0,
  18742. (validEnd - validStart) - initialSize);
  18743. }
  18744. }
  18745. }
  18746. nextPlayPos += info.numSamples;
  18747. if (source->isLooping() && nextPlayPos > 0)
  18748. nextPlayPos %= source->getTotalLength();
  18749. }
  18750. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18751. if (thread != 0)
  18752. thread->notify();
  18753. }
  18754. int BufferingAudioSource::getNextReadPosition() const
  18755. {
  18756. return (source->isLooping() && nextPlayPos > 0)
  18757. ? nextPlayPos % source->getTotalLength()
  18758. : nextPlayPos;
  18759. }
  18760. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18761. {
  18762. const ScopedLock sl (bufferStartPosLock);
  18763. nextPlayPos = newPosition;
  18764. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18765. if (thread != 0)
  18766. thread->notify();
  18767. }
  18768. bool BufferingAudioSource::readNextBufferChunk()
  18769. {
  18770. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18771. {
  18772. const ScopedLock sl (bufferStartPosLock);
  18773. if (wasSourceLooping != isLooping())
  18774. {
  18775. wasSourceLooping = isLooping();
  18776. bufferValidStart = 0;
  18777. bufferValidEnd = 0;
  18778. }
  18779. newBVS = jmax (0, nextPlayPos);
  18780. newBVE = newBVS + buffer.getNumSamples() - 4;
  18781. sectionToReadStart = 0;
  18782. sectionToReadEnd = 0;
  18783. const int maxChunkSize = 2048;
  18784. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18785. {
  18786. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18787. sectionToReadStart = newBVS;
  18788. sectionToReadEnd = newBVE;
  18789. bufferValidStart = 0;
  18790. bufferValidEnd = 0;
  18791. }
  18792. else if (abs (newBVS - bufferValidStart) > 512
  18793. || abs (newBVE - bufferValidEnd) > 512)
  18794. {
  18795. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18796. sectionToReadStart = bufferValidEnd;
  18797. sectionToReadEnd = newBVE;
  18798. bufferValidStart = newBVS;
  18799. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18800. }
  18801. }
  18802. if (sectionToReadStart != sectionToReadEnd)
  18803. {
  18804. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18805. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18806. if (bufferIndexStart < bufferIndexEnd)
  18807. {
  18808. readBufferSection (sectionToReadStart,
  18809. sectionToReadEnd - sectionToReadStart,
  18810. bufferIndexStart);
  18811. }
  18812. else
  18813. {
  18814. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18815. readBufferSection (sectionToReadStart,
  18816. initialSize,
  18817. bufferIndexStart);
  18818. readBufferSection (sectionToReadStart + initialSize,
  18819. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18820. 0);
  18821. }
  18822. const ScopedLock sl2 (bufferStartPosLock);
  18823. bufferValidStart = newBVS;
  18824. bufferValidEnd = newBVE;
  18825. return true;
  18826. }
  18827. else
  18828. {
  18829. return false;
  18830. }
  18831. }
  18832. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18833. {
  18834. if (source->getNextReadPosition() != start)
  18835. source->setNextReadPosition (start);
  18836. AudioSourceChannelInfo info;
  18837. info.buffer = &buffer;
  18838. info.startSample = bufferOffset;
  18839. info.numSamples = length;
  18840. source->getNextAudioBlock (info);
  18841. }
  18842. END_JUCE_NAMESPACE
  18843. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18844. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18845. BEGIN_JUCE_NAMESPACE
  18846. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18847. const bool deleteSourceWhenDeleted_)
  18848. : requiredNumberOfChannels (2),
  18849. source (source_),
  18850. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18851. buffer (2, 16)
  18852. {
  18853. remappedInfo.buffer = &buffer;
  18854. remappedInfo.startSample = 0;
  18855. }
  18856. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18857. {
  18858. if (deleteSourceWhenDeleted)
  18859. delete source;
  18860. }
  18861. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18862. {
  18863. const ScopedLock sl (lock);
  18864. requiredNumberOfChannels = requiredNumberOfChannels_;
  18865. }
  18866. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18867. {
  18868. const ScopedLock sl (lock);
  18869. remappedInputs.clear();
  18870. remappedOutputs.clear();
  18871. }
  18872. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18873. {
  18874. const ScopedLock sl (lock);
  18875. while (remappedInputs.size() < destIndex)
  18876. remappedInputs.add (-1);
  18877. remappedInputs.set (destIndex, sourceIndex);
  18878. }
  18879. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18880. {
  18881. const ScopedLock sl (lock);
  18882. while (remappedOutputs.size() < sourceIndex)
  18883. remappedOutputs.add (-1);
  18884. remappedOutputs.set (sourceIndex, destIndex);
  18885. }
  18886. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18887. {
  18888. const ScopedLock sl (lock);
  18889. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18890. return remappedInputs.getUnchecked (inputChannelIndex);
  18891. return -1;
  18892. }
  18893. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18894. {
  18895. const ScopedLock sl (lock);
  18896. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18897. return remappedOutputs .getUnchecked (outputChannelIndex);
  18898. return -1;
  18899. }
  18900. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18901. {
  18902. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18903. }
  18904. void ChannelRemappingAudioSource::releaseResources()
  18905. {
  18906. source->releaseResources();
  18907. }
  18908. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18909. {
  18910. const ScopedLock sl (lock);
  18911. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18912. const int numChans = bufferToFill.buffer->getNumChannels();
  18913. int i;
  18914. for (i = 0; i < buffer.getNumChannels(); ++i)
  18915. {
  18916. const int remappedChan = getRemappedInputChannel (i);
  18917. if (remappedChan >= 0 && remappedChan < numChans)
  18918. {
  18919. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18920. remappedChan,
  18921. bufferToFill.startSample,
  18922. bufferToFill.numSamples);
  18923. }
  18924. else
  18925. {
  18926. buffer.clear (i, 0, bufferToFill.numSamples);
  18927. }
  18928. }
  18929. remappedInfo.numSamples = bufferToFill.numSamples;
  18930. source->getNextAudioBlock (remappedInfo);
  18931. bufferToFill.clearActiveBufferRegion();
  18932. for (i = 0; i < requiredNumberOfChannels; ++i)
  18933. {
  18934. const int remappedChan = getRemappedOutputChannel (i);
  18935. if (remappedChan >= 0 && remappedChan < numChans)
  18936. {
  18937. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18938. buffer, i, 0, bufferToFill.numSamples);
  18939. }
  18940. }
  18941. }
  18942. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18943. {
  18944. XmlElement* e = new XmlElement ("MAPPINGS");
  18945. String ins, outs;
  18946. int i;
  18947. const ScopedLock sl (lock);
  18948. for (i = 0; i < remappedInputs.size(); ++i)
  18949. ins << remappedInputs.getUnchecked(i) << ' ';
  18950. for (i = 0; i < remappedOutputs.size(); ++i)
  18951. outs << remappedOutputs.getUnchecked(i) << ' ';
  18952. e->setAttribute ("inputs", ins.trimEnd());
  18953. e->setAttribute ("outputs", outs.trimEnd());
  18954. return e;
  18955. }
  18956. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18957. {
  18958. if (e.hasTagName ("MAPPINGS"))
  18959. {
  18960. const ScopedLock sl (lock);
  18961. clearAllMappings();
  18962. StringArray ins, outs;
  18963. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18964. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18965. int i;
  18966. for (i = 0; i < ins.size(); ++i)
  18967. remappedInputs.add (ins[i].getIntValue());
  18968. for (i = 0; i < outs.size(); ++i)
  18969. remappedOutputs.add (outs[i].getIntValue());
  18970. }
  18971. }
  18972. END_JUCE_NAMESPACE
  18973. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18974. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18975. BEGIN_JUCE_NAMESPACE
  18976. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18977. const bool deleteInputWhenDeleted_)
  18978. : input (inputSource),
  18979. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18980. {
  18981. jassert (inputSource != 0);
  18982. for (int i = 2; --i >= 0;)
  18983. iirFilters.add (new IIRFilter());
  18984. }
  18985. IIRFilterAudioSource::~IIRFilterAudioSource()
  18986. {
  18987. if (deleteInputWhenDeleted)
  18988. delete input;
  18989. }
  18990. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18991. {
  18992. for (int i = iirFilters.size(); --i >= 0;)
  18993. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18994. }
  18995. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18996. {
  18997. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18998. for (int i = iirFilters.size(); --i >= 0;)
  18999. iirFilters.getUnchecked(i)->reset();
  19000. }
  19001. void IIRFilterAudioSource::releaseResources()
  19002. {
  19003. input->releaseResources();
  19004. }
  19005. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19006. {
  19007. input->getNextAudioBlock (bufferToFill);
  19008. const int numChannels = bufferToFill.buffer->getNumChannels();
  19009. while (numChannels > iirFilters.size())
  19010. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19011. for (int i = 0; i < numChannels; ++i)
  19012. iirFilters.getUnchecked(i)
  19013. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19014. bufferToFill.numSamples);
  19015. }
  19016. END_JUCE_NAMESPACE
  19017. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19018. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19019. BEGIN_JUCE_NAMESPACE
  19020. MixerAudioSource::MixerAudioSource()
  19021. : tempBuffer (2, 0),
  19022. currentSampleRate (0.0),
  19023. bufferSizeExpected (0)
  19024. {
  19025. }
  19026. MixerAudioSource::~MixerAudioSource()
  19027. {
  19028. removeAllInputs();
  19029. }
  19030. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19031. {
  19032. if (input != 0 && ! inputs.contains (input))
  19033. {
  19034. double localRate;
  19035. int localBufferSize;
  19036. {
  19037. const ScopedLock sl (lock);
  19038. localRate = currentSampleRate;
  19039. localBufferSize = bufferSizeExpected;
  19040. }
  19041. if (localRate != 0.0)
  19042. input->prepareToPlay (localBufferSize, localRate);
  19043. const ScopedLock sl (lock);
  19044. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19045. inputs.add (input);
  19046. }
  19047. }
  19048. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19049. {
  19050. if (input != 0)
  19051. {
  19052. int index;
  19053. {
  19054. const ScopedLock sl (lock);
  19055. index = inputs.indexOf (input);
  19056. if (index >= 0)
  19057. {
  19058. inputsToDelete.shiftBits (index, 1);
  19059. inputs.remove (index);
  19060. }
  19061. }
  19062. if (index >= 0)
  19063. {
  19064. input->releaseResources();
  19065. if (deleteInput)
  19066. delete input;
  19067. }
  19068. }
  19069. }
  19070. void MixerAudioSource::removeAllInputs()
  19071. {
  19072. OwnedArray<AudioSource> toDelete;
  19073. {
  19074. const ScopedLock sl (lock);
  19075. for (int i = inputs.size(); --i >= 0;)
  19076. if (inputsToDelete[i])
  19077. toDelete.add (inputs.getUnchecked(i));
  19078. }
  19079. }
  19080. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19081. {
  19082. tempBuffer.setSize (2, samplesPerBlockExpected);
  19083. const ScopedLock sl (lock);
  19084. currentSampleRate = sampleRate;
  19085. bufferSizeExpected = samplesPerBlockExpected;
  19086. for (int i = inputs.size(); --i >= 0;)
  19087. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19088. }
  19089. void MixerAudioSource::releaseResources()
  19090. {
  19091. const ScopedLock sl (lock);
  19092. for (int i = inputs.size(); --i >= 0;)
  19093. inputs.getUnchecked(i)->releaseResources();
  19094. tempBuffer.setSize (2, 0);
  19095. currentSampleRate = 0;
  19096. bufferSizeExpected = 0;
  19097. }
  19098. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19099. {
  19100. const ScopedLock sl (lock);
  19101. if (inputs.size() > 0)
  19102. {
  19103. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19104. if (inputs.size() > 1)
  19105. {
  19106. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19107. info.buffer->getNumSamples());
  19108. AudioSourceChannelInfo info2;
  19109. info2.buffer = &tempBuffer;
  19110. info2.numSamples = info.numSamples;
  19111. info2.startSample = 0;
  19112. for (int i = 1; i < inputs.size(); ++i)
  19113. {
  19114. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19115. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19116. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19117. }
  19118. }
  19119. }
  19120. else
  19121. {
  19122. info.clearActiveBufferRegion();
  19123. }
  19124. }
  19125. END_JUCE_NAMESPACE
  19126. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19127. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19128. BEGIN_JUCE_NAMESPACE
  19129. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19130. const bool deleteInputWhenDeleted_,
  19131. const int numChannels_)
  19132. : input (inputSource),
  19133. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19134. ratio (1.0),
  19135. lastRatio (1.0),
  19136. buffer (numChannels_, 0),
  19137. sampsInBuffer (0),
  19138. numChannels (numChannels_)
  19139. {
  19140. jassert (input != 0);
  19141. }
  19142. ResamplingAudioSource::~ResamplingAudioSource()
  19143. {
  19144. if (deleteInputWhenDeleted)
  19145. delete input;
  19146. }
  19147. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19148. {
  19149. jassert (samplesInPerOutputSample > 0);
  19150. const ScopedLock sl (ratioLock);
  19151. ratio = jmax (0.0, samplesInPerOutputSample);
  19152. }
  19153. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19154. double sampleRate)
  19155. {
  19156. const ScopedLock sl (ratioLock);
  19157. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19158. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19159. buffer.clear();
  19160. sampsInBuffer = 0;
  19161. bufferPos = 0;
  19162. subSampleOffset = 0.0;
  19163. filterStates.calloc (numChannels);
  19164. srcBuffers.calloc (numChannels);
  19165. destBuffers.calloc (numChannels);
  19166. createLowPass (ratio);
  19167. resetFilters();
  19168. }
  19169. void ResamplingAudioSource::releaseResources()
  19170. {
  19171. input->releaseResources();
  19172. buffer.setSize (numChannels, 0);
  19173. }
  19174. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19175. {
  19176. const ScopedLock sl (ratioLock);
  19177. if (lastRatio != ratio)
  19178. {
  19179. createLowPass (ratio);
  19180. lastRatio = ratio;
  19181. }
  19182. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19183. int bufferSize = buffer.getNumSamples();
  19184. if (bufferSize < sampsNeeded + 8)
  19185. {
  19186. bufferPos %= bufferSize;
  19187. bufferSize = sampsNeeded + 32;
  19188. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19189. }
  19190. bufferPos %= bufferSize;
  19191. int endOfBufferPos = bufferPos + sampsInBuffer;
  19192. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19193. while (sampsNeeded > sampsInBuffer)
  19194. {
  19195. endOfBufferPos %= bufferSize;
  19196. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19197. bufferSize - endOfBufferPos);
  19198. AudioSourceChannelInfo readInfo;
  19199. readInfo.buffer = &buffer;
  19200. readInfo.numSamples = numToDo;
  19201. readInfo.startSample = endOfBufferPos;
  19202. input->getNextAudioBlock (readInfo);
  19203. if (ratio > 1.0001)
  19204. {
  19205. // for down-sampling, pre-apply the filter..
  19206. for (int i = channelsToProcess; --i >= 0;)
  19207. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19208. }
  19209. sampsInBuffer += numToDo;
  19210. endOfBufferPos += numToDo;
  19211. }
  19212. for (int channel = 0; channel < channelsToProcess; ++channel)
  19213. {
  19214. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19215. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19216. }
  19217. int nextPos = (bufferPos + 1) % bufferSize;
  19218. for (int m = info.numSamples; --m >= 0;)
  19219. {
  19220. const float alpha = (float) subSampleOffset;
  19221. const float invAlpha = 1.0f - alpha;
  19222. for (int channel = 0; channel < channelsToProcess; ++channel)
  19223. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19224. subSampleOffset += ratio;
  19225. jassert (sampsInBuffer > 0);
  19226. while (subSampleOffset >= 1.0)
  19227. {
  19228. if (++bufferPos >= bufferSize)
  19229. bufferPos = 0;
  19230. --sampsInBuffer;
  19231. nextPos = (bufferPos + 1) % bufferSize;
  19232. subSampleOffset -= 1.0;
  19233. }
  19234. }
  19235. if (ratio < 0.9999)
  19236. {
  19237. // for up-sampling, apply the filter after transposing..
  19238. for (int i = channelsToProcess; --i >= 0;)
  19239. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19240. }
  19241. else if (ratio <= 1.0001)
  19242. {
  19243. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19244. for (int i = channelsToProcess; --i >= 0;)
  19245. {
  19246. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19247. FilterState& fs = filterStates[i];
  19248. if (info.numSamples > 1)
  19249. {
  19250. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19251. }
  19252. else
  19253. {
  19254. fs.y2 = fs.y1;
  19255. fs.x2 = fs.x1;
  19256. }
  19257. fs.y1 = fs.x1 = *endOfBuffer;
  19258. }
  19259. }
  19260. jassert (sampsInBuffer >= 0);
  19261. }
  19262. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19263. {
  19264. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19265. : 0.5 * frequencyRatio;
  19266. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19267. const double nSquared = n * n;
  19268. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19269. setFilterCoefficients (c1,
  19270. c1 * 2.0f,
  19271. c1,
  19272. 1.0,
  19273. c1 * 2.0 * (1.0 - nSquared),
  19274. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19275. }
  19276. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19277. {
  19278. const double a = 1.0 / c4;
  19279. c1 *= a;
  19280. c2 *= a;
  19281. c3 *= a;
  19282. c5 *= a;
  19283. c6 *= a;
  19284. coefficients[0] = c1;
  19285. coefficients[1] = c2;
  19286. coefficients[2] = c3;
  19287. coefficients[3] = c4;
  19288. coefficients[4] = c5;
  19289. coefficients[5] = c6;
  19290. }
  19291. void ResamplingAudioSource::resetFilters()
  19292. {
  19293. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19294. }
  19295. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19296. {
  19297. while (--num >= 0)
  19298. {
  19299. const double in = *samples;
  19300. double out = coefficients[0] * in
  19301. + coefficients[1] * fs.x1
  19302. + coefficients[2] * fs.x2
  19303. - coefficients[4] * fs.y1
  19304. - coefficients[5] * fs.y2;
  19305. #if JUCE_INTEL
  19306. if (! (out < -1.0e-8 || out > 1.0e-8))
  19307. out = 0;
  19308. #endif
  19309. fs.x2 = fs.x1;
  19310. fs.x1 = in;
  19311. fs.y2 = fs.y1;
  19312. fs.y1 = out;
  19313. *samples++ = (float) out;
  19314. }
  19315. }
  19316. END_JUCE_NAMESPACE
  19317. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19318. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19319. BEGIN_JUCE_NAMESPACE
  19320. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19321. : frequency (1000.0),
  19322. sampleRate (44100.0),
  19323. currentPhase (0.0),
  19324. phasePerSample (0.0),
  19325. amplitude (0.5f)
  19326. {
  19327. }
  19328. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19329. {
  19330. }
  19331. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19332. {
  19333. amplitude = newAmplitude;
  19334. }
  19335. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19336. {
  19337. frequency = newFrequencyHz;
  19338. phasePerSample = 0.0;
  19339. }
  19340. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19341. double sampleRate_)
  19342. {
  19343. currentPhase = 0.0;
  19344. phasePerSample = 0.0;
  19345. sampleRate = sampleRate_;
  19346. }
  19347. void ToneGeneratorAudioSource::releaseResources()
  19348. {
  19349. }
  19350. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19351. {
  19352. if (phasePerSample == 0.0)
  19353. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19354. for (int i = 0; i < info.numSamples; ++i)
  19355. {
  19356. const float sample = amplitude * (float) std::sin (currentPhase);
  19357. currentPhase += phasePerSample;
  19358. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19359. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19360. }
  19361. }
  19362. END_JUCE_NAMESPACE
  19363. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19364. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19365. BEGIN_JUCE_NAMESPACE
  19366. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19367. : sampleRate (0),
  19368. bufferSize (0),
  19369. useDefaultInputChannels (true),
  19370. useDefaultOutputChannels (true)
  19371. {
  19372. }
  19373. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19374. {
  19375. return outputDeviceName == other.outputDeviceName
  19376. && inputDeviceName == other.inputDeviceName
  19377. && sampleRate == other.sampleRate
  19378. && bufferSize == other.bufferSize
  19379. && inputChannels == other.inputChannels
  19380. && useDefaultInputChannels == other.useDefaultInputChannels
  19381. && outputChannels == other.outputChannels
  19382. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19383. }
  19384. AudioDeviceManager::AudioDeviceManager()
  19385. : currentAudioDevice (0),
  19386. numInputChansNeeded (0),
  19387. numOutputChansNeeded (2),
  19388. listNeedsScanning (true),
  19389. useInputNames (false),
  19390. inputLevelMeasurementEnabledCount (0),
  19391. inputLevel (0),
  19392. tempBuffer (2, 2),
  19393. defaultMidiOutput (0),
  19394. cpuUsageMs (0),
  19395. timeToCpuScale (0)
  19396. {
  19397. callbackHandler.owner = this;
  19398. }
  19399. AudioDeviceManager::~AudioDeviceManager()
  19400. {
  19401. currentAudioDevice = 0;
  19402. defaultMidiOutput = 0;
  19403. }
  19404. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19405. {
  19406. if (availableDeviceTypes.size() == 0)
  19407. {
  19408. createAudioDeviceTypes (availableDeviceTypes);
  19409. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19410. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19411. if (availableDeviceTypes.size() > 0)
  19412. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19413. }
  19414. }
  19415. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19416. {
  19417. scanDevicesIfNeeded();
  19418. return availableDeviceTypes;
  19419. }
  19420. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19421. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19422. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19423. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19424. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19425. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19426. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19427. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19428. {
  19429. (void) list; // (to avoid 'unused param' warnings)
  19430. #if JUCE_WINDOWS
  19431. #if JUCE_WASAPI
  19432. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19433. list.add (juce_createAudioIODeviceType_WASAPI());
  19434. #endif
  19435. #if JUCE_DIRECTSOUND
  19436. list.add (juce_createAudioIODeviceType_DirectSound());
  19437. #endif
  19438. #if JUCE_ASIO
  19439. list.add (juce_createAudioIODeviceType_ASIO());
  19440. #endif
  19441. #endif
  19442. #if JUCE_MAC
  19443. list.add (juce_createAudioIODeviceType_CoreAudio());
  19444. #endif
  19445. #if JUCE_IOS
  19446. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19447. #endif
  19448. #if JUCE_LINUX && JUCE_ALSA
  19449. list.add (juce_createAudioIODeviceType_ALSA());
  19450. #endif
  19451. #if JUCE_LINUX && JUCE_JACK
  19452. list.add (juce_createAudioIODeviceType_JACK());
  19453. #endif
  19454. }
  19455. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19456. const int numOutputChannelsNeeded,
  19457. const XmlElement* const e,
  19458. const bool selectDefaultDeviceOnFailure,
  19459. const String& preferredDefaultDeviceName,
  19460. const AudioDeviceSetup* preferredSetupOptions)
  19461. {
  19462. scanDevicesIfNeeded();
  19463. numInputChansNeeded = numInputChannelsNeeded;
  19464. numOutputChansNeeded = numOutputChannelsNeeded;
  19465. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19466. {
  19467. lastExplicitSettings = new XmlElement (*e);
  19468. String error;
  19469. AudioDeviceSetup setup;
  19470. if (preferredSetupOptions != 0)
  19471. setup = *preferredSetupOptions;
  19472. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19473. {
  19474. setup.inputDeviceName = setup.outputDeviceName
  19475. = e->getStringAttribute ("audioDeviceName");
  19476. }
  19477. else
  19478. {
  19479. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19480. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19481. }
  19482. currentDeviceType = e->getStringAttribute ("deviceType");
  19483. if (currentDeviceType.isEmpty())
  19484. {
  19485. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19486. if (type != 0)
  19487. currentDeviceType = type->getTypeName();
  19488. else if (availableDeviceTypes.size() > 0)
  19489. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19490. }
  19491. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19492. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19493. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19494. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19495. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19496. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19497. error = setAudioDeviceSetup (setup, true);
  19498. midiInsFromXml.clear();
  19499. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19500. midiInsFromXml.add (c->getStringAttribute ("name"));
  19501. const StringArray allMidiIns (MidiInput::getDevices());
  19502. for (int i = allMidiIns.size(); --i >= 0;)
  19503. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19504. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19505. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19506. false, preferredDefaultDeviceName);
  19507. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19508. return error;
  19509. }
  19510. else
  19511. {
  19512. AudioDeviceSetup setup;
  19513. if (preferredSetupOptions != 0)
  19514. {
  19515. setup = *preferredSetupOptions;
  19516. }
  19517. else if (preferredDefaultDeviceName.isNotEmpty())
  19518. {
  19519. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19520. {
  19521. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19522. StringArray outs (type->getDeviceNames (false));
  19523. int i;
  19524. for (i = 0; i < outs.size(); ++i)
  19525. {
  19526. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19527. {
  19528. setup.outputDeviceName = outs[i];
  19529. break;
  19530. }
  19531. }
  19532. StringArray ins (type->getDeviceNames (true));
  19533. for (i = 0; i < ins.size(); ++i)
  19534. {
  19535. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19536. {
  19537. setup.inputDeviceName = ins[i];
  19538. break;
  19539. }
  19540. }
  19541. }
  19542. }
  19543. insertDefaultDeviceNames (setup);
  19544. return setAudioDeviceSetup (setup, false);
  19545. }
  19546. }
  19547. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19548. {
  19549. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19550. if (type != 0)
  19551. {
  19552. if (setup.outputDeviceName.isEmpty())
  19553. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19554. if (setup.inputDeviceName.isEmpty())
  19555. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19556. }
  19557. }
  19558. XmlElement* AudioDeviceManager::createStateXml() const
  19559. {
  19560. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19561. }
  19562. void AudioDeviceManager::scanDevicesIfNeeded()
  19563. {
  19564. if (listNeedsScanning)
  19565. {
  19566. listNeedsScanning = false;
  19567. createDeviceTypesIfNeeded();
  19568. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19569. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19570. }
  19571. }
  19572. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19573. {
  19574. scanDevicesIfNeeded();
  19575. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19576. {
  19577. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19578. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19579. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19580. {
  19581. return type;
  19582. }
  19583. }
  19584. return 0;
  19585. }
  19586. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19587. {
  19588. setup = currentSetup;
  19589. }
  19590. void AudioDeviceManager::deleteCurrentDevice()
  19591. {
  19592. currentAudioDevice = 0;
  19593. currentSetup.inputDeviceName = String::empty;
  19594. currentSetup.outputDeviceName = String::empty;
  19595. }
  19596. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19597. const bool treatAsChosenDevice)
  19598. {
  19599. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19600. {
  19601. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19602. && currentDeviceType != type)
  19603. {
  19604. currentDeviceType = type;
  19605. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19606. insertDefaultDeviceNames (s);
  19607. setAudioDeviceSetup (s, treatAsChosenDevice);
  19608. sendChangeMessage (this);
  19609. break;
  19610. }
  19611. }
  19612. }
  19613. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19614. {
  19615. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19616. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19617. return availableDeviceTypes[i];
  19618. return availableDeviceTypes[0];
  19619. }
  19620. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19621. const bool treatAsChosenDevice)
  19622. {
  19623. jassert (&newSetup != &currentSetup); // this will have no effect
  19624. if (newSetup == currentSetup && currentAudioDevice != 0)
  19625. return String::empty;
  19626. if (! (newSetup == currentSetup))
  19627. sendChangeMessage (this);
  19628. stopDevice();
  19629. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19630. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19631. String error;
  19632. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19633. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19634. {
  19635. deleteCurrentDevice();
  19636. if (treatAsChosenDevice)
  19637. updateXml();
  19638. return String::empty;
  19639. }
  19640. if (currentSetup.inputDeviceName != newInputDeviceName
  19641. || currentSetup.outputDeviceName != newOutputDeviceName
  19642. || currentAudioDevice == 0)
  19643. {
  19644. deleteCurrentDevice();
  19645. scanDevicesIfNeeded();
  19646. if (newOutputDeviceName.isNotEmpty()
  19647. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19648. {
  19649. return "No such device: " + newOutputDeviceName;
  19650. }
  19651. if (newInputDeviceName.isNotEmpty()
  19652. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19653. {
  19654. return "No such device: " + newInputDeviceName;
  19655. }
  19656. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19657. if (currentAudioDevice == 0)
  19658. 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!";
  19659. else
  19660. error = currentAudioDevice->getLastError();
  19661. if (error.isNotEmpty())
  19662. {
  19663. deleteCurrentDevice();
  19664. return error;
  19665. }
  19666. if (newSetup.useDefaultInputChannels)
  19667. {
  19668. inputChannels.clear();
  19669. inputChannels.setRange (0, numInputChansNeeded, true);
  19670. }
  19671. if (newSetup.useDefaultOutputChannels)
  19672. {
  19673. outputChannels.clear();
  19674. outputChannels.setRange (0, numOutputChansNeeded, true);
  19675. }
  19676. if (newInputDeviceName.isEmpty())
  19677. inputChannels.clear();
  19678. if (newOutputDeviceName.isEmpty())
  19679. outputChannels.clear();
  19680. }
  19681. if (! newSetup.useDefaultInputChannels)
  19682. inputChannels = newSetup.inputChannels;
  19683. if (! newSetup.useDefaultOutputChannels)
  19684. outputChannels = newSetup.outputChannels;
  19685. currentSetup = newSetup;
  19686. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19687. error = currentAudioDevice->open (inputChannels,
  19688. outputChannels,
  19689. currentSetup.sampleRate,
  19690. currentSetup.bufferSize);
  19691. if (error.isEmpty())
  19692. {
  19693. currentDeviceType = currentAudioDevice->getTypeName();
  19694. currentAudioDevice->start (&callbackHandler);
  19695. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19696. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19697. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19698. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19699. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19700. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19701. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19702. if (treatAsChosenDevice)
  19703. updateXml();
  19704. }
  19705. else
  19706. {
  19707. deleteCurrentDevice();
  19708. }
  19709. return error;
  19710. }
  19711. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19712. {
  19713. jassert (currentAudioDevice != 0);
  19714. if (rate > 0)
  19715. {
  19716. bool ok = false;
  19717. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19718. {
  19719. const double sr = currentAudioDevice->getSampleRate (i);
  19720. if (sr == rate)
  19721. ok = true;
  19722. }
  19723. if (! ok)
  19724. rate = 0;
  19725. }
  19726. if (rate == 0)
  19727. {
  19728. double lowestAbove44 = 0.0;
  19729. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19730. {
  19731. const double sr = currentAudioDevice->getSampleRate (i);
  19732. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19733. lowestAbove44 = sr;
  19734. }
  19735. if (lowestAbove44 == 0.0)
  19736. rate = currentAudioDevice->getSampleRate (0);
  19737. else
  19738. rate = lowestAbove44;
  19739. }
  19740. return rate;
  19741. }
  19742. void AudioDeviceManager::stopDevice()
  19743. {
  19744. if (currentAudioDevice != 0)
  19745. currentAudioDevice->stop();
  19746. testSound = 0;
  19747. }
  19748. void AudioDeviceManager::closeAudioDevice()
  19749. {
  19750. stopDevice();
  19751. currentAudioDevice = 0;
  19752. }
  19753. void AudioDeviceManager::restartLastAudioDevice()
  19754. {
  19755. if (currentAudioDevice == 0)
  19756. {
  19757. if (currentSetup.inputDeviceName.isEmpty()
  19758. && currentSetup.outputDeviceName.isEmpty())
  19759. {
  19760. // This method will only reload the last device that was running
  19761. // before closeAudioDevice() was called - you need to actually open
  19762. // one first, with setAudioDevice().
  19763. jassertfalse;
  19764. return;
  19765. }
  19766. AudioDeviceSetup s (currentSetup);
  19767. setAudioDeviceSetup (s, false);
  19768. }
  19769. }
  19770. void AudioDeviceManager::updateXml()
  19771. {
  19772. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19773. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19774. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19775. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19776. if (currentAudioDevice != 0)
  19777. {
  19778. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19779. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19780. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19781. if (! currentSetup.useDefaultInputChannels)
  19782. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19783. if (! currentSetup.useDefaultOutputChannels)
  19784. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19785. }
  19786. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19787. {
  19788. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19789. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19790. }
  19791. if (midiInsFromXml.size() > 0)
  19792. {
  19793. // Add any midi devices that have been enabled before, but which aren't currently
  19794. // open because the device has been disconnected.
  19795. const StringArray availableMidiDevices (MidiInput::getDevices());
  19796. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19797. {
  19798. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19799. {
  19800. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19801. m->setAttribute ("name", midiInsFromXml[i]);
  19802. }
  19803. }
  19804. }
  19805. if (defaultMidiOutputName.isNotEmpty())
  19806. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19807. }
  19808. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19809. {
  19810. {
  19811. const ScopedLock sl (audioCallbackLock);
  19812. if (callbacks.contains (newCallback))
  19813. return;
  19814. }
  19815. if (currentAudioDevice != 0 && newCallback != 0)
  19816. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19817. const ScopedLock sl (audioCallbackLock);
  19818. callbacks.add (newCallback);
  19819. }
  19820. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19821. {
  19822. if (callback != 0)
  19823. {
  19824. bool needsDeinitialising = currentAudioDevice != 0;
  19825. {
  19826. const ScopedLock sl (audioCallbackLock);
  19827. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19828. callbacks.removeValue (callback);
  19829. }
  19830. if (needsDeinitialising)
  19831. callback->audioDeviceStopped();
  19832. }
  19833. }
  19834. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19835. int numInputChannels,
  19836. float** outputChannelData,
  19837. int numOutputChannels,
  19838. int numSamples)
  19839. {
  19840. const ScopedLock sl (audioCallbackLock);
  19841. if (inputLevelMeasurementEnabledCount > 0)
  19842. {
  19843. for (int j = 0; j < numSamples; ++j)
  19844. {
  19845. float s = 0;
  19846. for (int i = 0; i < numInputChannels; ++i)
  19847. s += std::abs (inputChannelData[i][j]);
  19848. s /= numInputChannels;
  19849. const double decayFactor = 0.99992;
  19850. if (s > inputLevel)
  19851. inputLevel = s;
  19852. else if (inputLevel > 0.001f)
  19853. inputLevel *= decayFactor;
  19854. else
  19855. inputLevel = 0;
  19856. }
  19857. }
  19858. if (callbacks.size() > 0)
  19859. {
  19860. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19861. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19862. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19863. outputChannelData, numOutputChannels, numSamples);
  19864. float** const tempChans = tempBuffer.getArrayOfChannels();
  19865. for (int i = callbacks.size(); --i > 0;)
  19866. {
  19867. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19868. tempChans, numOutputChannels, numSamples);
  19869. for (int chan = 0; chan < numOutputChannels; ++chan)
  19870. {
  19871. const float* const src = tempChans [chan];
  19872. float* const dst = outputChannelData [chan];
  19873. if (src != 0 && dst != 0)
  19874. for (int j = 0; j < numSamples; ++j)
  19875. dst[j] += src[j];
  19876. }
  19877. }
  19878. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19879. const double filterAmount = 0.2;
  19880. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19881. }
  19882. else
  19883. {
  19884. for (int i = 0; i < numOutputChannels; ++i)
  19885. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19886. }
  19887. if (testSound != 0)
  19888. {
  19889. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19890. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19891. for (int i = 0; i < numOutputChannels; ++i)
  19892. for (int j = 0; j < numSamps; ++j)
  19893. outputChannelData [i][j] += src[j];
  19894. testSoundPosition += numSamps;
  19895. if (testSoundPosition >= testSound->getNumSamples())
  19896. testSound = 0;
  19897. }
  19898. }
  19899. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19900. {
  19901. cpuUsageMs = 0;
  19902. const double sampleRate = device->getCurrentSampleRate();
  19903. const int blockSize = device->getCurrentBufferSizeSamples();
  19904. if (sampleRate > 0.0 && blockSize > 0)
  19905. {
  19906. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19907. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19908. }
  19909. {
  19910. const ScopedLock sl (audioCallbackLock);
  19911. for (int i = callbacks.size(); --i >= 0;)
  19912. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19913. }
  19914. sendChangeMessage (this);
  19915. }
  19916. void AudioDeviceManager::audioDeviceStoppedInt()
  19917. {
  19918. cpuUsageMs = 0;
  19919. timeToCpuScale = 0;
  19920. sendChangeMessage (this);
  19921. const ScopedLock sl (audioCallbackLock);
  19922. for (int i = callbacks.size(); --i >= 0;)
  19923. callbacks.getUnchecked(i)->audioDeviceStopped();
  19924. }
  19925. double AudioDeviceManager::getCpuUsage() const
  19926. {
  19927. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19928. }
  19929. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19930. const bool enabled)
  19931. {
  19932. if (enabled != isMidiInputEnabled (name))
  19933. {
  19934. if (enabled)
  19935. {
  19936. const int index = MidiInput::getDevices().indexOf (name);
  19937. if (index >= 0)
  19938. {
  19939. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19940. if (min != 0)
  19941. {
  19942. enabledMidiInputs.add (min);
  19943. min->start();
  19944. }
  19945. }
  19946. }
  19947. else
  19948. {
  19949. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19950. if (enabledMidiInputs[i]->getName() == name)
  19951. enabledMidiInputs.remove (i);
  19952. }
  19953. updateXml();
  19954. sendChangeMessage (this);
  19955. }
  19956. }
  19957. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19958. {
  19959. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19960. if (enabledMidiInputs[i]->getName() == name)
  19961. return true;
  19962. return false;
  19963. }
  19964. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19965. MidiInputCallback* callback)
  19966. {
  19967. removeMidiInputCallback (name, callback);
  19968. if (name.isEmpty())
  19969. {
  19970. midiCallbacks.add (callback);
  19971. midiCallbackDevices.add (0);
  19972. }
  19973. else
  19974. {
  19975. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19976. {
  19977. if (enabledMidiInputs[i]->getName() == name)
  19978. {
  19979. const ScopedLock sl (midiCallbackLock);
  19980. midiCallbacks.add (callback);
  19981. midiCallbackDevices.add (enabledMidiInputs[i]);
  19982. break;
  19983. }
  19984. }
  19985. }
  19986. }
  19987. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19988. MidiInputCallback* /*callback*/)
  19989. {
  19990. const ScopedLock sl (midiCallbackLock);
  19991. for (int i = midiCallbacks.size(); --i >= 0;)
  19992. {
  19993. String devName;
  19994. if (midiCallbackDevices.getUnchecked(i) != 0)
  19995. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19996. if (devName == name)
  19997. {
  19998. midiCallbacks.remove (i);
  19999. midiCallbackDevices.remove (i);
  20000. }
  20001. }
  20002. }
  20003. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20004. const MidiMessage& message)
  20005. {
  20006. if (! message.isActiveSense())
  20007. {
  20008. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20009. const ScopedLock sl (midiCallbackLock);
  20010. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20011. {
  20012. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20013. if (md == source || (md == 0 && isDefaultSource))
  20014. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20015. }
  20016. }
  20017. }
  20018. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20019. {
  20020. if (defaultMidiOutputName != deviceName)
  20021. {
  20022. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20023. {
  20024. const ScopedLock sl (audioCallbackLock);
  20025. oldCallbacks = callbacks;
  20026. callbacks.clear();
  20027. }
  20028. if (currentAudioDevice != 0)
  20029. for (int i = oldCallbacks.size(); --i >= 0;)
  20030. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20031. defaultMidiOutput = 0;
  20032. defaultMidiOutputName = deviceName;
  20033. if (deviceName.isNotEmpty())
  20034. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20035. if (currentAudioDevice != 0)
  20036. for (int i = oldCallbacks.size(); --i >= 0;)
  20037. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20038. {
  20039. const ScopedLock sl (audioCallbackLock);
  20040. callbacks = oldCallbacks;
  20041. }
  20042. updateXml();
  20043. sendChangeMessage (this);
  20044. }
  20045. }
  20046. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20047. int numInputChannels,
  20048. float** outputChannelData,
  20049. int numOutputChannels,
  20050. int numSamples)
  20051. {
  20052. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20053. }
  20054. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20055. {
  20056. owner->audioDeviceAboutToStartInt (device);
  20057. }
  20058. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20059. {
  20060. owner->audioDeviceStoppedInt();
  20061. }
  20062. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20063. {
  20064. owner->handleIncomingMidiMessageInt (source, message);
  20065. }
  20066. void AudioDeviceManager::playTestSound()
  20067. {
  20068. { // cunningly nested to swap, unlock and delete in that order.
  20069. ScopedPointer <AudioSampleBuffer> oldSound;
  20070. {
  20071. const ScopedLock sl (audioCallbackLock);
  20072. oldSound = testSound;
  20073. }
  20074. }
  20075. testSoundPosition = 0;
  20076. if (currentAudioDevice != 0)
  20077. {
  20078. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20079. const int soundLength = (int) sampleRate;
  20080. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20081. float* samples = newSound->getSampleData (0);
  20082. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20083. const float amplitude = 0.5f;
  20084. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20085. for (int i = 0; i < soundLength; ++i)
  20086. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20087. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20088. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20089. const ScopedLock sl (audioCallbackLock);
  20090. testSound = newSound;
  20091. }
  20092. }
  20093. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20094. {
  20095. const ScopedLock sl (audioCallbackLock);
  20096. if (enableMeasurement)
  20097. ++inputLevelMeasurementEnabledCount;
  20098. else
  20099. --inputLevelMeasurementEnabledCount;
  20100. inputLevel = 0;
  20101. }
  20102. double AudioDeviceManager::getCurrentInputLevel() const
  20103. {
  20104. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20105. return inputLevel;
  20106. }
  20107. END_JUCE_NAMESPACE
  20108. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20109. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20110. BEGIN_JUCE_NAMESPACE
  20111. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20112. : name (deviceName),
  20113. typeName (typeName_)
  20114. {
  20115. }
  20116. AudioIODevice::~AudioIODevice()
  20117. {
  20118. }
  20119. bool AudioIODevice::hasControlPanel() const
  20120. {
  20121. return false;
  20122. }
  20123. bool AudioIODevice::showControlPanel()
  20124. {
  20125. jassertfalse; // this should only be called for devices which return true from
  20126. // their hasControlPanel() method.
  20127. return false;
  20128. }
  20129. END_JUCE_NAMESPACE
  20130. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20131. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20132. BEGIN_JUCE_NAMESPACE
  20133. AudioIODeviceType::AudioIODeviceType (const String& name)
  20134. : typeName (name)
  20135. {
  20136. }
  20137. AudioIODeviceType::~AudioIODeviceType()
  20138. {
  20139. }
  20140. END_JUCE_NAMESPACE
  20141. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20142. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20143. BEGIN_JUCE_NAMESPACE
  20144. MidiOutput::MidiOutput()
  20145. : Thread ("midi out"),
  20146. internal (0),
  20147. firstMessage (0)
  20148. {
  20149. }
  20150. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20151. const double sampleNumber)
  20152. : message (data, len, sampleNumber)
  20153. {
  20154. }
  20155. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20156. const double millisecondCounterToStartAt,
  20157. double samplesPerSecondForBuffer)
  20158. {
  20159. // You've got to call startBackgroundThread() for this to actually work..
  20160. jassert (isThreadRunning());
  20161. // this needs to be a value in the future - RTFM for this method!
  20162. jassert (millisecondCounterToStartAt > 0);
  20163. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20164. MidiBuffer::Iterator i (buffer);
  20165. const uint8* data;
  20166. int len, time;
  20167. while (i.getNextEvent (data, len, time))
  20168. {
  20169. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20170. PendingMessage* const m
  20171. = new PendingMessage (data, len, eventTime);
  20172. const ScopedLock sl (lock);
  20173. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20174. {
  20175. m->next = firstMessage;
  20176. firstMessage = m;
  20177. }
  20178. else
  20179. {
  20180. PendingMessage* mm = firstMessage;
  20181. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20182. mm = mm->next;
  20183. m->next = mm->next;
  20184. mm->next = m;
  20185. }
  20186. }
  20187. notify();
  20188. }
  20189. void MidiOutput::clearAllPendingMessages()
  20190. {
  20191. const ScopedLock sl (lock);
  20192. while (firstMessage != 0)
  20193. {
  20194. PendingMessage* const m = firstMessage;
  20195. firstMessage = firstMessage->next;
  20196. delete m;
  20197. }
  20198. }
  20199. void MidiOutput::startBackgroundThread()
  20200. {
  20201. startThread (9);
  20202. }
  20203. void MidiOutput::stopBackgroundThread()
  20204. {
  20205. stopThread (5000);
  20206. }
  20207. void MidiOutput::run()
  20208. {
  20209. while (! threadShouldExit())
  20210. {
  20211. uint32 now = Time::getMillisecondCounter();
  20212. uint32 eventTime = 0;
  20213. uint32 timeToWait = 500;
  20214. PendingMessage* message;
  20215. {
  20216. const ScopedLock sl (lock);
  20217. message = firstMessage;
  20218. if (message != 0)
  20219. {
  20220. eventTime = roundToInt (message->message.getTimeStamp());
  20221. if (eventTime > now + 20)
  20222. {
  20223. timeToWait = eventTime - (now + 20);
  20224. message = 0;
  20225. }
  20226. else
  20227. {
  20228. firstMessage = message->next;
  20229. }
  20230. }
  20231. }
  20232. if (message != 0)
  20233. {
  20234. if (eventTime > now)
  20235. {
  20236. Time::waitForMillisecondCounter (eventTime);
  20237. if (threadShouldExit())
  20238. break;
  20239. }
  20240. if (eventTime > now - 200)
  20241. sendMessageNow (message->message);
  20242. delete message;
  20243. }
  20244. else
  20245. {
  20246. jassert (timeToWait < 1000 * 30);
  20247. wait (timeToWait);
  20248. }
  20249. }
  20250. clearAllPendingMessages();
  20251. }
  20252. END_JUCE_NAMESPACE
  20253. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20254. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20255. BEGIN_JUCE_NAMESPACE
  20256. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20257. {
  20258. const double maxVal = (double) 0x7fff;
  20259. char* intData = static_cast <char*> (dest);
  20260. if (dest != (void*) source || destBytesPerSample <= 4)
  20261. {
  20262. for (int i = 0; i < numSamples; ++i)
  20263. {
  20264. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20265. intData += destBytesPerSample;
  20266. }
  20267. }
  20268. else
  20269. {
  20270. intData += destBytesPerSample * numSamples;
  20271. for (int i = numSamples; --i >= 0;)
  20272. {
  20273. intData -= destBytesPerSample;
  20274. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20275. }
  20276. }
  20277. }
  20278. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20279. {
  20280. const double maxVal = (double) 0x7fff;
  20281. char* intData = static_cast <char*> (dest);
  20282. if (dest != (void*) source || destBytesPerSample <= 4)
  20283. {
  20284. for (int i = 0; i < numSamples; ++i)
  20285. {
  20286. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20287. intData += destBytesPerSample;
  20288. }
  20289. }
  20290. else
  20291. {
  20292. intData += destBytesPerSample * numSamples;
  20293. for (int i = numSamples; --i >= 0;)
  20294. {
  20295. intData -= destBytesPerSample;
  20296. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20297. }
  20298. }
  20299. }
  20300. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20301. {
  20302. const double maxVal = (double) 0x7fffff;
  20303. char* intData = static_cast <char*> (dest);
  20304. if (dest != (void*) source || destBytesPerSample <= 4)
  20305. {
  20306. for (int i = 0; i < numSamples; ++i)
  20307. {
  20308. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20309. intData += destBytesPerSample;
  20310. }
  20311. }
  20312. else
  20313. {
  20314. intData += destBytesPerSample * numSamples;
  20315. for (int i = numSamples; --i >= 0;)
  20316. {
  20317. intData -= destBytesPerSample;
  20318. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20319. }
  20320. }
  20321. }
  20322. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20323. {
  20324. const double maxVal = (double) 0x7fffff;
  20325. char* intData = static_cast <char*> (dest);
  20326. if (dest != (void*) source || destBytesPerSample <= 4)
  20327. {
  20328. for (int i = 0; i < numSamples; ++i)
  20329. {
  20330. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20331. intData += destBytesPerSample;
  20332. }
  20333. }
  20334. else
  20335. {
  20336. intData += destBytesPerSample * numSamples;
  20337. for (int i = numSamples; --i >= 0;)
  20338. {
  20339. intData -= destBytesPerSample;
  20340. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20341. }
  20342. }
  20343. }
  20344. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20345. {
  20346. const double maxVal = (double) 0x7fffffff;
  20347. char* intData = static_cast <char*> (dest);
  20348. if (dest != (void*) source || destBytesPerSample <= 4)
  20349. {
  20350. for (int i = 0; i < numSamples; ++i)
  20351. {
  20352. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20353. intData += destBytesPerSample;
  20354. }
  20355. }
  20356. else
  20357. {
  20358. intData += destBytesPerSample * numSamples;
  20359. for (int i = numSamples; --i >= 0;)
  20360. {
  20361. intData -= destBytesPerSample;
  20362. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20363. }
  20364. }
  20365. }
  20366. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20367. {
  20368. const double maxVal = (double) 0x7fffffff;
  20369. char* intData = static_cast <char*> (dest);
  20370. if (dest != (void*) source || destBytesPerSample <= 4)
  20371. {
  20372. for (int i = 0; i < numSamples; ++i)
  20373. {
  20374. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20375. intData += destBytesPerSample;
  20376. }
  20377. }
  20378. else
  20379. {
  20380. intData += destBytesPerSample * numSamples;
  20381. for (int i = numSamples; --i >= 0;)
  20382. {
  20383. intData -= destBytesPerSample;
  20384. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20385. }
  20386. }
  20387. }
  20388. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20389. {
  20390. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20391. char* d = static_cast <char*> (dest);
  20392. for (int i = 0; i < numSamples; ++i)
  20393. {
  20394. *(float*) d = source[i];
  20395. #if JUCE_BIG_ENDIAN
  20396. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20397. #endif
  20398. d += destBytesPerSample;
  20399. }
  20400. }
  20401. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20402. {
  20403. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20404. char* d = static_cast <char*> (dest);
  20405. for (int i = 0; i < numSamples; ++i)
  20406. {
  20407. *(float*) d = source[i];
  20408. #if JUCE_LITTLE_ENDIAN
  20409. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20410. #endif
  20411. d += destBytesPerSample;
  20412. }
  20413. }
  20414. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20415. {
  20416. const float scale = 1.0f / 0x7fff;
  20417. const char* intData = static_cast <const char*> (source);
  20418. if (source != (void*) dest || srcBytesPerSample >= 4)
  20419. {
  20420. for (int i = 0; i < numSamples; ++i)
  20421. {
  20422. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20423. intData += srcBytesPerSample;
  20424. }
  20425. }
  20426. else
  20427. {
  20428. intData += srcBytesPerSample * numSamples;
  20429. for (int i = numSamples; --i >= 0;)
  20430. {
  20431. intData -= srcBytesPerSample;
  20432. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20433. }
  20434. }
  20435. }
  20436. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20437. {
  20438. const float scale = 1.0f / 0x7fff;
  20439. const char* intData = static_cast <const char*> (source);
  20440. if (source != (void*) dest || srcBytesPerSample >= 4)
  20441. {
  20442. for (int i = 0; i < numSamples; ++i)
  20443. {
  20444. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20445. intData += srcBytesPerSample;
  20446. }
  20447. }
  20448. else
  20449. {
  20450. intData += srcBytesPerSample * numSamples;
  20451. for (int i = numSamples; --i >= 0;)
  20452. {
  20453. intData -= srcBytesPerSample;
  20454. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20455. }
  20456. }
  20457. }
  20458. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20459. {
  20460. const float scale = 1.0f / 0x7fffff;
  20461. const char* intData = static_cast <const char*> (source);
  20462. if (source != (void*) dest || srcBytesPerSample >= 4)
  20463. {
  20464. for (int i = 0; i < numSamples; ++i)
  20465. {
  20466. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20467. intData += srcBytesPerSample;
  20468. }
  20469. }
  20470. else
  20471. {
  20472. intData += srcBytesPerSample * numSamples;
  20473. for (int i = numSamples; --i >= 0;)
  20474. {
  20475. intData -= srcBytesPerSample;
  20476. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20477. }
  20478. }
  20479. }
  20480. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20481. {
  20482. const float scale = 1.0f / 0x7fffff;
  20483. const char* intData = static_cast <const char*> (source);
  20484. if (source != (void*) dest || srcBytesPerSample >= 4)
  20485. {
  20486. for (int i = 0; i < numSamples; ++i)
  20487. {
  20488. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20489. intData += srcBytesPerSample;
  20490. }
  20491. }
  20492. else
  20493. {
  20494. intData += srcBytesPerSample * numSamples;
  20495. for (int i = numSamples; --i >= 0;)
  20496. {
  20497. intData -= srcBytesPerSample;
  20498. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20499. }
  20500. }
  20501. }
  20502. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20503. {
  20504. const float scale = 1.0f / 0x7fffffff;
  20505. const char* intData = static_cast <const char*> (source);
  20506. if (source != (void*) dest || srcBytesPerSample >= 4)
  20507. {
  20508. for (int i = 0; i < numSamples; ++i)
  20509. {
  20510. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20511. intData += srcBytesPerSample;
  20512. }
  20513. }
  20514. else
  20515. {
  20516. intData += srcBytesPerSample * numSamples;
  20517. for (int i = numSamples; --i >= 0;)
  20518. {
  20519. intData -= srcBytesPerSample;
  20520. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20521. }
  20522. }
  20523. }
  20524. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20525. {
  20526. const float scale = 1.0f / 0x7fffffff;
  20527. const char* intData = static_cast <const char*> (source);
  20528. if (source != (void*) dest || srcBytesPerSample >= 4)
  20529. {
  20530. for (int i = 0; i < numSamples; ++i)
  20531. {
  20532. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20533. intData += srcBytesPerSample;
  20534. }
  20535. }
  20536. else
  20537. {
  20538. intData += srcBytesPerSample * numSamples;
  20539. for (int i = numSamples; --i >= 0;)
  20540. {
  20541. intData -= srcBytesPerSample;
  20542. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20543. }
  20544. }
  20545. }
  20546. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20547. {
  20548. const char* s = static_cast <const char*> (source);
  20549. for (int i = 0; i < numSamples; ++i)
  20550. {
  20551. dest[i] = *(float*)s;
  20552. #if JUCE_BIG_ENDIAN
  20553. uint32* const d = (uint32*) (dest + i);
  20554. *d = ByteOrder::swap (*d);
  20555. #endif
  20556. s += srcBytesPerSample;
  20557. }
  20558. }
  20559. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20560. {
  20561. const char* s = static_cast <const char*> (source);
  20562. for (int i = 0; i < numSamples; ++i)
  20563. {
  20564. dest[i] = *(float*)s;
  20565. #if JUCE_LITTLE_ENDIAN
  20566. uint32* const d = (uint32*) (dest + i);
  20567. *d = ByteOrder::swap (*d);
  20568. #endif
  20569. s += srcBytesPerSample;
  20570. }
  20571. }
  20572. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20573. const float* const source,
  20574. void* const dest,
  20575. const int numSamples)
  20576. {
  20577. switch (destFormat)
  20578. {
  20579. case int16LE:
  20580. convertFloatToInt16LE (source, dest, numSamples);
  20581. break;
  20582. case int16BE:
  20583. convertFloatToInt16BE (source, dest, numSamples);
  20584. break;
  20585. case int24LE:
  20586. convertFloatToInt24LE (source, dest, numSamples);
  20587. break;
  20588. case int24BE:
  20589. convertFloatToInt24BE (source, dest, numSamples);
  20590. break;
  20591. case int32LE:
  20592. convertFloatToInt32LE (source, dest, numSamples);
  20593. break;
  20594. case int32BE:
  20595. convertFloatToInt32BE (source, dest, numSamples);
  20596. break;
  20597. case float32LE:
  20598. convertFloatToFloat32LE (source, dest, numSamples);
  20599. break;
  20600. case float32BE:
  20601. convertFloatToFloat32BE (source, dest, numSamples);
  20602. break;
  20603. default:
  20604. jassertfalse;
  20605. break;
  20606. }
  20607. }
  20608. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20609. const void* const source,
  20610. float* const dest,
  20611. const int numSamples)
  20612. {
  20613. switch (sourceFormat)
  20614. {
  20615. case int16LE:
  20616. convertInt16LEToFloat (source, dest, numSamples);
  20617. break;
  20618. case int16BE:
  20619. convertInt16BEToFloat (source, dest, numSamples);
  20620. break;
  20621. case int24LE:
  20622. convertInt24LEToFloat (source, dest, numSamples);
  20623. break;
  20624. case int24BE:
  20625. convertInt24BEToFloat (source, dest, numSamples);
  20626. break;
  20627. case int32LE:
  20628. convertInt32LEToFloat (source, dest, numSamples);
  20629. break;
  20630. case int32BE:
  20631. convertInt32BEToFloat (source, dest, numSamples);
  20632. break;
  20633. case float32LE:
  20634. convertFloat32LEToFloat (source, dest, numSamples);
  20635. break;
  20636. case float32BE:
  20637. convertFloat32BEToFloat (source, dest, numSamples);
  20638. break;
  20639. default:
  20640. jassertfalse;
  20641. break;
  20642. }
  20643. }
  20644. void AudioDataConverters::interleaveSamples (const float** const source,
  20645. float* const dest,
  20646. const int numSamples,
  20647. const int numChannels)
  20648. {
  20649. for (int chan = 0; chan < numChannels; ++chan)
  20650. {
  20651. int i = chan;
  20652. const float* src = source [chan];
  20653. for (int j = 0; j < numSamples; ++j)
  20654. {
  20655. dest [i] = src [j];
  20656. i += numChannels;
  20657. }
  20658. }
  20659. }
  20660. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20661. float** const dest,
  20662. const int numSamples,
  20663. const int numChannels)
  20664. {
  20665. for (int chan = 0; chan < numChannels; ++chan)
  20666. {
  20667. int i = chan;
  20668. float* dst = dest [chan];
  20669. for (int j = 0; j < numSamples; ++j)
  20670. {
  20671. dst [j] = source [i];
  20672. i += numChannels;
  20673. }
  20674. }
  20675. }
  20676. END_JUCE_NAMESPACE
  20677. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20678. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20679. BEGIN_JUCE_NAMESPACE
  20680. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20681. const int numSamples) throw()
  20682. : numChannels (numChannels_),
  20683. size (numSamples)
  20684. {
  20685. jassert (numSamples >= 0);
  20686. jassert (numChannels_ > 0);
  20687. allocateData();
  20688. }
  20689. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20690. : numChannels (other.numChannels),
  20691. size (other.size)
  20692. {
  20693. allocateData();
  20694. const size_t numBytes = size * sizeof (float);
  20695. for (int i = 0; i < numChannels; ++i)
  20696. memcpy (channels[i], other.channels[i], numBytes);
  20697. }
  20698. void AudioSampleBuffer::allocateData()
  20699. {
  20700. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20701. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20702. allocatedData.malloc (allocatedBytes);
  20703. channels = reinterpret_cast <float**> (allocatedData.getData());
  20704. float* chan = (float*) (allocatedData + channelListSize);
  20705. for (int i = 0; i < numChannels; ++i)
  20706. {
  20707. channels[i] = chan;
  20708. chan += size;
  20709. }
  20710. channels [numChannels] = 0;
  20711. }
  20712. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20713. const int numChannels_,
  20714. const int numSamples) throw()
  20715. : numChannels (numChannels_),
  20716. size (numSamples),
  20717. allocatedBytes (0)
  20718. {
  20719. jassert (numChannels_ > 0);
  20720. allocateChannels (dataToReferTo);
  20721. }
  20722. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20723. const int newNumChannels,
  20724. const int newNumSamples) throw()
  20725. {
  20726. jassert (newNumChannels > 0);
  20727. allocatedBytes = 0;
  20728. allocatedData.free();
  20729. numChannels = newNumChannels;
  20730. size = newNumSamples;
  20731. allocateChannels (dataToReferTo);
  20732. }
  20733. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20734. {
  20735. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20736. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20737. {
  20738. channels = static_cast <float**> (preallocatedChannelSpace);
  20739. }
  20740. else
  20741. {
  20742. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20743. channels = reinterpret_cast <float**> (allocatedData.getData());
  20744. }
  20745. for (int i = 0; i < numChannels; ++i)
  20746. {
  20747. // you have to pass in the same number of valid pointers as numChannels
  20748. jassert (dataToReferTo[i] != 0);
  20749. channels[i] = dataToReferTo[i];
  20750. }
  20751. channels [numChannels] = 0;
  20752. }
  20753. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20754. {
  20755. if (this != &other)
  20756. {
  20757. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20758. const size_t numBytes = size * sizeof (float);
  20759. for (int i = 0; i < numChannels; ++i)
  20760. memcpy (channels[i], other.channels[i], numBytes);
  20761. }
  20762. return *this;
  20763. }
  20764. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20765. {
  20766. }
  20767. void AudioSampleBuffer::setSize (const int newNumChannels,
  20768. const int newNumSamples,
  20769. const bool keepExistingContent,
  20770. const bool clearExtraSpace,
  20771. const bool avoidReallocating) throw()
  20772. {
  20773. jassert (newNumChannels > 0);
  20774. if (newNumSamples != size || newNumChannels != numChannels)
  20775. {
  20776. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20777. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20778. if (keepExistingContent)
  20779. {
  20780. HeapBlock <char> newData;
  20781. newData.allocate (newTotalBytes, clearExtraSpace);
  20782. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20783. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20784. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20785. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20786. for (int i = 0; i < numChansToCopy; ++i)
  20787. {
  20788. memcpy (newChan, channels[i], numBytesToCopy);
  20789. newChannels[i] = newChan;
  20790. newChan += newNumSamples;
  20791. }
  20792. allocatedData.swapWith (newData);
  20793. allocatedBytes = (int) newTotalBytes;
  20794. channels = newChannels;
  20795. }
  20796. else
  20797. {
  20798. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20799. {
  20800. if (clearExtraSpace)
  20801. zeromem (allocatedData, newTotalBytes);
  20802. }
  20803. else
  20804. {
  20805. allocatedBytes = newTotalBytes;
  20806. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20807. channels = reinterpret_cast <float**> (allocatedData.getData());
  20808. }
  20809. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20810. for (int i = 0; i < newNumChannels; ++i)
  20811. {
  20812. channels[i] = chan;
  20813. chan += newNumSamples;
  20814. }
  20815. }
  20816. channels [newNumChannels] = 0;
  20817. size = newNumSamples;
  20818. numChannels = newNumChannels;
  20819. }
  20820. }
  20821. void AudioSampleBuffer::clear() throw()
  20822. {
  20823. for (int i = 0; i < numChannels; ++i)
  20824. zeromem (channels[i], size * sizeof (float));
  20825. }
  20826. void AudioSampleBuffer::clear (const int startSample,
  20827. const int numSamples) throw()
  20828. {
  20829. jassert (startSample >= 0 && startSample + numSamples <= size);
  20830. for (int i = 0; i < numChannels; ++i)
  20831. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20832. }
  20833. void AudioSampleBuffer::clear (const int channel,
  20834. const int startSample,
  20835. const int numSamples) throw()
  20836. {
  20837. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20838. jassert (startSample >= 0 && startSample + numSamples <= size);
  20839. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20840. }
  20841. void AudioSampleBuffer::applyGain (const int channel,
  20842. const int startSample,
  20843. int numSamples,
  20844. const float gain) throw()
  20845. {
  20846. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20847. jassert (startSample >= 0 && startSample + numSamples <= size);
  20848. if (gain != 1.0f)
  20849. {
  20850. float* d = channels [channel] + startSample;
  20851. if (gain == 0.0f)
  20852. {
  20853. zeromem (d, sizeof (float) * numSamples);
  20854. }
  20855. else
  20856. {
  20857. while (--numSamples >= 0)
  20858. *d++ *= gain;
  20859. }
  20860. }
  20861. }
  20862. void AudioSampleBuffer::applyGainRamp (const int channel,
  20863. const int startSample,
  20864. int numSamples,
  20865. float startGain,
  20866. float endGain) throw()
  20867. {
  20868. if (startGain == endGain)
  20869. {
  20870. applyGain (channel, startSample, numSamples, startGain);
  20871. }
  20872. else
  20873. {
  20874. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20875. jassert (startSample >= 0 && startSample + numSamples <= size);
  20876. const float increment = (endGain - startGain) / numSamples;
  20877. float* d = channels [channel] + startSample;
  20878. while (--numSamples >= 0)
  20879. {
  20880. *d++ *= startGain;
  20881. startGain += increment;
  20882. }
  20883. }
  20884. }
  20885. void AudioSampleBuffer::applyGain (const int startSample,
  20886. const int numSamples,
  20887. const float gain) throw()
  20888. {
  20889. for (int i = 0; i < numChannels; ++i)
  20890. applyGain (i, startSample, numSamples, gain);
  20891. }
  20892. void AudioSampleBuffer::addFrom (const int destChannel,
  20893. const int destStartSample,
  20894. const AudioSampleBuffer& source,
  20895. const int sourceChannel,
  20896. const int sourceStartSample,
  20897. int numSamples,
  20898. const float gain) throw()
  20899. {
  20900. jassert (&source != this || sourceChannel != destChannel);
  20901. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20902. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20903. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20904. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20905. if (gain != 0.0f && numSamples > 0)
  20906. {
  20907. float* d = channels [destChannel] + destStartSample;
  20908. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20909. if (gain != 1.0f)
  20910. {
  20911. while (--numSamples >= 0)
  20912. *d++ += gain * *s++;
  20913. }
  20914. else
  20915. {
  20916. while (--numSamples >= 0)
  20917. *d++ += *s++;
  20918. }
  20919. }
  20920. }
  20921. void AudioSampleBuffer::addFrom (const int destChannel,
  20922. const int destStartSample,
  20923. const float* source,
  20924. int numSamples,
  20925. const float gain) throw()
  20926. {
  20927. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20928. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20929. jassert (source != 0);
  20930. if (gain != 0.0f && numSamples > 0)
  20931. {
  20932. float* d = channels [destChannel] + destStartSample;
  20933. if (gain != 1.0f)
  20934. {
  20935. while (--numSamples >= 0)
  20936. *d++ += gain * *source++;
  20937. }
  20938. else
  20939. {
  20940. while (--numSamples >= 0)
  20941. *d++ += *source++;
  20942. }
  20943. }
  20944. }
  20945. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20946. const int destStartSample,
  20947. const float* source,
  20948. int numSamples,
  20949. float startGain,
  20950. const float endGain) throw()
  20951. {
  20952. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20953. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20954. jassert (source != 0);
  20955. if (startGain == endGain)
  20956. {
  20957. addFrom (destChannel,
  20958. destStartSample,
  20959. source,
  20960. numSamples,
  20961. startGain);
  20962. }
  20963. else
  20964. {
  20965. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20966. {
  20967. const float increment = (endGain - startGain) / numSamples;
  20968. float* d = channels [destChannel] + destStartSample;
  20969. while (--numSamples >= 0)
  20970. {
  20971. *d++ += startGain * *source++;
  20972. startGain += increment;
  20973. }
  20974. }
  20975. }
  20976. }
  20977. void AudioSampleBuffer::copyFrom (const int destChannel,
  20978. const int destStartSample,
  20979. const AudioSampleBuffer& source,
  20980. const int sourceChannel,
  20981. const int sourceStartSample,
  20982. int numSamples) throw()
  20983. {
  20984. jassert (&source != this || sourceChannel != destChannel);
  20985. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20986. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20987. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20988. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20989. if (numSamples > 0)
  20990. {
  20991. memcpy (channels [destChannel] + destStartSample,
  20992. source.channels [sourceChannel] + sourceStartSample,
  20993. sizeof (float) * numSamples);
  20994. }
  20995. }
  20996. void AudioSampleBuffer::copyFrom (const int destChannel,
  20997. const int destStartSample,
  20998. const float* source,
  20999. int numSamples) throw()
  21000. {
  21001. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21002. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21003. jassert (source != 0);
  21004. if (numSamples > 0)
  21005. {
  21006. memcpy (channels [destChannel] + destStartSample,
  21007. source,
  21008. sizeof (float) * numSamples);
  21009. }
  21010. }
  21011. void AudioSampleBuffer::copyFrom (const int destChannel,
  21012. const int destStartSample,
  21013. const float* source,
  21014. int numSamples,
  21015. const float gain) throw()
  21016. {
  21017. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21018. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21019. jassert (source != 0);
  21020. if (numSamples > 0)
  21021. {
  21022. float* d = channels [destChannel] + destStartSample;
  21023. if (gain != 1.0f)
  21024. {
  21025. if (gain == 0)
  21026. {
  21027. zeromem (d, sizeof (float) * numSamples);
  21028. }
  21029. else
  21030. {
  21031. while (--numSamples >= 0)
  21032. *d++ = gain * *source++;
  21033. }
  21034. }
  21035. else
  21036. {
  21037. memcpy (d, source, sizeof (float) * numSamples);
  21038. }
  21039. }
  21040. }
  21041. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21042. const int destStartSample,
  21043. const float* source,
  21044. int numSamples,
  21045. float startGain,
  21046. float endGain) throw()
  21047. {
  21048. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21049. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21050. jassert (source != 0);
  21051. if (startGain == endGain)
  21052. {
  21053. copyFrom (destChannel,
  21054. destStartSample,
  21055. source,
  21056. numSamples,
  21057. startGain);
  21058. }
  21059. else
  21060. {
  21061. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21062. {
  21063. const float increment = (endGain - startGain) / numSamples;
  21064. float* d = channels [destChannel] + destStartSample;
  21065. while (--numSamples >= 0)
  21066. {
  21067. *d++ = startGain * *source++;
  21068. startGain += increment;
  21069. }
  21070. }
  21071. }
  21072. }
  21073. void AudioSampleBuffer::findMinMax (const int channel,
  21074. const int startSample,
  21075. int numSamples,
  21076. float& minVal,
  21077. float& maxVal) const throw()
  21078. {
  21079. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21080. jassert (startSample >= 0 && startSample + numSamples <= size);
  21081. if (numSamples <= 0)
  21082. {
  21083. minVal = 0.0f;
  21084. maxVal = 0.0f;
  21085. }
  21086. else
  21087. {
  21088. const float* d = channels [channel] + startSample;
  21089. float mn = *d++;
  21090. float mx = mn;
  21091. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21092. {
  21093. const float samp = *d++;
  21094. if (samp > mx)
  21095. mx = samp;
  21096. if (samp < mn)
  21097. mn = samp;
  21098. }
  21099. maxVal = mx;
  21100. minVal = mn;
  21101. }
  21102. }
  21103. float AudioSampleBuffer::getMagnitude (const int channel,
  21104. const int startSample,
  21105. const int numSamples) const throw()
  21106. {
  21107. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21108. jassert (startSample >= 0 && startSample + numSamples <= size);
  21109. float mn, mx;
  21110. findMinMax (channel, startSample, numSamples, mn, mx);
  21111. return jmax (mn, -mn, mx, -mx);
  21112. }
  21113. float AudioSampleBuffer::getMagnitude (const int startSample,
  21114. const int numSamples) const throw()
  21115. {
  21116. float mag = 0.0f;
  21117. for (int i = 0; i < numChannels; ++i)
  21118. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21119. return mag;
  21120. }
  21121. float AudioSampleBuffer::getRMSLevel (const int channel,
  21122. const int startSample,
  21123. const int numSamples) const throw()
  21124. {
  21125. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21126. jassert (startSample >= 0 && startSample + numSamples <= size);
  21127. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21128. return 0.0f;
  21129. const float* const data = channels [channel] + startSample;
  21130. double sum = 0.0;
  21131. for (int i = 0; i < numSamples; ++i)
  21132. {
  21133. const float sample = data [i];
  21134. sum += sample * sample;
  21135. }
  21136. return (float) std::sqrt (sum / numSamples);
  21137. }
  21138. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21139. const int startSample,
  21140. const int numSamples,
  21141. const int readerStartSample,
  21142. const bool useLeftChan,
  21143. const bool useRightChan)
  21144. {
  21145. jassert (reader != 0);
  21146. jassert (startSample >= 0 && startSample + numSamples <= size);
  21147. if (numSamples > 0)
  21148. {
  21149. int* chans[3];
  21150. if (useLeftChan == useRightChan)
  21151. {
  21152. chans[0] = (int*) getSampleData (0, startSample);
  21153. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21154. }
  21155. else if (useLeftChan || (reader->numChannels == 1))
  21156. {
  21157. chans[0] = (int*) getSampleData (0, startSample);
  21158. chans[1] = 0;
  21159. }
  21160. else if (useRightChan)
  21161. {
  21162. chans[0] = 0;
  21163. chans[1] = (int*) getSampleData (0, startSample);
  21164. }
  21165. chans[2] = 0;
  21166. reader->read (chans, 2, readerStartSample, numSamples, true);
  21167. if (! reader->usesFloatingPointData)
  21168. {
  21169. for (int j = 0; j < 2; ++j)
  21170. {
  21171. float* const d = reinterpret_cast <float*> (chans[j]);
  21172. if (d != 0)
  21173. {
  21174. const float multiplier = 1.0f / 0x7fffffff;
  21175. for (int i = 0; i < numSamples; ++i)
  21176. d[i] = *(int*)(d + i) * multiplier;
  21177. }
  21178. }
  21179. }
  21180. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21181. {
  21182. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21183. memcpy (getSampleData (1, startSample),
  21184. getSampleData (0, startSample),
  21185. sizeof (float) * numSamples);
  21186. }
  21187. }
  21188. }
  21189. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21190. const int startSample,
  21191. const int numSamples) const
  21192. {
  21193. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  21194. if (numSamples > 0)
  21195. {
  21196. HeapBlock<int> tempBuffer;
  21197. HeapBlock<int*> chans (numChannels + 1);
  21198. chans [numChannels] = 0;
  21199. if (writer->isFloatingPoint())
  21200. {
  21201. for (int i = numChannels; --i >= 0;)
  21202. chans[i] = (int*) channels[i] + startSample;
  21203. }
  21204. else
  21205. {
  21206. tempBuffer.malloc (numSamples * numChannels);
  21207. for (int j = 0; j < numChannels; ++j)
  21208. {
  21209. int* const dest = tempBuffer + j * numSamples;
  21210. const float* const src = channels[j] + startSample;
  21211. chans[j] = dest;
  21212. for (int i = 0; i < numSamples; ++i)
  21213. {
  21214. const double samp = src[i];
  21215. if (samp <= -1.0)
  21216. dest[i] = std::numeric_limits<int>::min();
  21217. else if (samp >= 1.0)
  21218. dest[i] = std::numeric_limits<int>::max();
  21219. else
  21220. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21221. }
  21222. }
  21223. }
  21224. writer->write ((const int**) chans.getData(), numSamples);
  21225. }
  21226. }
  21227. END_JUCE_NAMESPACE
  21228. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21229. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21230. BEGIN_JUCE_NAMESPACE
  21231. IIRFilter::IIRFilter()
  21232. : active (false)
  21233. {
  21234. reset();
  21235. }
  21236. IIRFilter::IIRFilter (const IIRFilter& other)
  21237. : active (other.active)
  21238. {
  21239. const ScopedLock sl (other.processLock);
  21240. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21241. reset();
  21242. }
  21243. IIRFilter::~IIRFilter()
  21244. {
  21245. }
  21246. void IIRFilter::reset() throw()
  21247. {
  21248. const ScopedLock sl (processLock);
  21249. x1 = 0;
  21250. x2 = 0;
  21251. y1 = 0;
  21252. y2 = 0;
  21253. }
  21254. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21255. {
  21256. float out = coefficients[0] * in
  21257. + coefficients[1] * x1
  21258. + coefficients[2] * x2
  21259. - coefficients[4] * y1
  21260. - coefficients[5] * y2;
  21261. #if JUCE_INTEL
  21262. if (! (out < -1.0e-8 || out > 1.0e-8))
  21263. out = 0;
  21264. #endif
  21265. x2 = x1;
  21266. x1 = in;
  21267. y2 = y1;
  21268. y1 = out;
  21269. return out;
  21270. }
  21271. void IIRFilter::processSamples (float* const samples,
  21272. const int numSamples) throw()
  21273. {
  21274. const ScopedLock sl (processLock);
  21275. if (active)
  21276. {
  21277. for (int i = 0; i < numSamples; ++i)
  21278. {
  21279. const float in = samples[i];
  21280. float out = coefficients[0] * in
  21281. + coefficients[1] * x1
  21282. + coefficients[2] * x2
  21283. - coefficients[4] * y1
  21284. - coefficients[5] * y2;
  21285. #if JUCE_INTEL
  21286. if (! (out < -1.0e-8 || out > 1.0e-8))
  21287. out = 0;
  21288. #endif
  21289. x2 = x1;
  21290. x1 = in;
  21291. y2 = y1;
  21292. y1 = out;
  21293. samples[i] = out;
  21294. }
  21295. }
  21296. }
  21297. void IIRFilter::makeLowPass (const double sampleRate,
  21298. const double frequency) throw()
  21299. {
  21300. jassert (sampleRate > 0);
  21301. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21302. const double nSquared = n * n;
  21303. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21304. setCoefficients (c1,
  21305. c1 * 2.0f,
  21306. c1,
  21307. 1.0,
  21308. c1 * 2.0 * (1.0 - nSquared),
  21309. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21310. }
  21311. void IIRFilter::makeHighPass (const double sampleRate,
  21312. const double frequency) throw()
  21313. {
  21314. const double n = tan (double_Pi * frequency / sampleRate);
  21315. const double nSquared = n * n;
  21316. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21317. setCoefficients (c1,
  21318. c1 * -2.0f,
  21319. c1,
  21320. 1.0,
  21321. c1 * 2.0 * (nSquared - 1.0),
  21322. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21323. }
  21324. void IIRFilter::makeLowShelf (const double sampleRate,
  21325. const double cutOffFrequency,
  21326. const double Q,
  21327. const float gainFactor) throw()
  21328. {
  21329. jassert (sampleRate > 0);
  21330. jassert (Q > 0);
  21331. const double A = jmax (0.0f, gainFactor);
  21332. const double aminus1 = A - 1.0;
  21333. const double aplus1 = A + 1.0;
  21334. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21335. const double coso = std::cos (omega);
  21336. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21337. const double aminus1TimesCoso = aminus1 * coso;
  21338. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21339. A * 2.0 * (aminus1 - aplus1 * coso),
  21340. A * (aplus1 - aminus1TimesCoso - beta),
  21341. aplus1 + aminus1TimesCoso + beta,
  21342. -2.0 * (aminus1 + aplus1 * coso),
  21343. aplus1 + aminus1TimesCoso - beta);
  21344. }
  21345. void IIRFilter::makeHighShelf (const double sampleRate,
  21346. const double cutOffFrequency,
  21347. const double Q,
  21348. const float gainFactor) throw()
  21349. {
  21350. jassert (sampleRate > 0);
  21351. jassert (Q > 0);
  21352. const double A = jmax (0.0f, gainFactor);
  21353. const double aminus1 = A - 1.0;
  21354. const double aplus1 = A + 1.0;
  21355. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21356. const double coso = std::cos (omega);
  21357. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21358. const double aminus1TimesCoso = aminus1 * coso;
  21359. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21360. A * -2.0 * (aminus1 + aplus1 * coso),
  21361. A * (aplus1 + aminus1TimesCoso - beta),
  21362. aplus1 - aminus1TimesCoso + beta,
  21363. 2.0 * (aminus1 - aplus1 * coso),
  21364. aplus1 - aminus1TimesCoso - beta);
  21365. }
  21366. void IIRFilter::makeBandPass (const double sampleRate,
  21367. const double centreFrequency,
  21368. const double Q,
  21369. const float gainFactor) throw()
  21370. {
  21371. jassert (sampleRate > 0);
  21372. jassert (Q > 0);
  21373. const double A = jmax (0.0f, gainFactor);
  21374. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21375. const double alpha = 0.5 * std::sin (omega) / Q;
  21376. const double c2 = -2.0 * std::cos (omega);
  21377. const double alphaTimesA = alpha * A;
  21378. const double alphaOverA = alpha / A;
  21379. setCoefficients (1.0 + alphaTimesA,
  21380. c2,
  21381. 1.0 - alphaTimesA,
  21382. 1.0 + alphaOverA,
  21383. c2,
  21384. 1.0 - alphaOverA);
  21385. }
  21386. void IIRFilter::makeInactive() throw()
  21387. {
  21388. const ScopedLock sl (processLock);
  21389. active = false;
  21390. }
  21391. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21392. {
  21393. const ScopedLock sl (processLock);
  21394. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21395. active = other.active;
  21396. }
  21397. void IIRFilter::setCoefficients (double c1,
  21398. double c2,
  21399. double c3,
  21400. double c4,
  21401. double c5,
  21402. double c6) throw()
  21403. {
  21404. const double a = 1.0 / c4;
  21405. c1 *= a;
  21406. c2 *= a;
  21407. c3 *= a;
  21408. c5 *= a;
  21409. c6 *= a;
  21410. const ScopedLock sl (processLock);
  21411. coefficients[0] = (float) c1;
  21412. coefficients[1] = (float) c2;
  21413. coefficients[2] = (float) c3;
  21414. coefficients[3] = (float) c4;
  21415. coefficients[4] = (float) c5;
  21416. coefficients[5] = (float) c6;
  21417. active = true;
  21418. }
  21419. END_JUCE_NAMESPACE
  21420. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21421. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21422. BEGIN_JUCE_NAMESPACE
  21423. MidiBuffer::MidiBuffer() throw()
  21424. : bytesUsed (0)
  21425. {
  21426. }
  21427. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21428. : bytesUsed (0)
  21429. {
  21430. addEvent (message, 0);
  21431. }
  21432. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21433. : data (other.data),
  21434. bytesUsed (other.bytesUsed)
  21435. {
  21436. }
  21437. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21438. {
  21439. bytesUsed = other.bytesUsed;
  21440. data = other.data;
  21441. return *this;
  21442. }
  21443. void MidiBuffer::swapWith (MidiBuffer& other)
  21444. {
  21445. data.swapWith (other.data);
  21446. swapVariables <int> (bytesUsed, other.bytesUsed);
  21447. }
  21448. MidiBuffer::~MidiBuffer() throw()
  21449. {
  21450. }
  21451. inline uint8* MidiBuffer::getData() const throw()
  21452. {
  21453. return static_cast <uint8*> (data.getData());
  21454. }
  21455. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21456. {
  21457. return *static_cast <const int*> (d);
  21458. }
  21459. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21460. {
  21461. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21462. }
  21463. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21464. {
  21465. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21466. }
  21467. void MidiBuffer::clear() throw()
  21468. {
  21469. bytesUsed = 0;
  21470. }
  21471. void MidiBuffer::clear (const int startSample,
  21472. const int numSamples) throw()
  21473. {
  21474. uint8* const start = findEventAfter (getData(), startSample - 1);
  21475. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21476. if (end > start)
  21477. {
  21478. const int bytesToMove = bytesUsed - (int) (end - getData());
  21479. if (bytesToMove > 0)
  21480. memmove (start, end, bytesToMove);
  21481. bytesUsed -= (int) (end - start);
  21482. }
  21483. }
  21484. void MidiBuffer::addEvent (const MidiMessage& m,
  21485. const int sampleNumber) throw()
  21486. {
  21487. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21488. }
  21489. static int findActualEventLength (const uint8* const data,
  21490. const int maxBytes) throw()
  21491. {
  21492. unsigned int byte = (unsigned int) *data;
  21493. int size = 0;
  21494. if (byte == 0xf0 || byte == 0xf7)
  21495. {
  21496. const uint8* d = data + 1;
  21497. while (d < data + maxBytes)
  21498. if (*d++ == 0xf7)
  21499. break;
  21500. size = (int) (d - data);
  21501. }
  21502. else if (byte == 0xff)
  21503. {
  21504. int n;
  21505. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21506. size = jmin (maxBytes, n + 2 + bytesLeft);
  21507. }
  21508. else if (byte >= 0x80)
  21509. {
  21510. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21511. }
  21512. return size;
  21513. }
  21514. void MidiBuffer::addEvent (const uint8* const newData,
  21515. const int maxBytes,
  21516. const int sampleNumber) throw()
  21517. {
  21518. const int numBytes = findActualEventLength (newData, maxBytes);
  21519. if (numBytes > 0)
  21520. {
  21521. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21522. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21523. uint8* d = findEventAfter (getData(), sampleNumber);
  21524. const int bytesToMove = bytesUsed - (int) (d - getData());
  21525. if (bytesToMove > 0)
  21526. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21527. *reinterpret_cast <int*> (d) = sampleNumber;
  21528. d += sizeof (int);
  21529. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21530. d += sizeof (uint16);
  21531. memcpy (d, newData, numBytes);
  21532. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21533. }
  21534. }
  21535. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21536. const int startSample,
  21537. const int numSamples,
  21538. const int sampleDeltaToAdd) throw()
  21539. {
  21540. Iterator i (otherBuffer);
  21541. i.setNextSamplePosition (startSample);
  21542. const uint8* eventData;
  21543. int eventSize, position;
  21544. while (i.getNextEvent (eventData, eventSize, position)
  21545. && (position < startSample + numSamples || numSamples < 0))
  21546. {
  21547. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21548. }
  21549. }
  21550. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21551. {
  21552. data.ensureSize (minimumNumBytes);
  21553. }
  21554. bool MidiBuffer::isEmpty() const throw()
  21555. {
  21556. return bytesUsed == 0;
  21557. }
  21558. int MidiBuffer::getNumEvents() const throw()
  21559. {
  21560. int n = 0;
  21561. const uint8* d = getData();
  21562. const uint8* const end = d + bytesUsed;
  21563. while (d < end)
  21564. {
  21565. d += getEventTotalSize (d);
  21566. ++n;
  21567. }
  21568. return n;
  21569. }
  21570. int MidiBuffer::getFirstEventTime() const throw()
  21571. {
  21572. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21573. }
  21574. int MidiBuffer::getLastEventTime() const throw()
  21575. {
  21576. if (bytesUsed == 0)
  21577. return 0;
  21578. const uint8* d = getData();
  21579. const uint8* const endData = d + bytesUsed;
  21580. for (;;)
  21581. {
  21582. const uint8* const nextOne = d + getEventTotalSize (d);
  21583. if (nextOne >= endData)
  21584. return getEventTime (d);
  21585. d = nextOne;
  21586. }
  21587. }
  21588. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21589. {
  21590. const uint8* const endData = getData() + bytesUsed;
  21591. while (d < endData && getEventTime (d) <= samplePosition)
  21592. d += getEventTotalSize (d);
  21593. return d;
  21594. }
  21595. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21596. : buffer (buffer_),
  21597. data (buffer_.getData())
  21598. {
  21599. }
  21600. MidiBuffer::Iterator::~Iterator() throw()
  21601. {
  21602. }
  21603. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21604. {
  21605. data = buffer.getData();
  21606. const uint8* dataEnd = data + buffer.bytesUsed;
  21607. while (data < dataEnd && getEventTime (data) < samplePosition)
  21608. data += getEventTotalSize (data);
  21609. }
  21610. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21611. {
  21612. if (data >= buffer.getData() + buffer.bytesUsed)
  21613. return false;
  21614. samplePosition = getEventTime (data);
  21615. numBytes = getEventDataSize (data);
  21616. data += sizeof (int) + sizeof (uint16);
  21617. midiData = data;
  21618. data += numBytes;
  21619. return true;
  21620. }
  21621. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21622. {
  21623. if (data >= buffer.getData() + buffer.bytesUsed)
  21624. return false;
  21625. samplePosition = getEventTime (data);
  21626. const int numBytes = getEventDataSize (data);
  21627. data += sizeof (int) + sizeof (uint16);
  21628. result = MidiMessage (data, numBytes, samplePosition);
  21629. data += numBytes;
  21630. return true;
  21631. }
  21632. END_JUCE_NAMESPACE
  21633. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21634. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21635. BEGIN_JUCE_NAMESPACE
  21636. namespace MidiFileHelpers
  21637. {
  21638. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21639. {
  21640. unsigned int buffer = v & 0x7F;
  21641. while ((v >>= 7) != 0)
  21642. {
  21643. buffer <<= 8;
  21644. buffer |= ((v & 0x7F) | 0x80);
  21645. }
  21646. for (;;)
  21647. {
  21648. out.writeByte ((char) buffer);
  21649. if (buffer & 0x80)
  21650. buffer >>= 8;
  21651. else
  21652. break;
  21653. }
  21654. }
  21655. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21656. {
  21657. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21658. data += 4;
  21659. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21660. {
  21661. bool ok = false;
  21662. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21663. {
  21664. for (int i = 0; i < 8; ++i)
  21665. {
  21666. ch = ByteOrder::bigEndianInt (data);
  21667. data += 4;
  21668. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21669. {
  21670. ok = true;
  21671. break;
  21672. }
  21673. }
  21674. }
  21675. if (! ok)
  21676. return false;
  21677. }
  21678. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21679. data += 4;
  21680. fileType = (short) ByteOrder::bigEndianShort (data);
  21681. data += 2;
  21682. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21683. data += 2;
  21684. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21685. data += 2;
  21686. bytesRemaining -= 6;
  21687. data += bytesRemaining;
  21688. return true;
  21689. }
  21690. static double convertTicksToSeconds (const double time,
  21691. const MidiMessageSequence& tempoEvents,
  21692. const int timeFormat)
  21693. {
  21694. if (timeFormat > 0)
  21695. {
  21696. int numer = 4, denom = 4;
  21697. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21698. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21699. double secsPerTick = 0.5 * tickLen;
  21700. const int numEvents = tempoEvents.getNumEvents();
  21701. for (int i = 0; i < numEvents; ++i)
  21702. {
  21703. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21704. if (time <= m.getTimeStamp())
  21705. break;
  21706. if (timeFormat > 0)
  21707. {
  21708. correctedTempoTime = correctedTempoTime
  21709. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21710. }
  21711. else
  21712. {
  21713. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21714. }
  21715. tempoTime = m.getTimeStamp();
  21716. if (m.isTempoMetaEvent())
  21717. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21718. else if (m.isTimeSignatureMetaEvent())
  21719. m.getTimeSignatureInfo (numer, denom);
  21720. while (i + 1 < numEvents)
  21721. {
  21722. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21723. if (m2.getTimeStamp() == tempoTime)
  21724. {
  21725. ++i;
  21726. if (m2.isTempoMetaEvent())
  21727. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21728. else if (m2.isTimeSignatureMetaEvent())
  21729. m2.getTimeSignatureInfo (numer, denom);
  21730. }
  21731. else
  21732. {
  21733. break;
  21734. }
  21735. }
  21736. }
  21737. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21738. }
  21739. else
  21740. {
  21741. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21742. }
  21743. }
  21744. }
  21745. MidiFile::MidiFile()
  21746. : timeFormat ((short) (unsigned short) 0xe728)
  21747. {
  21748. }
  21749. MidiFile::~MidiFile()
  21750. {
  21751. clear();
  21752. }
  21753. void MidiFile::clear()
  21754. {
  21755. tracks.clear();
  21756. }
  21757. int MidiFile::getNumTracks() const throw()
  21758. {
  21759. return tracks.size();
  21760. }
  21761. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21762. {
  21763. return tracks [index];
  21764. }
  21765. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21766. {
  21767. tracks.add (new MidiMessageSequence (trackSequence));
  21768. }
  21769. short MidiFile::getTimeFormat() const throw()
  21770. {
  21771. return timeFormat;
  21772. }
  21773. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21774. {
  21775. timeFormat = (short) ticks;
  21776. }
  21777. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21778. const int subframeResolution) throw()
  21779. {
  21780. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21781. }
  21782. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21783. {
  21784. for (int i = tracks.size(); --i >= 0;)
  21785. {
  21786. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21787. for (int j = 0; j < numEvents; ++j)
  21788. {
  21789. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21790. if (m.isTempoMetaEvent())
  21791. tempoChangeEvents.addEvent (m);
  21792. }
  21793. }
  21794. }
  21795. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21796. {
  21797. for (int i = tracks.size(); --i >= 0;)
  21798. {
  21799. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21800. for (int j = 0; j < numEvents; ++j)
  21801. {
  21802. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21803. if (m.isTimeSignatureMetaEvent())
  21804. timeSigEvents.addEvent (m);
  21805. }
  21806. }
  21807. }
  21808. double MidiFile::getLastTimestamp() const
  21809. {
  21810. double t = 0.0;
  21811. for (int i = tracks.size(); --i >= 0;)
  21812. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21813. return t;
  21814. }
  21815. bool MidiFile::readFrom (InputStream& sourceStream)
  21816. {
  21817. clear();
  21818. MemoryBlock data;
  21819. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21820. // (put a sanity-check on the file size, as midi files are generally small)
  21821. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21822. {
  21823. size_t size = data.getSize();
  21824. const uint8* d = static_cast <const uint8*> (data.getData());
  21825. short fileType, expectedTracks;
  21826. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21827. {
  21828. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21829. int track = 0;
  21830. while (size > 0 && track < expectedTracks)
  21831. {
  21832. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21833. d += 4;
  21834. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21835. d += 4;
  21836. if (chunkSize <= 0)
  21837. break;
  21838. if (size < 0)
  21839. return false;
  21840. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21841. {
  21842. readNextTrack (d, chunkSize);
  21843. }
  21844. size -= chunkSize + 8;
  21845. d += chunkSize;
  21846. ++track;
  21847. }
  21848. return true;
  21849. }
  21850. }
  21851. return false;
  21852. }
  21853. // a comparator that puts all the note-offs before note-ons that have the same time
  21854. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21855. const MidiMessageSequence::MidiEventHolder* const second)
  21856. {
  21857. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21858. if (diff == 0)
  21859. {
  21860. if (first->message.isNoteOff() && second->message.isNoteOn())
  21861. return -1;
  21862. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21863. return 1;
  21864. else
  21865. return 0;
  21866. }
  21867. else
  21868. {
  21869. return (diff > 0) ? 1 : -1;
  21870. }
  21871. }
  21872. void MidiFile::readNextTrack (const uint8* data, int size)
  21873. {
  21874. double time = 0;
  21875. char lastStatusByte = 0;
  21876. MidiMessageSequence result;
  21877. while (size > 0)
  21878. {
  21879. int bytesUsed;
  21880. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21881. data += bytesUsed;
  21882. size -= bytesUsed;
  21883. time += delay;
  21884. int messSize = 0;
  21885. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21886. if (messSize <= 0)
  21887. break;
  21888. size -= messSize;
  21889. data += messSize;
  21890. result.addEvent (mm);
  21891. const char firstByte = *(mm.getRawData());
  21892. if ((firstByte & 0xf0) != 0xf0)
  21893. lastStatusByte = firstByte;
  21894. }
  21895. // use a sort that puts all the note-offs before note-ons that have the same time
  21896. result.list.sort (*this, true);
  21897. result.updateMatchedPairs();
  21898. addTrack (result);
  21899. }
  21900. void MidiFile::convertTimestampTicksToSeconds()
  21901. {
  21902. MidiMessageSequence tempoEvents;
  21903. findAllTempoEvents (tempoEvents);
  21904. findAllTimeSigEvents (tempoEvents);
  21905. for (int i = 0; i < tracks.size(); ++i)
  21906. {
  21907. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21908. for (int j = ms.getNumEvents(); --j >= 0;)
  21909. {
  21910. MidiMessage& m = ms.getEventPointer(j)->message;
  21911. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21912. tempoEvents,
  21913. timeFormat));
  21914. }
  21915. }
  21916. }
  21917. bool MidiFile::writeTo (OutputStream& out)
  21918. {
  21919. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21920. out.writeIntBigEndian (6);
  21921. out.writeShortBigEndian (1); // type
  21922. out.writeShortBigEndian ((short) tracks.size());
  21923. out.writeShortBigEndian (timeFormat);
  21924. for (int i = 0; i < tracks.size(); ++i)
  21925. writeTrack (out, i);
  21926. out.flush();
  21927. return true;
  21928. }
  21929. void MidiFile::writeTrack (OutputStream& mainOut,
  21930. const int trackNum)
  21931. {
  21932. MemoryOutputStream out;
  21933. const MidiMessageSequence& ms = *tracks[trackNum];
  21934. int lastTick = 0;
  21935. char lastStatusByte = 0;
  21936. for (int i = 0; i < ms.getNumEvents(); ++i)
  21937. {
  21938. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21939. const int tick = roundToInt (mm.getTimeStamp());
  21940. const int delta = jmax (0, tick - lastTick);
  21941. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21942. lastTick = tick;
  21943. const char statusByte = *(mm.getRawData());
  21944. if ((statusByte == lastStatusByte)
  21945. && ((statusByte & 0xf0) != 0xf0)
  21946. && i > 0
  21947. && mm.getRawDataSize() > 1)
  21948. {
  21949. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21950. }
  21951. else
  21952. {
  21953. out.write (mm.getRawData(), mm.getRawDataSize());
  21954. }
  21955. lastStatusByte = statusByte;
  21956. }
  21957. out.writeByte (0);
  21958. const MidiMessage m (MidiMessage::endOfTrack());
  21959. out.write (m.getRawData(),
  21960. m.getRawDataSize());
  21961. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21962. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21963. mainOut.write (out.getData(), (int) out.getDataSize());
  21964. }
  21965. END_JUCE_NAMESPACE
  21966. /*** End of inlined file: juce_MidiFile.cpp ***/
  21967. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21968. BEGIN_JUCE_NAMESPACE
  21969. MidiKeyboardState::MidiKeyboardState()
  21970. {
  21971. zerostruct (noteStates);
  21972. }
  21973. MidiKeyboardState::~MidiKeyboardState()
  21974. {
  21975. }
  21976. void MidiKeyboardState::reset()
  21977. {
  21978. const ScopedLock sl (lock);
  21979. zerostruct (noteStates);
  21980. eventsToAdd.clear();
  21981. }
  21982. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21983. {
  21984. jassert (midiChannel >= 0 && midiChannel <= 16);
  21985. return ((unsigned int) n) < 128
  21986. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21987. }
  21988. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21989. {
  21990. return ((unsigned int) n) < 128
  21991. && (noteStates[n] & midiChannelMask) != 0;
  21992. }
  21993. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21994. {
  21995. jassert (midiChannel >= 0 && midiChannel <= 16);
  21996. jassert (((unsigned int) midiNoteNumber) < 128);
  21997. const ScopedLock sl (lock);
  21998. if (((unsigned int) midiNoteNumber) < 128)
  21999. {
  22000. const int timeNow = (int) Time::getMillisecondCounter();
  22001. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22002. eventsToAdd.clear (0, timeNow - 500);
  22003. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22004. }
  22005. }
  22006. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22007. {
  22008. if (((unsigned int) midiNoteNumber) < 128)
  22009. {
  22010. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22011. for (int i = listeners.size(); --i >= 0;)
  22012. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22013. }
  22014. }
  22015. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22016. {
  22017. const ScopedLock sl (lock);
  22018. if (isNoteOn (midiChannel, midiNoteNumber))
  22019. {
  22020. const int timeNow = (int) Time::getMillisecondCounter();
  22021. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22022. eventsToAdd.clear (0, timeNow - 500);
  22023. noteOffInternal (midiChannel, midiNoteNumber);
  22024. }
  22025. }
  22026. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22027. {
  22028. if (isNoteOn (midiChannel, midiNoteNumber))
  22029. {
  22030. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22031. for (int i = listeners.size(); --i >= 0;)
  22032. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22033. }
  22034. }
  22035. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22036. {
  22037. const ScopedLock sl (lock);
  22038. if (midiChannel <= 0)
  22039. {
  22040. for (int i = 1; i <= 16; ++i)
  22041. allNotesOff (i);
  22042. }
  22043. else
  22044. {
  22045. for (int i = 0; i < 128; ++i)
  22046. noteOff (midiChannel, i);
  22047. }
  22048. }
  22049. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22050. {
  22051. if (message.isNoteOn())
  22052. {
  22053. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22054. }
  22055. else if (message.isNoteOff())
  22056. {
  22057. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22058. }
  22059. else if (message.isAllNotesOff())
  22060. {
  22061. for (int i = 0; i < 128; ++i)
  22062. noteOffInternal (message.getChannel(), i);
  22063. }
  22064. }
  22065. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22066. const int startSample,
  22067. const int numSamples,
  22068. const bool injectIndirectEvents)
  22069. {
  22070. MidiBuffer::Iterator i (buffer);
  22071. MidiMessage message (0xf4, 0.0);
  22072. int time;
  22073. const ScopedLock sl (lock);
  22074. while (i.getNextEvent (message, time))
  22075. processNextMidiEvent (message);
  22076. if (injectIndirectEvents)
  22077. {
  22078. MidiBuffer::Iterator i2 (eventsToAdd);
  22079. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22080. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22081. while (i2.getNextEvent (message, time))
  22082. {
  22083. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22084. buffer.addEvent (message, startSample + pos);
  22085. }
  22086. }
  22087. eventsToAdd.clear();
  22088. }
  22089. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22090. {
  22091. const ScopedLock sl (lock);
  22092. listeners.addIfNotAlreadyThere (listener);
  22093. }
  22094. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22095. {
  22096. const ScopedLock sl (lock);
  22097. listeners.removeValue (listener);
  22098. }
  22099. END_JUCE_NAMESPACE
  22100. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22101. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22102. BEGIN_JUCE_NAMESPACE
  22103. int MidiMessage::readVariableLengthVal (const uint8* data,
  22104. int& numBytesUsed) throw()
  22105. {
  22106. numBytesUsed = 0;
  22107. int v = 0;
  22108. int i;
  22109. do
  22110. {
  22111. i = (int) *data++;
  22112. if (++numBytesUsed > 6)
  22113. break;
  22114. v = (v << 7) + (i & 0x7f);
  22115. } while (i & 0x80);
  22116. return v;
  22117. }
  22118. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22119. {
  22120. // this method only works for valid starting bytes of a short midi message
  22121. jassert (firstByte >= 0x80
  22122. && firstByte != 0xf0
  22123. && firstByte != 0xf7);
  22124. static const char messageLengths[] =
  22125. {
  22126. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22127. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22128. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22129. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22130. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22131. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22132. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22133. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22134. };
  22135. return messageLengths [firstByte & 0x7f];
  22136. }
  22137. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22138. : timeStamp (t),
  22139. size (dataSize)
  22140. {
  22141. jassert (dataSize > 0);
  22142. if (dataSize <= 4)
  22143. data = static_cast<uint8*> (preallocatedData.asBytes);
  22144. else
  22145. data = new uint8 [dataSize];
  22146. memcpy (data, d, dataSize);
  22147. // check that the length matches the data..
  22148. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22149. }
  22150. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22151. : timeStamp (t),
  22152. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22153. size (1)
  22154. {
  22155. data[0] = (uint8) byte1;
  22156. // check that the length matches the data..
  22157. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22158. }
  22159. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22160. : timeStamp (t),
  22161. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22162. size (2)
  22163. {
  22164. data[0] = (uint8) byte1;
  22165. data[1] = (uint8) byte2;
  22166. // check that the length matches the data..
  22167. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22168. }
  22169. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22170. : timeStamp (t),
  22171. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22172. size (3)
  22173. {
  22174. data[0] = (uint8) byte1;
  22175. data[1] = (uint8) byte2;
  22176. data[2] = (uint8) byte3;
  22177. // check that the length matches the data..
  22178. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22179. }
  22180. MidiMessage::MidiMessage (const MidiMessage& other)
  22181. : timeStamp (other.timeStamp),
  22182. size (other.size)
  22183. {
  22184. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22185. {
  22186. data = new uint8 [size];
  22187. memcpy (data, other.data, size);
  22188. }
  22189. else
  22190. {
  22191. data = static_cast<uint8*> (preallocatedData.asBytes);
  22192. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22193. }
  22194. }
  22195. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22196. : timeStamp (newTimeStamp),
  22197. size (other.size)
  22198. {
  22199. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22200. {
  22201. data = new uint8 [size];
  22202. memcpy (data, other.data, size);
  22203. }
  22204. else
  22205. {
  22206. data = static_cast<uint8*> (preallocatedData.asBytes);
  22207. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22208. }
  22209. }
  22210. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22211. : timeStamp (t),
  22212. data (static_cast<uint8*> (preallocatedData.asBytes))
  22213. {
  22214. const uint8* src = static_cast <const uint8*> (src_);
  22215. unsigned int byte = (unsigned int) *src;
  22216. if (byte < 0x80)
  22217. {
  22218. byte = (unsigned int) (uint8) lastStatusByte;
  22219. numBytesUsed = -1;
  22220. }
  22221. else
  22222. {
  22223. numBytesUsed = 0;
  22224. --sz;
  22225. ++src;
  22226. }
  22227. if (byte >= 0x80)
  22228. {
  22229. if (byte == 0xf0)
  22230. {
  22231. const uint8* d = src;
  22232. while (d < src + sz)
  22233. {
  22234. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22235. {
  22236. if (*d == 0xf7) // include an 0xf7 if we hit one
  22237. ++d;
  22238. break;
  22239. }
  22240. ++d;
  22241. }
  22242. size = 1 + (int) (d - src);
  22243. data = new uint8 [size];
  22244. *data = (uint8) byte;
  22245. memcpy (data + 1, src, size - 1);
  22246. }
  22247. else if (byte == 0xff)
  22248. {
  22249. int n;
  22250. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22251. size = jmin (sz + 1, n + 2 + bytesLeft);
  22252. data = new uint8 [size];
  22253. *data = (uint8) byte;
  22254. memcpy (data + 1, src, size - 1);
  22255. }
  22256. else
  22257. {
  22258. preallocatedData.asInt32 = 0;
  22259. size = getMessageLengthFromFirstByte ((uint8) byte);
  22260. data[0] = (uint8) byte;
  22261. if (size > 1)
  22262. {
  22263. data[1] = src[0];
  22264. if (size > 2)
  22265. data[2] = src[1];
  22266. }
  22267. }
  22268. numBytesUsed += size;
  22269. }
  22270. else
  22271. {
  22272. preallocatedData.asInt32 = 0;
  22273. size = 0;
  22274. }
  22275. }
  22276. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22277. {
  22278. if (this != &other)
  22279. {
  22280. timeStamp = other.timeStamp;
  22281. size = other.size;
  22282. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22283. delete[] data;
  22284. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22285. {
  22286. data = new uint8 [size];
  22287. memcpy (data, other.data, size);
  22288. }
  22289. else
  22290. {
  22291. data = static_cast<uint8*> (preallocatedData.asBytes);
  22292. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22293. }
  22294. }
  22295. return *this;
  22296. }
  22297. MidiMessage::~MidiMessage()
  22298. {
  22299. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22300. delete[] data;
  22301. }
  22302. int MidiMessage::getChannel() const throw()
  22303. {
  22304. if ((data[0] & 0xf0) != 0xf0)
  22305. return (data[0] & 0xf) + 1;
  22306. else
  22307. return 0;
  22308. }
  22309. bool MidiMessage::isForChannel (const int channel) const throw()
  22310. {
  22311. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22312. return ((data[0] & 0xf) == channel - 1)
  22313. && ((data[0] & 0xf0) != 0xf0);
  22314. }
  22315. void MidiMessage::setChannel (const int channel) throw()
  22316. {
  22317. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22318. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22319. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22320. | (uint8)(channel - 1));
  22321. }
  22322. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22323. {
  22324. return ((data[0] & 0xf0) == 0x90)
  22325. && (returnTrueForVelocity0 || data[2] != 0);
  22326. }
  22327. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22328. {
  22329. return ((data[0] & 0xf0) == 0x80)
  22330. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22331. }
  22332. bool MidiMessage::isNoteOnOrOff() const throw()
  22333. {
  22334. const int d = data[0] & 0xf0;
  22335. return (d == 0x90) || (d == 0x80);
  22336. }
  22337. int MidiMessage::getNoteNumber() const throw()
  22338. {
  22339. return data[1];
  22340. }
  22341. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22342. {
  22343. if (isNoteOnOrOff())
  22344. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22345. }
  22346. uint8 MidiMessage::getVelocity() const throw()
  22347. {
  22348. if (isNoteOnOrOff())
  22349. return data[2];
  22350. else
  22351. return 0;
  22352. }
  22353. float MidiMessage::getFloatVelocity() const throw()
  22354. {
  22355. return getVelocity() * (1.0f / 127.0f);
  22356. }
  22357. void MidiMessage::setVelocity (const float newVelocity) throw()
  22358. {
  22359. if (isNoteOnOrOff())
  22360. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22361. }
  22362. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22363. {
  22364. if (isNoteOnOrOff())
  22365. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22366. }
  22367. bool MidiMessage::isAftertouch() const throw()
  22368. {
  22369. return (data[0] & 0xf0) == 0xa0;
  22370. }
  22371. int MidiMessage::getAfterTouchValue() const throw()
  22372. {
  22373. return data[2];
  22374. }
  22375. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22376. const int noteNum,
  22377. const int aftertouchValue) throw()
  22378. {
  22379. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22380. jassert (((unsigned int) noteNum) <= 127);
  22381. jassert (((unsigned int) aftertouchValue) <= 127);
  22382. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22383. noteNum & 0x7f,
  22384. aftertouchValue & 0x7f);
  22385. }
  22386. bool MidiMessage::isChannelPressure() const throw()
  22387. {
  22388. return (data[0] & 0xf0) == 0xd0;
  22389. }
  22390. int MidiMessage::getChannelPressureValue() const throw()
  22391. {
  22392. jassert (isChannelPressure());
  22393. return data[1];
  22394. }
  22395. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22396. const int pressure) throw()
  22397. {
  22398. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22399. jassert (((unsigned int) pressure) <= 127);
  22400. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22401. pressure & 0x7f);
  22402. }
  22403. bool MidiMessage::isProgramChange() const throw()
  22404. {
  22405. return (data[0] & 0xf0) == 0xc0;
  22406. }
  22407. int MidiMessage::getProgramChangeNumber() const throw()
  22408. {
  22409. return data[1];
  22410. }
  22411. const MidiMessage MidiMessage::programChange (const int channel,
  22412. const int programNumber) throw()
  22413. {
  22414. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22415. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22416. programNumber & 0x7f);
  22417. }
  22418. bool MidiMessage::isPitchWheel() const throw()
  22419. {
  22420. return (data[0] & 0xf0) == 0xe0;
  22421. }
  22422. int MidiMessage::getPitchWheelValue() const throw()
  22423. {
  22424. return data[1] | (data[2] << 7);
  22425. }
  22426. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22427. const int position) throw()
  22428. {
  22429. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22430. jassert (((unsigned int) position) <= 0x3fff);
  22431. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22432. position & 127,
  22433. (position >> 7) & 127);
  22434. }
  22435. bool MidiMessage::isController() const throw()
  22436. {
  22437. return (data[0] & 0xf0) == 0xb0;
  22438. }
  22439. int MidiMessage::getControllerNumber() const throw()
  22440. {
  22441. jassert (isController());
  22442. return data[1];
  22443. }
  22444. int MidiMessage::getControllerValue() const throw()
  22445. {
  22446. jassert (isController());
  22447. return data[2];
  22448. }
  22449. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22450. const int controllerType,
  22451. const int value) throw()
  22452. {
  22453. // the channel must be between 1 and 16 inclusive
  22454. jassert (channel > 0 && channel <= 16);
  22455. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22456. controllerType & 127,
  22457. value & 127);
  22458. }
  22459. const MidiMessage MidiMessage::noteOn (const int channel,
  22460. const int noteNumber,
  22461. const float velocity) throw()
  22462. {
  22463. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22464. }
  22465. const MidiMessage MidiMessage::noteOn (const int channel,
  22466. const int noteNumber,
  22467. const uint8 velocity) throw()
  22468. {
  22469. jassert (channel > 0 && channel <= 16);
  22470. jassert (((unsigned int) noteNumber) <= 127);
  22471. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22472. noteNumber & 127,
  22473. jlimit (0, 127, roundToInt (velocity)));
  22474. }
  22475. const MidiMessage MidiMessage::noteOff (const int channel,
  22476. const int noteNumber) throw()
  22477. {
  22478. jassert (channel > 0 && channel <= 16);
  22479. jassert (((unsigned int) noteNumber) <= 127);
  22480. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22481. }
  22482. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22483. {
  22484. jassert (channel > 0 && channel <= 16);
  22485. return controllerEvent (channel, 123, 0);
  22486. }
  22487. bool MidiMessage::isAllNotesOff() const throw()
  22488. {
  22489. return (data[0] & 0xf0) == 0xb0
  22490. && data[1] == 123;
  22491. }
  22492. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22493. {
  22494. return controllerEvent (channel, 120, 0);
  22495. }
  22496. bool MidiMessage::isAllSoundOff() const throw()
  22497. {
  22498. return (data[0] & 0xf0) == 0xb0
  22499. && data[1] == 120;
  22500. }
  22501. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22502. {
  22503. return controllerEvent (channel, 121, 0);
  22504. }
  22505. const MidiMessage MidiMessage::masterVolume (const float volume)
  22506. {
  22507. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22508. uint8 buf[8];
  22509. buf[0] = 0xf0;
  22510. buf[1] = 0x7f;
  22511. buf[2] = 0x7f;
  22512. buf[3] = 0x04;
  22513. buf[4] = 0x01;
  22514. buf[5] = (uint8) (vol & 0x7f);
  22515. buf[6] = (uint8) (vol >> 7);
  22516. buf[7] = 0xf7;
  22517. return MidiMessage (buf, 8);
  22518. }
  22519. bool MidiMessage::isSysEx() const throw()
  22520. {
  22521. return *data == 0xf0;
  22522. }
  22523. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22524. {
  22525. MemoryBlock mm (dataSize + 2);
  22526. uint8* const m = static_cast <uint8*> (mm.getData());
  22527. m[0] = 0xf0;
  22528. memcpy (m + 1, sysexData, dataSize);
  22529. m[dataSize + 1] = 0xf7;
  22530. return MidiMessage (m, dataSize + 2);
  22531. }
  22532. const uint8* MidiMessage::getSysExData() const throw()
  22533. {
  22534. return (isSysEx()) ? getRawData() + 1 : 0;
  22535. }
  22536. int MidiMessage::getSysExDataSize() const throw()
  22537. {
  22538. return (isSysEx()) ? size - 2 : 0;
  22539. }
  22540. bool MidiMessage::isMetaEvent() const throw()
  22541. {
  22542. return *data == 0xff;
  22543. }
  22544. bool MidiMessage::isActiveSense() const throw()
  22545. {
  22546. return *data == 0xfe;
  22547. }
  22548. int MidiMessage::getMetaEventType() const throw()
  22549. {
  22550. if (*data != 0xff)
  22551. return -1;
  22552. else
  22553. return data[1];
  22554. }
  22555. int MidiMessage::getMetaEventLength() const throw()
  22556. {
  22557. if (*data == 0xff)
  22558. {
  22559. int n;
  22560. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22561. }
  22562. return 0;
  22563. }
  22564. const uint8* MidiMessage::getMetaEventData() const throw()
  22565. {
  22566. int n;
  22567. const uint8* d = data + 2;
  22568. readVariableLengthVal (d, n);
  22569. return d + n;
  22570. }
  22571. bool MidiMessage::isTrackMetaEvent() const throw()
  22572. {
  22573. return getMetaEventType() == 0;
  22574. }
  22575. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22576. {
  22577. return getMetaEventType() == 47;
  22578. }
  22579. bool MidiMessage::isTextMetaEvent() const throw()
  22580. {
  22581. const int t = getMetaEventType();
  22582. return t > 0 && t < 16;
  22583. }
  22584. const String MidiMessage::getTextFromTextMetaEvent() const
  22585. {
  22586. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22587. }
  22588. bool MidiMessage::isTrackNameEvent() const throw()
  22589. {
  22590. return (data[1] == 3)
  22591. && (*data == 0xff);
  22592. }
  22593. bool MidiMessage::isTempoMetaEvent() const throw()
  22594. {
  22595. return (data[1] == 81)
  22596. && (*data == 0xff);
  22597. }
  22598. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22599. {
  22600. return (data[1] == 0x20)
  22601. && (*data == 0xff)
  22602. && (data[2] == 1);
  22603. }
  22604. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22605. {
  22606. return data[3] + 1;
  22607. }
  22608. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22609. {
  22610. if (! isTempoMetaEvent())
  22611. return 0.0;
  22612. const uint8* const d = getMetaEventData();
  22613. return (((unsigned int) d[0] << 16)
  22614. | ((unsigned int) d[1] << 8)
  22615. | d[2])
  22616. / 1000000.0;
  22617. }
  22618. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22619. {
  22620. if (timeFormat > 0)
  22621. {
  22622. if (! isTempoMetaEvent())
  22623. return 0.5 / timeFormat;
  22624. return getTempoSecondsPerQuarterNote() / timeFormat;
  22625. }
  22626. else
  22627. {
  22628. const int frameCode = (-timeFormat) >> 8;
  22629. double framesPerSecond;
  22630. switch (frameCode)
  22631. {
  22632. case 24: framesPerSecond = 24.0; break;
  22633. case 25: framesPerSecond = 25.0; break;
  22634. case 29: framesPerSecond = 29.97; break;
  22635. case 30: framesPerSecond = 30.0; break;
  22636. default: framesPerSecond = 30.0; break;
  22637. }
  22638. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22639. }
  22640. }
  22641. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22642. {
  22643. uint8 d[8];
  22644. d[0] = 0xff;
  22645. d[1] = 81;
  22646. d[2] = 3;
  22647. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22648. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22649. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22650. return MidiMessage (d, 6, 0.0);
  22651. }
  22652. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22653. {
  22654. return (data[1] == 0x58)
  22655. && (*data == (uint8) 0xff);
  22656. }
  22657. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22658. {
  22659. if (isTimeSignatureMetaEvent())
  22660. {
  22661. const uint8* const d = getMetaEventData();
  22662. numerator = d[0];
  22663. denominator = 1 << d[1];
  22664. }
  22665. else
  22666. {
  22667. numerator = 4;
  22668. denominator = 4;
  22669. }
  22670. }
  22671. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22672. {
  22673. uint8 d[8];
  22674. d[0] = 0xff;
  22675. d[1] = 0x58;
  22676. d[2] = 0x04;
  22677. d[3] = (uint8) numerator;
  22678. int n = 1;
  22679. int powerOfTwo = 0;
  22680. while (n < denominator)
  22681. {
  22682. n <<= 1;
  22683. ++powerOfTwo;
  22684. }
  22685. d[4] = (uint8) powerOfTwo;
  22686. d[5] = 0x01;
  22687. d[6] = 96;
  22688. return MidiMessage (d, 7, 0.0);
  22689. }
  22690. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22691. {
  22692. uint8 d[8];
  22693. d[0] = 0xff;
  22694. d[1] = 0x20;
  22695. d[2] = 0x01;
  22696. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22697. return MidiMessage (d, 4, 0.0);
  22698. }
  22699. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22700. {
  22701. return getMetaEventType() == 89;
  22702. }
  22703. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22704. {
  22705. return (int) *getMetaEventData();
  22706. }
  22707. const MidiMessage MidiMessage::endOfTrack() throw()
  22708. {
  22709. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22710. }
  22711. bool MidiMessage::isSongPositionPointer() const throw()
  22712. {
  22713. return *data == 0xf2;
  22714. }
  22715. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22716. {
  22717. return data[1] | (data[2] << 7);
  22718. }
  22719. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22720. {
  22721. return MidiMessage (0xf2,
  22722. positionInMidiBeats & 127,
  22723. (positionInMidiBeats >> 7) & 127);
  22724. }
  22725. bool MidiMessage::isMidiStart() const throw()
  22726. {
  22727. return *data == 0xfa;
  22728. }
  22729. const MidiMessage MidiMessage::midiStart() throw()
  22730. {
  22731. return MidiMessage (0xfa);
  22732. }
  22733. bool MidiMessage::isMidiContinue() const throw()
  22734. {
  22735. return *data == 0xfb;
  22736. }
  22737. const MidiMessage MidiMessage::midiContinue() throw()
  22738. {
  22739. return MidiMessage (0xfb);
  22740. }
  22741. bool MidiMessage::isMidiStop() const throw()
  22742. {
  22743. return *data == 0xfc;
  22744. }
  22745. const MidiMessage MidiMessage::midiStop() throw()
  22746. {
  22747. return MidiMessage (0xfc);
  22748. }
  22749. bool MidiMessage::isMidiClock() const throw()
  22750. {
  22751. return *data == 0xf8;
  22752. }
  22753. const MidiMessage MidiMessage::midiClock() throw()
  22754. {
  22755. return MidiMessage (0xf8);
  22756. }
  22757. bool MidiMessage::isQuarterFrame() const throw()
  22758. {
  22759. return *data == 0xf1;
  22760. }
  22761. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22762. {
  22763. return ((int) data[1]) >> 4;
  22764. }
  22765. int MidiMessage::getQuarterFrameValue() const throw()
  22766. {
  22767. return ((int) data[1]) & 0x0f;
  22768. }
  22769. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22770. const int value) throw()
  22771. {
  22772. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22773. }
  22774. bool MidiMessage::isFullFrame() const throw()
  22775. {
  22776. return data[0] == 0xf0
  22777. && data[1] == 0x7f
  22778. && size >= 10
  22779. && data[3] == 0x01
  22780. && data[4] == 0x01;
  22781. }
  22782. void MidiMessage::getFullFrameParameters (int& hours,
  22783. int& minutes,
  22784. int& seconds,
  22785. int& frames,
  22786. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22787. {
  22788. jassert (isFullFrame());
  22789. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22790. hours = data[5] & 0x1f;
  22791. minutes = data[6];
  22792. seconds = data[7];
  22793. frames = data[8];
  22794. }
  22795. const MidiMessage MidiMessage::fullFrame (const int hours,
  22796. const int minutes,
  22797. const int seconds,
  22798. const int frames,
  22799. MidiMessage::SmpteTimecodeType timecodeType)
  22800. {
  22801. uint8 d[10];
  22802. d[0] = 0xf0;
  22803. d[1] = 0x7f;
  22804. d[2] = 0x7f;
  22805. d[3] = 0x01;
  22806. d[4] = 0x01;
  22807. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22808. d[6] = (uint8) minutes;
  22809. d[7] = (uint8) seconds;
  22810. d[8] = (uint8) frames;
  22811. d[9] = 0xf7;
  22812. return MidiMessage (d, 10, 0.0);
  22813. }
  22814. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22815. {
  22816. return data[0] == 0xf0
  22817. && data[1] == 0x7f
  22818. && data[3] == 0x06
  22819. && size > 5;
  22820. }
  22821. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22822. {
  22823. jassert (isMidiMachineControlMessage());
  22824. return (MidiMachineControlCommand) data[4];
  22825. }
  22826. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22827. {
  22828. uint8 d[6];
  22829. d[0] = 0xf0;
  22830. d[1] = 0x7f;
  22831. d[2] = 0x00;
  22832. d[3] = 0x06;
  22833. d[4] = (uint8) command;
  22834. d[5] = 0xf7;
  22835. return MidiMessage (d, 6, 0.0);
  22836. }
  22837. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22838. int& minutes,
  22839. int& seconds,
  22840. int& frames) const throw()
  22841. {
  22842. if (size >= 12
  22843. && data[0] == 0xf0
  22844. && data[1] == 0x7f
  22845. && data[3] == 0x06
  22846. && data[4] == 0x44
  22847. && data[5] == 0x06
  22848. && data[6] == 0x01)
  22849. {
  22850. hours = data[7] % 24; // (that some machines send out hours > 24)
  22851. minutes = data[8];
  22852. seconds = data[9];
  22853. frames = data[10];
  22854. return true;
  22855. }
  22856. return false;
  22857. }
  22858. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22859. int minutes,
  22860. int seconds,
  22861. int frames)
  22862. {
  22863. uint8 d[12];
  22864. d[0] = 0xf0;
  22865. d[1] = 0x7f;
  22866. d[2] = 0x00;
  22867. d[3] = 0x06;
  22868. d[4] = 0x44;
  22869. d[5] = 0x06;
  22870. d[6] = 0x01;
  22871. d[7] = (uint8) hours;
  22872. d[8] = (uint8) minutes;
  22873. d[9] = (uint8) seconds;
  22874. d[10] = (uint8) frames;
  22875. d[11] = 0xf7;
  22876. return MidiMessage (d, 12, 0.0);
  22877. }
  22878. const String MidiMessage::getMidiNoteName (int note,
  22879. bool useSharps,
  22880. bool includeOctaveNumber,
  22881. int octaveNumForMiddleC) throw()
  22882. {
  22883. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22884. "F", "F#", "G", "G#", "A",
  22885. "A#", "B" };
  22886. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22887. "F", "Gb", "G", "Ab", "A",
  22888. "Bb", "B" };
  22889. if (((unsigned int) note) < 128)
  22890. {
  22891. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22892. : flatNoteNames [note % 12]);
  22893. if (includeOctaveNumber)
  22894. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22895. else
  22896. return s;
  22897. }
  22898. return String::empty;
  22899. }
  22900. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22901. {
  22902. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22903. return 440.0 * pow (2.0, noteNumber / 12.0);
  22904. }
  22905. const String MidiMessage::getGMInstrumentName (int n) throw()
  22906. {
  22907. const char *names[] =
  22908. {
  22909. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22910. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22911. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22912. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22913. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22914. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22915. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22916. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22917. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22918. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22919. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22920. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22921. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22922. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22923. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22924. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22925. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22926. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22927. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22928. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22929. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22930. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22931. "Applause", "Gunshot"
  22932. };
  22933. return (((unsigned int) n) < 128) ? names[n]
  22934. : (const char*)0;
  22935. }
  22936. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22937. {
  22938. const char* names[] =
  22939. {
  22940. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22941. "Bass", "Strings", "Ensemble", "Brass",
  22942. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22943. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22944. };
  22945. return (((unsigned int) n) <= 15) ? names[n]
  22946. : (const char*)0;
  22947. }
  22948. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22949. {
  22950. const char* names[] =
  22951. {
  22952. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22953. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22954. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22955. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22956. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22957. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22958. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22959. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22960. "Mute Triangle", "Open Triangle"
  22961. };
  22962. return (n >= 35 && n <= 81) ? names [n - 35]
  22963. : (const char*)0;
  22964. }
  22965. const String MidiMessage::getControllerName (int n) throw()
  22966. {
  22967. const char* names[] =
  22968. {
  22969. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22970. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22971. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22972. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22973. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22974. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22975. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22976. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22977. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22978. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22979. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22980. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22981. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22982. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22983. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22984. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22985. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22986. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22987. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22989. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22990. "Poly Operation"
  22991. };
  22992. return (((unsigned int) n) < 128) ? names[n]
  22993. : (const char*)0;
  22994. }
  22995. END_JUCE_NAMESPACE
  22996. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22997. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22998. BEGIN_JUCE_NAMESPACE
  22999. MidiMessageCollector::MidiMessageCollector()
  23000. : lastCallbackTime (0),
  23001. sampleRate (44100.0001)
  23002. {
  23003. }
  23004. MidiMessageCollector::~MidiMessageCollector()
  23005. {
  23006. }
  23007. void MidiMessageCollector::reset (const double sampleRate_)
  23008. {
  23009. jassert (sampleRate_ > 0);
  23010. const ScopedLock sl (midiCallbackLock);
  23011. sampleRate = sampleRate_;
  23012. incomingMessages.clear();
  23013. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23014. }
  23015. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23016. {
  23017. // you need to call reset() to set the correct sample rate before using this object
  23018. jassert (sampleRate != 44100.0001);
  23019. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23020. // for details of what the number should be.
  23021. jassert (message.getTimeStamp() != 0);
  23022. const ScopedLock sl (midiCallbackLock);
  23023. const int sampleNumber
  23024. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23025. incomingMessages.addEvent (message, sampleNumber);
  23026. // if the messages don't get used for over a second, we'd better
  23027. // get rid of any old ones to avoid the queue getting too big
  23028. if (sampleNumber > sampleRate)
  23029. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23030. }
  23031. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23032. const int numSamples)
  23033. {
  23034. // you need to call reset() to set the correct sample rate before using this object
  23035. jassert (sampleRate != 44100.0001);
  23036. const double timeNow = Time::getMillisecondCounterHiRes();
  23037. const double msElapsed = timeNow - lastCallbackTime;
  23038. const ScopedLock sl (midiCallbackLock);
  23039. lastCallbackTime = timeNow;
  23040. if (! incomingMessages.isEmpty())
  23041. {
  23042. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23043. int startSample = 0;
  23044. int scale = 1 << 16;
  23045. const uint8* midiData;
  23046. int numBytes, samplePosition;
  23047. MidiBuffer::Iterator iter (incomingMessages);
  23048. if (numSourceSamples > numSamples)
  23049. {
  23050. // if our list of events is longer than the buffer we're being
  23051. // asked for, scale them down to squeeze them all in..
  23052. const int maxBlockLengthToUse = numSamples << 5;
  23053. if (numSourceSamples > maxBlockLengthToUse)
  23054. {
  23055. startSample = numSourceSamples - maxBlockLengthToUse;
  23056. numSourceSamples = maxBlockLengthToUse;
  23057. iter.setNextSamplePosition (startSample);
  23058. }
  23059. scale = (numSamples << 10) / numSourceSamples;
  23060. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23061. {
  23062. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23063. destBuffer.addEvent (midiData, numBytes,
  23064. jlimit (0, numSamples - 1, samplePosition));
  23065. }
  23066. }
  23067. else
  23068. {
  23069. // if our event list is shorter than the number we need, put them
  23070. // towards the end of the buffer
  23071. startSample = numSamples - numSourceSamples;
  23072. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23073. {
  23074. destBuffer.addEvent (midiData, numBytes,
  23075. jlimit (0, numSamples - 1, samplePosition + startSample));
  23076. }
  23077. }
  23078. incomingMessages.clear();
  23079. }
  23080. }
  23081. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23082. {
  23083. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23084. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23085. addMessageToQueue (m);
  23086. }
  23087. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23088. {
  23089. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23090. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23091. addMessageToQueue (m);
  23092. }
  23093. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23094. {
  23095. addMessageToQueue (message);
  23096. }
  23097. END_JUCE_NAMESPACE
  23098. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23099. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23100. BEGIN_JUCE_NAMESPACE
  23101. MidiMessageSequence::MidiMessageSequence()
  23102. {
  23103. }
  23104. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23105. {
  23106. list.ensureStorageAllocated (other.list.size());
  23107. for (int i = 0; i < other.list.size(); ++i)
  23108. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23109. }
  23110. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23111. {
  23112. MidiMessageSequence otherCopy (other);
  23113. swapWith (otherCopy);
  23114. return *this;
  23115. }
  23116. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23117. {
  23118. list.swapWithArray (other.list);
  23119. }
  23120. MidiMessageSequence::~MidiMessageSequence()
  23121. {
  23122. }
  23123. void MidiMessageSequence::clear()
  23124. {
  23125. list.clear();
  23126. }
  23127. int MidiMessageSequence::getNumEvents() const
  23128. {
  23129. return list.size();
  23130. }
  23131. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23132. {
  23133. return list [index];
  23134. }
  23135. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23136. {
  23137. const MidiEventHolder* const meh = list [index];
  23138. if (meh != 0 && meh->noteOffObject != 0)
  23139. return meh->noteOffObject->message.getTimeStamp();
  23140. else
  23141. return 0.0;
  23142. }
  23143. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23144. {
  23145. const MidiEventHolder* const meh = list [index];
  23146. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23147. }
  23148. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23149. {
  23150. return list.indexOf (event);
  23151. }
  23152. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23153. {
  23154. const int numEvents = list.size();
  23155. int i;
  23156. for (i = 0; i < numEvents; ++i)
  23157. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23158. break;
  23159. return i;
  23160. }
  23161. double MidiMessageSequence::getStartTime() const
  23162. {
  23163. if (list.size() > 0)
  23164. return list.getUnchecked(0)->message.getTimeStamp();
  23165. else
  23166. return 0;
  23167. }
  23168. double MidiMessageSequence::getEndTime() const
  23169. {
  23170. if (list.size() > 0)
  23171. return list.getLast()->message.getTimeStamp();
  23172. else
  23173. return 0;
  23174. }
  23175. double MidiMessageSequence::getEventTime (const int index) const
  23176. {
  23177. if (((unsigned int) index) < (unsigned int) list.size())
  23178. return list.getUnchecked (index)->message.getTimeStamp();
  23179. return 0.0;
  23180. }
  23181. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23182. double timeAdjustment)
  23183. {
  23184. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23185. timeAdjustment += newMessage.getTimeStamp();
  23186. newOne->message.setTimeStamp (timeAdjustment);
  23187. int i;
  23188. for (i = list.size(); --i >= 0;)
  23189. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23190. break;
  23191. list.insert (i + 1, newOne);
  23192. }
  23193. void MidiMessageSequence::deleteEvent (const int index,
  23194. const bool deleteMatchingNoteUp)
  23195. {
  23196. if (((unsigned int) index) < (unsigned int) list.size())
  23197. {
  23198. if (deleteMatchingNoteUp)
  23199. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23200. list.remove (index);
  23201. }
  23202. }
  23203. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23204. double timeAdjustment,
  23205. double firstAllowableTime,
  23206. double endOfAllowableDestTimes)
  23207. {
  23208. firstAllowableTime -= timeAdjustment;
  23209. endOfAllowableDestTimes -= timeAdjustment;
  23210. for (int i = 0; i < other.list.size(); ++i)
  23211. {
  23212. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23213. const double t = m.getTimeStamp();
  23214. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23215. {
  23216. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23217. newOne->message.setTimeStamp (timeAdjustment + t);
  23218. list.add (newOne);
  23219. }
  23220. }
  23221. sort();
  23222. }
  23223. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23224. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23225. {
  23226. const double diff = first->message.getTimeStamp()
  23227. - second->message.getTimeStamp();
  23228. return (diff > 0) - (diff < 0);
  23229. }
  23230. void MidiMessageSequence::sort()
  23231. {
  23232. list.sort (*this, true);
  23233. }
  23234. void MidiMessageSequence::updateMatchedPairs()
  23235. {
  23236. for (int i = 0; i < list.size(); ++i)
  23237. {
  23238. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23239. if (m1.isNoteOn())
  23240. {
  23241. list.getUnchecked(i)->noteOffObject = 0;
  23242. const int note = m1.getNoteNumber();
  23243. const int chan = m1.getChannel();
  23244. const int len = list.size();
  23245. for (int j = i + 1; j < len; ++j)
  23246. {
  23247. const MidiMessage& m = list.getUnchecked(j)->message;
  23248. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23249. {
  23250. if (m.isNoteOff())
  23251. {
  23252. list.getUnchecked(i)->noteOffObject = list[j];
  23253. break;
  23254. }
  23255. else if (m.isNoteOn())
  23256. {
  23257. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23258. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23259. list.getUnchecked(i)->noteOffObject = list[j];
  23260. break;
  23261. }
  23262. }
  23263. }
  23264. }
  23265. }
  23266. }
  23267. void MidiMessageSequence::addTimeToMessages (const double delta)
  23268. {
  23269. for (int i = list.size(); --i >= 0;)
  23270. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23271. + delta);
  23272. }
  23273. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23274. MidiMessageSequence& destSequence,
  23275. const bool alsoIncludeMetaEvents) const
  23276. {
  23277. for (int i = 0; i < list.size(); ++i)
  23278. {
  23279. const MidiMessage& mm = list.getUnchecked(i)->message;
  23280. if (mm.isForChannel (channelNumberToExtract)
  23281. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23282. {
  23283. destSequence.addEvent (mm);
  23284. }
  23285. }
  23286. }
  23287. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23288. {
  23289. for (int i = 0; i < list.size(); ++i)
  23290. {
  23291. const MidiMessage& mm = list.getUnchecked(i)->message;
  23292. if (mm.isSysEx())
  23293. destSequence.addEvent (mm);
  23294. }
  23295. }
  23296. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23297. {
  23298. for (int i = list.size(); --i >= 0;)
  23299. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23300. list.remove(i);
  23301. }
  23302. void MidiMessageSequence::deleteSysExMessages()
  23303. {
  23304. for (int i = list.size(); --i >= 0;)
  23305. if (list.getUnchecked(i)->message.isSysEx())
  23306. list.remove(i);
  23307. }
  23308. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23309. const double time,
  23310. OwnedArray<MidiMessage>& dest)
  23311. {
  23312. bool doneProg = false;
  23313. bool donePitchWheel = false;
  23314. Array <int> doneControllers;
  23315. doneControllers.ensureStorageAllocated (32);
  23316. for (int i = list.size(); --i >= 0;)
  23317. {
  23318. const MidiMessage& mm = list.getUnchecked(i)->message;
  23319. if (mm.isForChannel (channelNumber)
  23320. && mm.getTimeStamp() <= time)
  23321. {
  23322. if (mm.isProgramChange())
  23323. {
  23324. if (! doneProg)
  23325. {
  23326. dest.add (new MidiMessage (mm, 0.0));
  23327. doneProg = true;
  23328. }
  23329. }
  23330. else if (mm.isController())
  23331. {
  23332. if (! doneControllers.contains (mm.getControllerNumber()))
  23333. {
  23334. dest.add (new MidiMessage (mm, 0.0));
  23335. doneControllers.add (mm.getControllerNumber());
  23336. }
  23337. }
  23338. else if (mm.isPitchWheel())
  23339. {
  23340. if (! donePitchWheel)
  23341. {
  23342. dest.add (new MidiMessage (mm, 0.0));
  23343. donePitchWheel = true;
  23344. }
  23345. }
  23346. }
  23347. }
  23348. }
  23349. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23350. : message (message_),
  23351. noteOffObject (0)
  23352. {
  23353. }
  23354. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23355. {
  23356. }
  23357. END_JUCE_NAMESPACE
  23358. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23359. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23360. BEGIN_JUCE_NAMESPACE
  23361. AudioPluginFormat::AudioPluginFormat() throw()
  23362. {
  23363. }
  23364. AudioPluginFormat::~AudioPluginFormat()
  23365. {
  23366. }
  23367. END_JUCE_NAMESPACE
  23368. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23369. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23370. BEGIN_JUCE_NAMESPACE
  23371. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23372. {
  23373. }
  23374. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23375. {
  23376. clearSingletonInstance();
  23377. }
  23378. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23379. void AudioPluginFormatManager::addDefaultFormats()
  23380. {
  23381. #if JUCE_DEBUG
  23382. // you should only call this method once!
  23383. for (int i = formats.size(); --i >= 0;)
  23384. {
  23385. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23386. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23387. #endif
  23388. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23389. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23390. #endif
  23391. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23392. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23393. #endif
  23394. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23395. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23396. #endif
  23397. }
  23398. #endif
  23399. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23400. formats.add (new AudioUnitPluginFormat());
  23401. #endif
  23402. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23403. formats.add (new VSTPluginFormat());
  23404. #endif
  23405. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23406. formats.add (new DirectXPluginFormat());
  23407. #endif
  23408. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23409. formats.add (new LADSPAPluginFormat());
  23410. #endif
  23411. }
  23412. int AudioPluginFormatManager::getNumFormats() throw()
  23413. {
  23414. return formats.size();
  23415. }
  23416. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23417. {
  23418. return formats [index];
  23419. }
  23420. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23421. {
  23422. formats.add (format);
  23423. }
  23424. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23425. String& errorMessage) const
  23426. {
  23427. AudioPluginInstance* result = 0;
  23428. for (int i = 0; i < formats.size(); ++i)
  23429. {
  23430. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23431. if (result != 0)
  23432. break;
  23433. }
  23434. if (result == 0)
  23435. {
  23436. if (! doesPluginStillExist (description))
  23437. errorMessage = TRANS ("This plug-in file no longer exists");
  23438. else
  23439. errorMessage = TRANS ("This plug-in failed to load correctly");
  23440. }
  23441. return result;
  23442. }
  23443. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23444. {
  23445. for (int i = 0; i < formats.size(); ++i)
  23446. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23447. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23448. return false;
  23449. }
  23450. END_JUCE_NAMESPACE
  23451. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23452. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23453. #define JUCE_PLUGIN_HOST 1
  23454. BEGIN_JUCE_NAMESPACE
  23455. AudioPluginInstance::AudioPluginInstance()
  23456. {
  23457. }
  23458. AudioPluginInstance::~AudioPluginInstance()
  23459. {
  23460. }
  23461. END_JUCE_NAMESPACE
  23462. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23463. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23464. BEGIN_JUCE_NAMESPACE
  23465. KnownPluginList::KnownPluginList()
  23466. {
  23467. }
  23468. KnownPluginList::~KnownPluginList()
  23469. {
  23470. }
  23471. void KnownPluginList::clear()
  23472. {
  23473. if (types.size() > 0)
  23474. {
  23475. types.clear();
  23476. sendChangeMessage (this);
  23477. }
  23478. }
  23479. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23480. {
  23481. for (int i = 0; i < types.size(); ++i)
  23482. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23483. return types.getUnchecked(i);
  23484. return 0;
  23485. }
  23486. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23487. {
  23488. for (int i = 0; i < types.size(); ++i)
  23489. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23490. return types.getUnchecked(i);
  23491. return 0;
  23492. }
  23493. bool KnownPluginList::addType (const PluginDescription& type)
  23494. {
  23495. for (int i = types.size(); --i >= 0;)
  23496. {
  23497. if (types.getUnchecked(i)->isDuplicateOf (type))
  23498. {
  23499. // strange - found a duplicate plugin with different info..
  23500. jassert (types.getUnchecked(i)->name == type.name);
  23501. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23502. *types.getUnchecked(i) = type;
  23503. return false;
  23504. }
  23505. }
  23506. types.add (new PluginDescription (type));
  23507. sendChangeMessage (this);
  23508. return true;
  23509. }
  23510. void KnownPluginList::removeType (const int index) throw()
  23511. {
  23512. types.remove (index);
  23513. sendChangeMessage (this);
  23514. }
  23515. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23516. {
  23517. if (fileOrIdentifier.startsWithChar ('/')
  23518. || fileOrIdentifier[1] == ':')
  23519. {
  23520. return File (fileOrIdentifier).getLastModificationTime();
  23521. }
  23522. return Time (0);
  23523. }
  23524. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23525. {
  23526. return t1 != t2 || t1 == Time (0);
  23527. }
  23528. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23529. {
  23530. if (getTypeForFile (fileOrIdentifier) == 0)
  23531. return false;
  23532. for (int i = types.size(); --i >= 0;)
  23533. {
  23534. const PluginDescription* const d = types.getUnchecked(i);
  23535. if (d->fileOrIdentifier == fileOrIdentifier
  23536. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23537. {
  23538. return false;
  23539. }
  23540. }
  23541. return true;
  23542. }
  23543. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23544. const bool dontRescanIfAlreadyInList,
  23545. OwnedArray <PluginDescription>& typesFound,
  23546. AudioPluginFormat& format)
  23547. {
  23548. bool addedOne = false;
  23549. if (dontRescanIfAlreadyInList
  23550. && getTypeForFile (fileOrIdentifier) != 0)
  23551. {
  23552. bool needsRescanning = false;
  23553. for (int i = types.size(); --i >= 0;)
  23554. {
  23555. const PluginDescription* const d = types.getUnchecked(i);
  23556. if (d->fileOrIdentifier == fileOrIdentifier)
  23557. {
  23558. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23559. needsRescanning = true;
  23560. else
  23561. typesFound.add (new PluginDescription (*d));
  23562. }
  23563. }
  23564. if (! needsRescanning)
  23565. return false;
  23566. }
  23567. OwnedArray <PluginDescription> found;
  23568. format.findAllTypesForFile (found, fileOrIdentifier);
  23569. for (int i = 0; i < found.size(); ++i)
  23570. {
  23571. PluginDescription* const desc = found.getUnchecked(i);
  23572. jassert (desc != 0);
  23573. if (addType (*desc))
  23574. addedOne = true;
  23575. typesFound.add (new PluginDescription (*desc));
  23576. }
  23577. return addedOne;
  23578. }
  23579. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23580. OwnedArray <PluginDescription>& typesFound)
  23581. {
  23582. for (int i = 0; i < files.size(); ++i)
  23583. {
  23584. bool loaded = false;
  23585. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23586. {
  23587. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23588. if (scanAndAddFile (files[i], true, typesFound, *format))
  23589. loaded = true;
  23590. }
  23591. if (! loaded)
  23592. {
  23593. const File f (files[i]);
  23594. if (f.isDirectory())
  23595. {
  23596. StringArray s;
  23597. {
  23598. Array<File> subFiles;
  23599. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23600. for (int j = 0; j < subFiles.size(); ++j)
  23601. s.add (subFiles.getReference(j).getFullPathName());
  23602. }
  23603. scanAndAddDragAndDroppedFiles (s, typesFound);
  23604. }
  23605. }
  23606. }
  23607. }
  23608. class PluginSorter
  23609. {
  23610. public:
  23611. KnownPluginList::SortMethod method;
  23612. PluginSorter() throw() {}
  23613. int compareElements (const PluginDescription* const first,
  23614. const PluginDescription* const second) const throw()
  23615. {
  23616. int diff = 0;
  23617. if (method == KnownPluginList::sortByCategory)
  23618. diff = first->category.compareLexicographically (second->category);
  23619. else if (method == KnownPluginList::sortByManufacturer)
  23620. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23621. else if (method == KnownPluginList::sortByFileSystemLocation)
  23622. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23623. .upToLastOccurrenceOf ("/", false, false)
  23624. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23625. .upToLastOccurrenceOf ("/", false, false));
  23626. if (diff == 0)
  23627. diff = first->name.compareLexicographically (second->name);
  23628. return diff;
  23629. }
  23630. };
  23631. void KnownPluginList::sort (const SortMethod method)
  23632. {
  23633. if (method != defaultOrder)
  23634. {
  23635. PluginSorter sorter;
  23636. sorter.method = method;
  23637. types.sort (sorter, true);
  23638. sendChangeMessage (this);
  23639. }
  23640. }
  23641. XmlElement* KnownPluginList::createXml() const
  23642. {
  23643. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23644. for (int i = 0; i < types.size(); ++i)
  23645. e->addChildElement (types.getUnchecked(i)->createXml());
  23646. return e;
  23647. }
  23648. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23649. {
  23650. clear();
  23651. if (xml.hasTagName ("KNOWNPLUGINS"))
  23652. {
  23653. forEachXmlChildElement (xml, e)
  23654. {
  23655. PluginDescription info;
  23656. if (info.loadFromXml (*e))
  23657. addType (info);
  23658. }
  23659. }
  23660. }
  23661. const int menuIdBase = 0x324503f4;
  23662. // This is used to turn a bunch of paths into a nested menu structure.
  23663. struct PluginFilesystemTree
  23664. {
  23665. private:
  23666. String folder;
  23667. OwnedArray <PluginFilesystemTree> subFolders;
  23668. Array <PluginDescription*> plugins;
  23669. void addPlugin (PluginDescription* const pd, const String& path)
  23670. {
  23671. if (path.isEmpty())
  23672. {
  23673. plugins.add (pd);
  23674. }
  23675. else
  23676. {
  23677. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23678. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23679. for (int i = subFolders.size(); --i >= 0;)
  23680. {
  23681. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23682. {
  23683. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23684. return;
  23685. }
  23686. }
  23687. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23688. newFolder->folder = firstSubFolder;
  23689. subFolders.add (newFolder);
  23690. newFolder->addPlugin (pd, remainingPath);
  23691. }
  23692. }
  23693. // removes any deeply nested folders that don't contain any actual plugins
  23694. void optimise()
  23695. {
  23696. for (int i = subFolders.size(); --i >= 0;)
  23697. {
  23698. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23699. sub->optimise();
  23700. if (sub->plugins.size() == 0)
  23701. {
  23702. for (int j = 0; j < sub->subFolders.size(); ++j)
  23703. subFolders.add (sub->subFolders.getUnchecked(j));
  23704. sub->subFolders.clear (false);
  23705. subFolders.remove (i);
  23706. }
  23707. }
  23708. }
  23709. public:
  23710. void buildTree (const Array <PluginDescription*>& allPlugins)
  23711. {
  23712. for (int i = 0; i < allPlugins.size(); ++i)
  23713. {
  23714. String path (allPlugins.getUnchecked(i)
  23715. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23716. .upToLastOccurrenceOf ("/", false, false));
  23717. if (path.substring (1, 2) == ":")
  23718. path = path.substring (2);
  23719. addPlugin (allPlugins.getUnchecked(i), path);
  23720. }
  23721. optimise();
  23722. }
  23723. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23724. {
  23725. int i;
  23726. for (i = 0; i < subFolders.size(); ++i)
  23727. {
  23728. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23729. PopupMenu subMenu;
  23730. sub->addToMenu (subMenu, allPlugins);
  23731. #if JUCE_MAC
  23732. // avoid the special AU formatting nonsense on Mac..
  23733. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23734. #else
  23735. m.addSubMenu (sub->folder, subMenu);
  23736. #endif
  23737. }
  23738. for (i = 0; i < plugins.size(); ++i)
  23739. {
  23740. PluginDescription* const plugin = plugins.getUnchecked(i);
  23741. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23742. plugin->name, true, false);
  23743. }
  23744. }
  23745. };
  23746. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23747. {
  23748. Array <PluginDescription*> sorted;
  23749. {
  23750. PluginSorter sorter;
  23751. sorter.method = sortMethod;
  23752. for (int i = 0; i < types.size(); ++i)
  23753. sorted.addSorted (sorter, types.getUnchecked(i));
  23754. }
  23755. if (sortMethod == sortByCategory
  23756. || sortMethod == sortByManufacturer)
  23757. {
  23758. String lastSubMenuName;
  23759. PopupMenu sub;
  23760. for (int i = 0; i < sorted.size(); ++i)
  23761. {
  23762. const PluginDescription* const pd = sorted.getUnchecked(i);
  23763. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23764. : pd->manufacturerName);
  23765. if (! thisSubMenuName.containsNonWhitespaceChars())
  23766. thisSubMenuName = "Other";
  23767. if (thisSubMenuName != lastSubMenuName)
  23768. {
  23769. if (sub.getNumItems() > 0)
  23770. {
  23771. menu.addSubMenu (lastSubMenuName, sub);
  23772. sub.clear();
  23773. }
  23774. lastSubMenuName = thisSubMenuName;
  23775. }
  23776. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23777. }
  23778. if (sub.getNumItems() > 0)
  23779. menu.addSubMenu (lastSubMenuName, sub);
  23780. }
  23781. else if (sortMethod == sortByFileSystemLocation)
  23782. {
  23783. PluginFilesystemTree root;
  23784. root.buildTree (sorted);
  23785. root.addToMenu (menu, types);
  23786. }
  23787. else
  23788. {
  23789. for (int i = 0; i < sorted.size(); ++i)
  23790. {
  23791. const PluginDescription* const pd = sorted.getUnchecked(i);
  23792. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23793. }
  23794. }
  23795. }
  23796. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23797. {
  23798. const int i = menuResultCode - menuIdBase;
  23799. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23800. }
  23801. END_JUCE_NAMESPACE
  23802. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23803. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23804. BEGIN_JUCE_NAMESPACE
  23805. PluginDescription::PluginDescription() throw()
  23806. : uid (0),
  23807. isInstrument (false),
  23808. numInputChannels (0),
  23809. numOutputChannels (0)
  23810. {
  23811. }
  23812. PluginDescription::~PluginDescription() throw()
  23813. {
  23814. }
  23815. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23816. : name (other.name),
  23817. pluginFormatName (other.pluginFormatName),
  23818. category (other.category),
  23819. manufacturerName (other.manufacturerName),
  23820. version (other.version),
  23821. fileOrIdentifier (other.fileOrIdentifier),
  23822. lastFileModTime (other.lastFileModTime),
  23823. uid (other.uid),
  23824. isInstrument (other.isInstrument),
  23825. numInputChannels (other.numInputChannels),
  23826. numOutputChannels (other.numOutputChannels)
  23827. {
  23828. }
  23829. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23830. {
  23831. name = other.name;
  23832. pluginFormatName = other.pluginFormatName;
  23833. category = other.category;
  23834. manufacturerName = other.manufacturerName;
  23835. version = other.version;
  23836. fileOrIdentifier = other.fileOrIdentifier;
  23837. uid = other.uid;
  23838. isInstrument = other.isInstrument;
  23839. lastFileModTime = other.lastFileModTime;
  23840. numInputChannels = other.numInputChannels;
  23841. numOutputChannels = other.numOutputChannels;
  23842. return *this;
  23843. }
  23844. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23845. {
  23846. return fileOrIdentifier == other.fileOrIdentifier
  23847. && uid == other.uid;
  23848. }
  23849. const String PluginDescription::createIdentifierString() const throw()
  23850. {
  23851. return pluginFormatName
  23852. + "-" + name
  23853. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23854. + "-" + String::toHexString (uid);
  23855. }
  23856. XmlElement* PluginDescription::createXml() const
  23857. {
  23858. XmlElement* const e = new XmlElement ("PLUGIN");
  23859. e->setAttribute ("name", name);
  23860. e->setAttribute ("format", pluginFormatName);
  23861. e->setAttribute ("category", category);
  23862. e->setAttribute ("manufacturer", manufacturerName);
  23863. e->setAttribute ("version", version);
  23864. e->setAttribute ("file", fileOrIdentifier);
  23865. e->setAttribute ("uid", String::toHexString (uid));
  23866. e->setAttribute ("isInstrument", isInstrument);
  23867. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23868. e->setAttribute ("numInputs", numInputChannels);
  23869. e->setAttribute ("numOutputs", numOutputChannels);
  23870. return e;
  23871. }
  23872. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23873. {
  23874. if (xml.hasTagName ("PLUGIN"))
  23875. {
  23876. name = xml.getStringAttribute ("name");
  23877. pluginFormatName = xml.getStringAttribute ("format");
  23878. category = xml.getStringAttribute ("category");
  23879. manufacturerName = xml.getStringAttribute ("manufacturer");
  23880. version = xml.getStringAttribute ("version");
  23881. fileOrIdentifier = xml.getStringAttribute ("file");
  23882. uid = xml.getStringAttribute ("uid").getHexValue32();
  23883. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23884. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23885. numInputChannels = xml.getIntAttribute ("numInputs");
  23886. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23887. return true;
  23888. }
  23889. return false;
  23890. }
  23891. END_JUCE_NAMESPACE
  23892. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23893. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23894. BEGIN_JUCE_NAMESPACE
  23895. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23896. AudioPluginFormat& formatToLookFor,
  23897. FileSearchPath directoriesToSearch,
  23898. const bool recursive,
  23899. const File& deadMansPedalFile_)
  23900. : list (listToAddTo),
  23901. format (formatToLookFor),
  23902. deadMansPedalFile (deadMansPedalFile_),
  23903. nextIndex (0),
  23904. progress (0)
  23905. {
  23906. directoriesToSearch.removeRedundantPaths();
  23907. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23908. // If any plugins have crashed recently when being loaded, move them to the
  23909. // end of the list to give the others a chance to load correctly..
  23910. const StringArray crashedPlugins (getDeadMansPedalFile());
  23911. for (int i = 0; i < crashedPlugins.size(); ++i)
  23912. {
  23913. const String f = crashedPlugins[i];
  23914. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23915. if (f == filesOrIdentifiersToScan[j])
  23916. filesOrIdentifiersToScan.move (j, -1);
  23917. }
  23918. }
  23919. PluginDirectoryScanner::~PluginDirectoryScanner()
  23920. {
  23921. }
  23922. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23923. {
  23924. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23925. }
  23926. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23927. {
  23928. String file (filesOrIdentifiersToScan [nextIndex]);
  23929. if (file.isNotEmpty())
  23930. {
  23931. if (! list.isListingUpToDate (file))
  23932. {
  23933. OwnedArray <PluginDescription> typesFound;
  23934. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23935. StringArray crashedPlugins (getDeadMansPedalFile());
  23936. crashedPlugins.removeString (file);
  23937. crashedPlugins.add (file);
  23938. setDeadMansPedalFile (crashedPlugins);
  23939. list.scanAndAddFile (file,
  23940. dontRescanIfAlreadyInList,
  23941. typesFound,
  23942. format);
  23943. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23944. crashedPlugins.removeString (file);
  23945. setDeadMansPedalFile (crashedPlugins);
  23946. if (typesFound.size() == 0)
  23947. failedFiles.add (file);
  23948. }
  23949. ++nextIndex;
  23950. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23951. }
  23952. return nextIndex < filesOrIdentifiersToScan.size();
  23953. }
  23954. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23955. {
  23956. StringArray lines;
  23957. if (deadMansPedalFile != File::nonexistent)
  23958. {
  23959. lines.addLines (deadMansPedalFile.loadFileAsString());
  23960. lines.removeEmptyStrings();
  23961. }
  23962. return lines;
  23963. }
  23964. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23965. {
  23966. if (deadMansPedalFile != File::nonexistent)
  23967. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23968. }
  23969. END_JUCE_NAMESPACE
  23970. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23971. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23972. BEGIN_JUCE_NAMESPACE
  23973. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23974. const File& deadMansPedalFile_,
  23975. PropertiesFile* const propertiesToUse_)
  23976. : list (listToEdit),
  23977. deadMansPedalFile (deadMansPedalFile_),
  23978. propertiesToUse (propertiesToUse_)
  23979. {
  23980. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23981. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23982. optionsButton->addButtonListener (this);
  23983. optionsButton->setTriggeredOnMouseDown (true);
  23984. setSize (400, 600);
  23985. list.addChangeListener (this);
  23986. changeListenerCallback (0);
  23987. }
  23988. PluginListComponent::~PluginListComponent()
  23989. {
  23990. list.removeChangeListener (this);
  23991. deleteAllChildren();
  23992. }
  23993. void PluginListComponent::resized()
  23994. {
  23995. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23996. optionsButton->changeWidthToFitText (24);
  23997. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23998. }
  23999. void PluginListComponent::changeListenerCallback (void*)
  24000. {
  24001. listBox->updateContent();
  24002. listBox->repaint();
  24003. }
  24004. int PluginListComponent::getNumRows()
  24005. {
  24006. return list.getNumTypes();
  24007. }
  24008. void PluginListComponent::paintListBoxItem (int row,
  24009. Graphics& g,
  24010. int width, int height,
  24011. bool rowIsSelected)
  24012. {
  24013. if (rowIsSelected)
  24014. g.fillAll (findColour (TextEditor::highlightColourId));
  24015. const PluginDescription* const pd = list.getType (row);
  24016. if (pd != 0)
  24017. {
  24018. GlyphArrangement ga;
  24019. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24020. g.setColour (Colours::black);
  24021. ga.draw (g);
  24022. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24023. String desc;
  24024. desc << pd->pluginFormatName
  24025. << (pd->isInstrument ? " instrument" : " effect")
  24026. << " - "
  24027. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24028. << " / "
  24029. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24030. if (pd->manufacturerName.isNotEmpty())
  24031. desc << " - " << pd->manufacturerName;
  24032. if (pd->version.isNotEmpty())
  24033. desc << " - " << pd->version;
  24034. if (pd->category.isNotEmpty())
  24035. desc << " - category: '" << pd->category << '\'';
  24036. g.setColour (Colours::grey);
  24037. ga.clear();
  24038. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24039. ga.draw (g);
  24040. }
  24041. }
  24042. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24043. {
  24044. list.removeType (lastRowSelected);
  24045. }
  24046. void PluginListComponent::buttonClicked (Button* b)
  24047. {
  24048. if (optionsButton == b)
  24049. {
  24050. PopupMenu menu;
  24051. menu.addItem (1, TRANS("Clear list"));
  24052. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24053. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24054. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24055. menu.addSeparator();
  24056. menu.addItem (2, TRANS("Sort alphabetically"));
  24057. menu.addItem (3, TRANS("Sort by category"));
  24058. menu.addItem (4, TRANS("Sort by manufacturer"));
  24059. menu.addSeparator();
  24060. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24061. {
  24062. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24063. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24064. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24065. }
  24066. const int r = menu.showAt (optionsButton);
  24067. if (r == 1)
  24068. {
  24069. list.clear();
  24070. }
  24071. else if (r == 2)
  24072. {
  24073. list.sort (KnownPluginList::sortAlphabetically);
  24074. }
  24075. else if (r == 3)
  24076. {
  24077. list.sort (KnownPluginList::sortByCategory);
  24078. }
  24079. else if (r == 4)
  24080. {
  24081. list.sort (KnownPluginList::sortByManufacturer);
  24082. }
  24083. else if (r == 5)
  24084. {
  24085. const SparseSet <int> selected (listBox->getSelectedRows());
  24086. for (int i = list.getNumTypes(); --i >= 0;)
  24087. if (selected.contains (i))
  24088. list.removeType (i);
  24089. }
  24090. else if (r == 6)
  24091. {
  24092. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24093. if (desc != 0)
  24094. {
  24095. if (File (desc->fileOrIdentifier).existsAsFile())
  24096. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24097. }
  24098. }
  24099. else if (r == 7)
  24100. {
  24101. for (int i = list.getNumTypes(); --i >= 0;)
  24102. {
  24103. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24104. {
  24105. list.removeType (i);
  24106. }
  24107. }
  24108. }
  24109. else if (r != 0)
  24110. {
  24111. typeToScan = r - 10;
  24112. startTimer (1);
  24113. }
  24114. }
  24115. }
  24116. void PluginListComponent::timerCallback()
  24117. {
  24118. stopTimer();
  24119. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24120. }
  24121. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24122. {
  24123. return true;
  24124. }
  24125. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24126. {
  24127. OwnedArray <PluginDescription> typesFound;
  24128. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24129. }
  24130. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24131. {
  24132. if (format == 0)
  24133. return;
  24134. FileSearchPath path (format->getDefaultLocationsToSearch());
  24135. if (propertiesToUse != 0)
  24136. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24137. {
  24138. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24139. FileSearchPathListComponent pathList;
  24140. pathList.setSize (500, 300);
  24141. pathList.setPath (path);
  24142. aw.addCustomComponent (&pathList);
  24143. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24144. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24145. if (aw.runModalLoop() == 0)
  24146. return;
  24147. path = pathList.getPath();
  24148. }
  24149. if (propertiesToUse != 0)
  24150. {
  24151. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24152. propertiesToUse->saveIfNeeded();
  24153. }
  24154. double progress = 0.0;
  24155. AlertWindow aw (TRANS("Scanning for plugins..."),
  24156. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24157. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24158. aw.addProgressBarComponent (progress);
  24159. aw.enterModalState();
  24160. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24161. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24162. for (;;)
  24163. {
  24164. aw.setMessage (TRANS("Testing:\n\n")
  24165. + scanner.getNextPluginFileThatWillBeScanned());
  24166. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24167. if (! scanner.scanNextFile (true))
  24168. break;
  24169. if (! aw.isCurrentlyModal())
  24170. break;
  24171. progress = scanner.getProgress();
  24172. }
  24173. if (scanner.getFailedFiles().size() > 0)
  24174. {
  24175. StringArray shortNames;
  24176. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24177. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24178. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24179. TRANS("Scan complete"),
  24180. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24181. + shortNames.joinIntoString (", "));
  24182. }
  24183. }
  24184. END_JUCE_NAMESPACE
  24185. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24186. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24187. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24188. #include <AudioUnit/AudioUnit.h>
  24189. #include <AudioUnit/AUCocoaUIView.h>
  24190. #include <CoreAudioKit/AUGenericView.h>
  24191. #if JUCE_SUPPORT_CARBON
  24192. #include <AudioToolbox/AudioUnitUtilities.h>
  24193. #include <AudioUnit/AudioUnitCarbonView.h>
  24194. #endif
  24195. BEGIN_JUCE_NAMESPACE
  24196. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24197. #endif
  24198. #if JUCE_MAC
  24199. // Change this to disable logging of various activities
  24200. #ifndef AU_LOGGING
  24201. #define AU_LOGGING 1
  24202. #endif
  24203. #if AU_LOGGING
  24204. #define log(a) Logger::writeToLog(a);
  24205. #else
  24206. #define log(a)
  24207. #endif
  24208. namespace AudioUnitFormatHelpers
  24209. {
  24210. static int insideCallback = 0;
  24211. static const String osTypeToString (OSType type)
  24212. {
  24213. char s[4];
  24214. s[0] = (char) (((uint32) type) >> 24);
  24215. s[1] = (char) (((uint32) type) >> 16);
  24216. s[2] = (char) (((uint32) type) >> 8);
  24217. s[3] = (char) ((uint32) type);
  24218. return String (s, 4);
  24219. }
  24220. static OSType stringToOSType (const String& s1)
  24221. {
  24222. const String s (s1 + " ");
  24223. return (((OSType) (unsigned char) s[0]) << 24)
  24224. | (((OSType) (unsigned char) s[1]) << 16)
  24225. | (((OSType) (unsigned char) s[2]) << 8)
  24226. | ((OSType) (unsigned char) s[3]);
  24227. }
  24228. static const char* auIdentifierPrefix = "AudioUnit:";
  24229. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24230. {
  24231. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24232. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24233. String s (auIdentifierPrefix);
  24234. if (desc.componentType == kAudioUnitType_MusicDevice)
  24235. s << "Synths/";
  24236. else if (desc.componentType == kAudioUnitType_MusicEffect
  24237. || desc.componentType == kAudioUnitType_Effect)
  24238. s << "Effects/";
  24239. else if (desc.componentType == kAudioUnitType_Generator)
  24240. s << "Generators/";
  24241. else if (desc.componentType == kAudioUnitType_Panner)
  24242. s << "Panners/";
  24243. s << osTypeToString (desc.componentType) << ","
  24244. << osTypeToString (desc.componentSubType) << ","
  24245. << osTypeToString (desc.componentManufacturer);
  24246. return s;
  24247. }
  24248. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24249. {
  24250. Handle componentNameHandle = NewHandle (sizeof (void*));
  24251. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24252. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24253. {
  24254. ComponentDescription desc;
  24255. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24256. {
  24257. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24258. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24259. if (nameString != 0 && nameString[0] != 0)
  24260. {
  24261. const String all ((const char*) nameString + 1, nameString[0]);
  24262. DBG ("name: "+ all);
  24263. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24264. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24265. }
  24266. if (infoString != 0 && infoString[0] != 0)
  24267. {
  24268. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24269. }
  24270. if (name.isEmpty())
  24271. name = "<Unknown>";
  24272. }
  24273. DisposeHandle (componentNameHandle);
  24274. DisposeHandle (componentInfoHandle);
  24275. }
  24276. }
  24277. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24278. String& name, String& version, String& manufacturer)
  24279. {
  24280. zerostruct (desc);
  24281. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24282. {
  24283. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24284. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24285. StringArray tokens;
  24286. tokens.addTokens (s, ",", String::empty);
  24287. tokens.trim();
  24288. tokens.removeEmptyStrings();
  24289. if (tokens.size() == 3)
  24290. {
  24291. desc.componentType = stringToOSType (tokens[0]);
  24292. desc.componentSubType = stringToOSType (tokens[1]);
  24293. desc.componentManufacturer = stringToOSType (tokens[2]);
  24294. ComponentRecord* comp = FindNextComponent (0, &desc);
  24295. if (comp != 0)
  24296. {
  24297. getAUDetails (comp, name, manufacturer);
  24298. return true;
  24299. }
  24300. }
  24301. }
  24302. return false;
  24303. }
  24304. }
  24305. class AudioUnitPluginWindowCarbon;
  24306. class AudioUnitPluginWindowCocoa;
  24307. class AudioUnitPluginInstance : public AudioPluginInstance
  24308. {
  24309. public:
  24310. ~AudioUnitPluginInstance();
  24311. // AudioPluginInstance methods:
  24312. void fillInPluginDescription (PluginDescription& desc) const
  24313. {
  24314. desc.name = pluginName;
  24315. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24316. desc.uid = ((int) componentDesc.componentType)
  24317. ^ ((int) componentDesc.componentSubType)
  24318. ^ ((int) componentDesc.componentManufacturer);
  24319. desc.lastFileModTime = 0;
  24320. desc.pluginFormatName = "AudioUnit";
  24321. desc.category = getCategory();
  24322. desc.manufacturerName = manufacturer;
  24323. desc.version = version;
  24324. desc.numInputChannels = getNumInputChannels();
  24325. desc.numOutputChannels = getNumOutputChannels();
  24326. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24327. }
  24328. const String getName() const { return pluginName; }
  24329. bool acceptsMidi() const { return wantsMidiMessages; }
  24330. bool producesMidi() const { return false; }
  24331. // AudioProcessor methods:
  24332. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24333. void releaseResources();
  24334. void processBlock (AudioSampleBuffer& buffer,
  24335. MidiBuffer& midiMessages);
  24336. AudioProcessorEditor* createEditor();
  24337. const String getInputChannelName (const int index) const;
  24338. bool isInputChannelStereoPair (int index) const;
  24339. const String getOutputChannelName (const int index) const;
  24340. bool isOutputChannelStereoPair (int index) const;
  24341. int getNumParameters();
  24342. float getParameter (int index);
  24343. void setParameter (int index, float newValue);
  24344. const String getParameterName (int index);
  24345. const String getParameterText (int index);
  24346. bool isParameterAutomatable (int index) const;
  24347. int getNumPrograms();
  24348. int getCurrentProgram();
  24349. void setCurrentProgram (int index);
  24350. const String getProgramName (int index);
  24351. void changeProgramName (int index, const String& newName);
  24352. void getStateInformation (MemoryBlock& destData);
  24353. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24354. void setStateInformation (const void* data, int sizeInBytes);
  24355. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24356. juce_UseDebuggingNewOperator
  24357. private:
  24358. friend class AudioUnitPluginWindowCarbon;
  24359. friend class AudioUnitPluginWindowCocoa;
  24360. friend class AudioUnitPluginFormat;
  24361. ComponentDescription componentDesc;
  24362. String pluginName, manufacturer, version;
  24363. String fileOrIdentifier;
  24364. CriticalSection lock;
  24365. bool initialised, wantsMidiMessages, wasPlaying;
  24366. HeapBlock <AudioBufferList> outputBufferList;
  24367. AudioTimeStamp timeStamp;
  24368. AudioSampleBuffer* currentBuffer;
  24369. AudioUnit audioUnit;
  24370. Array <int> parameterIds;
  24371. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24372. void initialise();
  24373. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24374. const AudioTimeStamp* inTimeStamp,
  24375. UInt32 inBusNumber,
  24376. UInt32 inNumberFrames,
  24377. AudioBufferList* ioData) const;
  24378. static OSStatus renderGetInputCallback (void* inRefCon,
  24379. AudioUnitRenderActionFlags* ioActionFlags,
  24380. const AudioTimeStamp* inTimeStamp,
  24381. UInt32 inBusNumber,
  24382. UInt32 inNumberFrames,
  24383. AudioBufferList* ioData)
  24384. {
  24385. return ((AudioUnitPluginInstance*) inRefCon)
  24386. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24387. }
  24388. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24389. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24390. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24391. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24392. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24393. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24394. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24395. {
  24396. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24397. }
  24398. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24399. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24400. Float64* outCurrentMeasureDownBeat)
  24401. {
  24402. return ((AudioUnitPluginInstance*) inHostUserData)
  24403. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24404. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24405. }
  24406. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24407. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24408. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24409. {
  24410. return ((AudioUnitPluginInstance*) inHostUserData)
  24411. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24412. outCurrentSampleInTimeLine, outIsCycling,
  24413. outCycleStartBeat, outCycleEndBeat);
  24414. }
  24415. void getNumChannels (int& numIns, int& numOuts)
  24416. {
  24417. numIns = 0;
  24418. numOuts = 0;
  24419. AUChannelInfo supportedChannels [128];
  24420. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24421. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24422. 0, supportedChannels, &supportedChannelsSize) == noErr
  24423. && supportedChannelsSize > 0)
  24424. {
  24425. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24426. {
  24427. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24428. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24429. }
  24430. }
  24431. else
  24432. {
  24433. // (this really means the plugin will take any number of ins/outs as long
  24434. // as they are the same)
  24435. numIns = numOuts = 2;
  24436. }
  24437. }
  24438. const String getCategory() const;
  24439. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24440. };
  24441. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24442. : fileOrIdentifier (fileOrIdentifier),
  24443. initialised (false),
  24444. wantsMidiMessages (false),
  24445. audioUnit (0),
  24446. currentBuffer (0)
  24447. {
  24448. using namespace AudioUnitFormatHelpers;
  24449. try
  24450. {
  24451. ++insideCallback;
  24452. log ("Opening AU: " + fileOrIdentifier);
  24453. if (getComponentDescFromFile (fileOrIdentifier))
  24454. {
  24455. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24456. if (comp != 0)
  24457. {
  24458. audioUnit = (AudioUnit) OpenComponent (comp);
  24459. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24460. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24461. }
  24462. }
  24463. --insideCallback;
  24464. }
  24465. catch (...)
  24466. {
  24467. --insideCallback;
  24468. }
  24469. }
  24470. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24471. {
  24472. const ScopedLock sl (lock);
  24473. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  24474. if (audioUnit != 0)
  24475. {
  24476. AudioUnitUninitialize (audioUnit);
  24477. CloseComponent (audioUnit);
  24478. audioUnit = 0;
  24479. }
  24480. }
  24481. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24482. {
  24483. zerostruct (componentDesc);
  24484. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24485. return true;
  24486. const File file (fileOrIdentifier);
  24487. if (! file.hasFileExtension (".component"))
  24488. return false;
  24489. const char* const utf8 = fileOrIdentifier.toUTF8();
  24490. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24491. strlen (utf8), file.isDirectory());
  24492. if (url != 0)
  24493. {
  24494. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24495. CFRelease (url);
  24496. if (bundleRef != 0)
  24497. {
  24498. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24499. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24500. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24501. if (pluginName.isEmpty())
  24502. pluginName = file.getFileNameWithoutExtension();
  24503. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24504. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24505. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24506. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24507. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24508. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24509. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24510. UseResFile (resFileId);
  24511. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24512. {
  24513. Handle h = Get1IndResource ('thng', i);
  24514. if (h != 0)
  24515. {
  24516. HLock (h);
  24517. const uint32* const types = (const uint32*) *h;
  24518. if (types[0] == kAudioUnitType_MusicDevice
  24519. || types[0] == kAudioUnitType_MusicEffect
  24520. || types[0] == kAudioUnitType_Effect
  24521. || types[0] == kAudioUnitType_Generator
  24522. || types[0] == kAudioUnitType_Panner)
  24523. {
  24524. componentDesc.componentType = types[0];
  24525. componentDesc.componentSubType = types[1];
  24526. componentDesc.componentManufacturer = types[2];
  24527. break;
  24528. }
  24529. HUnlock (h);
  24530. ReleaseResource (h);
  24531. }
  24532. }
  24533. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24534. CFRelease (bundleRef);
  24535. }
  24536. }
  24537. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24538. }
  24539. void AudioUnitPluginInstance::initialise()
  24540. {
  24541. if (initialised || audioUnit == 0)
  24542. return;
  24543. log ("Initialising AU: " + pluginName);
  24544. parameterIds.clear();
  24545. {
  24546. UInt32 paramListSize = 0;
  24547. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24548. 0, 0, &paramListSize);
  24549. if (paramListSize > 0)
  24550. {
  24551. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24552. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24553. 0, &parameterIds.getReference(0), &paramListSize);
  24554. }
  24555. }
  24556. {
  24557. AURenderCallbackStruct info;
  24558. zerostruct (info);
  24559. info.inputProcRefCon = this;
  24560. info.inputProc = renderGetInputCallback;
  24561. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24562. 0, &info, sizeof (info));
  24563. }
  24564. {
  24565. HostCallbackInfo info;
  24566. zerostruct (info);
  24567. info.hostUserData = this;
  24568. info.beatAndTempoProc = getBeatAndTempoCallback;
  24569. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24570. info.transportStateProc = getTransportStateCallback;
  24571. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24572. 0, &info, sizeof (info));
  24573. }
  24574. int numIns, numOuts;
  24575. getNumChannels (numIns, numOuts);
  24576. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24577. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24578. setLatencySamples (0);
  24579. }
  24580. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24581. int samplesPerBlockExpected)
  24582. {
  24583. if (audioUnit != 0)
  24584. {
  24585. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24586. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24587. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24588. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24589. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24590. {
  24591. if (initialised)
  24592. {
  24593. AudioUnitUninitialize (audioUnit);
  24594. initialised = false;
  24595. }
  24596. Float64 sr = sampleRate_;
  24597. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24598. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24599. }
  24600. }
  24601. initialise();
  24602. if (initialised)
  24603. {
  24604. int numIns, numOuts;
  24605. getNumChannels (numIns, numOuts);
  24606. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24607. Float64 latencySecs = 0.0;
  24608. UInt32 latencySize = sizeof (latencySecs);
  24609. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24610. 0, &latencySecs, &latencySize);
  24611. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24612. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24613. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24614. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24615. AudioStreamBasicDescription stream;
  24616. zerostruct (stream);
  24617. stream.mSampleRate = sampleRate_;
  24618. stream.mFormatID = kAudioFormatLinearPCM;
  24619. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24620. stream.mFramesPerPacket = 1;
  24621. stream.mBytesPerPacket = 4;
  24622. stream.mBytesPerFrame = 4;
  24623. stream.mBitsPerChannel = 32;
  24624. stream.mChannelsPerFrame = numIns;
  24625. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24626. 0, &stream, sizeof (stream));
  24627. stream.mChannelsPerFrame = numOuts;
  24628. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24629. 0, &stream, sizeof (stream));
  24630. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24631. outputBufferList->mNumberBuffers = numOuts;
  24632. for (int i = numOuts; --i >= 0;)
  24633. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24634. zerostruct (timeStamp);
  24635. timeStamp.mSampleTime = 0;
  24636. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24637. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24638. currentBuffer = 0;
  24639. wasPlaying = false;
  24640. }
  24641. }
  24642. void AudioUnitPluginInstance::releaseResources()
  24643. {
  24644. if (initialised)
  24645. {
  24646. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24647. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24648. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24649. outputBufferList.free();
  24650. currentBuffer = 0;
  24651. }
  24652. }
  24653. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24654. const AudioTimeStamp* inTimeStamp,
  24655. UInt32 inBusNumber,
  24656. UInt32 inNumberFrames,
  24657. AudioBufferList* ioData) const
  24658. {
  24659. if (inBusNumber == 0
  24660. && currentBuffer != 0)
  24661. {
  24662. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24663. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24664. {
  24665. if (i < currentBuffer->getNumChannels())
  24666. {
  24667. memcpy (ioData->mBuffers[i].mData,
  24668. currentBuffer->getSampleData (i, 0),
  24669. sizeof (float) * inNumberFrames);
  24670. }
  24671. else
  24672. {
  24673. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24674. }
  24675. }
  24676. }
  24677. return noErr;
  24678. }
  24679. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24680. MidiBuffer& midiMessages)
  24681. {
  24682. const int numSamples = buffer.getNumSamples();
  24683. if (initialised)
  24684. {
  24685. AudioUnitRenderActionFlags flags = 0;
  24686. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24687. for (int i = getNumOutputChannels(); --i >= 0;)
  24688. {
  24689. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24690. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24691. }
  24692. currentBuffer = &buffer;
  24693. if (wantsMidiMessages)
  24694. {
  24695. const uint8* midiEventData;
  24696. int midiEventSize, midiEventPosition;
  24697. MidiBuffer::Iterator i (midiMessages);
  24698. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24699. {
  24700. if (midiEventSize <= 3)
  24701. MusicDeviceMIDIEvent (audioUnit,
  24702. midiEventData[0], midiEventData[1], midiEventData[2],
  24703. midiEventPosition);
  24704. else
  24705. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24706. }
  24707. midiMessages.clear();
  24708. }
  24709. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24710. 0, numSamples, outputBufferList);
  24711. timeStamp.mSampleTime += numSamples;
  24712. }
  24713. else
  24714. {
  24715. // Not initialised, so just bypass..
  24716. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24717. buffer.clear (i, 0, buffer.getNumSamples());
  24718. }
  24719. }
  24720. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24721. {
  24722. AudioPlayHead* const ph = getPlayHead();
  24723. AudioPlayHead::CurrentPositionInfo result;
  24724. if (ph != 0 && ph->getCurrentPosition (result))
  24725. {
  24726. if (outCurrentBeat != 0)
  24727. *outCurrentBeat = result.ppqPosition;
  24728. if (outCurrentTempo != 0)
  24729. *outCurrentTempo = result.bpm;
  24730. }
  24731. else
  24732. {
  24733. if (outCurrentBeat != 0)
  24734. *outCurrentBeat = 0;
  24735. if (outCurrentTempo != 0)
  24736. *outCurrentTempo = 120.0;
  24737. }
  24738. return noErr;
  24739. }
  24740. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24741. Float32* outTimeSig_Numerator,
  24742. UInt32* outTimeSig_Denominator,
  24743. Float64* outCurrentMeasureDownBeat) const
  24744. {
  24745. AudioPlayHead* const ph = getPlayHead();
  24746. AudioPlayHead::CurrentPositionInfo result;
  24747. if (ph != 0 && ph->getCurrentPosition (result))
  24748. {
  24749. if (outTimeSig_Numerator != 0)
  24750. *outTimeSig_Numerator = result.timeSigNumerator;
  24751. if (outTimeSig_Denominator != 0)
  24752. *outTimeSig_Denominator = result.timeSigDenominator;
  24753. if (outDeltaSampleOffsetToNextBeat != 0)
  24754. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24755. if (outCurrentMeasureDownBeat != 0)
  24756. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24757. }
  24758. else
  24759. {
  24760. if (outDeltaSampleOffsetToNextBeat != 0)
  24761. *outDeltaSampleOffsetToNextBeat = 0;
  24762. if (outTimeSig_Numerator != 0)
  24763. *outTimeSig_Numerator = 4;
  24764. if (outTimeSig_Denominator != 0)
  24765. *outTimeSig_Denominator = 4;
  24766. if (outCurrentMeasureDownBeat != 0)
  24767. *outCurrentMeasureDownBeat = 0;
  24768. }
  24769. return noErr;
  24770. }
  24771. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24772. Boolean* outTransportStateChanged,
  24773. Float64* outCurrentSampleInTimeLine,
  24774. Boolean* outIsCycling,
  24775. Float64* outCycleStartBeat,
  24776. Float64* outCycleEndBeat)
  24777. {
  24778. AudioPlayHead* const ph = getPlayHead();
  24779. AudioPlayHead::CurrentPositionInfo result;
  24780. if (ph != 0 && ph->getCurrentPosition (result))
  24781. {
  24782. if (outIsPlaying != 0)
  24783. *outIsPlaying = result.isPlaying;
  24784. if (outTransportStateChanged != 0)
  24785. {
  24786. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24787. wasPlaying = result.isPlaying;
  24788. }
  24789. if (outCurrentSampleInTimeLine != 0)
  24790. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24791. if (outIsCycling != 0)
  24792. *outIsCycling = false;
  24793. if (outCycleStartBeat != 0)
  24794. *outCycleStartBeat = 0;
  24795. if (outCycleEndBeat != 0)
  24796. *outCycleEndBeat = 0;
  24797. }
  24798. else
  24799. {
  24800. if (outIsPlaying != 0)
  24801. *outIsPlaying = false;
  24802. if (outTransportStateChanged != 0)
  24803. *outTransportStateChanged = false;
  24804. if (outCurrentSampleInTimeLine != 0)
  24805. *outCurrentSampleInTimeLine = 0;
  24806. if (outIsCycling != 0)
  24807. *outIsCycling = false;
  24808. if (outCycleStartBeat != 0)
  24809. *outCycleStartBeat = 0;
  24810. if (outCycleEndBeat != 0)
  24811. *outCycleEndBeat = 0;
  24812. }
  24813. return noErr;
  24814. }
  24815. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24816. {
  24817. public:
  24818. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24819. : AudioProcessorEditor (&plugin_),
  24820. plugin (plugin_),
  24821. wrapper (0)
  24822. {
  24823. addAndMakeVisible (wrapper = new NSViewComponent());
  24824. setOpaque (true);
  24825. setVisible (true);
  24826. setSize (100, 100);
  24827. createView (createGenericViewIfNeeded);
  24828. }
  24829. ~AudioUnitPluginWindowCocoa()
  24830. {
  24831. const bool wasValid = isValid();
  24832. wrapper->setView (0);
  24833. if (wasValid)
  24834. plugin.editorBeingDeleted (this);
  24835. delete wrapper;
  24836. }
  24837. bool isValid() const { return wrapper->getView() != 0; }
  24838. void paint (Graphics& g)
  24839. {
  24840. g.fillAll (Colours::white);
  24841. }
  24842. void resized()
  24843. {
  24844. wrapper->setSize (getWidth(), getHeight());
  24845. }
  24846. private:
  24847. AudioUnitPluginInstance& plugin;
  24848. NSViewComponent* wrapper;
  24849. bool createView (const bool createGenericViewIfNeeded)
  24850. {
  24851. NSView* pluginView = 0;
  24852. UInt32 dataSize = 0;
  24853. Boolean isWritable = false;
  24854. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24855. 0, &dataSize, &isWritable) == noErr
  24856. && dataSize != 0
  24857. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24858. 0, &dataSize, &isWritable) == noErr)
  24859. {
  24860. HeapBlock <AudioUnitCocoaViewInfo> info;
  24861. info.calloc (dataSize, 1);
  24862. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24863. 0, info, &dataSize) == noErr)
  24864. {
  24865. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24866. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24867. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24868. Class viewClass = [viewBundle classNamed: viewClassName];
  24869. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24870. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24871. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24872. {
  24873. id factory = [[[viewClass alloc] init] autorelease];
  24874. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24875. withSize: NSMakeSize (getWidth(), getHeight())];
  24876. }
  24877. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24878. {
  24879. CFRelease (info->mCocoaAUViewClass[i]);
  24880. CFRelease (info->mCocoaAUViewBundleLocation);
  24881. }
  24882. }
  24883. }
  24884. if (createGenericViewIfNeeded && (pluginView == 0))
  24885. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24886. wrapper->setView (pluginView);
  24887. if (pluginView != 0)
  24888. setSize ([pluginView frame].size.width,
  24889. [pluginView frame].size.height);
  24890. return pluginView != 0;
  24891. }
  24892. };
  24893. #if JUCE_SUPPORT_CARBON
  24894. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24895. {
  24896. public:
  24897. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24898. : AudioProcessorEditor (&plugin_),
  24899. plugin (plugin_),
  24900. viewComponent (0)
  24901. {
  24902. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24903. setOpaque (true);
  24904. setVisible (true);
  24905. setSize (400, 300);
  24906. ComponentDescription viewList [16];
  24907. UInt32 viewListSize = sizeof (viewList);
  24908. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24909. 0, &viewList, &viewListSize);
  24910. componentRecord = FindNextComponent (0, &viewList[0]);
  24911. }
  24912. ~AudioUnitPluginWindowCarbon()
  24913. {
  24914. innerWrapper = 0;
  24915. if (isValid())
  24916. plugin.editorBeingDeleted (this);
  24917. }
  24918. bool isValid() const throw() { return componentRecord != 0; }
  24919. void paint (Graphics& g)
  24920. {
  24921. g.fillAll (Colours::black);
  24922. }
  24923. void resized()
  24924. {
  24925. innerWrapper->setSize (getWidth(), getHeight());
  24926. }
  24927. bool keyStateChanged (bool)
  24928. {
  24929. return false;
  24930. }
  24931. bool keyPressed (const KeyPress&)
  24932. {
  24933. return false;
  24934. }
  24935. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24936. AudioUnitCarbonView getViewComponent()
  24937. {
  24938. if (viewComponent == 0 && componentRecord != 0)
  24939. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24940. return viewComponent;
  24941. }
  24942. void closeViewComponent()
  24943. {
  24944. if (viewComponent != 0)
  24945. {
  24946. CloseComponent (viewComponent);
  24947. viewComponent = 0;
  24948. }
  24949. }
  24950. juce_UseDebuggingNewOperator
  24951. private:
  24952. AudioUnitPluginInstance& plugin;
  24953. ComponentRecord* componentRecord;
  24954. AudioUnitCarbonView viewComponent;
  24955. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24956. {
  24957. public:
  24958. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24959. : owner (owner_)
  24960. {
  24961. }
  24962. ~InnerWrapperComponent()
  24963. {
  24964. deleteWindow();
  24965. }
  24966. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24967. {
  24968. log ("Opening AU GUI: " + owner->plugin.getName());
  24969. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24970. if (viewComponent == 0)
  24971. return 0;
  24972. Float32Point pos = { 0, 0 };
  24973. Float32Point size = { 250, 200 };
  24974. HIViewRef pluginView = 0;
  24975. AudioUnitCarbonViewCreate (viewComponent,
  24976. owner->getAudioUnit(),
  24977. windowRef,
  24978. rootView,
  24979. &pos,
  24980. &size,
  24981. (ControlRef*) &pluginView);
  24982. return pluginView;
  24983. }
  24984. void removeView (HIViewRef)
  24985. {
  24986. log ("Closing AU GUI: " + owner->plugin.getName());
  24987. owner->closeViewComponent();
  24988. }
  24989. private:
  24990. AudioUnitPluginWindowCarbon* const owner;
  24991. };
  24992. friend class InnerWrapperComponent;
  24993. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24994. };
  24995. #endif
  24996. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24997. {
  24998. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24999. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25000. w = 0;
  25001. #if JUCE_SUPPORT_CARBON
  25002. if (w == 0)
  25003. {
  25004. w = new AudioUnitPluginWindowCarbon (*this);
  25005. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25006. w = 0;
  25007. }
  25008. #endif
  25009. if (w == 0)
  25010. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25011. return w.release();
  25012. }
  25013. const String AudioUnitPluginInstance::getCategory() const
  25014. {
  25015. const char* result = 0;
  25016. switch (componentDesc.componentType)
  25017. {
  25018. case kAudioUnitType_Effect:
  25019. case kAudioUnitType_MusicEffect:
  25020. result = "Effect";
  25021. break;
  25022. case kAudioUnitType_MusicDevice:
  25023. result = "Synth";
  25024. break;
  25025. case kAudioUnitType_Generator:
  25026. result = "Generator";
  25027. break;
  25028. case kAudioUnitType_Panner:
  25029. result = "Panner";
  25030. break;
  25031. default:
  25032. break;
  25033. }
  25034. return result;
  25035. }
  25036. int AudioUnitPluginInstance::getNumParameters()
  25037. {
  25038. return parameterIds.size();
  25039. }
  25040. float AudioUnitPluginInstance::getParameter (int index)
  25041. {
  25042. const ScopedLock sl (lock);
  25043. Float32 value = 0.0f;
  25044. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25045. {
  25046. AudioUnitGetParameter (audioUnit,
  25047. (UInt32) parameterIds.getUnchecked (index),
  25048. kAudioUnitScope_Global, 0,
  25049. &value);
  25050. }
  25051. return value;
  25052. }
  25053. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25054. {
  25055. const ScopedLock sl (lock);
  25056. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25057. {
  25058. AudioUnitSetParameter (audioUnit,
  25059. (UInt32) parameterIds.getUnchecked (index),
  25060. kAudioUnitScope_Global, 0,
  25061. newValue, 0);
  25062. }
  25063. }
  25064. const String AudioUnitPluginInstance::getParameterName (int index)
  25065. {
  25066. AudioUnitParameterInfo info;
  25067. zerostruct (info);
  25068. UInt32 sz = sizeof (info);
  25069. String name;
  25070. if (AudioUnitGetProperty (audioUnit,
  25071. kAudioUnitProperty_ParameterInfo,
  25072. kAudioUnitScope_Global,
  25073. parameterIds [index], &info, &sz) == noErr)
  25074. {
  25075. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25076. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25077. else
  25078. name = String (info.name, sizeof (info.name));
  25079. }
  25080. return name;
  25081. }
  25082. const String AudioUnitPluginInstance::getParameterText (int index)
  25083. {
  25084. return String (getParameter (index));
  25085. }
  25086. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25087. {
  25088. AudioUnitParameterInfo info;
  25089. UInt32 sz = sizeof (info);
  25090. if (AudioUnitGetProperty (audioUnit,
  25091. kAudioUnitProperty_ParameterInfo,
  25092. kAudioUnitScope_Global,
  25093. parameterIds [index], &info, &sz) == noErr)
  25094. {
  25095. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25096. }
  25097. return true;
  25098. }
  25099. int AudioUnitPluginInstance::getNumPrograms()
  25100. {
  25101. CFArrayRef presets;
  25102. UInt32 sz = sizeof (CFArrayRef);
  25103. int num = 0;
  25104. if (AudioUnitGetProperty (audioUnit,
  25105. kAudioUnitProperty_FactoryPresets,
  25106. kAudioUnitScope_Global,
  25107. 0, &presets, &sz) == noErr)
  25108. {
  25109. num = (int) CFArrayGetCount (presets);
  25110. CFRelease (presets);
  25111. }
  25112. return num;
  25113. }
  25114. int AudioUnitPluginInstance::getCurrentProgram()
  25115. {
  25116. AUPreset current;
  25117. current.presetNumber = 0;
  25118. UInt32 sz = sizeof (AUPreset);
  25119. AudioUnitGetProperty (audioUnit,
  25120. kAudioUnitProperty_FactoryPresets,
  25121. kAudioUnitScope_Global,
  25122. 0, &current, &sz);
  25123. return current.presetNumber;
  25124. }
  25125. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25126. {
  25127. AUPreset current;
  25128. current.presetNumber = newIndex;
  25129. current.presetName = 0;
  25130. AudioUnitSetProperty (audioUnit,
  25131. kAudioUnitProperty_FactoryPresets,
  25132. kAudioUnitScope_Global,
  25133. 0, &current, sizeof (AUPreset));
  25134. }
  25135. const String AudioUnitPluginInstance::getProgramName (int index)
  25136. {
  25137. String s;
  25138. CFArrayRef presets;
  25139. UInt32 sz = sizeof (CFArrayRef);
  25140. if (AudioUnitGetProperty (audioUnit,
  25141. kAudioUnitProperty_FactoryPresets,
  25142. kAudioUnitScope_Global,
  25143. 0, &presets, &sz) == noErr)
  25144. {
  25145. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25146. {
  25147. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25148. if (p != 0 && p->presetNumber == index)
  25149. {
  25150. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25151. break;
  25152. }
  25153. }
  25154. CFRelease (presets);
  25155. }
  25156. return s;
  25157. }
  25158. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25159. {
  25160. jassertfalse; // xxx not implemented!
  25161. }
  25162. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25163. {
  25164. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25165. return "Input " + String (index + 1);
  25166. return String::empty;
  25167. }
  25168. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25169. {
  25170. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25171. return false;
  25172. return true;
  25173. }
  25174. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25175. {
  25176. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25177. return "Output " + String (index + 1);
  25178. return String::empty;
  25179. }
  25180. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25181. {
  25182. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25183. return false;
  25184. return true;
  25185. }
  25186. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25187. {
  25188. getCurrentProgramStateInformation (destData);
  25189. }
  25190. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25191. {
  25192. CFPropertyListRef propertyList = 0;
  25193. UInt32 sz = sizeof (CFPropertyListRef);
  25194. if (AudioUnitGetProperty (audioUnit,
  25195. kAudioUnitProperty_ClassInfo,
  25196. kAudioUnitScope_Global,
  25197. 0, &propertyList, &sz) == noErr)
  25198. {
  25199. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25200. CFWriteStreamOpen (stream);
  25201. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25202. CFWriteStreamClose (stream);
  25203. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25204. destData.setSize (bytesWritten);
  25205. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25206. CFRelease (data);
  25207. CFRelease (stream);
  25208. CFRelease (propertyList);
  25209. }
  25210. }
  25211. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25212. {
  25213. setCurrentProgramStateInformation (data, sizeInBytes);
  25214. }
  25215. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25216. {
  25217. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25218. (const UInt8*) data,
  25219. sizeInBytes,
  25220. kCFAllocatorNull);
  25221. CFReadStreamOpen (stream);
  25222. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25223. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25224. stream,
  25225. 0,
  25226. kCFPropertyListImmutable,
  25227. &format,
  25228. 0);
  25229. CFRelease (stream);
  25230. if (propertyList != 0)
  25231. AudioUnitSetProperty (audioUnit,
  25232. kAudioUnitProperty_ClassInfo,
  25233. kAudioUnitScope_Global,
  25234. 0, &propertyList, sizeof (propertyList));
  25235. }
  25236. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25237. {
  25238. }
  25239. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25240. {
  25241. }
  25242. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25243. const String& fileOrIdentifier)
  25244. {
  25245. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25246. return;
  25247. PluginDescription desc;
  25248. desc.fileOrIdentifier = fileOrIdentifier;
  25249. desc.uid = 0;
  25250. try
  25251. {
  25252. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25253. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25254. if (auInstance != 0)
  25255. {
  25256. auInstance->fillInPluginDescription (desc);
  25257. results.add (new PluginDescription (desc));
  25258. }
  25259. }
  25260. catch (...)
  25261. {
  25262. // crashed while loading...
  25263. }
  25264. }
  25265. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25266. {
  25267. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25268. {
  25269. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25270. if (result->audioUnit != 0)
  25271. {
  25272. result->initialise();
  25273. return result.release();
  25274. }
  25275. }
  25276. return 0;
  25277. }
  25278. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25279. const bool /*recursive*/)
  25280. {
  25281. StringArray result;
  25282. ComponentRecord* comp = 0;
  25283. ComponentDescription desc;
  25284. zerostruct (desc);
  25285. for (;;)
  25286. {
  25287. zerostruct (desc);
  25288. comp = FindNextComponent (comp, &desc);
  25289. if (comp == 0)
  25290. break;
  25291. GetComponentInfo (comp, &desc, 0, 0, 0);
  25292. if (desc.componentType == kAudioUnitType_MusicDevice
  25293. || desc.componentType == kAudioUnitType_MusicEffect
  25294. || desc.componentType == kAudioUnitType_Effect
  25295. || desc.componentType == kAudioUnitType_Generator
  25296. || desc.componentType == kAudioUnitType_Panner)
  25297. {
  25298. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25299. DBG (s);
  25300. result.add (s);
  25301. }
  25302. }
  25303. return result;
  25304. }
  25305. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25306. {
  25307. ComponentDescription desc;
  25308. String name, version, manufacturer;
  25309. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25310. return FindNextComponent (0, &desc) != 0;
  25311. const File f (fileOrIdentifier);
  25312. return f.hasFileExtension (".component")
  25313. && f.isDirectory();
  25314. }
  25315. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25316. {
  25317. ComponentDescription desc;
  25318. String name, version, manufacturer;
  25319. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25320. if (name.isEmpty())
  25321. name = fileOrIdentifier;
  25322. return name;
  25323. }
  25324. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25325. {
  25326. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  25327. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25328. else
  25329. return File (desc.fileOrIdentifier).exists();
  25330. }
  25331. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25332. {
  25333. return FileSearchPath ("/(Default AudioUnit locations)");
  25334. }
  25335. #endif
  25336. END_JUCE_NAMESPACE
  25337. #undef log
  25338. #endif
  25339. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25340. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25341. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25342. #define JUCE_MAC_VST_INCLUDED 1
  25343. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25344. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25345. #if JUCE_WINDOWS
  25346. #undef _WIN32_WINNT
  25347. #define _WIN32_WINNT 0x500
  25348. #undef STRICT
  25349. #define STRICT
  25350. #include <windows.h>
  25351. #include <float.h>
  25352. #pragma warning (disable : 4312 4355)
  25353. #elif JUCE_LINUX
  25354. #include <float.h>
  25355. #include <sys/time.h>
  25356. #include <X11/Xlib.h>
  25357. #include <X11/Xutil.h>
  25358. #include <X11/Xatom.h>
  25359. #undef Font
  25360. #undef KeyPress
  25361. #undef Drawable
  25362. #undef Time
  25363. #else
  25364. #include <Cocoa/Cocoa.h>
  25365. #include <Carbon/Carbon.h>
  25366. #endif
  25367. #if ! (JUCE_MAC && JUCE_64BIT)
  25368. BEGIN_JUCE_NAMESPACE
  25369. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25370. #endif
  25371. #undef PRAGMA_ALIGN_SUPPORTED
  25372. #define VST_FORCE_DEPRECATED 0
  25373. #if JUCE_MSVC
  25374. #pragma warning (push)
  25375. #pragma warning (disable: 4996)
  25376. #endif
  25377. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25378. your include path if you want to add VST support.
  25379. If you're not interested in VSTs, you can disable them by changing the
  25380. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25381. */
  25382. #include "pluginterfaces/vst2.x/aeffectx.h"
  25383. #if JUCE_MSVC
  25384. #pragma warning (pop)
  25385. #endif
  25386. #if JUCE_LINUX
  25387. #define Font JUCE_NAMESPACE::Font
  25388. #define KeyPress JUCE_NAMESPACE::KeyPress
  25389. #define Drawable JUCE_NAMESPACE::Drawable
  25390. #define Time JUCE_NAMESPACE::Time
  25391. #endif
  25392. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25393. #ifdef __aeffect__
  25394. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25395. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25396. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25397. events to the list.
  25398. This is used by both the VST hosting code and the plugin wrapper.
  25399. */
  25400. class VSTMidiEventList
  25401. {
  25402. public:
  25403. VSTMidiEventList()
  25404. : numEventsUsed (0), numEventsAllocated (0)
  25405. {
  25406. }
  25407. ~VSTMidiEventList()
  25408. {
  25409. freeEvents();
  25410. }
  25411. void clear()
  25412. {
  25413. numEventsUsed = 0;
  25414. if (events != 0)
  25415. events->numEvents = 0;
  25416. }
  25417. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25418. {
  25419. ensureSize (numEventsUsed + 1);
  25420. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25421. events->numEvents = ++numEventsUsed;
  25422. if (numBytes <= 4)
  25423. {
  25424. if (e->type == kVstSysExType)
  25425. {
  25426. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25427. e->type = kVstMidiType;
  25428. e->byteSize = sizeof (VstMidiEvent);
  25429. e->noteLength = 0;
  25430. e->noteOffset = 0;
  25431. e->detune = 0;
  25432. e->noteOffVelocity = 0;
  25433. }
  25434. e->deltaFrames = frameOffset;
  25435. memcpy (e->midiData, midiData, numBytes);
  25436. }
  25437. else
  25438. {
  25439. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25440. if (se->type == kVstSysExType)
  25441. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25442. else
  25443. se->sysexDump = (char*) juce_malloc (numBytes);
  25444. memcpy (se->sysexDump, midiData, numBytes);
  25445. se->type = kVstSysExType;
  25446. se->byteSize = sizeof (VstMidiSysexEvent);
  25447. se->deltaFrames = frameOffset;
  25448. se->flags = 0;
  25449. se->dumpBytes = numBytes;
  25450. se->resvd1 = 0;
  25451. se->resvd2 = 0;
  25452. }
  25453. }
  25454. // Handy method to pull the events out of an event buffer supplied by the host
  25455. // or plugin.
  25456. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25457. {
  25458. for (int i = 0; i < events->numEvents; ++i)
  25459. {
  25460. const VstEvent* const e = events->events[i];
  25461. if (e != 0)
  25462. {
  25463. if (e->type == kVstMidiType)
  25464. {
  25465. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25466. 4, e->deltaFrames);
  25467. }
  25468. else if (e->type == kVstSysExType)
  25469. {
  25470. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25471. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25472. e->deltaFrames);
  25473. }
  25474. }
  25475. }
  25476. }
  25477. void ensureSize (int numEventsNeeded)
  25478. {
  25479. if (numEventsNeeded > numEventsAllocated)
  25480. {
  25481. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25482. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25483. if (events == 0)
  25484. events.calloc (size, 1);
  25485. else
  25486. events.realloc (size, 1);
  25487. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25488. {
  25489. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25490. (int) sizeof (VstMidiSysexEvent)));
  25491. e->type = kVstMidiType;
  25492. e->byteSize = sizeof (VstMidiEvent);
  25493. events->events[i] = (VstEvent*) e;
  25494. }
  25495. numEventsAllocated = numEventsNeeded;
  25496. }
  25497. }
  25498. void freeEvents()
  25499. {
  25500. if (events != 0)
  25501. {
  25502. for (int i = numEventsAllocated; --i >= 0;)
  25503. {
  25504. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25505. if (e->type == kVstSysExType)
  25506. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25507. juce_free (e);
  25508. }
  25509. events.free();
  25510. numEventsUsed = 0;
  25511. numEventsAllocated = 0;
  25512. }
  25513. }
  25514. HeapBlock <VstEvents> events;
  25515. private:
  25516. int numEventsUsed, numEventsAllocated;
  25517. };
  25518. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25519. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25520. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25521. #if ! JUCE_WINDOWS
  25522. static void _fpreset() {}
  25523. static void _clearfp() {}
  25524. #endif
  25525. extern void juce_callAnyTimersSynchronously();
  25526. const int fxbVersionNum = 1;
  25527. struct fxProgram
  25528. {
  25529. long chunkMagic; // 'CcnK'
  25530. long byteSize; // of this chunk, excl. magic + byteSize
  25531. long fxMagic; // 'FxCk'
  25532. long version;
  25533. long fxID; // fx unique id
  25534. long fxVersion;
  25535. long numParams;
  25536. char prgName[28];
  25537. float params[1]; // variable no. of parameters
  25538. };
  25539. struct fxSet
  25540. {
  25541. long chunkMagic; // 'CcnK'
  25542. long byteSize; // of this chunk, excl. magic + byteSize
  25543. long fxMagic; // 'FxBk'
  25544. long version;
  25545. long fxID; // fx unique id
  25546. long fxVersion;
  25547. long numPrograms;
  25548. char future[128];
  25549. fxProgram programs[1]; // variable no. of programs
  25550. };
  25551. struct fxChunkSet
  25552. {
  25553. long chunkMagic; // 'CcnK'
  25554. long byteSize; // of this chunk, excl. magic + byteSize
  25555. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25556. long version;
  25557. long fxID; // fx unique id
  25558. long fxVersion;
  25559. long numPrograms;
  25560. char future[128];
  25561. long chunkSize;
  25562. char chunk[8]; // variable
  25563. };
  25564. struct fxProgramSet
  25565. {
  25566. long chunkMagic; // 'CcnK'
  25567. long byteSize; // of this chunk, excl. magic + byteSize
  25568. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25569. long version;
  25570. long fxID; // fx unique id
  25571. long fxVersion;
  25572. long numPrograms;
  25573. char name[28];
  25574. long chunkSize;
  25575. char chunk[8]; // variable
  25576. };
  25577. static long vst_swap (const long x) throw()
  25578. {
  25579. #ifdef JUCE_LITTLE_ENDIAN
  25580. return (long) ByteOrder::swap ((uint32) x);
  25581. #else
  25582. return x;
  25583. #endif
  25584. }
  25585. static float vst_swapFloat (const float x) throw()
  25586. {
  25587. #ifdef JUCE_LITTLE_ENDIAN
  25588. union { uint32 asInt; float asFloat; } n;
  25589. n.asFloat = x;
  25590. n.asInt = ByteOrder::swap (n.asInt);
  25591. return n.asFloat;
  25592. #else
  25593. return x;
  25594. #endif
  25595. }
  25596. typedef AEffect* (*MainCall) (audioMasterCallback);
  25597. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25598. static int shellUIDToCreate = 0;
  25599. static int insideVSTCallback = 0;
  25600. class VSTPluginWindow;
  25601. // Change this to disable logging of various VST activities
  25602. #ifndef VST_LOGGING
  25603. #define VST_LOGGING 1
  25604. #endif
  25605. #if VST_LOGGING
  25606. #define log(a) Logger::writeToLog(a);
  25607. #else
  25608. #define log(a)
  25609. #endif
  25610. #if JUCE_MAC && JUCE_PPC
  25611. static void* NewCFMFromMachO (void* const machofp) throw()
  25612. {
  25613. void* result = juce_malloc (8);
  25614. ((void**) result)[0] = machofp;
  25615. ((void**) result)[1] = result;
  25616. return result;
  25617. }
  25618. #endif
  25619. #if JUCE_LINUX
  25620. extern Display* display;
  25621. extern XContext windowHandleXContext;
  25622. typedef void (*EventProcPtr) (XEvent* ev);
  25623. static bool xErrorTriggered;
  25624. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25625. {
  25626. xErrorTriggered = true;
  25627. return 0;
  25628. }
  25629. static int getPropertyFromXWindow (Window handle, Atom atom)
  25630. {
  25631. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25632. xErrorTriggered = false;
  25633. int userSize;
  25634. unsigned long bytes, userCount;
  25635. unsigned char* data;
  25636. Atom userType;
  25637. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25638. &userType, &userSize, &userCount, &bytes, &data);
  25639. XSetErrorHandler (oldErrorHandler);
  25640. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25641. : 0;
  25642. }
  25643. static Window getChildWindow (Window windowToCheck)
  25644. {
  25645. Window rootWindow, parentWindow;
  25646. Window* childWindows;
  25647. unsigned int numChildren;
  25648. XQueryTree (display,
  25649. windowToCheck,
  25650. &rootWindow,
  25651. &parentWindow,
  25652. &childWindows,
  25653. &numChildren);
  25654. if (numChildren > 0)
  25655. return childWindows [0];
  25656. return 0;
  25657. }
  25658. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25659. {
  25660. if (e.mods.isLeftButtonDown())
  25661. {
  25662. ev.xbutton.button = Button1;
  25663. ev.xbutton.state |= Button1Mask;
  25664. }
  25665. else if (e.mods.isRightButtonDown())
  25666. {
  25667. ev.xbutton.button = Button3;
  25668. ev.xbutton.state |= Button3Mask;
  25669. }
  25670. else if (e.mods.isMiddleButtonDown())
  25671. {
  25672. ev.xbutton.button = Button2;
  25673. ev.xbutton.state |= Button2Mask;
  25674. }
  25675. }
  25676. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25677. {
  25678. if (e.mods.isLeftButtonDown())
  25679. ev.xmotion.state |= Button1Mask;
  25680. else if (e.mods.isRightButtonDown())
  25681. ev.xmotion.state |= Button3Mask;
  25682. else if (e.mods.isMiddleButtonDown())
  25683. ev.xmotion.state |= Button2Mask;
  25684. }
  25685. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25686. {
  25687. if (e.mods.isLeftButtonDown())
  25688. ev.xcrossing.state |= Button1Mask;
  25689. else if (e.mods.isRightButtonDown())
  25690. ev.xcrossing.state |= Button3Mask;
  25691. else if (e.mods.isMiddleButtonDown())
  25692. ev.xcrossing.state |= Button2Mask;
  25693. }
  25694. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25695. {
  25696. if (increment < 0)
  25697. {
  25698. ev.xbutton.button = Button5;
  25699. ev.xbutton.state |= Button5Mask;
  25700. }
  25701. else if (increment > 0)
  25702. {
  25703. ev.xbutton.button = Button4;
  25704. ev.xbutton.state |= Button4Mask;
  25705. }
  25706. }
  25707. #endif
  25708. class ModuleHandle : public ReferenceCountedObject
  25709. {
  25710. public:
  25711. File file;
  25712. MainCall moduleMain;
  25713. String pluginName;
  25714. static Array <ModuleHandle*>& getActiveModules()
  25715. {
  25716. static Array <ModuleHandle*> activeModules;
  25717. return activeModules;
  25718. }
  25719. static ModuleHandle* findOrCreateModule (const File& file)
  25720. {
  25721. for (int i = getActiveModules().size(); --i >= 0;)
  25722. {
  25723. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25724. if (module->file == file)
  25725. return module;
  25726. }
  25727. _fpreset(); // (doesn't do any harm)
  25728. ++insideVSTCallback;
  25729. shellUIDToCreate = 0;
  25730. log ("Attempting to load VST: " + file.getFullPathName());
  25731. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25732. if (! m->open())
  25733. m = 0;
  25734. --insideVSTCallback;
  25735. _fpreset(); // (doesn't do any harm)
  25736. return m.release();
  25737. }
  25738. ModuleHandle (const File& file_)
  25739. : file (file_),
  25740. moduleMain (0),
  25741. #if JUCE_WINDOWS || JUCE_LINUX
  25742. hModule (0)
  25743. #elif JUCE_MAC
  25744. fragId (0),
  25745. resHandle (0),
  25746. bundleRef (0),
  25747. resFileId (0)
  25748. #endif
  25749. {
  25750. getActiveModules().add (this);
  25751. #if JUCE_WINDOWS || JUCE_LINUX
  25752. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25753. #elif JUCE_MAC
  25754. FSRef ref;
  25755. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25756. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25757. #endif
  25758. }
  25759. ~ModuleHandle()
  25760. {
  25761. getActiveModules().removeValue (this);
  25762. close();
  25763. }
  25764. juce_UseDebuggingNewOperator
  25765. #if JUCE_WINDOWS || JUCE_LINUX
  25766. void* hModule;
  25767. String fullParentDirectoryPathName;
  25768. bool open()
  25769. {
  25770. #if JUCE_WINDOWS
  25771. static bool timePeriodSet = false;
  25772. if (! timePeriodSet)
  25773. {
  25774. timePeriodSet = true;
  25775. timeBeginPeriod (2);
  25776. }
  25777. #endif
  25778. pluginName = file.getFileNameWithoutExtension();
  25779. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25780. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25781. if (moduleMain == 0)
  25782. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25783. return moduleMain != 0;
  25784. }
  25785. void close()
  25786. {
  25787. _fpreset(); // (doesn't do any harm)
  25788. PlatformUtilities::freeDynamicLibrary (hModule);
  25789. }
  25790. void closeEffect (AEffect* eff)
  25791. {
  25792. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25793. }
  25794. #else
  25795. CFragConnectionID fragId;
  25796. Handle resHandle;
  25797. CFBundleRef bundleRef;
  25798. FSSpec parentDirFSSpec;
  25799. short resFileId;
  25800. bool open()
  25801. {
  25802. bool ok = false;
  25803. const String filename (file.getFullPathName());
  25804. if (file.hasFileExtension (".vst"))
  25805. {
  25806. const char* const utf8 = filename.toUTF8();
  25807. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25808. strlen (utf8), file.isDirectory());
  25809. if (url != 0)
  25810. {
  25811. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25812. CFRelease (url);
  25813. if (bundleRef != 0)
  25814. {
  25815. if (CFBundleLoadExecutable (bundleRef))
  25816. {
  25817. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25818. if (moduleMain == 0)
  25819. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25820. if (moduleMain != 0)
  25821. {
  25822. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25823. if (name != 0)
  25824. {
  25825. if (CFGetTypeID (name) == CFStringGetTypeID())
  25826. {
  25827. char buffer[1024];
  25828. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25829. pluginName = buffer;
  25830. }
  25831. }
  25832. if (pluginName.isEmpty())
  25833. pluginName = file.getFileNameWithoutExtension();
  25834. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25835. ok = true;
  25836. }
  25837. }
  25838. if (! ok)
  25839. {
  25840. CFBundleUnloadExecutable (bundleRef);
  25841. CFRelease (bundleRef);
  25842. bundleRef = 0;
  25843. }
  25844. }
  25845. }
  25846. }
  25847. #if JUCE_PPC
  25848. else
  25849. {
  25850. FSRef fn;
  25851. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25852. {
  25853. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25854. if (resFileId != -1)
  25855. {
  25856. const int numEffs = Count1Resources ('aEff');
  25857. for (int i = 0; i < numEffs; ++i)
  25858. {
  25859. resHandle = Get1IndResource ('aEff', i + 1);
  25860. if (resHandle != 0)
  25861. {
  25862. OSType type;
  25863. Str255 name;
  25864. SInt16 id;
  25865. GetResInfo (resHandle, &id, &type, name);
  25866. pluginName = String ((const char*) name + 1, name[0]);
  25867. DetachResource (resHandle);
  25868. HLock (resHandle);
  25869. Ptr ptr;
  25870. Str255 errorText;
  25871. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25872. name, kPrivateCFragCopy,
  25873. &fragId, &ptr, errorText);
  25874. if (err == noErr)
  25875. {
  25876. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25877. ok = true;
  25878. }
  25879. else
  25880. {
  25881. HUnlock (resHandle);
  25882. }
  25883. break;
  25884. }
  25885. }
  25886. if (! ok)
  25887. CloseResFile (resFileId);
  25888. }
  25889. }
  25890. }
  25891. #endif
  25892. return ok;
  25893. }
  25894. void close()
  25895. {
  25896. #if JUCE_PPC
  25897. if (fragId != 0)
  25898. {
  25899. if (moduleMain != 0)
  25900. disposeMachOFromCFM ((void*) moduleMain);
  25901. CloseConnection (&fragId);
  25902. HUnlock (resHandle);
  25903. if (resFileId != 0)
  25904. CloseResFile (resFileId);
  25905. }
  25906. else
  25907. #endif
  25908. if (bundleRef != 0)
  25909. {
  25910. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25911. if (CFGetRetainCount (bundleRef) == 1)
  25912. CFBundleUnloadExecutable (bundleRef);
  25913. if (CFGetRetainCount (bundleRef) > 0)
  25914. CFRelease (bundleRef);
  25915. }
  25916. }
  25917. void closeEffect (AEffect* eff)
  25918. {
  25919. #if JUCE_PPC
  25920. if (fragId != 0)
  25921. {
  25922. Array<void*> thingsToDelete;
  25923. thingsToDelete.add ((void*) eff->dispatcher);
  25924. thingsToDelete.add ((void*) eff->process);
  25925. thingsToDelete.add ((void*) eff->setParameter);
  25926. thingsToDelete.add ((void*) eff->getParameter);
  25927. thingsToDelete.add ((void*) eff->processReplacing);
  25928. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25929. for (int i = thingsToDelete.size(); --i >= 0;)
  25930. disposeMachOFromCFM (thingsToDelete[i]);
  25931. }
  25932. else
  25933. #endif
  25934. {
  25935. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25936. }
  25937. }
  25938. #if JUCE_PPC
  25939. static void* newMachOFromCFM (void* cfmfp)
  25940. {
  25941. if (cfmfp == 0)
  25942. return 0;
  25943. UInt32* const mfp = new UInt32[6];
  25944. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25945. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25946. mfp[2] = 0x800c0000;
  25947. mfp[3] = 0x804c0004;
  25948. mfp[4] = 0x7c0903a6;
  25949. mfp[5] = 0x4e800420;
  25950. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25951. return mfp;
  25952. }
  25953. static void disposeMachOFromCFM (void* ptr)
  25954. {
  25955. delete[] static_cast <UInt32*> (ptr);
  25956. }
  25957. void coerceAEffectFunctionCalls (AEffect* eff)
  25958. {
  25959. if (fragId != 0)
  25960. {
  25961. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25962. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25963. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25964. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25965. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25966. }
  25967. }
  25968. #endif
  25969. #endif
  25970. };
  25971. /**
  25972. An instance of a plugin, created by a VSTPluginFormat.
  25973. */
  25974. class VSTPluginInstance : public AudioPluginInstance,
  25975. private Timer,
  25976. private AsyncUpdater
  25977. {
  25978. public:
  25979. ~VSTPluginInstance();
  25980. // AudioPluginInstance methods:
  25981. void fillInPluginDescription (PluginDescription& desc) const
  25982. {
  25983. desc.name = name;
  25984. desc.fileOrIdentifier = module->file.getFullPathName();
  25985. desc.uid = getUID();
  25986. desc.lastFileModTime = module->file.getLastModificationTime();
  25987. desc.pluginFormatName = "VST";
  25988. desc.category = getCategory();
  25989. {
  25990. char buffer [kVstMaxVendorStrLen + 8];
  25991. zerostruct (buffer);
  25992. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25993. desc.manufacturerName = buffer;
  25994. }
  25995. desc.version = getVersion();
  25996. desc.numInputChannels = getNumInputChannels();
  25997. desc.numOutputChannels = getNumOutputChannels();
  25998. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25999. }
  26000. const String getName() const { return name; }
  26001. int getUID() const throw();
  26002. bool acceptsMidi() const { return wantsMidiMessages; }
  26003. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26004. // AudioProcessor methods:
  26005. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26006. void releaseResources();
  26007. void processBlock (AudioSampleBuffer& buffer,
  26008. MidiBuffer& midiMessages);
  26009. AudioProcessorEditor* createEditor();
  26010. const String getInputChannelName (const int index) const;
  26011. bool isInputChannelStereoPair (int index) const;
  26012. const String getOutputChannelName (const int index) const;
  26013. bool isOutputChannelStereoPair (int index) const;
  26014. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26015. float getParameter (int index);
  26016. void setParameter (int index, float newValue);
  26017. const String getParameterName (int index);
  26018. const String getParameterText (int index);
  26019. bool isParameterAutomatable (int index) const;
  26020. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26021. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26022. void setCurrentProgram (int index);
  26023. const String getProgramName (int index);
  26024. void changeProgramName (int index, const String& newName);
  26025. void getStateInformation (MemoryBlock& destData);
  26026. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26027. void setStateInformation (const void* data, int sizeInBytes);
  26028. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26029. void timerCallback();
  26030. void handleAsyncUpdate();
  26031. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26032. juce_UseDebuggingNewOperator
  26033. private:
  26034. friend class VSTPluginWindow;
  26035. friend class VSTPluginFormat;
  26036. AEffect* effect;
  26037. String name;
  26038. CriticalSection lock;
  26039. bool wantsMidiMessages, initialised, isPowerOn;
  26040. mutable StringArray programNames;
  26041. AudioSampleBuffer tempBuffer;
  26042. CriticalSection midiInLock;
  26043. MidiBuffer incomingMidi;
  26044. VSTMidiEventList midiEventsToSend;
  26045. VstTimeInfo vstHostTime;
  26046. HeapBlock <float*> channels;
  26047. ReferenceCountedObjectPtr <ModuleHandle> module;
  26048. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26049. bool restoreProgramSettings (const fxProgram* const prog);
  26050. const String getCurrentProgramName();
  26051. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26052. void updateStoredProgramNames();
  26053. void initialise();
  26054. void handleMidiFromPlugin (const VstEvents* const events);
  26055. void createTempParameterStore (MemoryBlock& dest);
  26056. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26057. const String getParameterLabel (int index) const;
  26058. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26059. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26060. void setChunkData (const char* data, int size, bool isPreset);
  26061. bool loadFromFXBFile (const void* data, int numBytes);
  26062. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26063. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26064. const String getVersion() const throw();
  26065. const String getCategory() const throw();
  26066. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26067. void setPower (const bool on);
  26068. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26069. };
  26070. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26071. : effect (0),
  26072. wantsMidiMessages (false),
  26073. initialised (false),
  26074. isPowerOn (false),
  26075. tempBuffer (1, 1),
  26076. module (module_)
  26077. {
  26078. try
  26079. {
  26080. _fpreset();
  26081. ++insideVSTCallback;
  26082. name = module->pluginName;
  26083. log ("Creating VST instance: " + name);
  26084. #if JUCE_MAC
  26085. if (module->resFileId != 0)
  26086. UseResFile (module->resFileId);
  26087. #if JUCE_PPC
  26088. if (module->fragId != 0)
  26089. {
  26090. static void* audioMasterCoerced = 0;
  26091. if (audioMasterCoerced == 0)
  26092. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26093. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26094. }
  26095. else
  26096. #endif
  26097. #endif
  26098. {
  26099. effect = module->moduleMain (&audioMaster);
  26100. }
  26101. --insideVSTCallback;
  26102. if (effect != 0 && effect->magic == kEffectMagic)
  26103. {
  26104. #if JUCE_PPC
  26105. module->coerceAEffectFunctionCalls (effect);
  26106. #endif
  26107. jassert (effect->resvd2 == 0);
  26108. jassert (effect->object != 0);
  26109. _fpreset(); // some dodgy plugs fuck around with this
  26110. }
  26111. else
  26112. {
  26113. effect = 0;
  26114. }
  26115. }
  26116. catch (...)
  26117. {
  26118. --insideVSTCallback;
  26119. }
  26120. }
  26121. VSTPluginInstance::~VSTPluginInstance()
  26122. {
  26123. {
  26124. const ScopedLock sl (lock);
  26125. jassert (insideVSTCallback == 0);
  26126. if (effect != 0 && effect->magic == kEffectMagic)
  26127. {
  26128. try
  26129. {
  26130. #if JUCE_MAC
  26131. if (module->resFileId != 0)
  26132. UseResFile (module->resFileId);
  26133. #endif
  26134. // Must delete any editors before deleting the plugin instance!
  26135. jassert (getActiveEditor() == 0);
  26136. _fpreset(); // some dodgy plugs fuck around with this
  26137. module->closeEffect (effect);
  26138. }
  26139. catch (...)
  26140. {}
  26141. }
  26142. module = 0;
  26143. effect = 0;
  26144. }
  26145. }
  26146. void VSTPluginInstance::initialise()
  26147. {
  26148. if (initialised || effect == 0)
  26149. return;
  26150. log ("Initialising VST: " + module->pluginName);
  26151. initialised = true;
  26152. dispatch (effIdentify, 0, 0, 0, 0);
  26153. // this code would ask the plugin for its name, but so few plugins
  26154. // actually bother implementing this correctly, that it's better to
  26155. // just ignore it and use the file name instead.
  26156. /* {
  26157. char buffer [256];
  26158. zerostruct (buffer);
  26159. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26160. name = String (buffer).trim();
  26161. if (name.isEmpty())
  26162. name = module->pluginName;
  26163. }
  26164. */
  26165. if (getSampleRate() > 0)
  26166. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26167. if (getBlockSize() > 0)
  26168. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26169. dispatch (effOpen, 0, 0, 0, 0);
  26170. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26171. getSampleRate(), getBlockSize());
  26172. if (getNumPrograms() > 1)
  26173. setCurrentProgram (0);
  26174. else
  26175. dispatch (effSetProgram, 0, 0, 0, 0);
  26176. int i;
  26177. for (i = effect->numInputs; --i >= 0;)
  26178. dispatch (effConnectInput, i, 1, 0, 0);
  26179. for (i = effect->numOutputs; --i >= 0;)
  26180. dispatch (effConnectOutput, i, 1, 0, 0);
  26181. updateStoredProgramNames();
  26182. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26183. setLatencySamples (effect->initialDelay);
  26184. }
  26185. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26186. int samplesPerBlockExpected)
  26187. {
  26188. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26189. sampleRate_, samplesPerBlockExpected);
  26190. setLatencySamples (effect->initialDelay);
  26191. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26192. vstHostTime.tempo = 120.0;
  26193. vstHostTime.timeSigNumerator = 4;
  26194. vstHostTime.timeSigDenominator = 4;
  26195. vstHostTime.sampleRate = sampleRate_;
  26196. vstHostTime.samplePos = 0;
  26197. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26198. initialise();
  26199. if (initialised)
  26200. {
  26201. wantsMidiMessages = wantsMidiMessages
  26202. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26203. if (wantsMidiMessages)
  26204. midiEventsToSend.ensureSize (256);
  26205. else
  26206. midiEventsToSend.freeEvents();
  26207. incomingMidi.clear();
  26208. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26209. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26210. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26211. if (! isPowerOn)
  26212. setPower (true);
  26213. // dodgy hack to force some plugins to initialise the sample rate..
  26214. if ((! hasEditor()) && getNumParameters() > 0)
  26215. {
  26216. const float old = getParameter (0);
  26217. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26218. setParameter (0, old);
  26219. }
  26220. dispatch (effStartProcess, 0, 0, 0, 0);
  26221. }
  26222. }
  26223. void VSTPluginInstance::releaseResources()
  26224. {
  26225. if (initialised)
  26226. {
  26227. dispatch (effStopProcess, 0, 0, 0, 0);
  26228. setPower (false);
  26229. }
  26230. tempBuffer.setSize (1, 1);
  26231. incomingMidi.clear();
  26232. midiEventsToSend.freeEvents();
  26233. channels.free();
  26234. }
  26235. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26236. MidiBuffer& midiMessages)
  26237. {
  26238. const int numSamples = buffer.getNumSamples();
  26239. if (initialised)
  26240. {
  26241. AudioPlayHead* playHead = getPlayHead();
  26242. if (playHead != 0)
  26243. {
  26244. AudioPlayHead::CurrentPositionInfo position;
  26245. playHead->getCurrentPosition (position);
  26246. vstHostTime.tempo = position.bpm;
  26247. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26248. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26249. vstHostTime.ppqPos = position.ppqPosition;
  26250. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26251. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26252. if (position.isPlaying)
  26253. vstHostTime.flags |= kVstTransportPlaying;
  26254. else
  26255. vstHostTime.flags &= ~kVstTransportPlaying;
  26256. }
  26257. #if JUCE_WINDOWS
  26258. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26259. #elif JUCE_LINUX
  26260. timeval micro;
  26261. gettimeofday (&micro, 0);
  26262. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26263. #elif JUCE_MAC
  26264. UnsignedWide micro;
  26265. Microseconds (&micro);
  26266. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26267. #endif
  26268. if (wantsMidiMessages)
  26269. {
  26270. midiEventsToSend.clear();
  26271. midiEventsToSend.ensureSize (1);
  26272. MidiBuffer::Iterator iter (midiMessages);
  26273. const uint8* midiData;
  26274. int numBytesOfMidiData, samplePosition;
  26275. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26276. {
  26277. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26278. jlimit (0, numSamples - 1, samplePosition));
  26279. }
  26280. try
  26281. {
  26282. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26283. }
  26284. catch (...)
  26285. {}
  26286. }
  26287. int i;
  26288. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26289. for (i = 0; i < maxChans; ++i)
  26290. channels[i] = buffer.getSampleData (i);
  26291. channels [maxChans] = 0;
  26292. _clearfp();
  26293. if ((effect->flags & effFlagsCanReplacing) != 0)
  26294. {
  26295. try
  26296. {
  26297. effect->processReplacing (effect, channels, channels, numSamples);
  26298. }
  26299. catch (...)
  26300. {}
  26301. }
  26302. else
  26303. {
  26304. tempBuffer.setSize (effect->numOutputs, numSamples);
  26305. tempBuffer.clear();
  26306. float* outs [64];
  26307. for (i = effect->numOutputs; --i >= 0;)
  26308. outs[i] = tempBuffer.getSampleData (i);
  26309. outs [effect->numOutputs] = 0;
  26310. try
  26311. {
  26312. effect->process (effect, channels, outs, numSamples);
  26313. }
  26314. catch (...)
  26315. {}
  26316. for (i = effect->numOutputs; --i >= 0;)
  26317. buffer.copyFrom (i, 0, outs[i], numSamples);
  26318. }
  26319. }
  26320. else
  26321. {
  26322. // Not initialised, so just bypass..
  26323. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26324. buffer.clear (i, 0, buffer.getNumSamples());
  26325. }
  26326. {
  26327. // copy any incoming midi..
  26328. const ScopedLock sl (midiInLock);
  26329. midiMessages.swapWith (incomingMidi);
  26330. incomingMidi.clear();
  26331. }
  26332. }
  26333. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26334. {
  26335. if (events != 0)
  26336. {
  26337. const ScopedLock sl (midiInLock);
  26338. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26339. }
  26340. }
  26341. static Array <VSTPluginWindow*> activeVSTWindows;
  26342. class VSTPluginWindow : public AudioProcessorEditor,
  26343. #if ! JUCE_MAC
  26344. public ComponentMovementWatcher,
  26345. #endif
  26346. public Timer
  26347. {
  26348. public:
  26349. VSTPluginWindow (VSTPluginInstance& plugin_)
  26350. : AudioProcessorEditor (&plugin_),
  26351. #if ! JUCE_MAC
  26352. ComponentMovementWatcher (this),
  26353. #endif
  26354. plugin (plugin_),
  26355. isOpen (false),
  26356. wasShowing (false),
  26357. pluginRefusesToResize (false),
  26358. pluginWantsKeys (false),
  26359. alreadyInside (false),
  26360. recursiveResize (false)
  26361. {
  26362. #if JUCE_WINDOWS
  26363. sizeCheckCount = 0;
  26364. pluginHWND = 0;
  26365. #elif JUCE_LINUX
  26366. pluginWindow = None;
  26367. pluginProc = None;
  26368. #else
  26369. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26370. #endif
  26371. activeVSTWindows.add (this);
  26372. setSize (1, 1);
  26373. setOpaque (true);
  26374. setVisible (true);
  26375. }
  26376. ~VSTPluginWindow()
  26377. {
  26378. #if JUCE_MAC
  26379. innerWrapper = 0;
  26380. #else
  26381. closePluginWindow();
  26382. #endif
  26383. activeVSTWindows.removeValue (this);
  26384. plugin.editorBeingDeleted (this);
  26385. }
  26386. #if ! JUCE_MAC
  26387. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26388. {
  26389. if (recursiveResize)
  26390. return;
  26391. Component* const topComp = getTopLevelComponent();
  26392. if (topComp->getPeer() != 0)
  26393. {
  26394. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26395. recursiveResize = true;
  26396. #if JUCE_WINDOWS
  26397. if (pluginHWND != 0)
  26398. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26399. #elif JUCE_LINUX
  26400. if (pluginWindow != 0)
  26401. {
  26402. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26403. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26404. XMapRaised (display, pluginWindow);
  26405. }
  26406. #endif
  26407. recursiveResize = false;
  26408. }
  26409. }
  26410. void componentVisibilityChanged (Component&)
  26411. {
  26412. const bool isShowingNow = isShowing();
  26413. if (wasShowing != isShowingNow)
  26414. {
  26415. wasShowing = isShowingNow;
  26416. if (isShowingNow)
  26417. openPluginWindow();
  26418. else
  26419. closePluginWindow();
  26420. }
  26421. componentMovedOrResized (true, true);
  26422. }
  26423. void componentPeerChanged()
  26424. {
  26425. closePluginWindow();
  26426. openPluginWindow();
  26427. }
  26428. #endif
  26429. bool keyStateChanged (bool)
  26430. {
  26431. return pluginWantsKeys;
  26432. }
  26433. bool keyPressed (const KeyPress&)
  26434. {
  26435. return pluginWantsKeys;
  26436. }
  26437. #if JUCE_MAC
  26438. void paint (Graphics& g)
  26439. {
  26440. g.fillAll (Colours::black);
  26441. }
  26442. #else
  26443. void paint (Graphics& g)
  26444. {
  26445. if (isOpen)
  26446. {
  26447. ComponentPeer* const peer = getPeer();
  26448. if (peer != 0)
  26449. {
  26450. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26451. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26452. #if JUCE_LINUX
  26453. if (pluginWindow != 0)
  26454. {
  26455. const Rectangle<int> clip (g.getClipBounds());
  26456. XEvent ev;
  26457. zerostruct (ev);
  26458. ev.xexpose.type = Expose;
  26459. ev.xexpose.display = display;
  26460. ev.xexpose.window = pluginWindow;
  26461. ev.xexpose.x = clip.getX();
  26462. ev.xexpose.y = clip.getY();
  26463. ev.xexpose.width = clip.getWidth();
  26464. ev.xexpose.height = clip.getHeight();
  26465. sendEventToChild (&ev);
  26466. }
  26467. #endif
  26468. }
  26469. }
  26470. else
  26471. {
  26472. g.fillAll (Colours::black);
  26473. }
  26474. }
  26475. #endif
  26476. void timerCallback()
  26477. {
  26478. #if JUCE_WINDOWS
  26479. if (--sizeCheckCount <= 0)
  26480. {
  26481. sizeCheckCount = 10;
  26482. checkPluginWindowSize();
  26483. }
  26484. #endif
  26485. try
  26486. {
  26487. static bool reentrant = false;
  26488. if (! reentrant)
  26489. {
  26490. reentrant = true;
  26491. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26492. reentrant = false;
  26493. }
  26494. }
  26495. catch (...)
  26496. {}
  26497. }
  26498. void mouseDown (const MouseEvent& e)
  26499. {
  26500. #if JUCE_LINUX
  26501. if (pluginWindow == 0)
  26502. return;
  26503. toFront (true);
  26504. XEvent ev;
  26505. zerostruct (ev);
  26506. ev.xbutton.display = display;
  26507. ev.xbutton.type = ButtonPress;
  26508. ev.xbutton.window = pluginWindow;
  26509. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26510. ev.xbutton.time = CurrentTime;
  26511. ev.xbutton.x = e.x;
  26512. ev.xbutton.y = e.y;
  26513. ev.xbutton.x_root = e.getScreenX();
  26514. ev.xbutton.y_root = e.getScreenY();
  26515. translateJuceToXButtonModifiers (e, ev);
  26516. sendEventToChild (&ev);
  26517. #elif JUCE_WINDOWS
  26518. (void) e;
  26519. toFront (true);
  26520. #endif
  26521. }
  26522. void broughtToFront()
  26523. {
  26524. activeVSTWindows.removeValue (this);
  26525. activeVSTWindows.add (this);
  26526. #if JUCE_MAC
  26527. dispatch (effEditTop, 0, 0, 0, 0);
  26528. #endif
  26529. }
  26530. juce_UseDebuggingNewOperator
  26531. private:
  26532. VSTPluginInstance& plugin;
  26533. bool isOpen, wasShowing, recursiveResize;
  26534. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26535. #if JUCE_WINDOWS
  26536. HWND pluginHWND;
  26537. void* originalWndProc;
  26538. int sizeCheckCount;
  26539. #elif JUCE_LINUX
  26540. Window pluginWindow;
  26541. EventProcPtr pluginProc;
  26542. #endif
  26543. #if JUCE_MAC
  26544. void openPluginWindow (WindowRef parentWindow)
  26545. {
  26546. if (isOpen || parentWindow == 0)
  26547. return;
  26548. isOpen = true;
  26549. ERect* rect = 0;
  26550. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26551. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26552. // do this before and after like in the steinberg example
  26553. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26554. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26555. // Install keyboard hooks
  26556. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26557. // double-check it's not too tiny
  26558. int w = 250, h = 150;
  26559. if (rect != 0)
  26560. {
  26561. w = rect->right - rect->left;
  26562. h = rect->bottom - rect->top;
  26563. if (w == 0 || h == 0)
  26564. {
  26565. w = 250;
  26566. h = 150;
  26567. }
  26568. }
  26569. w = jmax (w, 32);
  26570. h = jmax (h, 32);
  26571. setSize (w, h);
  26572. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26573. repaint();
  26574. }
  26575. #else
  26576. void openPluginWindow()
  26577. {
  26578. if (isOpen || getWindowHandle() == 0)
  26579. return;
  26580. log ("Opening VST UI: " + plugin.name);
  26581. isOpen = true;
  26582. ERect* rect = 0;
  26583. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26584. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26585. // do this before and after like in the steinberg example
  26586. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26587. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26588. // Install keyboard hooks
  26589. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26590. #if JUCE_WINDOWS
  26591. originalWndProc = 0;
  26592. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26593. if (pluginHWND == 0)
  26594. {
  26595. isOpen = false;
  26596. setSize (300, 150);
  26597. return;
  26598. }
  26599. #pragma warning (push)
  26600. #pragma warning (disable: 4244)
  26601. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26602. if (! pluginWantsKeys)
  26603. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26604. #pragma warning (pop)
  26605. int w, h;
  26606. RECT r;
  26607. GetWindowRect (pluginHWND, &r);
  26608. w = r.right - r.left;
  26609. h = r.bottom - r.top;
  26610. if (rect != 0)
  26611. {
  26612. const int rw = rect->right - rect->left;
  26613. const int rh = rect->bottom - rect->top;
  26614. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26615. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26616. {
  26617. // very dodgy logic to decide which size is right.
  26618. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26619. {
  26620. SetWindowPos (pluginHWND, 0,
  26621. 0, 0, rw, rh,
  26622. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26623. GetWindowRect (pluginHWND, &r);
  26624. w = r.right - r.left;
  26625. h = r.bottom - r.top;
  26626. pluginRefusesToResize = (w != rw) || (h != rh);
  26627. w = rw;
  26628. h = rh;
  26629. }
  26630. }
  26631. }
  26632. #elif JUCE_LINUX
  26633. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26634. if (pluginWindow != 0)
  26635. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26636. XInternAtom (display, "_XEventProc", False));
  26637. int w = 250, h = 150;
  26638. if (rect != 0)
  26639. {
  26640. w = rect->right - rect->left;
  26641. h = rect->bottom - rect->top;
  26642. if (w == 0 || h == 0)
  26643. {
  26644. w = 250;
  26645. h = 150;
  26646. }
  26647. }
  26648. if (pluginWindow != 0)
  26649. XMapRaised (display, pluginWindow);
  26650. #endif
  26651. // double-check it's not too tiny
  26652. w = jmax (w, 32);
  26653. h = jmax (h, 32);
  26654. setSize (w, h);
  26655. #if JUCE_WINDOWS
  26656. checkPluginWindowSize();
  26657. #endif
  26658. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26659. repaint();
  26660. }
  26661. #endif
  26662. #if ! JUCE_MAC
  26663. void closePluginWindow()
  26664. {
  26665. if (isOpen)
  26666. {
  26667. log ("Closing VST UI: " + plugin.getName());
  26668. isOpen = false;
  26669. dispatch (effEditClose, 0, 0, 0, 0);
  26670. #if JUCE_WINDOWS
  26671. #pragma warning (push)
  26672. #pragma warning (disable: 4244)
  26673. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26674. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26675. #pragma warning (pop)
  26676. stopTimer();
  26677. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26678. DestroyWindow (pluginHWND);
  26679. pluginHWND = 0;
  26680. #elif JUCE_LINUX
  26681. stopTimer();
  26682. pluginWindow = 0;
  26683. pluginProc = 0;
  26684. #endif
  26685. }
  26686. }
  26687. #endif
  26688. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26689. {
  26690. return plugin.dispatch (opcode, index, value, ptr, opt);
  26691. }
  26692. #if JUCE_WINDOWS
  26693. void checkPluginWindowSize() throw()
  26694. {
  26695. RECT r;
  26696. GetWindowRect (pluginHWND, &r);
  26697. const int w = r.right - r.left;
  26698. const int h = r.bottom - r.top;
  26699. if (isShowing() && w > 0 && h > 0
  26700. && (w != getWidth() || h != getHeight())
  26701. && ! pluginRefusesToResize)
  26702. {
  26703. setSize (w, h);
  26704. sizeCheckCount = 0;
  26705. }
  26706. }
  26707. // hooks to get keyboard events from VST windows..
  26708. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26709. {
  26710. for (int i = activeVSTWindows.size(); --i >= 0;)
  26711. {
  26712. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26713. if (w->pluginHWND == hW)
  26714. {
  26715. if (message == WM_CHAR
  26716. || message == WM_KEYDOWN
  26717. || message == WM_SYSKEYDOWN
  26718. || message == WM_KEYUP
  26719. || message == WM_SYSKEYUP
  26720. || message == WM_APPCOMMAND)
  26721. {
  26722. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26723. message, wParam, lParam);
  26724. }
  26725. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26726. (HWND) w->pluginHWND,
  26727. message,
  26728. wParam,
  26729. lParam);
  26730. }
  26731. }
  26732. return DefWindowProc (hW, message, wParam, lParam);
  26733. }
  26734. #endif
  26735. #if JUCE_LINUX
  26736. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26737. void sendEventToChild (XEvent* event)
  26738. {
  26739. if (pluginProc != 0)
  26740. {
  26741. // if the plugin publishes an event procedure, pass the event directly..
  26742. pluginProc (event);
  26743. }
  26744. else if (pluginWindow != 0)
  26745. {
  26746. // if the plugin has a window, then send the event to the window so that
  26747. // its message thread will pick it up..
  26748. XSendEvent (display, pluginWindow, False, 0L, event);
  26749. XFlush (display);
  26750. }
  26751. }
  26752. void mouseEnter (const MouseEvent& e)
  26753. {
  26754. if (pluginWindow != 0)
  26755. {
  26756. XEvent ev;
  26757. zerostruct (ev);
  26758. ev.xcrossing.display = display;
  26759. ev.xcrossing.type = EnterNotify;
  26760. ev.xcrossing.window = pluginWindow;
  26761. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26762. ev.xcrossing.time = CurrentTime;
  26763. ev.xcrossing.x = e.x;
  26764. ev.xcrossing.y = e.y;
  26765. ev.xcrossing.x_root = e.getScreenX();
  26766. ev.xcrossing.y_root = e.getScreenY();
  26767. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26768. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26769. translateJuceToXCrossingModifiers (e, ev);
  26770. sendEventToChild (&ev);
  26771. }
  26772. }
  26773. void mouseExit (const MouseEvent& e)
  26774. {
  26775. if (pluginWindow != 0)
  26776. {
  26777. XEvent ev;
  26778. zerostruct (ev);
  26779. ev.xcrossing.display = display;
  26780. ev.xcrossing.type = LeaveNotify;
  26781. ev.xcrossing.window = pluginWindow;
  26782. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26783. ev.xcrossing.time = CurrentTime;
  26784. ev.xcrossing.x = e.x;
  26785. ev.xcrossing.y = e.y;
  26786. ev.xcrossing.x_root = e.getScreenX();
  26787. ev.xcrossing.y_root = e.getScreenY();
  26788. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26789. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26790. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26791. translateJuceToXCrossingModifiers (e, ev);
  26792. sendEventToChild (&ev);
  26793. }
  26794. }
  26795. void mouseMove (const MouseEvent& e)
  26796. {
  26797. if (pluginWindow != 0)
  26798. {
  26799. XEvent ev;
  26800. zerostruct (ev);
  26801. ev.xmotion.display = display;
  26802. ev.xmotion.type = MotionNotify;
  26803. ev.xmotion.window = pluginWindow;
  26804. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26805. ev.xmotion.time = CurrentTime;
  26806. ev.xmotion.is_hint = NotifyNormal;
  26807. ev.xmotion.x = e.x;
  26808. ev.xmotion.y = e.y;
  26809. ev.xmotion.x_root = e.getScreenX();
  26810. ev.xmotion.y_root = e.getScreenY();
  26811. sendEventToChild (&ev);
  26812. }
  26813. }
  26814. void mouseDrag (const MouseEvent& e)
  26815. {
  26816. if (pluginWindow != 0)
  26817. {
  26818. XEvent ev;
  26819. zerostruct (ev);
  26820. ev.xmotion.display = display;
  26821. ev.xmotion.type = MotionNotify;
  26822. ev.xmotion.window = pluginWindow;
  26823. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26824. ev.xmotion.time = CurrentTime;
  26825. ev.xmotion.x = e.x ;
  26826. ev.xmotion.y = e.y;
  26827. ev.xmotion.x_root = e.getScreenX();
  26828. ev.xmotion.y_root = e.getScreenY();
  26829. ev.xmotion.is_hint = NotifyNormal;
  26830. translateJuceToXMotionModifiers (e, ev);
  26831. sendEventToChild (&ev);
  26832. }
  26833. }
  26834. void mouseUp (const MouseEvent& e)
  26835. {
  26836. if (pluginWindow != 0)
  26837. {
  26838. XEvent ev;
  26839. zerostruct (ev);
  26840. ev.xbutton.display = display;
  26841. ev.xbutton.type = ButtonRelease;
  26842. ev.xbutton.window = pluginWindow;
  26843. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26844. ev.xbutton.time = CurrentTime;
  26845. ev.xbutton.x = e.x;
  26846. ev.xbutton.y = e.y;
  26847. ev.xbutton.x_root = e.getScreenX();
  26848. ev.xbutton.y_root = e.getScreenY();
  26849. translateJuceToXButtonModifiers (e, ev);
  26850. sendEventToChild (&ev);
  26851. }
  26852. }
  26853. void mouseWheelMove (const MouseEvent& e,
  26854. float incrementX,
  26855. float incrementY)
  26856. {
  26857. if (pluginWindow != 0)
  26858. {
  26859. XEvent ev;
  26860. zerostruct (ev);
  26861. ev.xbutton.display = display;
  26862. ev.xbutton.type = ButtonPress;
  26863. ev.xbutton.window = pluginWindow;
  26864. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26865. ev.xbutton.time = CurrentTime;
  26866. ev.xbutton.x = e.x;
  26867. ev.xbutton.y = e.y;
  26868. ev.xbutton.x_root = e.getScreenX();
  26869. ev.xbutton.y_root = e.getScreenY();
  26870. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26871. sendEventToChild (&ev);
  26872. // TODO - put a usleep here ?
  26873. ev.xbutton.type = ButtonRelease;
  26874. sendEventToChild (&ev);
  26875. }
  26876. }
  26877. #endif
  26878. #if JUCE_MAC
  26879. #if ! JUCE_SUPPORT_CARBON
  26880. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26881. #endif
  26882. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26883. {
  26884. public:
  26885. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26886. : owner (owner_),
  26887. alreadyInside (false)
  26888. {
  26889. }
  26890. ~InnerWrapperComponent()
  26891. {
  26892. deleteWindow();
  26893. }
  26894. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26895. {
  26896. owner->openPluginWindow (windowRef);
  26897. return 0;
  26898. }
  26899. void removeView (HIViewRef)
  26900. {
  26901. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26902. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26903. }
  26904. bool getEmbeddedViewSize (int& w, int& h)
  26905. {
  26906. ERect* rect = 0;
  26907. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26908. w = rect->right - rect->left;
  26909. h = rect->bottom - rect->top;
  26910. return true;
  26911. }
  26912. void mouseDown (int x, int y)
  26913. {
  26914. if (! alreadyInside)
  26915. {
  26916. alreadyInside = true;
  26917. getTopLevelComponent()->toFront (true);
  26918. owner->dispatch (effEditMouse, x, y, 0, 0);
  26919. alreadyInside = false;
  26920. }
  26921. else
  26922. {
  26923. PostEvent (::mouseDown, 0);
  26924. }
  26925. }
  26926. void paint()
  26927. {
  26928. ComponentPeer* const peer = getPeer();
  26929. if (peer != 0)
  26930. {
  26931. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26932. ERect r;
  26933. r.left = pos.getX();
  26934. r.right = r.left + getWidth();
  26935. r.top = pos.getY();
  26936. r.bottom = r.top + getHeight();
  26937. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26938. }
  26939. }
  26940. private:
  26941. VSTPluginWindow* const owner;
  26942. bool alreadyInside;
  26943. };
  26944. friend class InnerWrapperComponent;
  26945. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26946. void resized()
  26947. {
  26948. innerWrapper->setSize (getWidth(), getHeight());
  26949. }
  26950. #endif
  26951. };
  26952. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26953. {
  26954. if (hasEditor())
  26955. return new VSTPluginWindow (*this);
  26956. return 0;
  26957. }
  26958. void VSTPluginInstance::handleAsyncUpdate()
  26959. {
  26960. // indicates that something about the plugin has changed..
  26961. updateHostDisplay();
  26962. }
  26963. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26964. {
  26965. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26966. {
  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. return true;
  26971. }
  26972. return false;
  26973. }
  26974. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26975. const int dataSize)
  26976. {
  26977. if (dataSize < 28)
  26978. return false;
  26979. const fxSet* const set = (const fxSet*) data;
  26980. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26981. || vst_swap (set->version) > fxbVersionNum)
  26982. return false;
  26983. if (vst_swap (set->fxMagic) == 'FxBk')
  26984. {
  26985. // bank of programs
  26986. if (vst_swap (set->numPrograms) >= 0)
  26987. {
  26988. const int oldProg = getCurrentProgram();
  26989. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26990. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26991. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26992. {
  26993. if (i != oldProg)
  26994. {
  26995. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26996. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26997. return false;
  26998. if (vst_swap (set->numPrograms) > 0)
  26999. setCurrentProgram (i);
  27000. if (! restoreProgramSettings (prog))
  27001. return false;
  27002. }
  27003. }
  27004. if (vst_swap (set->numPrograms) > 0)
  27005. setCurrentProgram (oldProg);
  27006. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27007. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27008. return false;
  27009. if (! restoreProgramSettings (prog))
  27010. return false;
  27011. }
  27012. }
  27013. else if (vst_swap (set->fxMagic) == 'FxCk')
  27014. {
  27015. // single program
  27016. const fxProgram* const prog = (const fxProgram*) data;
  27017. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27018. return false;
  27019. changeProgramName (getCurrentProgram(), prog->prgName);
  27020. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27021. setParameter (i, vst_swapFloat (prog->params[i]));
  27022. }
  27023. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27024. {
  27025. // non-preset chunk
  27026. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27027. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27028. return false;
  27029. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27030. }
  27031. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27032. {
  27033. // preset chunk
  27034. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27035. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27036. return false;
  27037. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27038. changeProgramName (getCurrentProgram(), cset->name);
  27039. }
  27040. else
  27041. {
  27042. return false;
  27043. }
  27044. return true;
  27045. }
  27046. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27047. {
  27048. const int numParams = getNumParameters();
  27049. prog->chunkMagic = vst_swap ('CcnK');
  27050. prog->byteSize = 0;
  27051. prog->fxMagic = vst_swap ('FxCk');
  27052. prog->version = vst_swap (fxbVersionNum);
  27053. prog->fxID = vst_swap (getUID());
  27054. prog->fxVersion = vst_swap (getVersionNumber());
  27055. prog->numParams = vst_swap (numParams);
  27056. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27057. for (int i = 0; i < numParams; ++i)
  27058. prog->params[i] = vst_swapFloat (getParameter (i));
  27059. }
  27060. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27061. {
  27062. const int numPrograms = getNumPrograms();
  27063. const int numParams = getNumParameters();
  27064. if (usesChunks())
  27065. {
  27066. if (isFXB)
  27067. {
  27068. MemoryBlock chunk;
  27069. getChunkData (chunk, false, maxSizeMB);
  27070. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27071. dest.setSize (totalLen, true);
  27072. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27073. set->chunkMagic = vst_swap ('CcnK');
  27074. set->byteSize = 0;
  27075. set->fxMagic = vst_swap ('FBCh');
  27076. set->version = vst_swap (fxbVersionNum);
  27077. set->fxID = vst_swap (getUID());
  27078. set->fxVersion = vst_swap (getVersionNumber());
  27079. set->numPrograms = vst_swap (numPrograms);
  27080. set->chunkSize = vst_swap ((long) chunk.getSize());
  27081. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27082. }
  27083. else
  27084. {
  27085. MemoryBlock chunk;
  27086. getChunkData (chunk, true, maxSizeMB);
  27087. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27088. dest.setSize (totalLen, true);
  27089. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27090. set->chunkMagic = vst_swap ('CcnK');
  27091. set->byteSize = 0;
  27092. set->fxMagic = vst_swap ('FPCh');
  27093. set->version = vst_swap (fxbVersionNum);
  27094. set->fxID = vst_swap (getUID());
  27095. set->fxVersion = vst_swap (getVersionNumber());
  27096. set->numPrograms = vst_swap (numPrograms);
  27097. set->chunkSize = vst_swap ((long) chunk.getSize());
  27098. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27099. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27100. }
  27101. }
  27102. else
  27103. {
  27104. if (isFXB)
  27105. {
  27106. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27107. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27108. dest.setSize (len, true);
  27109. fxSet* const set = (fxSet*) dest.getData();
  27110. set->chunkMagic = vst_swap ('CcnK');
  27111. set->byteSize = 0;
  27112. set->fxMagic = vst_swap ('FxBk');
  27113. set->version = vst_swap (fxbVersionNum);
  27114. set->fxID = vst_swap (getUID());
  27115. set->fxVersion = vst_swap (getVersionNumber());
  27116. set->numPrograms = vst_swap (numPrograms);
  27117. const int oldProgram = getCurrentProgram();
  27118. MemoryBlock oldSettings;
  27119. createTempParameterStore (oldSettings);
  27120. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27121. for (int i = 0; i < numPrograms; ++i)
  27122. {
  27123. if (i != oldProgram)
  27124. {
  27125. setCurrentProgram (i);
  27126. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27127. }
  27128. }
  27129. setCurrentProgram (oldProgram);
  27130. restoreFromTempParameterStore (oldSettings);
  27131. }
  27132. else
  27133. {
  27134. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27135. dest.setSize (totalLen, true);
  27136. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27137. }
  27138. }
  27139. return true;
  27140. }
  27141. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27142. {
  27143. if (usesChunks())
  27144. {
  27145. void* data = 0;
  27146. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27147. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27148. {
  27149. mb.setSize (bytes);
  27150. mb.copyFrom (data, 0, bytes);
  27151. }
  27152. }
  27153. }
  27154. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27155. {
  27156. if (size > 0 && usesChunks())
  27157. {
  27158. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27159. if (! isPreset)
  27160. updateStoredProgramNames();
  27161. }
  27162. }
  27163. void VSTPluginInstance::timerCallback()
  27164. {
  27165. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27166. stopTimer();
  27167. }
  27168. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27169. {
  27170. const ScopedLock sl (lock);
  27171. ++insideVSTCallback;
  27172. int result = 0;
  27173. try
  27174. {
  27175. if (effect != 0)
  27176. {
  27177. #if JUCE_MAC
  27178. if (module->resFileId != 0)
  27179. UseResFile (module->resFileId);
  27180. CGrafPtr oldPort;
  27181. if (getActiveEditor() != 0)
  27182. {
  27183. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27184. GetPort (&oldPort);
  27185. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27186. SetOrigin (-pos.getX(), -pos.getY());
  27187. }
  27188. #endif
  27189. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27190. #if JUCE_MAC
  27191. if (getActiveEditor() != 0)
  27192. SetPort (oldPort);
  27193. module->resFileId = CurResFile();
  27194. #endif
  27195. --insideVSTCallback;
  27196. return result;
  27197. }
  27198. }
  27199. catch (...)
  27200. {
  27201. }
  27202. --insideVSTCallback;
  27203. return result;
  27204. }
  27205. // handles non plugin-specific callbacks..
  27206. static const int defaultVSTSampleRateValue = 16384;
  27207. static const int defaultVSTBlockSizeValue = 512;
  27208. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27209. {
  27210. (void) index;
  27211. (void) value;
  27212. (void) opt;
  27213. switch (opcode)
  27214. {
  27215. case audioMasterCanDo:
  27216. {
  27217. static const char* canDos[] = { "supplyIdle",
  27218. "sendVstEvents",
  27219. "sendVstMidiEvent",
  27220. "sendVstTimeInfo",
  27221. "receiveVstEvents",
  27222. "receiveVstMidiEvent",
  27223. "supportShell",
  27224. "shellCategory" };
  27225. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27226. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27227. return 1;
  27228. return 0;
  27229. }
  27230. case audioMasterVersion:
  27231. return 0x2400;
  27232. case audioMasterCurrentId:
  27233. return shellUIDToCreate;
  27234. case audioMasterGetNumAutomatableParameters:
  27235. return 0;
  27236. case audioMasterGetAutomationState:
  27237. return 1;
  27238. case audioMasterGetVendorVersion:
  27239. return 0x0101;
  27240. case audioMasterGetVendorString:
  27241. case audioMasterGetProductString:
  27242. {
  27243. String hostName ("Juce VST Host");
  27244. if (JUCEApplication::getInstance() != 0)
  27245. hostName = JUCEApplication::getInstance()->getApplicationName();
  27246. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27247. }
  27248. break;
  27249. case audioMasterGetSampleRate:
  27250. return (VstIntPtr) defaultVSTSampleRateValue;
  27251. case audioMasterGetBlockSize:
  27252. return (VstIntPtr) defaultVSTBlockSizeValue;
  27253. case audioMasterSetOutputSampleRate:
  27254. return 0;
  27255. default:
  27256. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27257. break;
  27258. }
  27259. return 0;
  27260. }
  27261. // handles callbacks for a specific plugin
  27262. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27263. {
  27264. switch (opcode)
  27265. {
  27266. case audioMasterAutomate:
  27267. sendParamChangeMessageToListeners (index, opt);
  27268. break;
  27269. case audioMasterProcessEvents:
  27270. handleMidiFromPlugin ((const VstEvents*) ptr);
  27271. break;
  27272. case audioMasterGetTime:
  27273. #if JUCE_MSVC
  27274. #pragma warning (push)
  27275. #pragma warning (disable: 4311)
  27276. #endif
  27277. return (VstIntPtr) &vstHostTime;
  27278. #if JUCE_MSVC
  27279. #pragma warning (pop)
  27280. #endif
  27281. break;
  27282. case audioMasterIdle:
  27283. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27284. {
  27285. ++insideVSTCallback;
  27286. #if JUCE_MAC
  27287. if (getActiveEditor() != 0)
  27288. dispatch (effEditIdle, 0, 0, 0, 0);
  27289. #endif
  27290. juce_callAnyTimersSynchronously();
  27291. handleUpdateNowIfNeeded();
  27292. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27293. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27294. --insideVSTCallback;
  27295. }
  27296. break;
  27297. case audioMasterUpdateDisplay:
  27298. triggerAsyncUpdate();
  27299. break;
  27300. case audioMasterTempoAt:
  27301. // returns (10000 * bpm)
  27302. break;
  27303. case audioMasterNeedIdle:
  27304. startTimer (50);
  27305. break;
  27306. case audioMasterSizeWindow:
  27307. if (getActiveEditor() != 0)
  27308. getActiveEditor()->setSize (index, value);
  27309. return 1;
  27310. case audioMasterGetSampleRate:
  27311. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27312. case audioMasterGetBlockSize:
  27313. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27314. case audioMasterWantMidi:
  27315. wantsMidiMessages = true;
  27316. break;
  27317. case audioMasterGetDirectory:
  27318. #if JUCE_MAC
  27319. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27320. #else
  27321. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27322. #endif
  27323. case audioMasterGetAutomationState:
  27324. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27325. break;
  27326. // none of these are handled (yet)..
  27327. case audioMasterBeginEdit:
  27328. case audioMasterEndEdit:
  27329. case audioMasterSetTime:
  27330. case audioMasterPinConnected:
  27331. case audioMasterGetParameterQuantization:
  27332. case audioMasterIOChanged:
  27333. case audioMasterGetInputLatency:
  27334. case audioMasterGetOutputLatency:
  27335. case audioMasterGetPreviousPlug:
  27336. case audioMasterGetNextPlug:
  27337. case audioMasterWillReplaceOrAccumulate:
  27338. case audioMasterGetCurrentProcessLevel:
  27339. case audioMasterOfflineStart:
  27340. case audioMasterOfflineRead:
  27341. case audioMasterOfflineWrite:
  27342. case audioMasterOfflineGetCurrentPass:
  27343. case audioMasterOfflineGetCurrentMetaPass:
  27344. case audioMasterVendorSpecific:
  27345. case audioMasterSetIcon:
  27346. case audioMasterGetLanguage:
  27347. case audioMasterOpenWindow:
  27348. case audioMasterCloseWindow:
  27349. break;
  27350. default:
  27351. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27352. }
  27353. return 0;
  27354. }
  27355. // entry point for all callbacks from the plugin
  27356. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27357. {
  27358. try
  27359. {
  27360. if (effect != 0 && effect->resvd2 != 0)
  27361. {
  27362. return ((VSTPluginInstance*)(effect->resvd2))
  27363. ->handleCallback (opcode, index, value, ptr, opt);
  27364. }
  27365. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27366. }
  27367. catch (...)
  27368. {
  27369. return 0;
  27370. }
  27371. }
  27372. const String VSTPluginInstance::getVersion() const throw()
  27373. {
  27374. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27375. String s;
  27376. if (v == 0 || v == -1)
  27377. v = getVersionNumber();
  27378. if (v != 0)
  27379. {
  27380. int versionBits[4];
  27381. int n = 0;
  27382. while (v != 0)
  27383. {
  27384. versionBits [n++] = (v & 0xff);
  27385. v >>= 8;
  27386. }
  27387. s << 'V';
  27388. while (n > 0)
  27389. {
  27390. s << versionBits [--n];
  27391. if (n > 0)
  27392. s << '.';
  27393. }
  27394. }
  27395. return s;
  27396. }
  27397. int VSTPluginInstance::getUID() const throw()
  27398. {
  27399. int uid = effect != 0 ? effect->uniqueID : 0;
  27400. if (uid == 0)
  27401. uid = module->file.hashCode();
  27402. return uid;
  27403. }
  27404. const String VSTPluginInstance::getCategory() const throw()
  27405. {
  27406. const char* result = 0;
  27407. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27408. {
  27409. case kPlugCategEffect:
  27410. result = "Effect";
  27411. break;
  27412. case kPlugCategSynth:
  27413. result = "Synth";
  27414. break;
  27415. case kPlugCategAnalysis:
  27416. result = "Anaylsis";
  27417. break;
  27418. case kPlugCategMastering:
  27419. result = "Mastering";
  27420. break;
  27421. case kPlugCategSpacializer:
  27422. result = "Spacial";
  27423. break;
  27424. case kPlugCategRoomFx:
  27425. result = "Reverb";
  27426. break;
  27427. case kPlugSurroundFx:
  27428. result = "Surround";
  27429. break;
  27430. case kPlugCategRestoration:
  27431. result = "Restoration";
  27432. break;
  27433. case kPlugCategGenerator:
  27434. result = "Tone generation";
  27435. break;
  27436. default:
  27437. break;
  27438. }
  27439. return result;
  27440. }
  27441. float VSTPluginInstance::getParameter (int index)
  27442. {
  27443. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27444. {
  27445. try
  27446. {
  27447. const ScopedLock sl (lock);
  27448. return effect->getParameter (effect, index);
  27449. }
  27450. catch (...)
  27451. {
  27452. }
  27453. }
  27454. return 0.0f;
  27455. }
  27456. void VSTPluginInstance::setParameter (int index, float newValue)
  27457. {
  27458. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27459. {
  27460. try
  27461. {
  27462. const ScopedLock sl (lock);
  27463. if (effect->getParameter (effect, index) != newValue)
  27464. effect->setParameter (effect, index, newValue);
  27465. }
  27466. catch (...)
  27467. {
  27468. }
  27469. }
  27470. }
  27471. const String VSTPluginInstance::getParameterName (int index)
  27472. {
  27473. if (effect != 0)
  27474. {
  27475. jassert (index >= 0 && index < effect->numParams);
  27476. char nm [256];
  27477. zerostruct (nm);
  27478. dispatch (effGetParamName, index, 0, nm, 0);
  27479. return String (nm).trim();
  27480. }
  27481. return String::empty;
  27482. }
  27483. const String VSTPluginInstance::getParameterLabel (int index) const
  27484. {
  27485. if (effect != 0)
  27486. {
  27487. jassert (index >= 0 && index < effect->numParams);
  27488. char nm [256];
  27489. zerostruct (nm);
  27490. dispatch (effGetParamLabel, index, 0, nm, 0);
  27491. return String (nm).trim();
  27492. }
  27493. return String::empty;
  27494. }
  27495. const String VSTPluginInstance::getParameterText (int index)
  27496. {
  27497. if (effect != 0)
  27498. {
  27499. jassert (index >= 0 && index < effect->numParams);
  27500. char nm [256];
  27501. zerostruct (nm);
  27502. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27503. return String (nm).trim();
  27504. }
  27505. return String::empty;
  27506. }
  27507. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27508. {
  27509. if (effect != 0)
  27510. {
  27511. jassert (index >= 0 && index < effect->numParams);
  27512. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27513. }
  27514. return false;
  27515. }
  27516. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27517. {
  27518. dest.setSize (64 + 4 * getNumParameters());
  27519. dest.fillWith (0);
  27520. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27521. float* const p = (float*) (((char*) dest.getData()) + 64);
  27522. for (int i = 0; i < getNumParameters(); ++i)
  27523. p[i] = getParameter(i);
  27524. }
  27525. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27526. {
  27527. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27528. float* p = (float*) (((char*) m.getData()) + 64);
  27529. for (int i = 0; i < getNumParameters(); ++i)
  27530. setParameter (i, p[i]);
  27531. }
  27532. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27533. {
  27534. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27535. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27536. }
  27537. const String VSTPluginInstance::getProgramName (int index)
  27538. {
  27539. if (index == getCurrentProgram())
  27540. {
  27541. return getCurrentProgramName();
  27542. }
  27543. else if (effect != 0)
  27544. {
  27545. char nm [256];
  27546. zerostruct (nm);
  27547. if (dispatch (effGetProgramNameIndexed,
  27548. jlimit (0, getNumPrograms(), index),
  27549. -1, nm, 0) != 0)
  27550. {
  27551. return String (nm).trim();
  27552. }
  27553. }
  27554. return programNames [index];
  27555. }
  27556. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27557. {
  27558. if (index == getCurrentProgram())
  27559. {
  27560. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27561. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27562. }
  27563. else
  27564. {
  27565. jassertfalse; // xxx not implemented!
  27566. }
  27567. }
  27568. void VSTPluginInstance::updateStoredProgramNames()
  27569. {
  27570. if (effect != 0 && getNumPrograms() > 0)
  27571. {
  27572. char nm [256];
  27573. zerostruct (nm);
  27574. // only do this if the plugin can't use indexed names..
  27575. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27576. {
  27577. const int oldProgram = getCurrentProgram();
  27578. MemoryBlock oldSettings;
  27579. createTempParameterStore (oldSettings);
  27580. for (int i = 0; i < getNumPrograms(); ++i)
  27581. {
  27582. setCurrentProgram (i);
  27583. getCurrentProgramName(); // (this updates the list)
  27584. }
  27585. setCurrentProgram (oldProgram);
  27586. restoreFromTempParameterStore (oldSettings);
  27587. }
  27588. }
  27589. }
  27590. const String VSTPluginInstance::getCurrentProgramName()
  27591. {
  27592. if (effect != 0)
  27593. {
  27594. char nm [256];
  27595. zerostruct (nm);
  27596. dispatch (effGetProgramName, 0, 0, nm, 0);
  27597. const int index = getCurrentProgram();
  27598. if (programNames[index].isEmpty())
  27599. {
  27600. while (programNames.size() < index)
  27601. programNames.add (String::empty);
  27602. programNames.set (index, String (nm).trim());
  27603. }
  27604. return String (nm).trim();
  27605. }
  27606. return String::empty;
  27607. }
  27608. const String VSTPluginInstance::getInputChannelName (const int index) const
  27609. {
  27610. if (index >= 0 && index < getNumInputChannels())
  27611. {
  27612. VstPinProperties pinProps;
  27613. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27614. return String (pinProps.label, sizeof (pinProps.label));
  27615. }
  27616. return String::empty;
  27617. }
  27618. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27619. {
  27620. if (index < 0 || index >= getNumInputChannels())
  27621. return false;
  27622. VstPinProperties pinProps;
  27623. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27624. return (pinProps.flags & kVstPinIsStereo) != 0;
  27625. return true;
  27626. }
  27627. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27628. {
  27629. if (index >= 0 && index < getNumOutputChannels())
  27630. {
  27631. VstPinProperties pinProps;
  27632. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27633. return String (pinProps.label, sizeof (pinProps.label));
  27634. }
  27635. return String::empty;
  27636. }
  27637. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27638. {
  27639. if (index < 0 || index >= getNumOutputChannels())
  27640. return false;
  27641. VstPinProperties pinProps;
  27642. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27643. return (pinProps.flags & kVstPinIsStereo) != 0;
  27644. return true;
  27645. }
  27646. void VSTPluginInstance::setPower (const bool on)
  27647. {
  27648. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27649. isPowerOn = on;
  27650. }
  27651. const int defaultMaxSizeMB = 64;
  27652. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27653. {
  27654. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27655. }
  27656. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27657. {
  27658. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27659. }
  27660. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27661. {
  27662. loadFromFXBFile (data, sizeInBytes);
  27663. }
  27664. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27665. {
  27666. loadFromFXBFile (data, sizeInBytes);
  27667. }
  27668. VSTPluginFormat::VSTPluginFormat()
  27669. {
  27670. }
  27671. VSTPluginFormat::~VSTPluginFormat()
  27672. {
  27673. }
  27674. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27675. const String& fileOrIdentifier)
  27676. {
  27677. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27678. return;
  27679. PluginDescription desc;
  27680. desc.fileOrIdentifier = fileOrIdentifier;
  27681. desc.uid = 0;
  27682. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27683. if (instance == 0)
  27684. return;
  27685. try
  27686. {
  27687. #if JUCE_MAC
  27688. if (instance->module->resFileId != 0)
  27689. UseResFile (instance->module->resFileId);
  27690. #endif
  27691. instance->fillInPluginDescription (desc);
  27692. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27693. if (category != kPlugCategShell)
  27694. {
  27695. // Normal plugin...
  27696. results.add (new PluginDescription (desc));
  27697. ++insideVSTCallback;
  27698. instance->dispatch (effOpen, 0, 0, 0, 0);
  27699. --insideVSTCallback;
  27700. }
  27701. else
  27702. {
  27703. // It's a shell plugin, so iterate all the subtypes...
  27704. char shellEffectName [64];
  27705. for (;;)
  27706. {
  27707. zerostruct (shellEffectName);
  27708. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27709. if (uid == 0)
  27710. {
  27711. break;
  27712. }
  27713. else
  27714. {
  27715. desc.uid = uid;
  27716. desc.name = shellEffectName;
  27717. bool alreadyThere = false;
  27718. for (int i = results.size(); --i >= 0;)
  27719. {
  27720. PluginDescription* const d = results.getUnchecked(i);
  27721. if (d->isDuplicateOf (desc))
  27722. {
  27723. alreadyThere = true;
  27724. break;
  27725. }
  27726. }
  27727. if (! alreadyThere)
  27728. results.add (new PluginDescription (desc));
  27729. }
  27730. }
  27731. }
  27732. }
  27733. catch (...)
  27734. {
  27735. // crashed while loading...
  27736. }
  27737. }
  27738. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27739. {
  27740. ScopedPointer <VSTPluginInstance> result;
  27741. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27742. {
  27743. File file (desc.fileOrIdentifier);
  27744. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27745. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27746. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27747. if (module != 0)
  27748. {
  27749. shellUIDToCreate = desc.uid;
  27750. result = new VSTPluginInstance (module);
  27751. if (result->effect != 0)
  27752. {
  27753. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27754. result->initialise();
  27755. }
  27756. else
  27757. {
  27758. result = 0;
  27759. }
  27760. }
  27761. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27762. }
  27763. return result.release();
  27764. }
  27765. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27766. {
  27767. const File f (fileOrIdentifier);
  27768. #if JUCE_MAC
  27769. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27770. return true;
  27771. #if JUCE_PPC
  27772. FSRef fileRef;
  27773. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27774. {
  27775. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27776. if (resFileId != -1)
  27777. {
  27778. const int numEffects = Count1Resources ('aEff');
  27779. CloseResFile (resFileId);
  27780. if (numEffects > 0)
  27781. return true;
  27782. }
  27783. }
  27784. #endif
  27785. return false;
  27786. #elif JUCE_WINDOWS
  27787. return f.existsAsFile()
  27788. && f.hasFileExtension (".dll");
  27789. #elif JUCE_LINUX
  27790. return f.existsAsFile()
  27791. && f.hasFileExtension (".so");
  27792. #endif
  27793. }
  27794. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27795. {
  27796. return fileOrIdentifier;
  27797. }
  27798. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27799. {
  27800. return File (desc.fileOrIdentifier).exists();
  27801. }
  27802. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27803. {
  27804. StringArray results;
  27805. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27806. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27807. return results;
  27808. }
  27809. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27810. {
  27811. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27812. // .component or .vst directories.
  27813. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27814. while (iter.next())
  27815. {
  27816. const File f (iter.getFile());
  27817. bool isPlugin = false;
  27818. if (fileMightContainThisPluginType (f.getFullPathName()))
  27819. {
  27820. isPlugin = true;
  27821. results.add (f.getFullPathName());
  27822. }
  27823. if (recursive && (! isPlugin) && f.isDirectory())
  27824. recursiveFileSearch (results, f, true);
  27825. }
  27826. }
  27827. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27828. {
  27829. #if JUCE_MAC
  27830. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27831. #elif JUCE_WINDOWS
  27832. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27833. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27834. #elif JUCE_LINUX
  27835. return FileSearchPath ("/usr/lib/vst");
  27836. #endif
  27837. }
  27838. END_JUCE_NAMESPACE
  27839. #endif
  27840. #undef log
  27841. #endif
  27842. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27843. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27844. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27845. BEGIN_JUCE_NAMESPACE
  27846. AudioProcessor::AudioProcessor()
  27847. : playHead (0),
  27848. activeEditor (0),
  27849. sampleRate (0),
  27850. blockSize (0),
  27851. numInputChannels (0),
  27852. numOutputChannels (0),
  27853. latencySamples (0),
  27854. suspended (false),
  27855. nonRealtime (false)
  27856. {
  27857. }
  27858. AudioProcessor::~AudioProcessor()
  27859. {
  27860. // ooh, nasty - the editor should have been deleted before the filter
  27861. // that it refers to is deleted..
  27862. jassert (activeEditor == 0);
  27863. #if JUCE_DEBUG
  27864. // This will fail if you've called beginParameterChangeGesture() for one
  27865. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27866. jassert (changingParams.countNumberOfSetBits() == 0);
  27867. #endif
  27868. }
  27869. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27870. {
  27871. playHead = newPlayHead;
  27872. }
  27873. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27874. {
  27875. const ScopedLock sl (listenerLock);
  27876. listeners.addIfNotAlreadyThere (newListener);
  27877. }
  27878. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27879. {
  27880. const ScopedLock sl (listenerLock);
  27881. listeners.removeValue (listenerToRemove);
  27882. }
  27883. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27884. const int numOuts,
  27885. const double sampleRate_,
  27886. const int blockSize_) throw()
  27887. {
  27888. numInputChannels = numIns;
  27889. numOutputChannels = numOuts;
  27890. sampleRate = sampleRate_;
  27891. blockSize = blockSize_;
  27892. }
  27893. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27894. {
  27895. nonRealtime = nonRealtime_;
  27896. }
  27897. void AudioProcessor::setLatencySamples (const int newLatency)
  27898. {
  27899. if (latencySamples != newLatency)
  27900. {
  27901. latencySamples = newLatency;
  27902. updateHostDisplay();
  27903. }
  27904. }
  27905. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27906. const float newValue)
  27907. {
  27908. setParameter (parameterIndex, newValue);
  27909. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27910. }
  27911. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27912. {
  27913. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27914. for (int i = listeners.size(); --i >= 0;)
  27915. {
  27916. AudioProcessorListener* l;
  27917. {
  27918. const ScopedLock sl (listenerLock);
  27919. l = listeners [i];
  27920. }
  27921. if (l != 0)
  27922. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27923. }
  27924. }
  27925. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27926. {
  27927. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27928. #if JUCE_DEBUG
  27929. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27930. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27931. jassert (! changingParams [parameterIndex]);
  27932. changingParams.setBit (parameterIndex);
  27933. #endif
  27934. for (int i = listeners.size(); --i >= 0;)
  27935. {
  27936. AudioProcessorListener* l;
  27937. {
  27938. const ScopedLock sl (listenerLock);
  27939. l = listeners [i];
  27940. }
  27941. if (l != 0)
  27942. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27943. }
  27944. }
  27945. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27946. {
  27947. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27948. #if JUCE_DEBUG
  27949. // This means you've called endParameterChangeGesture without having previously called
  27950. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27951. // calls matched correctly.
  27952. jassert (changingParams [parameterIndex]);
  27953. changingParams.clearBit (parameterIndex);
  27954. #endif
  27955. for (int i = listeners.size(); --i >= 0;)
  27956. {
  27957. AudioProcessorListener* l;
  27958. {
  27959. const ScopedLock sl (listenerLock);
  27960. l = listeners [i];
  27961. }
  27962. if (l != 0)
  27963. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27964. }
  27965. }
  27966. void AudioProcessor::updateHostDisplay()
  27967. {
  27968. for (int i = listeners.size(); --i >= 0;)
  27969. {
  27970. AudioProcessorListener* l;
  27971. {
  27972. const ScopedLock sl (listenerLock);
  27973. l = listeners [i];
  27974. }
  27975. if (l != 0)
  27976. l->audioProcessorChanged (this);
  27977. }
  27978. }
  27979. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27980. {
  27981. return true;
  27982. }
  27983. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27984. {
  27985. return false;
  27986. }
  27987. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27988. {
  27989. const ScopedLock sl (callbackLock);
  27990. suspended = shouldBeSuspended;
  27991. }
  27992. void AudioProcessor::reset()
  27993. {
  27994. }
  27995. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27996. {
  27997. const ScopedLock sl (callbackLock);
  27998. jassert (activeEditor == editor);
  27999. if (activeEditor == editor)
  28000. activeEditor = 0;
  28001. }
  28002. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28003. {
  28004. if (activeEditor != 0)
  28005. return activeEditor;
  28006. AudioProcessorEditor* const ed = createEditor();
  28007. if (ed != 0)
  28008. {
  28009. // you must give your editor comp a size before returning it..
  28010. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28011. const ScopedLock sl (callbackLock);
  28012. activeEditor = ed;
  28013. }
  28014. return ed;
  28015. }
  28016. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28017. {
  28018. getStateInformation (destData);
  28019. }
  28020. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28021. {
  28022. setStateInformation (data, sizeInBytes);
  28023. }
  28024. // magic number to identify memory blocks that we've stored as XML
  28025. const uint32 magicXmlNumber = 0x21324356;
  28026. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28027. JUCE_NAMESPACE::MemoryBlock& destData)
  28028. {
  28029. const String xmlString (xml.createDocument (String::empty, true, false));
  28030. const int stringLength = xmlString.getNumBytesAsUTF8();
  28031. destData.setSize (stringLength + 10);
  28032. char* const d = (char*) destData.getData();
  28033. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28034. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28035. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28036. }
  28037. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28038. const int sizeInBytes)
  28039. {
  28040. if (sizeInBytes > 8
  28041. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28042. {
  28043. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28044. if (stringLength > 0)
  28045. {
  28046. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28047. jmin ((sizeInBytes - 8), stringLength)));
  28048. return doc.getDocumentElement();
  28049. }
  28050. }
  28051. return 0;
  28052. }
  28053. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28054. {
  28055. }
  28056. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28057. {
  28058. }
  28059. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28060. {
  28061. return timeInSeconds == other.timeInSeconds
  28062. && ppqPosition == other.ppqPosition
  28063. && editOriginTime == other.editOriginTime
  28064. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28065. && frameRate == other.frameRate
  28066. && isPlaying == other.isPlaying
  28067. && isRecording == other.isRecording
  28068. && bpm == other.bpm
  28069. && timeSigNumerator == other.timeSigNumerator
  28070. && timeSigDenominator == other.timeSigDenominator;
  28071. }
  28072. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28073. {
  28074. return ! operator== (other);
  28075. }
  28076. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28077. {
  28078. zerostruct (*this);
  28079. timeSigNumerator = 4;
  28080. timeSigDenominator = 4;
  28081. bpm = 120;
  28082. }
  28083. END_JUCE_NAMESPACE
  28084. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28085. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28086. BEGIN_JUCE_NAMESPACE
  28087. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28088. : owner (owner_)
  28089. {
  28090. // the filter must be valid..
  28091. jassert (owner != 0);
  28092. }
  28093. AudioProcessorEditor::~AudioProcessorEditor()
  28094. {
  28095. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28096. // filter for some reason..
  28097. jassert (owner->getActiveEditor() != this);
  28098. }
  28099. END_JUCE_NAMESPACE
  28100. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28101. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28102. BEGIN_JUCE_NAMESPACE
  28103. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28104. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28105. : id (id_),
  28106. processor (processor_),
  28107. isPrepared (false)
  28108. {
  28109. jassert (processor_ != 0);
  28110. }
  28111. AudioProcessorGraph::Node::~Node()
  28112. {
  28113. delete processor;
  28114. }
  28115. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28116. AudioProcessorGraph* const graph)
  28117. {
  28118. if (! isPrepared)
  28119. {
  28120. isPrepared = true;
  28121. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28122. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28123. if (ioProc != 0)
  28124. ioProc->setParentGraph (graph);
  28125. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28126. processor->getNumOutputChannels(),
  28127. sampleRate, blockSize);
  28128. processor->prepareToPlay (sampleRate, blockSize);
  28129. }
  28130. }
  28131. void AudioProcessorGraph::Node::unprepare()
  28132. {
  28133. if (isPrepared)
  28134. {
  28135. isPrepared = false;
  28136. processor->releaseResources();
  28137. }
  28138. }
  28139. AudioProcessorGraph::AudioProcessorGraph()
  28140. : lastNodeId (0),
  28141. renderingBuffers (1, 1),
  28142. currentAudioOutputBuffer (1, 1)
  28143. {
  28144. }
  28145. AudioProcessorGraph::~AudioProcessorGraph()
  28146. {
  28147. clearRenderingSequence();
  28148. clear();
  28149. }
  28150. const String AudioProcessorGraph::getName() const
  28151. {
  28152. return "Audio Graph";
  28153. }
  28154. void AudioProcessorGraph::clear()
  28155. {
  28156. nodes.clear();
  28157. connections.clear();
  28158. triggerAsyncUpdate();
  28159. }
  28160. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28161. {
  28162. for (int i = nodes.size(); --i >= 0;)
  28163. if (nodes.getUnchecked(i)->id == nodeId)
  28164. return nodes.getUnchecked(i);
  28165. return 0;
  28166. }
  28167. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28168. uint32 nodeId)
  28169. {
  28170. if (newProcessor == 0)
  28171. {
  28172. jassertfalse;
  28173. return 0;
  28174. }
  28175. if (nodeId == 0)
  28176. {
  28177. nodeId = ++lastNodeId;
  28178. }
  28179. else
  28180. {
  28181. // you can't add a node with an id that already exists in the graph..
  28182. jassert (getNodeForId (nodeId) == 0);
  28183. removeNode (nodeId);
  28184. }
  28185. lastNodeId = nodeId;
  28186. Node* const n = new Node (nodeId, newProcessor);
  28187. nodes.add (n);
  28188. triggerAsyncUpdate();
  28189. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28190. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28191. if (ioProc != 0)
  28192. ioProc->setParentGraph (this);
  28193. return n;
  28194. }
  28195. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28196. {
  28197. disconnectNode (nodeId);
  28198. for (int i = nodes.size(); --i >= 0;)
  28199. {
  28200. if (nodes.getUnchecked(i)->id == nodeId)
  28201. {
  28202. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28203. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28204. if (ioProc != 0)
  28205. ioProc->setParentGraph (0);
  28206. nodes.remove (i);
  28207. triggerAsyncUpdate();
  28208. return true;
  28209. }
  28210. }
  28211. return false;
  28212. }
  28213. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28214. const int sourceChannelIndex,
  28215. const uint32 destNodeId,
  28216. const int destChannelIndex) const
  28217. {
  28218. for (int i = connections.size(); --i >= 0;)
  28219. {
  28220. const Connection* const c = connections.getUnchecked(i);
  28221. if (c->sourceNodeId == sourceNodeId
  28222. && c->destNodeId == destNodeId
  28223. && c->sourceChannelIndex == sourceChannelIndex
  28224. && c->destChannelIndex == destChannelIndex)
  28225. {
  28226. return c;
  28227. }
  28228. }
  28229. return 0;
  28230. }
  28231. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28232. const uint32 possibleDestNodeId) const
  28233. {
  28234. for (int i = connections.size(); --i >= 0;)
  28235. {
  28236. const Connection* const c = connections.getUnchecked(i);
  28237. if (c->sourceNodeId == possibleSourceNodeId
  28238. && c->destNodeId == possibleDestNodeId)
  28239. {
  28240. return true;
  28241. }
  28242. }
  28243. return false;
  28244. }
  28245. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28246. const int sourceChannelIndex,
  28247. const uint32 destNodeId,
  28248. const int destChannelIndex) const
  28249. {
  28250. if (sourceChannelIndex < 0
  28251. || destChannelIndex < 0
  28252. || sourceNodeId == destNodeId
  28253. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28254. return false;
  28255. const Node* const source = getNodeForId (sourceNodeId);
  28256. if (source == 0
  28257. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28258. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28259. return false;
  28260. const Node* const dest = getNodeForId (destNodeId);
  28261. if (dest == 0
  28262. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28263. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28264. return false;
  28265. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28266. destNodeId, destChannelIndex) == 0;
  28267. }
  28268. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28269. const int sourceChannelIndex,
  28270. const uint32 destNodeId,
  28271. const int destChannelIndex)
  28272. {
  28273. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28274. return false;
  28275. Connection* const c = new Connection();
  28276. c->sourceNodeId = sourceNodeId;
  28277. c->sourceChannelIndex = sourceChannelIndex;
  28278. c->destNodeId = destNodeId;
  28279. c->destChannelIndex = destChannelIndex;
  28280. connections.add (c);
  28281. triggerAsyncUpdate();
  28282. return true;
  28283. }
  28284. void AudioProcessorGraph::removeConnection (const int index)
  28285. {
  28286. connections.remove (index);
  28287. triggerAsyncUpdate();
  28288. }
  28289. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28290. const uint32 destNodeId, const int destChannelIndex)
  28291. {
  28292. bool doneAnything = false;
  28293. for (int i = connections.size(); --i >= 0;)
  28294. {
  28295. const Connection* const c = connections.getUnchecked(i);
  28296. if (c->sourceNodeId == sourceNodeId
  28297. && c->destNodeId == destNodeId
  28298. && c->sourceChannelIndex == sourceChannelIndex
  28299. && c->destChannelIndex == destChannelIndex)
  28300. {
  28301. removeConnection (i);
  28302. doneAnything = true;
  28303. triggerAsyncUpdate();
  28304. }
  28305. }
  28306. return doneAnything;
  28307. }
  28308. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28309. {
  28310. bool doneAnything = false;
  28311. for (int i = connections.size(); --i >= 0;)
  28312. {
  28313. const Connection* const c = connections.getUnchecked(i);
  28314. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28315. {
  28316. removeConnection (i);
  28317. doneAnything = true;
  28318. triggerAsyncUpdate();
  28319. }
  28320. }
  28321. return doneAnything;
  28322. }
  28323. bool AudioProcessorGraph::removeIllegalConnections()
  28324. {
  28325. bool doneAnything = false;
  28326. for (int i = connections.size(); --i >= 0;)
  28327. {
  28328. const Connection* const c = connections.getUnchecked(i);
  28329. const Node* const source = getNodeForId (c->sourceNodeId);
  28330. const Node* const dest = getNodeForId (c->destNodeId);
  28331. if (source == 0 || dest == 0
  28332. || (c->sourceChannelIndex != midiChannelIndex
  28333. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28334. || (c->sourceChannelIndex == midiChannelIndex
  28335. && ! source->processor->producesMidi())
  28336. || (c->destChannelIndex != midiChannelIndex
  28337. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28338. || (c->destChannelIndex == midiChannelIndex
  28339. && ! dest->processor->acceptsMidi()))
  28340. {
  28341. removeConnection (i);
  28342. doneAnything = true;
  28343. triggerAsyncUpdate();
  28344. }
  28345. }
  28346. return doneAnything;
  28347. }
  28348. namespace GraphRenderingOps
  28349. {
  28350. class AudioGraphRenderingOp
  28351. {
  28352. public:
  28353. AudioGraphRenderingOp() {}
  28354. virtual ~AudioGraphRenderingOp() {}
  28355. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28356. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28357. const int numSamples) = 0;
  28358. juce_UseDebuggingNewOperator
  28359. };
  28360. class ClearChannelOp : public AudioGraphRenderingOp
  28361. {
  28362. public:
  28363. ClearChannelOp (const int channelNum_)
  28364. : channelNum (channelNum_)
  28365. {}
  28366. ~ClearChannelOp() {}
  28367. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28368. {
  28369. sharedBufferChans.clear (channelNum, 0, numSamples);
  28370. }
  28371. private:
  28372. const int channelNum;
  28373. ClearChannelOp (const ClearChannelOp&);
  28374. ClearChannelOp& operator= (const ClearChannelOp&);
  28375. };
  28376. class CopyChannelOp : public AudioGraphRenderingOp
  28377. {
  28378. public:
  28379. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28380. : srcChannelNum (srcChannelNum_),
  28381. dstChannelNum (dstChannelNum_)
  28382. {}
  28383. ~CopyChannelOp() {}
  28384. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28385. {
  28386. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28387. }
  28388. private:
  28389. const int srcChannelNum, dstChannelNum;
  28390. CopyChannelOp (const CopyChannelOp&);
  28391. CopyChannelOp& operator= (const CopyChannelOp&);
  28392. };
  28393. class AddChannelOp : public AudioGraphRenderingOp
  28394. {
  28395. public:
  28396. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28397. : srcChannelNum (srcChannelNum_),
  28398. dstChannelNum (dstChannelNum_)
  28399. {}
  28400. ~AddChannelOp() {}
  28401. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28402. {
  28403. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28404. }
  28405. private:
  28406. const int srcChannelNum, dstChannelNum;
  28407. AddChannelOp (const AddChannelOp&);
  28408. AddChannelOp& operator= (const AddChannelOp&);
  28409. };
  28410. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28411. {
  28412. public:
  28413. ClearMidiBufferOp (const int bufferNum_)
  28414. : bufferNum (bufferNum_)
  28415. {}
  28416. ~ClearMidiBufferOp() {}
  28417. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28418. {
  28419. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28420. }
  28421. private:
  28422. const int bufferNum;
  28423. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28424. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28425. };
  28426. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28427. {
  28428. public:
  28429. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28430. : srcBufferNum (srcBufferNum_),
  28431. dstBufferNum (dstBufferNum_)
  28432. {}
  28433. ~CopyMidiBufferOp() {}
  28434. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28435. {
  28436. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28437. }
  28438. private:
  28439. const int srcBufferNum, dstBufferNum;
  28440. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28441. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28442. };
  28443. class AddMidiBufferOp : public AudioGraphRenderingOp
  28444. {
  28445. public:
  28446. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28447. : srcBufferNum (srcBufferNum_),
  28448. dstBufferNum (dstBufferNum_)
  28449. {}
  28450. ~AddMidiBufferOp() {}
  28451. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28452. {
  28453. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28454. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28455. }
  28456. private:
  28457. const int srcBufferNum, dstBufferNum;
  28458. AddMidiBufferOp (const AddMidiBufferOp&);
  28459. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28460. };
  28461. class ProcessBufferOp : public AudioGraphRenderingOp
  28462. {
  28463. public:
  28464. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28465. const Array <int>& audioChannelsToUse_,
  28466. const int totalChans_,
  28467. const int midiBufferToUse_)
  28468. : node (node_),
  28469. processor (node_->processor),
  28470. audioChannelsToUse (audioChannelsToUse_),
  28471. totalChans (jmax (1, totalChans_)),
  28472. midiBufferToUse (midiBufferToUse_)
  28473. {
  28474. channels.calloc (totalChans);
  28475. while (audioChannelsToUse.size() < totalChans)
  28476. audioChannelsToUse.add (0);
  28477. }
  28478. ~ProcessBufferOp()
  28479. {
  28480. }
  28481. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28482. {
  28483. for (int i = totalChans; --i >= 0;)
  28484. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28485. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28486. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28487. }
  28488. const AudioProcessorGraph::Node::Ptr node;
  28489. AudioProcessor* const processor;
  28490. private:
  28491. Array <int> audioChannelsToUse;
  28492. HeapBlock <float*> channels;
  28493. int totalChans;
  28494. int midiBufferToUse;
  28495. ProcessBufferOp (const ProcessBufferOp&);
  28496. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28497. };
  28498. /** Used to calculate the correct sequence of rendering ops needed, based on
  28499. the best re-use of shared buffers at each stage.
  28500. */
  28501. class RenderingOpSequenceCalculator
  28502. {
  28503. public:
  28504. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28505. const Array<void*>& orderedNodes_,
  28506. Array<void*>& renderingOps)
  28507. : graph (graph_),
  28508. orderedNodes (orderedNodes_)
  28509. {
  28510. nodeIds.add (-2); // first buffer is read-only zeros
  28511. channels.add (0);
  28512. midiNodeIds.add (-2);
  28513. for (int i = 0; i < orderedNodes.size(); ++i)
  28514. {
  28515. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28516. renderingOps, i);
  28517. markAnyUnusedBuffersAsFree (i);
  28518. }
  28519. }
  28520. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28521. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28522. juce_UseDebuggingNewOperator
  28523. private:
  28524. AudioProcessorGraph& graph;
  28525. const Array<void*>& orderedNodes;
  28526. Array <int> nodeIds, channels, midiNodeIds;
  28527. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28528. Array<void*>& renderingOps,
  28529. const int ourRenderingIndex)
  28530. {
  28531. const int numIns = node->processor->getNumInputChannels();
  28532. const int numOuts = node->processor->getNumOutputChannels();
  28533. const int totalChans = jmax (numIns, numOuts);
  28534. Array <int> audioChannelsToUse;
  28535. int midiBufferToUse = -1;
  28536. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28537. {
  28538. // get a list of all the inputs to this node
  28539. Array <int> sourceNodes, sourceOutputChans;
  28540. for (int i = graph.getNumConnections(); --i >= 0;)
  28541. {
  28542. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28543. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28544. {
  28545. sourceNodes.add (c->sourceNodeId);
  28546. sourceOutputChans.add (c->sourceChannelIndex);
  28547. }
  28548. }
  28549. int bufIndex = -1;
  28550. if (sourceNodes.size() == 0)
  28551. {
  28552. // unconnected input channel
  28553. if (inputChan >= numOuts)
  28554. {
  28555. bufIndex = getReadOnlyEmptyBuffer();
  28556. jassert (bufIndex >= 0);
  28557. }
  28558. else
  28559. {
  28560. bufIndex = getFreeBuffer (false);
  28561. renderingOps.add (new ClearChannelOp (bufIndex));
  28562. }
  28563. }
  28564. else if (sourceNodes.size() == 1)
  28565. {
  28566. // channel with a straightforward single input..
  28567. const int srcNode = sourceNodes.getUnchecked(0);
  28568. const int srcChan = sourceOutputChans.getUnchecked(0);
  28569. bufIndex = getBufferContaining (srcNode, srcChan);
  28570. if (bufIndex < 0)
  28571. {
  28572. // if not found, this is probably a feedback loop
  28573. bufIndex = getReadOnlyEmptyBuffer();
  28574. jassert (bufIndex >= 0);
  28575. }
  28576. if (inputChan < numOuts
  28577. && isBufferNeededLater (ourRenderingIndex,
  28578. inputChan,
  28579. srcNode, srcChan))
  28580. {
  28581. // can't mess up this channel because it's needed later by another node, so we
  28582. // need to use a copy of it..
  28583. const int newFreeBuffer = getFreeBuffer (false);
  28584. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28585. bufIndex = newFreeBuffer;
  28586. }
  28587. }
  28588. else
  28589. {
  28590. // channel with a mix of several inputs..
  28591. // try to find a re-usable channel from our inputs..
  28592. int reusableInputIndex = -1;
  28593. for (int i = 0; i < sourceNodes.size(); ++i)
  28594. {
  28595. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28596. sourceOutputChans.getUnchecked(i));
  28597. if (sourceBufIndex >= 0
  28598. && ! isBufferNeededLater (ourRenderingIndex,
  28599. inputChan,
  28600. sourceNodes.getUnchecked(i),
  28601. sourceOutputChans.getUnchecked(i)))
  28602. {
  28603. // we've found one of our input chans that can be re-used..
  28604. reusableInputIndex = i;
  28605. bufIndex = sourceBufIndex;
  28606. break;
  28607. }
  28608. }
  28609. if (reusableInputIndex < 0)
  28610. {
  28611. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28612. bufIndex = getFreeBuffer (false);
  28613. jassert (bufIndex != 0);
  28614. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28615. sourceOutputChans.getUnchecked (0));
  28616. if (srcIndex < 0)
  28617. {
  28618. // if not found, this is probably a feedback loop
  28619. renderingOps.add (new ClearChannelOp (bufIndex));
  28620. }
  28621. else
  28622. {
  28623. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28624. }
  28625. reusableInputIndex = 0;
  28626. }
  28627. for (int j = 0; j < sourceNodes.size(); ++j)
  28628. {
  28629. if (j != reusableInputIndex)
  28630. {
  28631. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28632. sourceOutputChans.getUnchecked(j));
  28633. if (srcIndex >= 0)
  28634. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28635. }
  28636. }
  28637. }
  28638. jassert (bufIndex >= 0);
  28639. audioChannelsToUse.add (bufIndex);
  28640. if (inputChan < numOuts)
  28641. markBufferAsContaining (bufIndex, node->id, inputChan);
  28642. }
  28643. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28644. {
  28645. const int bufIndex = getFreeBuffer (false);
  28646. jassert (bufIndex != 0);
  28647. audioChannelsToUse.add (bufIndex);
  28648. markBufferAsContaining (bufIndex, node->id, outputChan);
  28649. }
  28650. // Now the same thing for midi..
  28651. Array <int> midiSourceNodes;
  28652. for (int i = graph.getNumConnections(); --i >= 0;)
  28653. {
  28654. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28655. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28656. midiSourceNodes.add (c->sourceNodeId);
  28657. }
  28658. if (midiSourceNodes.size() == 0)
  28659. {
  28660. // No midi inputs..
  28661. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28662. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28663. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28664. }
  28665. else if (midiSourceNodes.size() == 1)
  28666. {
  28667. // One midi input..
  28668. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28669. AudioProcessorGraph::midiChannelIndex);
  28670. if (midiBufferToUse >= 0)
  28671. {
  28672. if (isBufferNeededLater (ourRenderingIndex,
  28673. AudioProcessorGraph::midiChannelIndex,
  28674. midiSourceNodes.getUnchecked(0),
  28675. AudioProcessorGraph::midiChannelIndex))
  28676. {
  28677. // can't mess up this channel because it's needed later by another node, so we
  28678. // need to use a copy of it..
  28679. const int newFreeBuffer = getFreeBuffer (true);
  28680. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28681. midiBufferToUse = newFreeBuffer;
  28682. }
  28683. }
  28684. else
  28685. {
  28686. // probably a feedback loop, so just use an empty one..
  28687. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28688. }
  28689. }
  28690. else
  28691. {
  28692. // More than one midi input being mixed..
  28693. int reusableInputIndex = -1;
  28694. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28695. {
  28696. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28697. AudioProcessorGraph::midiChannelIndex);
  28698. if (sourceBufIndex >= 0
  28699. && ! isBufferNeededLater (ourRenderingIndex,
  28700. AudioProcessorGraph::midiChannelIndex,
  28701. midiSourceNodes.getUnchecked(i),
  28702. AudioProcessorGraph::midiChannelIndex))
  28703. {
  28704. // we've found one of our input buffers that can be re-used..
  28705. reusableInputIndex = i;
  28706. midiBufferToUse = sourceBufIndex;
  28707. break;
  28708. }
  28709. }
  28710. if (reusableInputIndex < 0)
  28711. {
  28712. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28713. midiBufferToUse = getFreeBuffer (true);
  28714. jassert (midiBufferToUse >= 0);
  28715. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28716. AudioProcessorGraph::midiChannelIndex);
  28717. if (srcIndex >= 0)
  28718. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28719. else
  28720. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28721. reusableInputIndex = 0;
  28722. }
  28723. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28724. {
  28725. if (j != reusableInputIndex)
  28726. {
  28727. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28728. AudioProcessorGraph::midiChannelIndex);
  28729. if (srcIndex >= 0)
  28730. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28731. }
  28732. }
  28733. }
  28734. if (node->processor->producesMidi())
  28735. markBufferAsContaining (midiBufferToUse, node->id,
  28736. AudioProcessorGraph::midiChannelIndex);
  28737. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28738. totalChans, midiBufferToUse));
  28739. }
  28740. int getFreeBuffer (const bool forMidi)
  28741. {
  28742. if (forMidi)
  28743. {
  28744. for (int i = 1; i < midiNodeIds.size(); ++i)
  28745. if (midiNodeIds.getUnchecked(i) < 0)
  28746. return i;
  28747. midiNodeIds.add (-1);
  28748. return midiNodeIds.size() - 1;
  28749. }
  28750. else
  28751. {
  28752. for (int i = 1; i < nodeIds.size(); ++i)
  28753. if (nodeIds.getUnchecked(i) < 0)
  28754. return i;
  28755. nodeIds.add (-1);
  28756. channels.add (0);
  28757. return nodeIds.size() - 1;
  28758. }
  28759. }
  28760. int getReadOnlyEmptyBuffer() const
  28761. {
  28762. return 0;
  28763. }
  28764. int getBufferContaining (const int nodeId, const int outputChannel) const
  28765. {
  28766. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28767. {
  28768. for (int i = midiNodeIds.size(); --i >= 0;)
  28769. if (midiNodeIds.getUnchecked(i) == nodeId)
  28770. return i;
  28771. }
  28772. else
  28773. {
  28774. for (int i = nodeIds.size(); --i >= 0;)
  28775. if (nodeIds.getUnchecked(i) == nodeId
  28776. && channels.getUnchecked(i) == outputChannel)
  28777. return i;
  28778. }
  28779. return -1;
  28780. }
  28781. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28782. {
  28783. int i;
  28784. for (i = 0; i < nodeIds.size(); ++i)
  28785. {
  28786. if (nodeIds.getUnchecked(i) >= 0
  28787. && ! isBufferNeededLater (stepIndex, -1,
  28788. nodeIds.getUnchecked(i),
  28789. channels.getUnchecked(i)))
  28790. {
  28791. nodeIds.set (i, -1);
  28792. }
  28793. }
  28794. for (i = 0; i < midiNodeIds.size(); ++i)
  28795. {
  28796. if (midiNodeIds.getUnchecked(i) >= 0
  28797. && ! isBufferNeededLater (stepIndex, -1,
  28798. midiNodeIds.getUnchecked(i),
  28799. AudioProcessorGraph::midiChannelIndex))
  28800. {
  28801. midiNodeIds.set (i, -1);
  28802. }
  28803. }
  28804. }
  28805. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28806. int inputChannelOfIndexToIgnore,
  28807. const int nodeId,
  28808. const int outputChanIndex) const
  28809. {
  28810. while (stepIndexToSearchFrom < orderedNodes.size())
  28811. {
  28812. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28813. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28814. {
  28815. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28816. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28817. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28818. return true;
  28819. }
  28820. else
  28821. {
  28822. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28823. if (i != inputChannelOfIndexToIgnore
  28824. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28825. node->id, i) != 0)
  28826. return true;
  28827. }
  28828. inputChannelOfIndexToIgnore = -1;
  28829. ++stepIndexToSearchFrom;
  28830. }
  28831. return false;
  28832. }
  28833. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28834. {
  28835. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28836. {
  28837. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28838. midiNodeIds.set (bufferNum, nodeId);
  28839. }
  28840. else
  28841. {
  28842. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28843. nodeIds.set (bufferNum, nodeId);
  28844. channels.set (bufferNum, outputIndex);
  28845. }
  28846. }
  28847. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28848. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28849. };
  28850. }
  28851. void AudioProcessorGraph::clearRenderingSequence()
  28852. {
  28853. const ScopedLock sl (renderLock);
  28854. for (int i = renderingOps.size(); --i >= 0;)
  28855. {
  28856. GraphRenderingOps::AudioGraphRenderingOp* const r
  28857. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28858. renderingOps.remove (i);
  28859. delete r;
  28860. }
  28861. }
  28862. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28863. const uint32 possibleDestinationId,
  28864. const int recursionCheck) const
  28865. {
  28866. if (recursionCheck > 0)
  28867. {
  28868. for (int i = connections.size(); --i >= 0;)
  28869. {
  28870. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28871. if (c->destNodeId == possibleDestinationId
  28872. && (c->sourceNodeId == possibleInputId
  28873. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28874. return true;
  28875. }
  28876. }
  28877. return false;
  28878. }
  28879. void AudioProcessorGraph::buildRenderingSequence()
  28880. {
  28881. Array<void*> newRenderingOps;
  28882. int numRenderingBuffersNeeded = 2;
  28883. int numMidiBuffersNeeded = 1;
  28884. {
  28885. MessageManagerLock mml;
  28886. Array<void*> orderedNodes;
  28887. int i;
  28888. for (i = 0; i < nodes.size(); ++i)
  28889. {
  28890. Node* const node = nodes.getUnchecked(i);
  28891. node->prepare (getSampleRate(), getBlockSize(), this);
  28892. int j = 0;
  28893. for (; j < orderedNodes.size(); ++j)
  28894. if (isAnInputTo (node->id,
  28895. ((Node*) orderedNodes.getUnchecked (j))->id,
  28896. nodes.size() + 1))
  28897. break;
  28898. orderedNodes.insert (j, node);
  28899. }
  28900. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28901. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28902. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28903. }
  28904. Array<void*> oldRenderingOps (renderingOps);
  28905. {
  28906. // swap over to the new rendering sequence..
  28907. const ScopedLock sl (renderLock);
  28908. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28909. renderingBuffers.clear();
  28910. for (int i = midiBuffers.size(); --i >= 0;)
  28911. midiBuffers.getUnchecked(i)->clear();
  28912. while (midiBuffers.size() < numMidiBuffersNeeded)
  28913. midiBuffers.add (new MidiBuffer());
  28914. renderingOps = newRenderingOps;
  28915. }
  28916. for (int i = oldRenderingOps.size(); --i >= 0;)
  28917. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28918. }
  28919. void AudioProcessorGraph::handleAsyncUpdate()
  28920. {
  28921. buildRenderingSequence();
  28922. }
  28923. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28924. {
  28925. currentAudioInputBuffer = 0;
  28926. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28927. currentMidiInputBuffer = 0;
  28928. currentMidiOutputBuffer.clear();
  28929. clearRenderingSequence();
  28930. buildRenderingSequence();
  28931. }
  28932. void AudioProcessorGraph::releaseResources()
  28933. {
  28934. for (int i = 0; i < nodes.size(); ++i)
  28935. nodes.getUnchecked(i)->unprepare();
  28936. renderingBuffers.setSize (1, 1);
  28937. midiBuffers.clear();
  28938. currentAudioInputBuffer = 0;
  28939. currentAudioOutputBuffer.setSize (1, 1);
  28940. currentMidiInputBuffer = 0;
  28941. currentMidiOutputBuffer.clear();
  28942. }
  28943. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28944. {
  28945. const int numSamples = buffer.getNumSamples();
  28946. const ScopedLock sl (renderLock);
  28947. currentAudioInputBuffer = &buffer;
  28948. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28949. currentAudioOutputBuffer.clear();
  28950. currentMidiInputBuffer = &midiMessages;
  28951. currentMidiOutputBuffer.clear();
  28952. int i;
  28953. for (i = 0; i < renderingOps.size(); ++i)
  28954. {
  28955. GraphRenderingOps::AudioGraphRenderingOp* const op
  28956. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28957. op->perform (renderingBuffers, midiBuffers, numSamples);
  28958. }
  28959. for (i = 0; i < buffer.getNumChannels(); ++i)
  28960. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28961. midiMessages.clear();
  28962. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28963. }
  28964. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28965. {
  28966. return "Input " + String (channelIndex + 1);
  28967. }
  28968. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28969. {
  28970. return "Output " + String (channelIndex + 1);
  28971. }
  28972. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28973. {
  28974. return true;
  28975. }
  28976. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28977. {
  28978. return true;
  28979. }
  28980. bool AudioProcessorGraph::acceptsMidi() const
  28981. {
  28982. return true;
  28983. }
  28984. bool AudioProcessorGraph::producesMidi() const
  28985. {
  28986. return true;
  28987. }
  28988. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28989. {
  28990. }
  28991. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28992. {
  28993. }
  28994. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28995. : type (type_),
  28996. graph (0)
  28997. {
  28998. }
  28999. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29000. {
  29001. }
  29002. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29003. {
  29004. switch (type)
  29005. {
  29006. case audioOutputNode:
  29007. return "Audio Output";
  29008. case audioInputNode:
  29009. return "Audio Input";
  29010. case midiOutputNode:
  29011. return "Midi Output";
  29012. case midiInputNode:
  29013. return "Midi Input";
  29014. default:
  29015. break;
  29016. }
  29017. return String::empty;
  29018. }
  29019. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29020. {
  29021. d.name = getName();
  29022. d.uid = d.name.hashCode();
  29023. d.category = "I/O devices";
  29024. d.pluginFormatName = "Internal";
  29025. d.manufacturerName = "Raw Material Software";
  29026. d.version = "1.0";
  29027. d.isInstrument = false;
  29028. d.numInputChannels = getNumInputChannels();
  29029. if (type == audioOutputNode && graph != 0)
  29030. d.numInputChannels = graph->getNumInputChannels();
  29031. d.numOutputChannels = getNumOutputChannels();
  29032. if (type == audioInputNode && graph != 0)
  29033. d.numOutputChannels = graph->getNumOutputChannels();
  29034. }
  29035. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29036. {
  29037. jassert (graph != 0);
  29038. }
  29039. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29040. {
  29041. }
  29042. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29043. MidiBuffer& midiMessages)
  29044. {
  29045. jassert (graph != 0);
  29046. switch (type)
  29047. {
  29048. case audioOutputNode:
  29049. {
  29050. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29051. buffer.getNumChannels()); --i >= 0;)
  29052. {
  29053. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29054. }
  29055. break;
  29056. }
  29057. case audioInputNode:
  29058. {
  29059. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29060. buffer.getNumChannels()); --i >= 0;)
  29061. {
  29062. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29063. }
  29064. break;
  29065. }
  29066. case midiOutputNode:
  29067. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29068. break;
  29069. case midiInputNode:
  29070. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29071. break;
  29072. default:
  29073. break;
  29074. }
  29075. }
  29076. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29077. {
  29078. return type == midiOutputNode;
  29079. }
  29080. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29081. {
  29082. return type == midiInputNode;
  29083. }
  29084. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29085. {
  29086. switch (type)
  29087. {
  29088. case audioOutputNode:
  29089. return "Output " + String (channelIndex + 1);
  29090. case midiOutputNode:
  29091. return "Midi Output";
  29092. default:
  29093. break;
  29094. }
  29095. return String::empty;
  29096. }
  29097. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29098. {
  29099. switch (type)
  29100. {
  29101. case audioInputNode:
  29102. return "Input " + String (channelIndex + 1);
  29103. case midiInputNode:
  29104. return "Midi Input";
  29105. default:
  29106. break;
  29107. }
  29108. return String::empty;
  29109. }
  29110. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29111. {
  29112. return type == audioInputNode || type == audioOutputNode;
  29113. }
  29114. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29115. {
  29116. return isInputChannelStereoPair (index);
  29117. }
  29118. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29119. {
  29120. return type == audioInputNode || type == midiInputNode;
  29121. }
  29122. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29123. {
  29124. return type == audioOutputNode || type == midiOutputNode;
  29125. }
  29126. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29127. {
  29128. return 0;
  29129. }
  29130. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29131. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29132. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29133. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29134. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29135. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29136. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29137. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29138. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29139. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29140. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29141. {
  29142. }
  29143. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29144. {
  29145. }
  29146. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29147. {
  29148. graph = newGraph;
  29149. if (graph != 0)
  29150. {
  29151. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29152. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29153. getSampleRate(),
  29154. getBlockSize());
  29155. updateHostDisplay();
  29156. }
  29157. }
  29158. END_JUCE_NAMESPACE
  29159. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29160. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29161. BEGIN_JUCE_NAMESPACE
  29162. AudioProcessorPlayer::AudioProcessorPlayer()
  29163. : processor (0),
  29164. sampleRate (0),
  29165. blockSize (0),
  29166. isPrepared (false),
  29167. numInputChans (0),
  29168. numOutputChans (0),
  29169. tempBuffer (1, 1)
  29170. {
  29171. }
  29172. AudioProcessorPlayer::~AudioProcessorPlayer()
  29173. {
  29174. setProcessor (0);
  29175. }
  29176. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29177. {
  29178. if (processor != processorToPlay)
  29179. {
  29180. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29181. {
  29182. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29183. sampleRate, blockSize);
  29184. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29185. }
  29186. AudioProcessor* oldOne;
  29187. {
  29188. const ScopedLock sl (lock);
  29189. oldOne = isPrepared ? processor : 0;
  29190. processor = processorToPlay;
  29191. isPrepared = true;
  29192. }
  29193. if (oldOne != 0)
  29194. oldOne->releaseResources();
  29195. }
  29196. }
  29197. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29198. const int numInputChannels,
  29199. float** const outputChannelData,
  29200. const int numOutputChannels,
  29201. const int numSamples)
  29202. {
  29203. // these should have been prepared by audioDeviceAboutToStart()...
  29204. jassert (sampleRate > 0 && blockSize > 0);
  29205. incomingMidi.clear();
  29206. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29207. int i, totalNumChans = 0;
  29208. if (numInputChannels > numOutputChannels)
  29209. {
  29210. // if there aren't enough output channels for the number of
  29211. // inputs, we need to create some temporary extra ones (can't
  29212. // use the input data in case it gets written to)
  29213. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29214. false, false, true);
  29215. for (i = 0; i < numOutputChannels; ++i)
  29216. {
  29217. channels[totalNumChans] = outputChannelData[i];
  29218. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29219. ++totalNumChans;
  29220. }
  29221. for (i = numOutputChannels; i < numInputChannels; ++i)
  29222. {
  29223. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29224. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29225. ++totalNumChans;
  29226. }
  29227. }
  29228. else
  29229. {
  29230. for (i = 0; i < numInputChannels; ++i)
  29231. {
  29232. channels[totalNumChans] = outputChannelData[i];
  29233. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29234. ++totalNumChans;
  29235. }
  29236. for (i = numInputChannels; i < numOutputChannels; ++i)
  29237. {
  29238. channels[totalNumChans] = outputChannelData[i];
  29239. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29240. ++totalNumChans;
  29241. }
  29242. }
  29243. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29244. const ScopedLock sl (lock);
  29245. if (processor != 0)
  29246. {
  29247. const ScopedLock sl (processor->getCallbackLock());
  29248. if (processor->isSuspended())
  29249. {
  29250. for (i = 0; i < numOutputChannels; ++i)
  29251. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29252. }
  29253. else
  29254. {
  29255. processor->processBlock (buffer, incomingMidi);
  29256. }
  29257. }
  29258. }
  29259. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29260. {
  29261. const ScopedLock sl (lock);
  29262. sampleRate = device->getCurrentSampleRate();
  29263. blockSize = device->getCurrentBufferSizeSamples();
  29264. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29265. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29266. messageCollector.reset (sampleRate);
  29267. zeromem (channels, sizeof (channels));
  29268. if (processor != 0)
  29269. {
  29270. if (isPrepared)
  29271. processor->releaseResources();
  29272. AudioProcessor* const oldProcessor = processor;
  29273. setProcessor (0);
  29274. setProcessor (oldProcessor);
  29275. }
  29276. }
  29277. void AudioProcessorPlayer::audioDeviceStopped()
  29278. {
  29279. const ScopedLock sl (lock);
  29280. if (processor != 0 && isPrepared)
  29281. processor->releaseResources();
  29282. sampleRate = 0.0;
  29283. blockSize = 0;
  29284. isPrepared = false;
  29285. tempBuffer.setSize (1, 1);
  29286. }
  29287. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29288. {
  29289. messageCollector.addMessageToQueue (message);
  29290. }
  29291. END_JUCE_NAMESPACE
  29292. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29293. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29294. BEGIN_JUCE_NAMESPACE
  29295. class ProcessorParameterPropertyComp : public PropertyComponent,
  29296. public AudioProcessorListener,
  29297. public AsyncUpdater
  29298. {
  29299. public:
  29300. ProcessorParameterPropertyComp (const String& name,
  29301. AudioProcessor* const owner_,
  29302. const int index_)
  29303. : PropertyComponent (name),
  29304. owner (owner_),
  29305. index (index_)
  29306. {
  29307. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29308. owner_->addListener (this);
  29309. }
  29310. ~ProcessorParameterPropertyComp()
  29311. {
  29312. owner->removeListener (this);
  29313. deleteAllChildren();
  29314. }
  29315. void refresh()
  29316. {
  29317. slider->setValue (owner->getParameter (index), false);
  29318. }
  29319. void audioProcessorChanged (AudioProcessor*) {}
  29320. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29321. {
  29322. if (parameterIndex == index)
  29323. triggerAsyncUpdate();
  29324. }
  29325. void handleAsyncUpdate()
  29326. {
  29327. refresh();
  29328. }
  29329. juce_UseDebuggingNewOperator
  29330. private:
  29331. AudioProcessor* const owner;
  29332. const int index;
  29333. Slider* slider;
  29334. class ParamSlider : public Slider
  29335. {
  29336. public:
  29337. ParamSlider (AudioProcessor* const owner_, const int index_)
  29338. : Slider (String::empty),
  29339. owner (owner_),
  29340. index (index_)
  29341. {
  29342. setRange (0.0, 1.0, 0.0);
  29343. setSliderStyle (Slider::LinearBar);
  29344. setTextBoxIsEditable (false);
  29345. setScrollWheelEnabled (false);
  29346. }
  29347. ~ParamSlider()
  29348. {
  29349. }
  29350. void valueChanged()
  29351. {
  29352. const float newVal = (float) getValue();
  29353. if (owner->getParameter (index) != newVal)
  29354. owner->setParameter (index, newVal);
  29355. }
  29356. const String getTextFromValue (double /*value*/)
  29357. {
  29358. return owner->getParameterText (index);
  29359. }
  29360. juce_UseDebuggingNewOperator
  29361. private:
  29362. AudioProcessor* const owner;
  29363. const int index;
  29364. ParamSlider (const ParamSlider&);
  29365. ParamSlider& operator= (const ParamSlider&);
  29366. };
  29367. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29368. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29369. };
  29370. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29371. : AudioProcessorEditor (owner_)
  29372. {
  29373. setOpaque (true);
  29374. addAndMakeVisible (panel = new PropertyPanel());
  29375. Array <PropertyComponent*> params;
  29376. const int numParams = owner_->getNumParameters();
  29377. int totalHeight = 0;
  29378. for (int i = 0; i < numParams; ++i)
  29379. {
  29380. String name (owner_->getParameterName (i));
  29381. if (name.trim().isEmpty())
  29382. name = "Unnamed";
  29383. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29384. params.add (pc);
  29385. totalHeight += pc->getPreferredHeight();
  29386. }
  29387. panel->addProperties (params);
  29388. setSize (400, jlimit (25, 400, totalHeight));
  29389. }
  29390. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29391. {
  29392. deleteAllChildren();
  29393. }
  29394. void GenericAudioProcessorEditor::paint (Graphics& g)
  29395. {
  29396. g.fillAll (Colours::white);
  29397. }
  29398. void GenericAudioProcessorEditor::resized()
  29399. {
  29400. panel->setSize (getWidth(), getHeight());
  29401. }
  29402. END_JUCE_NAMESPACE
  29403. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29404. /*** Start of inlined file: juce_Sampler.cpp ***/
  29405. BEGIN_JUCE_NAMESPACE
  29406. SamplerSound::SamplerSound (const String& name_,
  29407. AudioFormatReader& source,
  29408. const BigInteger& midiNotes_,
  29409. const int midiNoteForNormalPitch,
  29410. const double attackTimeSecs,
  29411. const double releaseTimeSecs,
  29412. const double maxSampleLengthSeconds)
  29413. : name (name_),
  29414. midiNotes (midiNotes_),
  29415. midiRootNote (midiNoteForNormalPitch)
  29416. {
  29417. sourceSampleRate = source.sampleRate;
  29418. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29419. {
  29420. length = 0;
  29421. attackSamples = 0;
  29422. releaseSamples = 0;
  29423. }
  29424. else
  29425. {
  29426. length = jmin ((int) source.lengthInSamples,
  29427. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29428. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29429. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29430. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29431. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29432. }
  29433. }
  29434. SamplerSound::~SamplerSound()
  29435. {
  29436. }
  29437. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29438. {
  29439. return midiNotes [midiNoteNumber];
  29440. }
  29441. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29442. {
  29443. return true;
  29444. }
  29445. SamplerVoice::SamplerVoice()
  29446. : pitchRatio (0.0),
  29447. sourceSamplePosition (0.0),
  29448. lgain (0.0f),
  29449. rgain (0.0f),
  29450. isInAttack (false),
  29451. isInRelease (false)
  29452. {
  29453. }
  29454. SamplerVoice::~SamplerVoice()
  29455. {
  29456. }
  29457. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29458. {
  29459. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29460. }
  29461. void SamplerVoice::startNote (const int midiNoteNumber,
  29462. const float velocity,
  29463. SynthesiserSound* s,
  29464. const int /*currentPitchWheelPosition*/)
  29465. {
  29466. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29467. jassert (sound != 0); // this object can only play SamplerSounds!
  29468. if (sound != 0)
  29469. {
  29470. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29471. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29472. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29473. sourceSamplePosition = 0.0;
  29474. lgain = velocity;
  29475. rgain = velocity;
  29476. isInAttack = (sound->attackSamples > 0);
  29477. isInRelease = false;
  29478. if (isInAttack)
  29479. {
  29480. attackReleaseLevel = 0.0f;
  29481. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29482. }
  29483. else
  29484. {
  29485. attackReleaseLevel = 1.0f;
  29486. attackDelta = 0.0f;
  29487. }
  29488. if (sound->releaseSamples > 0)
  29489. {
  29490. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29491. }
  29492. else
  29493. {
  29494. releaseDelta = 0.0f;
  29495. }
  29496. }
  29497. }
  29498. void SamplerVoice::stopNote (const bool allowTailOff)
  29499. {
  29500. if (allowTailOff)
  29501. {
  29502. isInAttack = false;
  29503. isInRelease = true;
  29504. }
  29505. else
  29506. {
  29507. clearCurrentNote();
  29508. }
  29509. }
  29510. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29511. {
  29512. }
  29513. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29514. const int /*newValue*/)
  29515. {
  29516. }
  29517. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29518. {
  29519. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29520. if (playingSound != 0)
  29521. {
  29522. const float* const inL = playingSound->data->getSampleData (0, 0);
  29523. const float* const inR = playingSound->data->getNumChannels() > 1
  29524. ? playingSound->data->getSampleData (1, 0) : 0;
  29525. float* outL = outputBuffer.getSampleData (0, startSample);
  29526. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29527. while (--numSamples >= 0)
  29528. {
  29529. const int pos = (int) sourceSamplePosition;
  29530. const float alpha = (float) (sourceSamplePosition - pos);
  29531. const float invAlpha = 1.0f - alpha;
  29532. // just using a very simple linear interpolation here..
  29533. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29534. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29535. : l;
  29536. l *= lgain;
  29537. r *= rgain;
  29538. if (isInAttack)
  29539. {
  29540. l *= attackReleaseLevel;
  29541. r *= attackReleaseLevel;
  29542. attackReleaseLevel += attackDelta;
  29543. if (attackReleaseLevel >= 1.0f)
  29544. {
  29545. attackReleaseLevel = 1.0f;
  29546. isInAttack = false;
  29547. }
  29548. }
  29549. else if (isInRelease)
  29550. {
  29551. l *= attackReleaseLevel;
  29552. r *= attackReleaseLevel;
  29553. attackReleaseLevel += releaseDelta;
  29554. if (attackReleaseLevel <= 0.0f)
  29555. {
  29556. stopNote (false);
  29557. break;
  29558. }
  29559. }
  29560. if (outR != 0)
  29561. {
  29562. *outL++ += l;
  29563. *outR++ += r;
  29564. }
  29565. else
  29566. {
  29567. *outL++ += (l + r) * 0.5f;
  29568. }
  29569. sourceSamplePosition += pitchRatio;
  29570. if (sourceSamplePosition > playingSound->length)
  29571. {
  29572. stopNote (false);
  29573. break;
  29574. }
  29575. }
  29576. }
  29577. }
  29578. END_JUCE_NAMESPACE
  29579. /*** End of inlined file: juce_Sampler.cpp ***/
  29580. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29581. BEGIN_JUCE_NAMESPACE
  29582. SynthesiserSound::SynthesiserSound()
  29583. {
  29584. }
  29585. SynthesiserSound::~SynthesiserSound()
  29586. {
  29587. }
  29588. SynthesiserVoice::SynthesiserVoice()
  29589. : currentSampleRate (44100.0),
  29590. currentlyPlayingNote (-1),
  29591. noteOnTime (0),
  29592. currentlyPlayingSound (0)
  29593. {
  29594. }
  29595. SynthesiserVoice::~SynthesiserVoice()
  29596. {
  29597. }
  29598. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29599. {
  29600. return currentlyPlayingSound != 0
  29601. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29602. }
  29603. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29604. {
  29605. currentSampleRate = newRate;
  29606. }
  29607. void SynthesiserVoice::clearCurrentNote()
  29608. {
  29609. currentlyPlayingNote = -1;
  29610. currentlyPlayingSound = 0;
  29611. }
  29612. Synthesiser::Synthesiser()
  29613. : sampleRate (0),
  29614. lastNoteOnCounter (0),
  29615. shouldStealNotes (true)
  29616. {
  29617. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29618. lastPitchWheelValues[i] = 0x2000;
  29619. }
  29620. Synthesiser::~Synthesiser()
  29621. {
  29622. }
  29623. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29624. {
  29625. const ScopedLock sl (lock);
  29626. return voices [index];
  29627. }
  29628. void Synthesiser::clearVoices()
  29629. {
  29630. const ScopedLock sl (lock);
  29631. voices.clear();
  29632. }
  29633. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29634. {
  29635. const ScopedLock sl (lock);
  29636. voices.add (newVoice);
  29637. }
  29638. void Synthesiser::removeVoice (const int index)
  29639. {
  29640. const ScopedLock sl (lock);
  29641. voices.remove (index);
  29642. }
  29643. void Synthesiser::clearSounds()
  29644. {
  29645. const ScopedLock sl (lock);
  29646. sounds.clear();
  29647. }
  29648. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29649. {
  29650. const ScopedLock sl (lock);
  29651. sounds.add (newSound);
  29652. }
  29653. void Synthesiser::removeSound (const int index)
  29654. {
  29655. const ScopedLock sl (lock);
  29656. sounds.remove (index);
  29657. }
  29658. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29659. {
  29660. shouldStealNotes = shouldStealNotes_;
  29661. }
  29662. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29663. {
  29664. if (sampleRate != newRate)
  29665. {
  29666. const ScopedLock sl (lock);
  29667. allNotesOff (0, false);
  29668. sampleRate = newRate;
  29669. for (int i = voices.size(); --i >= 0;)
  29670. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29671. }
  29672. }
  29673. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29674. const MidiBuffer& midiData,
  29675. int startSample,
  29676. int numSamples)
  29677. {
  29678. // must set the sample rate before using this!
  29679. jassert (sampleRate != 0);
  29680. const ScopedLock sl (lock);
  29681. MidiBuffer::Iterator midiIterator (midiData);
  29682. midiIterator.setNextSamplePosition (startSample);
  29683. MidiMessage m (0xf4, 0.0);
  29684. while (numSamples > 0)
  29685. {
  29686. int midiEventPos;
  29687. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29688. && midiEventPos < startSample + numSamples;
  29689. const int numThisTime = useEvent ? midiEventPos - startSample
  29690. : numSamples;
  29691. if (numThisTime > 0)
  29692. {
  29693. for (int i = voices.size(); --i >= 0;)
  29694. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29695. }
  29696. if (useEvent)
  29697. {
  29698. if (m.isNoteOn())
  29699. {
  29700. const int channel = m.getChannel();
  29701. noteOn (channel,
  29702. m.getNoteNumber(),
  29703. m.getFloatVelocity());
  29704. }
  29705. else if (m.isNoteOff())
  29706. {
  29707. noteOff (m.getChannel(),
  29708. m.getNoteNumber(),
  29709. true);
  29710. }
  29711. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29712. {
  29713. allNotesOff (m.getChannel(), true);
  29714. }
  29715. else if (m.isPitchWheel())
  29716. {
  29717. const int channel = m.getChannel();
  29718. const int wheelPos = m.getPitchWheelValue();
  29719. lastPitchWheelValues [channel - 1] = wheelPos;
  29720. handlePitchWheel (channel, wheelPos);
  29721. }
  29722. else if (m.isController())
  29723. {
  29724. handleController (m.getChannel(),
  29725. m.getControllerNumber(),
  29726. m.getControllerValue());
  29727. }
  29728. }
  29729. startSample += numThisTime;
  29730. numSamples -= numThisTime;
  29731. }
  29732. }
  29733. void Synthesiser::noteOn (const int midiChannel,
  29734. const int midiNoteNumber,
  29735. const float velocity)
  29736. {
  29737. const ScopedLock sl (lock);
  29738. for (int i = sounds.size(); --i >= 0;)
  29739. {
  29740. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29741. if (sound->appliesToNote (midiNoteNumber)
  29742. && sound->appliesToChannel (midiChannel))
  29743. {
  29744. startVoice (findFreeVoice (sound, shouldStealNotes),
  29745. sound, midiChannel, midiNoteNumber, velocity);
  29746. }
  29747. }
  29748. }
  29749. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29750. SynthesiserSound* const sound,
  29751. const int midiChannel,
  29752. const int midiNoteNumber,
  29753. const float velocity)
  29754. {
  29755. if (voice != 0 && sound != 0)
  29756. {
  29757. if (voice->currentlyPlayingSound != 0)
  29758. voice->stopNote (false);
  29759. voice->startNote (midiNoteNumber,
  29760. velocity,
  29761. sound,
  29762. lastPitchWheelValues [midiChannel - 1]);
  29763. voice->currentlyPlayingNote = midiNoteNumber;
  29764. voice->noteOnTime = ++lastNoteOnCounter;
  29765. voice->currentlyPlayingSound = sound;
  29766. }
  29767. }
  29768. void Synthesiser::noteOff (const int midiChannel,
  29769. const int midiNoteNumber,
  29770. const bool allowTailOff)
  29771. {
  29772. const ScopedLock sl (lock);
  29773. for (int i = voices.size(); --i >= 0;)
  29774. {
  29775. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29776. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29777. {
  29778. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29779. if (sound != 0
  29780. && sound->appliesToNote (midiNoteNumber)
  29781. && sound->appliesToChannel (midiChannel))
  29782. {
  29783. voice->stopNote (allowTailOff);
  29784. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29785. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29786. }
  29787. }
  29788. }
  29789. }
  29790. void Synthesiser::allNotesOff (const int midiChannel,
  29791. const bool allowTailOff)
  29792. {
  29793. const ScopedLock sl (lock);
  29794. for (int i = voices.size(); --i >= 0;)
  29795. {
  29796. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29797. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29798. voice->stopNote (allowTailOff);
  29799. }
  29800. }
  29801. void Synthesiser::handlePitchWheel (const int midiChannel,
  29802. const int wheelValue)
  29803. {
  29804. const ScopedLock sl (lock);
  29805. for (int i = voices.size(); --i >= 0;)
  29806. {
  29807. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29808. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29809. {
  29810. voice->pitchWheelMoved (wheelValue);
  29811. }
  29812. }
  29813. }
  29814. void Synthesiser::handleController (const int midiChannel,
  29815. const int controllerNumber,
  29816. const int controllerValue)
  29817. {
  29818. const ScopedLock sl (lock);
  29819. for (int i = voices.size(); --i >= 0;)
  29820. {
  29821. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29822. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29823. voice->controllerMoved (controllerNumber, controllerValue);
  29824. }
  29825. }
  29826. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29827. const bool stealIfNoneAvailable) const
  29828. {
  29829. const ScopedLock sl (lock);
  29830. for (int i = voices.size(); --i >= 0;)
  29831. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29832. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29833. return voices.getUnchecked (i);
  29834. if (stealIfNoneAvailable)
  29835. {
  29836. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29837. SynthesiserVoice* oldest = 0;
  29838. for (int i = voices.size(); --i >= 0;)
  29839. {
  29840. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29841. if (voice->canPlaySound (soundToPlay)
  29842. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29843. oldest = voice;
  29844. }
  29845. jassert (oldest != 0);
  29846. return oldest;
  29847. }
  29848. return 0;
  29849. }
  29850. END_JUCE_NAMESPACE
  29851. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29852. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29853. BEGIN_JUCE_NAMESPACE
  29854. ActionBroadcaster::ActionBroadcaster() throw()
  29855. {
  29856. // are you trying to create this object before or after juce has been intialised??
  29857. jassert (MessageManager::instance != 0);
  29858. }
  29859. ActionBroadcaster::~ActionBroadcaster()
  29860. {
  29861. // all event-based objects must be deleted BEFORE juce is shut down!
  29862. jassert (MessageManager::instance != 0);
  29863. }
  29864. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29865. {
  29866. actionListenerList.addActionListener (listener);
  29867. }
  29868. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29869. {
  29870. jassert (actionListenerList.isValidMessageListener());
  29871. if (actionListenerList.isValidMessageListener())
  29872. actionListenerList.removeActionListener (listener);
  29873. }
  29874. void ActionBroadcaster::removeAllActionListeners()
  29875. {
  29876. actionListenerList.removeAllActionListeners();
  29877. }
  29878. void ActionBroadcaster::sendActionMessage (const String& message) const
  29879. {
  29880. actionListenerList.sendActionMessage (message);
  29881. }
  29882. END_JUCE_NAMESPACE
  29883. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29884. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29885. BEGIN_JUCE_NAMESPACE
  29886. // special message of our own with a string in it
  29887. class ActionMessage : public Message
  29888. {
  29889. public:
  29890. const String message;
  29891. ActionMessage (const String& messageText,
  29892. void* const listener_) throw()
  29893. : message (messageText)
  29894. {
  29895. pointerParameter = listener_;
  29896. }
  29897. ~ActionMessage() throw()
  29898. {
  29899. }
  29900. private:
  29901. ActionMessage (const ActionMessage&);
  29902. ActionMessage& operator= (const ActionMessage&);
  29903. };
  29904. ActionListenerList::ActionListenerList() throw()
  29905. {
  29906. }
  29907. ActionListenerList::~ActionListenerList() throw()
  29908. {
  29909. }
  29910. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29911. {
  29912. const ScopedLock sl (actionListenerLock_);
  29913. jassert (listener != 0);
  29914. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29915. if (listener != 0)
  29916. actionListeners_.add (listener);
  29917. }
  29918. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29919. {
  29920. const ScopedLock sl (actionListenerLock_);
  29921. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29922. actionListeners_.removeValue (listener);
  29923. }
  29924. void ActionListenerList::removeAllActionListeners() throw()
  29925. {
  29926. const ScopedLock sl (actionListenerLock_);
  29927. actionListeners_.clear();
  29928. }
  29929. void ActionListenerList::sendActionMessage (const String& message) const
  29930. {
  29931. const ScopedLock sl (actionListenerLock_);
  29932. for (int i = actionListeners_.size(); --i >= 0;)
  29933. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29934. }
  29935. void ActionListenerList::handleMessage (const Message& message)
  29936. {
  29937. const ActionMessage& am = (const ActionMessage&) message;
  29938. if (actionListeners_.contains (am.pointerParameter))
  29939. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29940. }
  29941. END_JUCE_NAMESPACE
  29942. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29943. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29944. BEGIN_JUCE_NAMESPACE
  29945. AsyncUpdater::AsyncUpdater() throw()
  29946. : asyncMessagePending (false)
  29947. {
  29948. internalAsyncHandler.owner = this;
  29949. }
  29950. AsyncUpdater::~AsyncUpdater()
  29951. {
  29952. }
  29953. void AsyncUpdater::triggerAsyncUpdate() throw()
  29954. {
  29955. if (! asyncMessagePending)
  29956. {
  29957. asyncMessagePending = true;
  29958. internalAsyncHandler.postMessage (new Message());
  29959. }
  29960. }
  29961. void AsyncUpdater::cancelPendingUpdate() throw()
  29962. {
  29963. asyncMessagePending = false;
  29964. }
  29965. void AsyncUpdater::handleUpdateNowIfNeeded()
  29966. {
  29967. if (asyncMessagePending)
  29968. {
  29969. asyncMessagePending = false;
  29970. handleAsyncUpdate();
  29971. }
  29972. }
  29973. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29974. {
  29975. owner->handleUpdateNowIfNeeded();
  29976. }
  29977. END_JUCE_NAMESPACE
  29978. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29979. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29980. BEGIN_JUCE_NAMESPACE
  29981. ChangeBroadcaster::ChangeBroadcaster() throw()
  29982. {
  29983. // are you trying to create this object before or after juce has been intialised??
  29984. jassert (MessageManager::instance != 0);
  29985. }
  29986. ChangeBroadcaster::~ChangeBroadcaster()
  29987. {
  29988. // all event-based objects must be deleted BEFORE juce is shut down!
  29989. jassert (MessageManager::instance != 0);
  29990. }
  29991. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29992. {
  29993. changeListenerList.addChangeListener (listener);
  29994. }
  29995. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29996. {
  29997. jassert (changeListenerList.isValidMessageListener());
  29998. if (changeListenerList.isValidMessageListener())
  29999. changeListenerList.removeChangeListener (listener);
  30000. }
  30001. void ChangeBroadcaster::removeAllChangeListeners() throw()
  30002. {
  30003. changeListenerList.removeAllChangeListeners();
  30004. }
  30005. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  30006. {
  30007. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30008. }
  30009. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30010. {
  30011. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30012. }
  30013. void ChangeBroadcaster::dispatchPendingMessages()
  30014. {
  30015. changeListenerList.dispatchPendingMessages();
  30016. }
  30017. END_JUCE_NAMESPACE
  30018. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30019. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30020. BEGIN_JUCE_NAMESPACE
  30021. ChangeListenerList::ChangeListenerList() throw()
  30022. : lastChangedObject (0),
  30023. messagePending (false)
  30024. {
  30025. }
  30026. ChangeListenerList::~ChangeListenerList() throw()
  30027. {
  30028. }
  30029. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  30030. {
  30031. const ScopedLock sl (lock);
  30032. jassert (listener != 0);
  30033. if (listener != 0)
  30034. listeners.add (listener);
  30035. }
  30036. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30037. {
  30038. const ScopedLock sl (lock);
  30039. listeners.removeValue (listener);
  30040. }
  30041. void ChangeListenerList::removeAllChangeListeners() throw()
  30042. {
  30043. const ScopedLock sl (lock);
  30044. listeners.clear();
  30045. }
  30046. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30047. {
  30048. const ScopedLock sl (lock);
  30049. if ((! messagePending) && (listeners.size() > 0))
  30050. {
  30051. lastChangedObject = objectThatHasChanged;
  30052. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30053. messagePending = true;
  30054. }
  30055. }
  30056. void ChangeListenerList::handleMessage (const Message& message)
  30057. {
  30058. sendSynchronousChangeMessage (message.pointerParameter);
  30059. }
  30060. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30061. {
  30062. const ScopedLock sl (lock);
  30063. messagePending = false;
  30064. for (int i = listeners.size(); --i >= 0;)
  30065. {
  30066. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30067. {
  30068. const ScopedUnlock tempUnlocker (lock);
  30069. l->changeListenerCallback (objectThatHasChanged);
  30070. }
  30071. i = jmin (i, listeners.size());
  30072. }
  30073. }
  30074. void ChangeListenerList::dispatchPendingMessages()
  30075. {
  30076. if (messagePending)
  30077. sendSynchronousChangeMessage (lastChangedObject);
  30078. }
  30079. END_JUCE_NAMESPACE
  30080. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30081. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30082. BEGIN_JUCE_NAMESPACE
  30083. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30084. const uint32 magicMessageHeaderNumber)
  30085. : Thread ("Juce IPC connection"),
  30086. callbackConnectionState (false),
  30087. useMessageThread (callbacksOnMessageThread),
  30088. magicMessageHeader (magicMessageHeaderNumber),
  30089. pipeReceiveMessageTimeout (-1)
  30090. {
  30091. }
  30092. InterprocessConnection::~InterprocessConnection()
  30093. {
  30094. callbackConnectionState = false;
  30095. disconnect();
  30096. }
  30097. bool InterprocessConnection::connectToSocket (const String& hostName,
  30098. const int portNumber,
  30099. const int timeOutMillisecs)
  30100. {
  30101. disconnect();
  30102. const ScopedLock sl (pipeAndSocketLock);
  30103. socket = new StreamingSocket();
  30104. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30105. {
  30106. connectionMadeInt();
  30107. startThread();
  30108. return true;
  30109. }
  30110. else
  30111. {
  30112. socket = 0;
  30113. return false;
  30114. }
  30115. }
  30116. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30117. const int pipeReceiveMessageTimeoutMs)
  30118. {
  30119. disconnect();
  30120. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30121. if (newPipe->openExisting (pipeName))
  30122. {
  30123. const ScopedLock sl (pipeAndSocketLock);
  30124. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30125. initialiseWithPipe (newPipe.release());
  30126. return true;
  30127. }
  30128. return false;
  30129. }
  30130. bool InterprocessConnection::createPipe (const String& pipeName,
  30131. const int pipeReceiveMessageTimeoutMs)
  30132. {
  30133. disconnect();
  30134. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30135. if (newPipe->createNewPipe (pipeName))
  30136. {
  30137. const ScopedLock sl (pipeAndSocketLock);
  30138. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30139. initialiseWithPipe (newPipe.release());
  30140. return true;
  30141. }
  30142. return false;
  30143. }
  30144. void InterprocessConnection::disconnect()
  30145. {
  30146. if (socket != 0)
  30147. socket->close();
  30148. if (pipe != 0)
  30149. {
  30150. pipe->cancelPendingReads();
  30151. pipe->close();
  30152. }
  30153. stopThread (4000);
  30154. {
  30155. const ScopedLock sl (pipeAndSocketLock);
  30156. socket = 0;
  30157. pipe = 0;
  30158. }
  30159. connectionLostInt();
  30160. }
  30161. bool InterprocessConnection::isConnected() const
  30162. {
  30163. const ScopedLock sl (pipeAndSocketLock);
  30164. return ((socket != 0 && socket->isConnected())
  30165. || (pipe != 0 && pipe->isOpen()))
  30166. && isThreadRunning();
  30167. }
  30168. const String InterprocessConnection::getConnectedHostName() const
  30169. {
  30170. if (pipe != 0)
  30171. {
  30172. return "localhost";
  30173. }
  30174. else if (socket != 0)
  30175. {
  30176. if (! socket->isLocal())
  30177. return socket->getHostName();
  30178. return "localhost";
  30179. }
  30180. return String::empty;
  30181. }
  30182. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30183. {
  30184. uint32 messageHeader[2];
  30185. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30186. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30187. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30188. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30189. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30190. size_t bytesWritten = 0;
  30191. const ScopedLock sl (pipeAndSocketLock);
  30192. if (socket != 0)
  30193. {
  30194. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30195. }
  30196. else if (pipe != 0)
  30197. {
  30198. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30199. }
  30200. if (bytesWritten < 0)
  30201. {
  30202. // error..
  30203. return false;
  30204. }
  30205. return (bytesWritten == messageData.getSize());
  30206. }
  30207. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30208. {
  30209. jassert (socket == 0);
  30210. socket = socket_;
  30211. connectionMadeInt();
  30212. startThread();
  30213. }
  30214. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30215. {
  30216. jassert (pipe == 0);
  30217. pipe = pipe_;
  30218. connectionMadeInt();
  30219. startThread();
  30220. }
  30221. const int messageMagicNumber = 0xb734128b;
  30222. void InterprocessConnection::handleMessage (const Message& message)
  30223. {
  30224. if (message.intParameter1 == messageMagicNumber)
  30225. {
  30226. switch (message.intParameter2)
  30227. {
  30228. case 0:
  30229. {
  30230. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30231. messageReceived (*data);
  30232. break;
  30233. }
  30234. case 1:
  30235. connectionMade();
  30236. break;
  30237. case 2:
  30238. connectionLost();
  30239. break;
  30240. }
  30241. }
  30242. }
  30243. void InterprocessConnection::connectionMadeInt()
  30244. {
  30245. if (! callbackConnectionState)
  30246. {
  30247. callbackConnectionState = true;
  30248. if (useMessageThread)
  30249. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30250. else
  30251. connectionMade();
  30252. }
  30253. }
  30254. void InterprocessConnection::connectionLostInt()
  30255. {
  30256. if (callbackConnectionState)
  30257. {
  30258. callbackConnectionState = false;
  30259. if (useMessageThread)
  30260. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30261. else
  30262. connectionLost();
  30263. }
  30264. }
  30265. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30266. {
  30267. jassert (callbackConnectionState);
  30268. if (useMessageThread)
  30269. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30270. else
  30271. messageReceived (data);
  30272. }
  30273. bool InterprocessConnection::readNextMessageInt()
  30274. {
  30275. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30276. uint32 messageHeader[2];
  30277. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30278. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30279. if (bytes == sizeof (messageHeader)
  30280. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30281. {
  30282. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30283. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30284. {
  30285. MemoryBlock messageData (bytesInMessage, true);
  30286. int bytesRead = 0;
  30287. while (bytesInMessage > 0)
  30288. {
  30289. if (threadShouldExit())
  30290. return false;
  30291. const int numThisTime = jmin (bytesInMessage, 65536);
  30292. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30293. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30294. if (bytesIn <= 0)
  30295. break;
  30296. bytesRead += bytesIn;
  30297. bytesInMessage -= bytesIn;
  30298. }
  30299. if (bytesRead >= 0)
  30300. deliverDataInt (messageData);
  30301. }
  30302. }
  30303. else if (bytes < 0)
  30304. {
  30305. {
  30306. const ScopedLock sl (pipeAndSocketLock);
  30307. socket = 0;
  30308. }
  30309. connectionLostInt();
  30310. return false;
  30311. }
  30312. return true;
  30313. }
  30314. void InterprocessConnection::run()
  30315. {
  30316. while (! threadShouldExit())
  30317. {
  30318. if (socket != 0)
  30319. {
  30320. const int ready = socket->waitUntilReady (true, 0);
  30321. if (ready < 0)
  30322. {
  30323. {
  30324. const ScopedLock sl (pipeAndSocketLock);
  30325. socket = 0;
  30326. }
  30327. connectionLostInt();
  30328. break;
  30329. }
  30330. else if (ready > 0)
  30331. {
  30332. if (! readNextMessageInt())
  30333. break;
  30334. }
  30335. else
  30336. {
  30337. Thread::sleep (2);
  30338. }
  30339. }
  30340. else if (pipe != 0)
  30341. {
  30342. if (! pipe->isOpen())
  30343. {
  30344. {
  30345. const ScopedLock sl (pipeAndSocketLock);
  30346. pipe = 0;
  30347. }
  30348. connectionLostInt();
  30349. break;
  30350. }
  30351. else
  30352. {
  30353. if (! readNextMessageInt())
  30354. break;
  30355. }
  30356. }
  30357. else
  30358. {
  30359. break;
  30360. }
  30361. }
  30362. }
  30363. END_JUCE_NAMESPACE
  30364. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30365. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30366. BEGIN_JUCE_NAMESPACE
  30367. InterprocessConnectionServer::InterprocessConnectionServer()
  30368. : Thread ("Juce IPC server")
  30369. {
  30370. }
  30371. InterprocessConnectionServer::~InterprocessConnectionServer()
  30372. {
  30373. stop();
  30374. }
  30375. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30376. {
  30377. stop();
  30378. socket = new StreamingSocket();
  30379. if (socket->createListener (portNumber))
  30380. {
  30381. startThread();
  30382. return true;
  30383. }
  30384. socket = 0;
  30385. return false;
  30386. }
  30387. void InterprocessConnectionServer::stop()
  30388. {
  30389. signalThreadShouldExit();
  30390. if (socket != 0)
  30391. socket->close();
  30392. stopThread (4000);
  30393. socket = 0;
  30394. }
  30395. void InterprocessConnectionServer::run()
  30396. {
  30397. while ((! threadShouldExit()) && socket != 0)
  30398. {
  30399. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30400. if (clientSocket != 0)
  30401. {
  30402. InterprocessConnection* newConnection = createConnectionObject();
  30403. if (newConnection != 0)
  30404. newConnection->initialiseWithSocket (clientSocket.release());
  30405. }
  30406. }
  30407. }
  30408. END_JUCE_NAMESPACE
  30409. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30410. /*** Start of inlined file: juce_Message.cpp ***/
  30411. BEGIN_JUCE_NAMESPACE
  30412. Message::Message() throw()
  30413. : intParameter1 (0),
  30414. intParameter2 (0),
  30415. intParameter3 (0),
  30416. pointerParameter (0)
  30417. {
  30418. }
  30419. Message::Message (const int intParameter1_,
  30420. const int intParameter2_,
  30421. const int intParameter3_,
  30422. void* const pointerParameter_) throw()
  30423. : intParameter1 (intParameter1_),
  30424. intParameter2 (intParameter2_),
  30425. intParameter3 (intParameter3_),
  30426. pointerParameter (pointerParameter_)
  30427. {
  30428. }
  30429. Message::~Message() throw()
  30430. {
  30431. }
  30432. END_JUCE_NAMESPACE
  30433. /*** End of inlined file: juce_Message.cpp ***/
  30434. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30435. BEGIN_JUCE_NAMESPACE
  30436. MessageListener::MessageListener() throw()
  30437. {
  30438. // are you trying to create a messagelistener before or after juce has been intialised??
  30439. jassert (MessageManager::instance != 0);
  30440. if (MessageManager::instance != 0)
  30441. MessageManager::instance->messageListeners.add (this);
  30442. }
  30443. MessageListener::~MessageListener()
  30444. {
  30445. if (MessageManager::instance != 0)
  30446. MessageManager::instance->messageListeners.removeValue (this);
  30447. }
  30448. void MessageListener::postMessage (Message* const message) const throw()
  30449. {
  30450. message->messageRecipient = const_cast <MessageListener*> (this);
  30451. if (MessageManager::instance == 0)
  30452. MessageManager::getInstance();
  30453. MessageManager::instance->postMessageToQueue (message);
  30454. }
  30455. bool MessageListener::isValidMessageListener() const throw()
  30456. {
  30457. return (MessageManager::instance != 0)
  30458. && MessageManager::instance->messageListeners.contains (this);
  30459. }
  30460. END_JUCE_NAMESPACE
  30461. /*** End of inlined file: juce_MessageListener.cpp ***/
  30462. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30463. BEGIN_JUCE_NAMESPACE
  30464. // platform-specific functions..
  30465. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30466. bool juce_postMessageToSystemQueue (Message* message);
  30467. MessageManager* MessageManager::instance = 0;
  30468. static const int quitMessageId = 0xfffff321;
  30469. MessageManager::MessageManager() throw()
  30470. : quitMessagePosted (false),
  30471. quitMessageReceived (false),
  30472. threadWithLock (0)
  30473. {
  30474. messageThreadId = Thread::getCurrentThreadId();
  30475. }
  30476. MessageManager::~MessageManager() throw()
  30477. {
  30478. broadcastListeners = 0;
  30479. doPlatformSpecificShutdown();
  30480. // If you hit this assertion, then you've probably leaked a Component or some other
  30481. // kind of MessageListener object...
  30482. jassert (messageListeners.size() == 0);
  30483. jassert (instance == this);
  30484. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30485. }
  30486. MessageManager* MessageManager::getInstance() throw()
  30487. {
  30488. if (instance == 0)
  30489. {
  30490. instance = new MessageManager();
  30491. doPlatformSpecificInitialisation();
  30492. }
  30493. return instance;
  30494. }
  30495. void MessageManager::postMessageToQueue (Message* const message)
  30496. {
  30497. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30498. delete message;
  30499. }
  30500. CallbackMessage::CallbackMessage() throw() {}
  30501. CallbackMessage::~CallbackMessage() throw() {}
  30502. void CallbackMessage::post()
  30503. {
  30504. if (MessageManager::instance != 0)
  30505. MessageManager::instance->postCallbackMessage (this);
  30506. }
  30507. void MessageManager::postCallbackMessage (Message* const message)
  30508. {
  30509. message->messageRecipient = 0;
  30510. postMessageToQueue (message);
  30511. }
  30512. // not for public use..
  30513. void MessageManager::deliverMessage (Message* const message)
  30514. {
  30515. const ScopedPointer <Message> messageDeleter (message);
  30516. MessageListener* const recipient = message->messageRecipient;
  30517. JUCE_TRY
  30518. {
  30519. if (messageListeners.contains (recipient))
  30520. {
  30521. recipient->handleMessage (*message);
  30522. }
  30523. else if (recipient == 0)
  30524. {
  30525. if (message->intParameter1 == quitMessageId)
  30526. {
  30527. quitMessageReceived = true;
  30528. }
  30529. else
  30530. {
  30531. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  30532. if (cm != 0)
  30533. cm->messageCallback();
  30534. }
  30535. }
  30536. }
  30537. JUCE_CATCH_EXCEPTION
  30538. }
  30539. #if ! (JUCE_MAC || JUCE_IOS)
  30540. void MessageManager::runDispatchLoop()
  30541. {
  30542. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30543. runDispatchLoopUntil (-1);
  30544. }
  30545. void MessageManager::stopDispatchLoop()
  30546. {
  30547. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30548. m->messageRecipient = 0;
  30549. postMessageToQueue (m);
  30550. quitMessagePosted = true;
  30551. }
  30552. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30553. {
  30554. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30555. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30556. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30557. && ! quitMessageReceived)
  30558. {
  30559. JUCE_TRY
  30560. {
  30561. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30562. {
  30563. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30564. if (msToWait > 0)
  30565. Thread::sleep (jmin (5, msToWait));
  30566. }
  30567. }
  30568. JUCE_CATCH_EXCEPTION
  30569. }
  30570. return ! quitMessageReceived;
  30571. }
  30572. #endif
  30573. void MessageManager::deliverBroadcastMessage (const String& value)
  30574. {
  30575. if (broadcastListeners != 0)
  30576. broadcastListeners->sendActionMessage (value);
  30577. }
  30578. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30579. {
  30580. if (broadcastListeners == 0)
  30581. broadcastListeners = new ActionListenerList();
  30582. broadcastListeners->addActionListener (listener);
  30583. }
  30584. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30585. {
  30586. if (broadcastListeners != 0)
  30587. broadcastListeners->removeActionListener (listener);
  30588. }
  30589. bool MessageManager::isThisTheMessageThread() const throw()
  30590. {
  30591. return Thread::getCurrentThreadId() == messageThreadId;
  30592. }
  30593. void MessageManager::setCurrentThreadAsMessageThread()
  30594. {
  30595. if (messageThreadId != Thread::getCurrentThreadId())
  30596. {
  30597. messageThreadId = Thread::getCurrentThreadId();
  30598. // This is needed on windows to make sure the message window is created by this thread
  30599. doPlatformSpecificShutdown();
  30600. doPlatformSpecificInitialisation();
  30601. }
  30602. }
  30603. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30604. {
  30605. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30606. return thisThread == messageThreadId || thisThread == threadWithLock;
  30607. }
  30608. /* The only safe way to lock the message thread while another thread does
  30609. some work is by posting a special message, whose purpose is to tie up the event
  30610. loop until the other thread has finished its business.
  30611. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30612. get locked before making an event callback, because if the same OS lock gets indirectly
  30613. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30614. in Cocoa).
  30615. */
  30616. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30617. {
  30618. public:
  30619. SharedEvents() {}
  30620. ~SharedEvents() {}
  30621. /* This class just holds a couple of events to communicate between the BlockingMessage
  30622. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30623. this shared data must be kept in a separate, ref-counted container. */
  30624. WaitableEvent lockedEvent, releaseEvent;
  30625. private:
  30626. SharedEvents (const SharedEvents&);
  30627. SharedEvents& operator= (const SharedEvents&);
  30628. };
  30629. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30630. {
  30631. public:
  30632. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30633. ~BlockingMessage() throw() {}
  30634. void messageCallback()
  30635. {
  30636. events->lockedEvent.signal();
  30637. events->releaseEvent.wait();
  30638. }
  30639. juce_UseDebuggingNewOperator
  30640. private:
  30641. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30642. BlockingMessage (const BlockingMessage&);
  30643. BlockingMessage& operator= (const BlockingMessage&);
  30644. };
  30645. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30646. : sharedEvents (0),
  30647. locked (false)
  30648. {
  30649. init (threadToCheck, 0);
  30650. }
  30651. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30652. : sharedEvents (0),
  30653. locked (false)
  30654. {
  30655. init (0, jobToCheckForExitSignal);
  30656. }
  30657. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30658. {
  30659. if (MessageManager::instance != 0)
  30660. {
  30661. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30662. {
  30663. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30664. }
  30665. else
  30666. {
  30667. if (threadToCheck == 0 && job == 0)
  30668. {
  30669. MessageManager::instance->lockingLock.enter();
  30670. }
  30671. else
  30672. {
  30673. while (! MessageManager::instance->lockingLock.tryEnter())
  30674. {
  30675. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30676. || (job != 0 && job->shouldExit()))
  30677. return;
  30678. Thread::sleep (1);
  30679. }
  30680. }
  30681. sharedEvents = new SharedEvents();
  30682. sharedEvents->incReferenceCount();
  30683. (new BlockingMessage (sharedEvents))->post();
  30684. while (! sharedEvents->lockedEvent.wait (50))
  30685. {
  30686. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30687. || (job != 0 && job->shouldExit()))
  30688. {
  30689. sharedEvents->releaseEvent.signal();
  30690. sharedEvents->decReferenceCount();
  30691. sharedEvents = 0;
  30692. MessageManager::instance->lockingLock.exit();
  30693. return;
  30694. }
  30695. }
  30696. jassert (MessageManager::instance->threadWithLock == 0);
  30697. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30698. locked = true;
  30699. }
  30700. }
  30701. }
  30702. MessageManagerLock::~MessageManagerLock() throw()
  30703. {
  30704. if (sharedEvents != 0)
  30705. {
  30706. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30707. sharedEvents->releaseEvent.signal();
  30708. sharedEvents->decReferenceCount();
  30709. if (MessageManager::instance != 0)
  30710. {
  30711. MessageManager::instance->threadWithLock = 0;
  30712. MessageManager::instance->lockingLock.exit();
  30713. }
  30714. }
  30715. }
  30716. END_JUCE_NAMESPACE
  30717. /*** End of inlined file: juce_MessageManager.cpp ***/
  30718. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30719. BEGIN_JUCE_NAMESPACE
  30720. class MultiTimer::MultiTimerCallback : public Timer
  30721. {
  30722. public:
  30723. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30724. : timerId (timerId_),
  30725. owner (owner_)
  30726. {
  30727. }
  30728. ~MultiTimerCallback()
  30729. {
  30730. }
  30731. void timerCallback()
  30732. {
  30733. owner.timerCallback (timerId);
  30734. }
  30735. const int timerId;
  30736. private:
  30737. MultiTimer& owner;
  30738. };
  30739. MultiTimer::MultiTimer() throw()
  30740. {
  30741. }
  30742. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30743. {
  30744. }
  30745. MultiTimer::~MultiTimer()
  30746. {
  30747. const ScopedLock sl (timerListLock);
  30748. timers.clear();
  30749. }
  30750. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30751. {
  30752. const ScopedLock sl (timerListLock);
  30753. for (int i = timers.size(); --i >= 0;)
  30754. {
  30755. MultiTimerCallback* const t = timers.getUnchecked(i);
  30756. if (t->timerId == timerId)
  30757. {
  30758. t->startTimer (intervalInMilliseconds);
  30759. return;
  30760. }
  30761. }
  30762. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30763. timers.add (newTimer);
  30764. newTimer->startTimer (intervalInMilliseconds);
  30765. }
  30766. void MultiTimer::stopTimer (const int timerId) throw()
  30767. {
  30768. const ScopedLock sl (timerListLock);
  30769. for (int i = timers.size(); --i >= 0;)
  30770. {
  30771. MultiTimerCallback* const t = timers.getUnchecked(i);
  30772. if (t->timerId == timerId)
  30773. t->stopTimer();
  30774. }
  30775. }
  30776. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30777. {
  30778. const ScopedLock sl (timerListLock);
  30779. for (int i = timers.size(); --i >= 0;)
  30780. {
  30781. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30782. if (t->timerId == timerId)
  30783. return t->isTimerRunning();
  30784. }
  30785. return false;
  30786. }
  30787. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30788. {
  30789. const ScopedLock sl (timerListLock);
  30790. for (int i = timers.size(); --i >= 0;)
  30791. {
  30792. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30793. if (t->timerId == timerId)
  30794. return t->getTimerInterval();
  30795. }
  30796. return 0;
  30797. }
  30798. END_JUCE_NAMESPACE
  30799. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30800. /*** Start of inlined file: juce_Timer.cpp ***/
  30801. BEGIN_JUCE_NAMESPACE
  30802. class InternalTimerThread : private Thread,
  30803. private MessageListener,
  30804. private DeletedAtShutdown,
  30805. private AsyncUpdater
  30806. {
  30807. public:
  30808. InternalTimerThread()
  30809. : Thread ("Juce Timer"),
  30810. firstTimer (0),
  30811. callbackNeeded (0)
  30812. {
  30813. triggerAsyncUpdate();
  30814. }
  30815. ~InternalTimerThread() throw()
  30816. {
  30817. stopThread (4000);
  30818. jassert (instance == this || instance == 0);
  30819. if (instance == this)
  30820. instance = 0;
  30821. }
  30822. void run()
  30823. {
  30824. uint32 lastTime = Time::getMillisecondCounter();
  30825. while (! threadShouldExit())
  30826. {
  30827. const uint32 now = Time::getMillisecondCounter();
  30828. if (now <= lastTime)
  30829. {
  30830. wait (2);
  30831. continue;
  30832. }
  30833. const int elapsed = now - lastTime;
  30834. lastTime = now;
  30835. int timeUntilFirstTimer = 1000;
  30836. {
  30837. const ScopedLock sl (lock);
  30838. decrementAllCounters (elapsed);
  30839. if (firstTimer != 0)
  30840. timeUntilFirstTimer = firstTimer->countdownMs;
  30841. }
  30842. if (timeUntilFirstTimer <= 0)
  30843. {
  30844. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30845. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30846. but if it fails it means the message-thread changed the value from under us so at least
  30847. some processing is happenening and we can just loop around and try again
  30848. */
  30849. if (callbackNeeded.compareAndSetBool (1, 0))
  30850. {
  30851. postMessage (new Message());
  30852. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30853. when the app has a modal loop), so this is how long to wait before assuming the
  30854. message has been lost and trying again.
  30855. */
  30856. const uint32 messageDeliveryTimeout = now + 2000;
  30857. while (callbackNeeded.get() != 0)
  30858. {
  30859. wait (4);
  30860. if (threadShouldExit())
  30861. return;
  30862. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30863. break;
  30864. }
  30865. }
  30866. }
  30867. else
  30868. {
  30869. // don't wait for too long because running this loop also helps keep the
  30870. // Time::getApproximateMillisecondTimer value stay up-to-date
  30871. wait (jlimit (1, 50, timeUntilFirstTimer));
  30872. }
  30873. }
  30874. }
  30875. void callTimers()
  30876. {
  30877. const ScopedLock sl (lock);
  30878. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30879. {
  30880. Timer* const t = firstTimer;
  30881. t->countdownMs = t->periodMs;
  30882. removeTimer (t);
  30883. addTimer (t);
  30884. const ScopedUnlock ul (lock);
  30885. JUCE_TRY
  30886. {
  30887. t->timerCallback();
  30888. }
  30889. JUCE_CATCH_EXCEPTION
  30890. }
  30891. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30892. before the boolean is set. This set should never fail since if it was false in the first place,
  30893. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30894. get a message then the value is true and the other thread can only set it to true again and
  30895. we will get another callback to set it to false.
  30896. */
  30897. callbackNeeded.set (0);
  30898. }
  30899. void handleMessage (const Message&)
  30900. {
  30901. callTimers();
  30902. }
  30903. void callTimersSynchronously()
  30904. {
  30905. if (! isThreadRunning())
  30906. {
  30907. // (This is relied on by some plugins in cases where the MM has
  30908. // had to restart and the async callback never started)
  30909. cancelPendingUpdate();
  30910. triggerAsyncUpdate();
  30911. }
  30912. callTimers();
  30913. }
  30914. static void callAnyTimersSynchronously()
  30915. {
  30916. if (InternalTimerThread::instance != 0)
  30917. InternalTimerThread::instance->callTimersSynchronously();
  30918. }
  30919. static inline void add (Timer* const tim) throw()
  30920. {
  30921. if (instance == 0)
  30922. instance = new InternalTimerThread();
  30923. const ScopedLock sl (instance->lock);
  30924. instance->addTimer (tim);
  30925. }
  30926. static inline void remove (Timer* const tim) throw()
  30927. {
  30928. if (instance != 0)
  30929. {
  30930. const ScopedLock sl (instance->lock);
  30931. instance->removeTimer (tim);
  30932. }
  30933. }
  30934. static inline void resetCounter (Timer* const tim,
  30935. const int newCounter) throw()
  30936. {
  30937. if (instance != 0)
  30938. {
  30939. tim->countdownMs = newCounter;
  30940. tim->periodMs = newCounter;
  30941. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30942. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30943. {
  30944. const ScopedLock sl (instance->lock);
  30945. instance->removeTimer (tim);
  30946. instance->addTimer (tim);
  30947. }
  30948. }
  30949. }
  30950. private:
  30951. friend class Timer;
  30952. static InternalTimerThread* instance;
  30953. static CriticalSection lock;
  30954. Timer* volatile firstTimer;
  30955. Atomic <int> callbackNeeded;
  30956. void addTimer (Timer* const t) throw()
  30957. {
  30958. #if JUCE_DEBUG
  30959. Timer* tt = firstTimer;
  30960. while (tt != 0)
  30961. {
  30962. // trying to add a timer that's already here - shouldn't get to this point,
  30963. // so if you get this assertion, let me know!
  30964. jassert (tt != t);
  30965. tt = tt->next;
  30966. }
  30967. jassert (t->previous == 0 && t->next == 0);
  30968. #endif
  30969. Timer* i = firstTimer;
  30970. if (i == 0 || i->countdownMs > t->countdownMs)
  30971. {
  30972. t->next = firstTimer;
  30973. firstTimer = t;
  30974. }
  30975. else
  30976. {
  30977. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30978. i = i->next;
  30979. jassert (i != 0);
  30980. t->next = i->next;
  30981. t->previous = i;
  30982. i->next = t;
  30983. }
  30984. if (t->next != 0)
  30985. t->next->previous = t;
  30986. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30987. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30988. notify();
  30989. }
  30990. void removeTimer (Timer* const t) throw()
  30991. {
  30992. #if JUCE_DEBUG
  30993. Timer* tt = firstTimer;
  30994. bool found = false;
  30995. while (tt != 0)
  30996. {
  30997. if (tt == t)
  30998. {
  30999. found = true;
  31000. break;
  31001. }
  31002. tt = tt->next;
  31003. }
  31004. // trying to remove a timer that's not here - shouldn't get to this point,
  31005. // so if you get this assertion, let me know!
  31006. jassert (found);
  31007. #endif
  31008. if (t->previous != 0)
  31009. {
  31010. jassert (firstTimer != t);
  31011. t->previous->next = t->next;
  31012. }
  31013. else
  31014. {
  31015. jassert (firstTimer == t);
  31016. firstTimer = t->next;
  31017. }
  31018. if (t->next != 0)
  31019. t->next->previous = t->previous;
  31020. t->next = 0;
  31021. t->previous = 0;
  31022. }
  31023. void decrementAllCounters (const int numMillisecs) const
  31024. {
  31025. Timer* t = firstTimer;
  31026. while (t != 0)
  31027. {
  31028. t->countdownMs -= numMillisecs;
  31029. t = t->next;
  31030. }
  31031. }
  31032. void handleAsyncUpdate()
  31033. {
  31034. startThread (7);
  31035. }
  31036. InternalTimerThread (const InternalTimerThread&);
  31037. InternalTimerThread& operator= (const InternalTimerThread&);
  31038. };
  31039. InternalTimerThread* InternalTimerThread::instance = 0;
  31040. CriticalSection InternalTimerThread::lock;
  31041. void juce_callAnyTimersSynchronously()
  31042. {
  31043. InternalTimerThread::callAnyTimersSynchronously();
  31044. }
  31045. #if JUCE_DEBUG
  31046. static SortedSet <Timer*> activeTimers;
  31047. #endif
  31048. Timer::Timer() throw()
  31049. : countdownMs (0),
  31050. periodMs (0),
  31051. previous (0),
  31052. next (0)
  31053. {
  31054. #if JUCE_DEBUG
  31055. activeTimers.add (this);
  31056. #endif
  31057. }
  31058. Timer::Timer (const Timer&) throw()
  31059. : countdownMs (0),
  31060. periodMs (0),
  31061. previous (0),
  31062. next (0)
  31063. {
  31064. #if JUCE_DEBUG
  31065. activeTimers.add (this);
  31066. #endif
  31067. }
  31068. Timer::~Timer()
  31069. {
  31070. stopTimer();
  31071. #if JUCE_DEBUG
  31072. activeTimers.removeValue (this);
  31073. #endif
  31074. }
  31075. void Timer::startTimer (const int interval) throw()
  31076. {
  31077. const ScopedLock sl (InternalTimerThread::lock);
  31078. #if JUCE_DEBUG
  31079. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31080. jassert (activeTimers.contains (this));
  31081. #endif
  31082. if (periodMs == 0)
  31083. {
  31084. countdownMs = interval;
  31085. periodMs = jmax (1, interval);
  31086. InternalTimerThread::add (this);
  31087. }
  31088. else
  31089. {
  31090. InternalTimerThread::resetCounter (this, interval);
  31091. }
  31092. }
  31093. void Timer::stopTimer() throw()
  31094. {
  31095. const ScopedLock sl (InternalTimerThread::lock);
  31096. #if JUCE_DEBUG
  31097. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31098. jassert (activeTimers.contains (this));
  31099. #endif
  31100. if (periodMs > 0)
  31101. {
  31102. InternalTimerThread::remove (this);
  31103. periodMs = 0;
  31104. }
  31105. }
  31106. END_JUCE_NAMESPACE
  31107. /*** End of inlined file: juce_Timer.cpp ***/
  31108. #endif
  31109. #if JUCE_BUILD_GUI
  31110. /*** Start of inlined file: juce_Component.cpp ***/
  31111. BEGIN_JUCE_NAMESPACE
  31112. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31113. enum ComponentMessageNumbers
  31114. {
  31115. customCommandMessage = 0x7fff0001,
  31116. exitModalStateMessage = 0x7fff0002
  31117. };
  31118. static uint32 nextComponentUID = 0;
  31119. Component* Component::currentlyFocusedComponent = 0;
  31120. Component::Component()
  31121. : parentComponent_ (0),
  31122. componentUID (++nextComponentUID),
  31123. numDeepMouseListeners (0),
  31124. lookAndFeel_ (0),
  31125. effect_ (0),
  31126. bufferedImage_ (0),
  31127. mouseListeners_ (0),
  31128. keyListeners_ (0),
  31129. componentFlags_ (0)
  31130. {
  31131. }
  31132. Component::Component (const String& name)
  31133. : componentName_ (name),
  31134. parentComponent_ (0),
  31135. componentUID (++nextComponentUID),
  31136. numDeepMouseListeners (0),
  31137. lookAndFeel_ (0),
  31138. effect_ (0),
  31139. bufferedImage_ (0),
  31140. mouseListeners_ (0),
  31141. keyListeners_ (0),
  31142. componentFlags_ (0)
  31143. {
  31144. }
  31145. Component::~Component()
  31146. {
  31147. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31148. if (parentComponent_ != 0)
  31149. {
  31150. parentComponent_->removeChildComponent (this);
  31151. }
  31152. else if ((currentlyFocusedComponent == this)
  31153. || isParentOf (currentlyFocusedComponent))
  31154. {
  31155. giveAwayFocus();
  31156. }
  31157. if (flags.hasHeavyweightPeerFlag)
  31158. removeFromDesktop();
  31159. for (int i = childComponentList_.size(); --i >= 0;)
  31160. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31161. delete mouseListeners_;
  31162. delete keyListeners_;
  31163. }
  31164. void Component::setName (const String& name)
  31165. {
  31166. // if component methods are being called from threads other than the message
  31167. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31168. checkMessageManagerIsLocked
  31169. if (componentName_ != name)
  31170. {
  31171. componentName_ = name;
  31172. if (flags.hasHeavyweightPeerFlag)
  31173. {
  31174. ComponentPeer* const peer = getPeer();
  31175. jassert (peer != 0);
  31176. if (peer != 0)
  31177. peer->setTitle (name);
  31178. }
  31179. BailOutChecker checker (this);
  31180. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31181. }
  31182. }
  31183. void Component::setVisible (bool shouldBeVisible)
  31184. {
  31185. if (flags.visibleFlag != shouldBeVisible)
  31186. {
  31187. // if component methods are being called from threads other than the message
  31188. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31189. checkMessageManagerIsLocked
  31190. SafePointer<Component> safePointer (this);
  31191. flags.visibleFlag = shouldBeVisible;
  31192. internalRepaint (0, 0, getWidth(), getHeight());
  31193. sendFakeMouseMove();
  31194. if (! shouldBeVisible)
  31195. {
  31196. if (currentlyFocusedComponent == this
  31197. || isParentOf (currentlyFocusedComponent))
  31198. {
  31199. if (parentComponent_ != 0)
  31200. parentComponent_->grabKeyboardFocus();
  31201. else
  31202. giveAwayFocus();
  31203. }
  31204. }
  31205. if (safePointer != 0)
  31206. {
  31207. sendVisibilityChangeMessage();
  31208. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31209. {
  31210. ComponentPeer* const peer = getPeer();
  31211. jassert (peer != 0);
  31212. if (peer != 0)
  31213. {
  31214. peer->setVisible (shouldBeVisible);
  31215. internalHierarchyChanged();
  31216. }
  31217. }
  31218. }
  31219. }
  31220. }
  31221. void Component::visibilityChanged()
  31222. {
  31223. }
  31224. void Component::sendVisibilityChangeMessage()
  31225. {
  31226. BailOutChecker checker (this);
  31227. visibilityChanged();
  31228. if (! checker.shouldBailOut())
  31229. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31230. }
  31231. bool Component::isShowing() const
  31232. {
  31233. if (flags.visibleFlag)
  31234. {
  31235. if (parentComponent_ != 0)
  31236. {
  31237. return parentComponent_->isShowing();
  31238. }
  31239. else
  31240. {
  31241. const ComponentPeer* const peer = getPeer();
  31242. return peer != 0 && ! peer->isMinimised();
  31243. }
  31244. }
  31245. return false;
  31246. }
  31247. class FadeOutProxyComponent : public Component,
  31248. public Timer
  31249. {
  31250. public:
  31251. FadeOutProxyComponent (Component* comp,
  31252. const int fadeLengthMs,
  31253. const int deltaXToMove,
  31254. const int deltaYToMove,
  31255. const float scaleFactorAtEnd)
  31256. : lastTime (0),
  31257. alpha (1.0f),
  31258. scale (1.0f)
  31259. {
  31260. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31261. setBounds (comp->getBounds());
  31262. comp->getParentComponent()->addAndMakeVisible (this);
  31263. toBehind (comp);
  31264. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31265. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31266. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31267. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31268. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31269. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31270. setInterceptsMouseClicks (false, false);
  31271. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31272. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31273. }
  31274. ~FadeOutProxyComponent()
  31275. {
  31276. }
  31277. void paint (Graphics& g)
  31278. {
  31279. g.setOpacity (alpha);
  31280. g.drawImage (image,
  31281. 0, 0, getWidth(), getHeight(),
  31282. 0, 0, image.getWidth(), image.getHeight());
  31283. }
  31284. void timerCallback()
  31285. {
  31286. const uint32 now = Time::getMillisecondCounter();
  31287. if (lastTime == 0)
  31288. lastTime = now;
  31289. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31290. lastTime = now;
  31291. alpha += alphaChangePerMs * msPassed;
  31292. if (alpha > 0)
  31293. {
  31294. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31295. {
  31296. centreX += xChangePerMs * msPassed;
  31297. centreY += yChangePerMs * msPassed;
  31298. scale += scaleChangePerMs * msPassed;
  31299. const int w = roundToInt (image.getWidth() * scale);
  31300. const int h = roundToInt (image.getHeight() * scale);
  31301. setBounds (roundToInt (centreX) - w / 2,
  31302. roundToInt (centreY) - h / 2,
  31303. w, h);
  31304. }
  31305. repaint();
  31306. }
  31307. else
  31308. {
  31309. delete this;
  31310. }
  31311. }
  31312. juce_UseDebuggingNewOperator
  31313. private:
  31314. Image image;
  31315. uint32 lastTime;
  31316. float alpha, alphaChangePerMs;
  31317. float centreX, xChangePerMs;
  31318. float centreY, yChangePerMs;
  31319. float scale, scaleChangePerMs;
  31320. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31321. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31322. };
  31323. void Component::fadeOutComponent (const int millisecondsToFade,
  31324. const int deltaXToMove,
  31325. const int deltaYToMove,
  31326. const float scaleFactorAtEnd)
  31327. {
  31328. //xxx won't work for comps without parents
  31329. if (isShowing() && millisecondsToFade > 0)
  31330. new FadeOutProxyComponent (this, millisecondsToFade,
  31331. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31332. setVisible (false);
  31333. }
  31334. bool Component::isValidComponent() const
  31335. {
  31336. return (this != 0) && isValidMessageListener();
  31337. }
  31338. void* Component::getWindowHandle() const
  31339. {
  31340. const ComponentPeer* const peer = getPeer();
  31341. if (peer != 0)
  31342. return peer->getNativeHandle();
  31343. return 0;
  31344. }
  31345. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31346. {
  31347. // if component methods are being called from threads other than the message
  31348. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31349. checkMessageManagerIsLocked
  31350. if (isOpaque())
  31351. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31352. else
  31353. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31354. int currentStyleFlags = 0;
  31355. // don't use getPeer(), so that we only get the peer that's specifically
  31356. // for this comp, and not for one of its parents.
  31357. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31358. if (peer != 0)
  31359. currentStyleFlags = peer->getStyleFlags();
  31360. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31361. {
  31362. SafePointer<Component> safePointer (this);
  31363. #if JUCE_LINUX
  31364. // it's wise to give the component a non-zero size before
  31365. // putting it on the desktop, as X windows get confused by this, and
  31366. // a (1, 1) minimum size is enforced here.
  31367. setSize (jmax (1, getWidth()),
  31368. jmax (1, getHeight()));
  31369. #endif
  31370. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31371. bool wasFullscreen = false;
  31372. bool wasMinimised = false;
  31373. ComponentBoundsConstrainer* currentConstainer = 0;
  31374. Rectangle<int> oldNonFullScreenBounds;
  31375. if (peer != 0)
  31376. {
  31377. wasFullscreen = peer->isFullScreen();
  31378. wasMinimised = peer->isMinimised();
  31379. currentConstainer = peer->getConstrainer();
  31380. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31381. removeFromDesktop();
  31382. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31383. }
  31384. if (parentComponent_ != 0)
  31385. parentComponent_->removeChildComponent (this);
  31386. if (safePointer != 0)
  31387. {
  31388. flags.hasHeavyweightPeerFlag = true;
  31389. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31390. Desktop::getInstance().addDesktopComponent (this);
  31391. bounds_.setPosition (topLeft);
  31392. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31393. peer->setVisible (isVisible());
  31394. if (wasFullscreen)
  31395. {
  31396. peer->setFullScreen (true);
  31397. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31398. }
  31399. if (wasMinimised)
  31400. peer->setMinimised (true);
  31401. if (isAlwaysOnTop())
  31402. peer->setAlwaysOnTop (true);
  31403. peer->setConstrainer (currentConstainer);
  31404. repaint();
  31405. }
  31406. internalHierarchyChanged();
  31407. }
  31408. }
  31409. void Component::removeFromDesktop()
  31410. {
  31411. // if component methods are being called from threads other than the message
  31412. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31413. checkMessageManagerIsLocked
  31414. if (flags.hasHeavyweightPeerFlag)
  31415. {
  31416. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31417. flags.hasHeavyweightPeerFlag = false;
  31418. jassert (peer != 0);
  31419. delete peer;
  31420. Desktop::getInstance().removeDesktopComponent (this);
  31421. }
  31422. }
  31423. bool Component::isOnDesktop() const throw()
  31424. {
  31425. return flags.hasHeavyweightPeerFlag;
  31426. }
  31427. void Component::userTriedToCloseWindow()
  31428. {
  31429. /* This means that the user's trying to get rid of your window with the 'close window' system
  31430. menu option (on windows) or possibly the task manager - you should really handle this
  31431. and delete or hide your component in an appropriate way.
  31432. If you want to ignore the event and don't want to trigger this assertion, just override
  31433. this method and do nothing.
  31434. */
  31435. jassertfalse;
  31436. }
  31437. void Component::minimisationStateChanged (bool)
  31438. {
  31439. }
  31440. void Component::setOpaque (const bool shouldBeOpaque)
  31441. {
  31442. if (shouldBeOpaque != flags.opaqueFlag)
  31443. {
  31444. flags.opaqueFlag = shouldBeOpaque;
  31445. if (flags.hasHeavyweightPeerFlag)
  31446. {
  31447. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31448. if (peer != 0)
  31449. {
  31450. // to make it recreate the heavyweight window
  31451. addToDesktop (peer->getStyleFlags());
  31452. }
  31453. }
  31454. repaint();
  31455. }
  31456. }
  31457. bool Component::isOpaque() const throw()
  31458. {
  31459. return flags.opaqueFlag;
  31460. }
  31461. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31462. {
  31463. if (shouldBeBuffered != flags.bufferToImageFlag)
  31464. {
  31465. bufferedImage_ = Image::null;
  31466. flags.bufferToImageFlag = shouldBeBuffered;
  31467. }
  31468. }
  31469. void Component::toFront (const bool setAsForeground)
  31470. {
  31471. // if component methods are being called from threads other than the message
  31472. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31473. checkMessageManagerIsLocked
  31474. if (flags.hasHeavyweightPeerFlag)
  31475. {
  31476. ComponentPeer* const peer = getPeer();
  31477. if (peer != 0)
  31478. {
  31479. peer->toFront (setAsForeground);
  31480. if (setAsForeground && ! hasKeyboardFocus (true))
  31481. grabKeyboardFocus();
  31482. }
  31483. }
  31484. else if (parentComponent_ != 0)
  31485. {
  31486. Array<Component*>& childList = parentComponent_->childComponentList_;
  31487. if (childList.getLast() != this)
  31488. {
  31489. const int index = childList.indexOf (this);
  31490. if (index >= 0)
  31491. {
  31492. int insertIndex = -1;
  31493. if (! flags.alwaysOnTopFlag)
  31494. {
  31495. insertIndex = childList.size() - 1;
  31496. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31497. --insertIndex;
  31498. }
  31499. if (index != insertIndex)
  31500. {
  31501. childList.move (index, insertIndex);
  31502. sendFakeMouseMove();
  31503. repaintParent();
  31504. }
  31505. }
  31506. }
  31507. if (setAsForeground)
  31508. {
  31509. internalBroughtToFront();
  31510. grabKeyboardFocus();
  31511. }
  31512. }
  31513. }
  31514. void Component::toBehind (Component* const other)
  31515. {
  31516. if (other != 0 && other != this)
  31517. {
  31518. // the two components must belong to the same parent..
  31519. jassert (parentComponent_ == other->parentComponent_);
  31520. if (parentComponent_ != 0)
  31521. {
  31522. Array<Component*>& childList = parentComponent_->childComponentList_;
  31523. const int index = childList.indexOf (this);
  31524. if (index >= 0 && childList [index + 1] != other)
  31525. {
  31526. int otherIndex = childList.indexOf (other);
  31527. if (otherIndex >= 0)
  31528. {
  31529. if (index < otherIndex)
  31530. --otherIndex;
  31531. childList.move (index, otherIndex);
  31532. sendFakeMouseMove();
  31533. repaintParent();
  31534. }
  31535. }
  31536. }
  31537. else if (isOnDesktop())
  31538. {
  31539. jassert (other->isOnDesktop());
  31540. if (other->isOnDesktop())
  31541. {
  31542. ComponentPeer* const us = getPeer();
  31543. ComponentPeer* const them = other->getPeer();
  31544. jassert (us != 0 && them != 0);
  31545. if (us != 0 && them != 0)
  31546. us->toBehind (them);
  31547. }
  31548. }
  31549. }
  31550. }
  31551. void Component::toBack()
  31552. {
  31553. Array<Component*>& childList = parentComponent_->childComponentList_;
  31554. if (isOnDesktop())
  31555. {
  31556. jassertfalse; //xxx need to add this to native window
  31557. }
  31558. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31559. {
  31560. const int index = childList.indexOf (this);
  31561. if (index > 0)
  31562. {
  31563. int insertIndex = 0;
  31564. if (flags.alwaysOnTopFlag)
  31565. {
  31566. while (insertIndex < childList.size()
  31567. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31568. {
  31569. ++insertIndex;
  31570. }
  31571. }
  31572. if (index != insertIndex)
  31573. {
  31574. childList.move (index, insertIndex);
  31575. sendFakeMouseMove();
  31576. repaintParent();
  31577. }
  31578. }
  31579. }
  31580. }
  31581. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31582. {
  31583. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31584. {
  31585. flags.alwaysOnTopFlag = shouldStayOnTop;
  31586. if (isOnDesktop())
  31587. {
  31588. ComponentPeer* const peer = getPeer();
  31589. jassert (peer != 0);
  31590. if (peer != 0)
  31591. {
  31592. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31593. {
  31594. // some kinds of peer can't change their always-on-top status, so
  31595. // for these, we'll need to create a new window
  31596. const int oldFlags = peer->getStyleFlags();
  31597. removeFromDesktop();
  31598. addToDesktop (oldFlags);
  31599. }
  31600. }
  31601. }
  31602. if (shouldStayOnTop)
  31603. toFront (false);
  31604. internalHierarchyChanged();
  31605. }
  31606. }
  31607. bool Component::isAlwaysOnTop() const throw()
  31608. {
  31609. return flags.alwaysOnTopFlag;
  31610. }
  31611. int Component::proportionOfWidth (const float proportion) const throw()
  31612. {
  31613. return roundToInt (proportion * bounds_.getWidth());
  31614. }
  31615. int Component::proportionOfHeight (const float proportion) const throw()
  31616. {
  31617. return roundToInt (proportion * bounds_.getHeight());
  31618. }
  31619. int Component::getParentWidth() const throw()
  31620. {
  31621. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31622. : getParentMonitorArea().getWidth();
  31623. }
  31624. int Component::getParentHeight() const throw()
  31625. {
  31626. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31627. : getParentMonitorArea().getHeight();
  31628. }
  31629. int Component::getScreenX() const
  31630. {
  31631. return getScreenPosition().getX();
  31632. }
  31633. int Component::getScreenY() const
  31634. {
  31635. return getScreenPosition().getY();
  31636. }
  31637. const Point<int> Component::getScreenPosition() const
  31638. {
  31639. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31640. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31641. : getPosition());
  31642. }
  31643. const Rectangle<int> Component::getScreenBounds() const
  31644. {
  31645. return bounds_.withPosition (getScreenPosition());
  31646. }
  31647. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31648. {
  31649. const Component* c = this;
  31650. Point<int> p (relativePosition);
  31651. do
  31652. {
  31653. if (c->flags.hasHeavyweightPeerFlag)
  31654. return c->getPeer()->relativePositionToGlobal (p);
  31655. p += c->getPosition();
  31656. c = c->parentComponent_;
  31657. }
  31658. while (c != 0);
  31659. return p;
  31660. }
  31661. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31662. {
  31663. if (flags.hasHeavyweightPeerFlag)
  31664. {
  31665. return getPeer()->globalPositionToRelative (screenPosition);
  31666. }
  31667. else
  31668. {
  31669. if (parentComponent_ != 0)
  31670. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31671. return screenPosition - getPosition();
  31672. }
  31673. }
  31674. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31675. {
  31676. Point<int> p (positionRelativeToThis);
  31677. if (targetComponent != 0)
  31678. {
  31679. const Component* c = this;
  31680. do
  31681. {
  31682. if (c == targetComponent)
  31683. return p;
  31684. if (c->flags.hasHeavyweightPeerFlag)
  31685. {
  31686. p = c->getPeer()->relativePositionToGlobal (p);
  31687. break;
  31688. }
  31689. p += c->getPosition();
  31690. c = c->parentComponent_;
  31691. }
  31692. while (c != 0);
  31693. p = targetComponent->globalPositionToRelative (p);
  31694. }
  31695. return p;
  31696. }
  31697. void Component::setBounds (const int x, const int y, int w, int h)
  31698. {
  31699. // if component methods are being called from threads other than the message
  31700. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31701. checkMessageManagerIsLocked
  31702. if (w < 0) w = 0;
  31703. if (h < 0) h = 0;
  31704. const bool wasResized = (getWidth() != w || getHeight() != h);
  31705. const bool wasMoved = (getX() != x || getY() != y);
  31706. #if JUCE_DEBUG
  31707. // It's a very bad idea to try to resize a window during its paint() method!
  31708. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31709. #endif
  31710. if (wasMoved || wasResized)
  31711. {
  31712. if (flags.visibleFlag)
  31713. {
  31714. // send a fake mouse move to trigger enter/exit messages if needed..
  31715. sendFakeMouseMove();
  31716. if (! flags.hasHeavyweightPeerFlag)
  31717. repaintParent();
  31718. }
  31719. bounds_.setBounds (x, y, w, h);
  31720. if (wasResized)
  31721. repaint();
  31722. else if (! flags.hasHeavyweightPeerFlag)
  31723. repaintParent();
  31724. if (flags.hasHeavyweightPeerFlag)
  31725. {
  31726. ComponentPeer* const peer = getPeer();
  31727. if (peer != 0)
  31728. {
  31729. if (wasMoved && wasResized)
  31730. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31731. else if (wasMoved)
  31732. peer->setPosition (getX(), getY());
  31733. else if (wasResized)
  31734. peer->setSize (getWidth(), getHeight());
  31735. }
  31736. }
  31737. sendMovedResizedMessages (wasMoved, wasResized);
  31738. }
  31739. }
  31740. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31741. {
  31742. JUCE_TRY
  31743. {
  31744. if (wasMoved)
  31745. moved();
  31746. if (wasResized)
  31747. {
  31748. resized();
  31749. for (int i = childComponentList_.size(); --i >= 0;)
  31750. {
  31751. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31752. i = jmin (i, childComponentList_.size());
  31753. }
  31754. }
  31755. BailOutChecker checker (this);
  31756. if (parentComponent_ != 0)
  31757. parentComponent_->childBoundsChanged (this);
  31758. if (! checker.shouldBailOut())
  31759. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31760. *this, wasMoved, wasResized);
  31761. }
  31762. JUCE_CATCH_EXCEPTION
  31763. }
  31764. void Component::setSize (const int w, const int h)
  31765. {
  31766. setBounds (getX(), getY(), w, h);
  31767. }
  31768. void Component::setTopLeftPosition (const int x, const int y)
  31769. {
  31770. setBounds (x, y, getWidth(), getHeight());
  31771. }
  31772. void Component::setTopRightPosition (const int x, const int y)
  31773. {
  31774. setTopLeftPosition (x - getWidth(), y);
  31775. }
  31776. void Component::setBounds (const Rectangle<int>& r)
  31777. {
  31778. setBounds (r.getX(),
  31779. r.getY(),
  31780. r.getWidth(),
  31781. r.getHeight());
  31782. }
  31783. void Component::setBoundsRelative (const float x, const float y,
  31784. const float w, const float h)
  31785. {
  31786. const int pw = getParentWidth();
  31787. const int ph = getParentHeight();
  31788. setBounds (roundToInt (x * pw),
  31789. roundToInt (y * ph),
  31790. roundToInt (w * pw),
  31791. roundToInt (h * ph));
  31792. }
  31793. void Component::setCentrePosition (const int x, const int y)
  31794. {
  31795. setTopLeftPosition (x - getWidth() / 2,
  31796. y - getHeight() / 2);
  31797. }
  31798. void Component::setCentreRelative (const float x, const float y)
  31799. {
  31800. setCentrePosition (roundToInt (getParentWidth() * x),
  31801. roundToInt (getParentHeight() * y));
  31802. }
  31803. void Component::centreWithSize (const int width, const int height)
  31804. {
  31805. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  31806. setBounds (parentArea.getCentreX() - width / 2,
  31807. parentArea.getCentreY() - height / 2,
  31808. width, height);
  31809. }
  31810. void Component::setBoundsInset (const BorderSize& borders)
  31811. {
  31812. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  31813. }
  31814. void Component::setBoundsToFit (int x, int y, int width, int height,
  31815. const Justification& justification,
  31816. const bool onlyReduceInSize)
  31817. {
  31818. // it's no good calling this method unless both the component and
  31819. // target rectangle have a finite size.
  31820. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31821. if (getWidth() > 0 && getHeight() > 0
  31822. && width > 0 && height > 0)
  31823. {
  31824. int newW, newH;
  31825. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31826. {
  31827. newW = getWidth();
  31828. newH = getHeight();
  31829. }
  31830. else
  31831. {
  31832. const double imageRatio = getHeight() / (double) getWidth();
  31833. const double targetRatio = height / (double) width;
  31834. if (imageRatio <= targetRatio)
  31835. {
  31836. newW = width;
  31837. newH = jmin (height, roundToInt (newW * imageRatio));
  31838. }
  31839. else
  31840. {
  31841. newH = height;
  31842. newW = jmin (width, roundToInt (newH / imageRatio));
  31843. }
  31844. }
  31845. if (newW > 0 && newH > 0)
  31846. {
  31847. int newX, newY;
  31848. justification.applyToRectangle (newX, newY, newW, newH,
  31849. x, y, width, height);
  31850. setBounds (newX, newY, newW, newH);
  31851. }
  31852. }
  31853. }
  31854. bool Component::hitTest (int x, int y)
  31855. {
  31856. if (! flags.ignoresMouseClicksFlag)
  31857. return true;
  31858. if (flags.allowChildMouseClicksFlag)
  31859. {
  31860. for (int i = getNumChildComponents(); --i >= 0;)
  31861. {
  31862. Component* const c = getChildComponent (i);
  31863. if (c->isVisible()
  31864. && c->bounds_.contains (x, y)
  31865. && c->hitTest (x - c->getX(),
  31866. y - c->getY()))
  31867. {
  31868. return true;
  31869. }
  31870. }
  31871. }
  31872. return false;
  31873. }
  31874. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31875. const bool allowClicksOnChildComponents) throw()
  31876. {
  31877. flags.ignoresMouseClicksFlag = ! allowClicks;
  31878. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31879. }
  31880. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31881. bool& allowsClicksOnChildComponents) const throw()
  31882. {
  31883. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31884. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31885. }
  31886. bool Component::contains (const int x, const int y)
  31887. {
  31888. if (((unsigned int) x) < (unsigned int) getWidth()
  31889. && ((unsigned int) y) < (unsigned int) getHeight()
  31890. && hitTest (x, y))
  31891. {
  31892. if (parentComponent_ != 0)
  31893. {
  31894. return parentComponent_->contains (x + getX(),
  31895. y + getY());
  31896. }
  31897. else if (flags.hasHeavyweightPeerFlag)
  31898. {
  31899. const ComponentPeer* const peer = getPeer();
  31900. if (peer != 0)
  31901. return peer->contains (Point<int> (x, y), true);
  31902. }
  31903. }
  31904. return false;
  31905. }
  31906. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31907. {
  31908. if (! contains (x, y))
  31909. return false;
  31910. Component* p = this;
  31911. while (p->parentComponent_ != 0)
  31912. {
  31913. x += p->getX();
  31914. y += p->getY();
  31915. p = p->parentComponent_;
  31916. }
  31917. const Component* const c = p->getComponentAt (x, y);
  31918. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31919. }
  31920. Component* Component::getComponentAt (const Point<int>& position)
  31921. {
  31922. return getComponentAt (position.getX(), position.getY());
  31923. }
  31924. Component* Component::getComponentAt (const int x, const int y)
  31925. {
  31926. if (flags.visibleFlag
  31927. && ((unsigned int) x) < (unsigned int) getWidth()
  31928. && ((unsigned int) y) < (unsigned int) getHeight()
  31929. && hitTest (x, y))
  31930. {
  31931. for (int i = childComponentList_.size(); --i >= 0;)
  31932. {
  31933. Component* const child = childComponentList_.getUnchecked(i);
  31934. Component* const c = child->getComponentAt (x - child->getX(),
  31935. y - child->getY());
  31936. if (c != 0)
  31937. return c;
  31938. }
  31939. return this;
  31940. }
  31941. return 0;
  31942. }
  31943. void Component::addChildComponent (Component* const child, int zOrder)
  31944. {
  31945. // if component methods are being called from threads other than the message
  31946. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31947. checkMessageManagerIsLocked
  31948. if (child != 0 && child->parentComponent_ != this)
  31949. {
  31950. if (child->parentComponent_ != 0)
  31951. child->parentComponent_->removeChildComponent (child);
  31952. else
  31953. child->removeFromDesktop();
  31954. child->parentComponent_ = this;
  31955. if (child->isVisible())
  31956. child->repaintParent();
  31957. if (! child->isAlwaysOnTop())
  31958. {
  31959. if (zOrder < 0 || zOrder > childComponentList_.size())
  31960. zOrder = childComponentList_.size();
  31961. while (zOrder > 0)
  31962. {
  31963. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31964. break;
  31965. --zOrder;
  31966. }
  31967. }
  31968. childComponentList_.insert (zOrder, child);
  31969. child->internalHierarchyChanged();
  31970. internalChildrenChanged();
  31971. }
  31972. }
  31973. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31974. {
  31975. if (child != 0)
  31976. {
  31977. child->setVisible (true);
  31978. addChildComponent (child, zOrder);
  31979. }
  31980. }
  31981. void Component::removeChildComponent (Component* const child)
  31982. {
  31983. removeChildComponent (childComponentList_.indexOf (child));
  31984. }
  31985. Component* Component::removeChildComponent (const int index)
  31986. {
  31987. // if component methods are being called from threads other than the message
  31988. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31989. checkMessageManagerIsLocked
  31990. Component* const child = childComponentList_ [index];
  31991. if (child != 0)
  31992. {
  31993. sendFakeMouseMove();
  31994. child->repaintParent();
  31995. childComponentList_.remove (index);
  31996. child->parentComponent_ = 0;
  31997. JUCE_TRY
  31998. {
  31999. if ((currentlyFocusedComponent == child)
  32000. || child->isParentOf (currentlyFocusedComponent))
  32001. {
  32002. // get rid first to force the grabKeyboardFocus to change to us.
  32003. giveAwayFocus();
  32004. grabKeyboardFocus();
  32005. }
  32006. }
  32007. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32008. catch (const std::exception& e)
  32009. {
  32010. currentlyFocusedComponent = 0;
  32011. Desktop::getInstance().triggerFocusCallback();
  32012. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32013. }
  32014. catch (...)
  32015. {
  32016. currentlyFocusedComponent = 0;
  32017. Desktop::getInstance().triggerFocusCallback();
  32018. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32019. }
  32020. #endif
  32021. child->internalHierarchyChanged();
  32022. internalChildrenChanged();
  32023. }
  32024. return child;
  32025. }
  32026. void Component::removeAllChildren()
  32027. {
  32028. while (childComponentList_.size() > 0)
  32029. removeChildComponent (childComponentList_.size() - 1);
  32030. }
  32031. void Component::deleteAllChildren()
  32032. {
  32033. while (childComponentList_.size() > 0)
  32034. delete (removeChildComponent (childComponentList_.size() - 1));
  32035. }
  32036. int Component::getNumChildComponents() const throw()
  32037. {
  32038. return childComponentList_.size();
  32039. }
  32040. Component* Component::getChildComponent (const int index) const throw()
  32041. {
  32042. return childComponentList_ [index];
  32043. }
  32044. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32045. {
  32046. return childComponentList_.indexOf (const_cast <Component*> (child));
  32047. }
  32048. Component* Component::getTopLevelComponent() const throw()
  32049. {
  32050. const Component* comp = this;
  32051. while (comp->parentComponent_ != 0)
  32052. comp = comp->parentComponent_;
  32053. return const_cast <Component*> (comp);
  32054. }
  32055. bool Component::isParentOf (const Component* possibleChild) const throw()
  32056. {
  32057. if (! possibleChild->isValidComponent())
  32058. {
  32059. jassert (possibleChild == 0);
  32060. return false;
  32061. }
  32062. while (possibleChild != 0)
  32063. {
  32064. possibleChild = possibleChild->parentComponent_;
  32065. if (possibleChild == this)
  32066. return true;
  32067. }
  32068. return false;
  32069. }
  32070. void Component::parentHierarchyChanged()
  32071. {
  32072. }
  32073. void Component::childrenChanged()
  32074. {
  32075. }
  32076. void Component::internalChildrenChanged()
  32077. {
  32078. if (componentListeners.isEmpty())
  32079. {
  32080. childrenChanged();
  32081. }
  32082. else
  32083. {
  32084. BailOutChecker checker (this);
  32085. childrenChanged();
  32086. if (! checker.shouldBailOut())
  32087. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32088. }
  32089. }
  32090. void Component::internalHierarchyChanged()
  32091. {
  32092. BailOutChecker checker (this);
  32093. parentHierarchyChanged();
  32094. if (checker.shouldBailOut())
  32095. return;
  32096. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32097. if (checker.shouldBailOut())
  32098. return;
  32099. for (int i = childComponentList_.size(); --i >= 0;)
  32100. {
  32101. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32102. if (checker.shouldBailOut())
  32103. {
  32104. // you really shouldn't delete the parent component during a callback telling you
  32105. // that it's changed..
  32106. jassertfalse;
  32107. return;
  32108. }
  32109. i = jmin (i, childComponentList_.size());
  32110. }
  32111. }
  32112. void* Component::runModalLoopCallback (void* userData)
  32113. {
  32114. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32115. }
  32116. int Component::runModalLoop()
  32117. {
  32118. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32119. {
  32120. // use a callback so this can be called from non-gui threads
  32121. return (int) (pointer_sized_int) MessageManager::getInstance()
  32122. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32123. }
  32124. if (! isCurrentlyModal())
  32125. enterModalState (true);
  32126. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32127. }
  32128. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32129. {
  32130. // if component methods are being called from threads other than the message
  32131. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32132. checkMessageManagerIsLocked
  32133. // Check for an attempt to make a component modal when it already is!
  32134. // This can cause nasty problems..
  32135. jassert (! flags.currentlyModalFlag);
  32136. if (! isCurrentlyModal())
  32137. {
  32138. ModalComponentManager::getInstance()->startModal (this, callback);
  32139. flags.currentlyModalFlag = true;
  32140. setVisible (true);
  32141. if (takeKeyboardFocus_)
  32142. grabKeyboardFocus();
  32143. }
  32144. }
  32145. void Component::exitModalState (const int returnValue)
  32146. {
  32147. if (isCurrentlyModal())
  32148. {
  32149. if (MessageManager::getInstance()->isThisTheMessageThread())
  32150. {
  32151. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32152. flags.currentlyModalFlag = false;
  32153. bringModalComponentToFront();
  32154. }
  32155. else
  32156. {
  32157. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32158. }
  32159. }
  32160. }
  32161. bool Component::isCurrentlyModal() const throw()
  32162. {
  32163. return flags.currentlyModalFlag
  32164. && getCurrentlyModalComponent() == this;
  32165. }
  32166. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32167. {
  32168. Component* const mc = getCurrentlyModalComponent();
  32169. return mc != 0
  32170. && mc != this
  32171. && (! mc->isParentOf (this))
  32172. && ! mc->canModalEventBeSentToComponent (this);
  32173. }
  32174. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32175. {
  32176. return ModalComponentManager::getInstance()->getNumModalComponents();
  32177. }
  32178. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32179. {
  32180. return ModalComponentManager::getInstance()->getModalComponent (index);
  32181. }
  32182. void Component::bringModalComponentToFront()
  32183. {
  32184. ComponentPeer* lastOne = 0;
  32185. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32186. {
  32187. Component* const c = getCurrentlyModalComponent (i);
  32188. if (c == 0)
  32189. break;
  32190. ComponentPeer* peer = c->getPeer();
  32191. if (peer != 0 && peer != lastOne)
  32192. {
  32193. if (lastOne == 0)
  32194. {
  32195. peer->toFront (true);
  32196. peer->grabFocus();
  32197. }
  32198. else
  32199. peer->toBehind (lastOne);
  32200. lastOne = peer;
  32201. }
  32202. }
  32203. }
  32204. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32205. {
  32206. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32207. }
  32208. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32209. {
  32210. return flags.bringToFrontOnClickFlag;
  32211. }
  32212. void Component::setMouseCursor (const MouseCursor& cursor)
  32213. {
  32214. if (cursor_ != cursor)
  32215. {
  32216. cursor_ = cursor;
  32217. if (flags.visibleFlag)
  32218. updateMouseCursor();
  32219. }
  32220. }
  32221. const MouseCursor Component::getMouseCursor()
  32222. {
  32223. return cursor_;
  32224. }
  32225. void Component::updateMouseCursor() const
  32226. {
  32227. sendFakeMouseMove();
  32228. }
  32229. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32230. {
  32231. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32232. }
  32233. void Component::repaintParent()
  32234. {
  32235. if (flags.visibleFlag)
  32236. internalRepaint (0, 0, getWidth(), getHeight());
  32237. }
  32238. void Component::repaint()
  32239. {
  32240. repaint (0, 0, getWidth(), getHeight());
  32241. }
  32242. void Component::repaint (const int x, const int y,
  32243. const int w, const int h)
  32244. {
  32245. bufferedImage_ = Image::null;
  32246. if (flags.visibleFlag)
  32247. internalRepaint (x, y, w, h);
  32248. }
  32249. void Component::repaint (const Rectangle<int>& area)
  32250. {
  32251. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32252. }
  32253. void Component::internalRepaint (int x, int y, int w, int h)
  32254. {
  32255. // if component methods are being called from threads other than the message
  32256. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32257. checkMessageManagerIsLocked
  32258. if (x < 0)
  32259. {
  32260. w += x;
  32261. x = 0;
  32262. }
  32263. if (x + w > getWidth())
  32264. w = getWidth() - x;
  32265. if (w > 0)
  32266. {
  32267. if (y < 0)
  32268. {
  32269. h += y;
  32270. y = 0;
  32271. }
  32272. if (y + h > getHeight())
  32273. h = getHeight() - y;
  32274. if (h > 0)
  32275. {
  32276. if (parentComponent_ != 0)
  32277. {
  32278. x += getX();
  32279. y += getY();
  32280. if (parentComponent_->flags.visibleFlag)
  32281. parentComponent_->internalRepaint (x, y, w, h);
  32282. }
  32283. else if (flags.hasHeavyweightPeerFlag)
  32284. {
  32285. ComponentPeer* const peer = getPeer();
  32286. if (peer != 0)
  32287. peer->repaint (Rectangle<int> (x, y, w, h));
  32288. }
  32289. }
  32290. }
  32291. }
  32292. void Component::renderComponent (Graphics& g)
  32293. {
  32294. const Rectangle<int> clipBounds (g.getClipBounds());
  32295. g.saveState();
  32296. clipObscuredRegions (g, clipBounds, 0, 0);
  32297. if (! g.isClipEmpty())
  32298. {
  32299. if (flags.bufferToImageFlag)
  32300. {
  32301. if (bufferedImage_.isNull())
  32302. {
  32303. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32304. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32305. Graphics imG (bufferedImage_);
  32306. paint (imG);
  32307. }
  32308. g.setColour (Colours::black);
  32309. g.drawImageAt (bufferedImage_, 0, 0);
  32310. }
  32311. else
  32312. {
  32313. paint (g);
  32314. }
  32315. }
  32316. g.restoreState();
  32317. for (int i = 0; i < childComponentList_.size(); ++i)
  32318. {
  32319. Component* const child = childComponentList_.getUnchecked (i);
  32320. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32321. {
  32322. g.saveState();
  32323. if (g.reduceClipRegion (child->getX(), child->getY(),
  32324. child->getWidth(), child->getHeight()))
  32325. {
  32326. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32327. {
  32328. const Component* const sibling = childComponentList_.getUnchecked (j);
  32329. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32330. g.excludeClipRegion (sibling->getBounds());
  32331. }
  32332. if (! g.isClipEmpty())
  32333. {
  32334. g.setOrigin (child->getX(), child->getY());
  32335. child->paintEntireComponent (g);
  32336. }
  32337. }
  32338. g.restoreState();
  32339. }
  32340. }
  32341. g.saveState();
  32342. paintOverChildren (g);
  32343. g.restoreState();
  32344. }
  32345. void Component::paintEntireComponent (Graphics& g)
  32346. {
  32347. jassert (! g.isClipEmpty());
  32348. #if JUCE_DEBUG
  32349. flags.isInsidePaintCall = true;
  32350. #endif
  32351. if (effect_ != 0)
  32352. {
  32353. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32354. getWidth(), getHeight(),
  32355. ! flags.opaqueFlag, Image::NativeImage);
  32356. {
  32357. Graphics g2 (effectImage);
  32358. renderComponent (g2);
  32359. }
  32360. effect_->applyEffect (effectImage, g);
  32361. }
  32362. else
  32363. {
  32364. renderComponent (g);
  32365. }
  32366. #if JUCE_DEBUG
  32367. flags.isInsidePaintCall = false;
  32368. #endif
  32369. }
  32370. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32371. const bool clipImageToComponentBounds)
  32372. {
  32373. Rectangle<int> r (areaToGrab);
  32374. if (clipImageToComponentBounds)
  32375. r = r.getIntersection (getLocalBounds());
  32376. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32377. jmax (1, r.getWidth()),
  32378. jmax (1, r.getHeight()),
  32379. true);
  32380. Graphics imageContext (componentImage);
  32381. imageContext.setOrigin (-r.getX(), -r.getY());
  32382. paintEntireComponent (imageContext);
  32383. return componentImage;
  32384. }
  32385. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32386. {
  32387. if (effect_ != effect)
  32388. {
  32389. effect_ = effect;
  32390. repaint();
  32391. }
  32392. }
  32393. LookAndFeel& Component::getLookAndFeel() const throw()
  32394. {
  32395. const Component* c = this;
  32396. do
  32397. {
  32398. if (c->lookAndFeel_ != 0)
  32399. return *(c->lookAndFeel_);
  32400. c = c->parentComponent_;
  32401. }
  32402. while (c != 0);
  32403. return LookAndFeel::getDefaultLookAndFeel();
  32404. }
  32405. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32406. {
  32407. if (lookAndFeel_ != newLookAndFeel)
  32408. {
  32409. lookAndFeel_ = newLookAndFeel;
  32410. sendLookAndFeelChange();
  32411. }
  32412. }
  32413. void Component::lookAndFeelChanged()
  32414. {
  32415. }
  32416. void Component::sendLookAndFeelChange()
  32417. {
  32418. repaint();
  32419. lookAndFeelChanged();
  32420. // (it's not a great idea to do anything that would delete this component
  32421. // during the lookAndFeelChanged() callback)
  32422. jassert (isValidComponent());
  32423. SafePointer<Component> safePointer (this);
  32424. for (int i = childComponentList_.size(); --i >= 0;)
  32425. {
  32426. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32427. if (safePointer == 0)
  32428. return;
  32429. i = jmin (i, childComponentList_.size());
  32430. }
  32431. }
  32432. static const Identifier getColourPropertyId (const int colourId)
  32433. {
  32434. String s;
  32435. s.preallocateStorage (18);
  32436. s << "jcclr_" << String::toHexString (colourId);
  32437. return s;
  32438. }
  32439. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32440. {
  32441. var* v = properties.getItem (getColourPropertyId (colourId));
  32442. if (v != 0)
  32443. return Colour ((int) *v);
  32444. if (inheritFromParent && parentComponent_ != 0)
  32445. return parentComponent_->findColour (colourId, true);
  32446. return getLookAndFeel().findColour (colourId);
  32447. }
  32448. bool Component::isColourSpecified (const int colourId) const
  32449. {
  32450. return properties.contains (getColourPropertyId (colourId));
  32451. }
  32452. void Component::removeColour (const int colourId)
  32453. {
  32454. if (properties.remove (getColourPropertyId (colourId)))
  32455. colourChanged();
  32456. }
  32457. void Component::setColour (const int colourId, const Colour& colour)
  32458. {
  32459. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32460. colourChanged();
  32461. }
  32462. void Component::copyAllExplicitColoursTo (Component& target) const
  32463. {
  32464. bool changed = false;
  32465. for (int i = properties.size(); --i >= 0;)
  32466. {
  32467. const Identifier name (properties.getName(i));
  32468. if (name.toString().startsWith ("jcclr_"))
  32469. if (target.properties.set (name, properties [name]))
  32470. changed = true;
  32471. }
  32472. if (changed)
  32473. target.colourChanged();
  32474. }
  32475. void Component::colourChanged()
  32476. {
  32477. }
  32478. const Rectangle<int> Component::getLocalBounds() const throw()
  32479. {
  32480. return Rectangle<int> (getWidth(), getHeight());
  32481. }
  32482. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  32483. {
  32484. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  32485. : Desktop::getInstance().getMainMonitorArea();
  32486. }
  32487. const Rectangle<int> Component::getUnclippedArea() const
  32488. {
  32489. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32490. Component* p = parentComponent_;
  32491. int px = getX();
  32492. int py = getY();
  32493. while (p != 0)
  32494. {
  32495. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32496. return Rectangle<int>();
  32497. px += p->getX();
  32498. py += p->getY();
  32499. p = p->parentComponent_;
  32500. }
  32501. return Rectangle<int> (x, y, w, h);
  32502. }
  32503. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32504. const int deltaX, const int deltaY) const
  32505. {
  32506. for (int i = childComponentList_.size(); --i >= 0;)
  32507. {
  32508. const Component* const c = childComponentList_.getUnchecked(i);
  32509. if (c->isVisible())
  32510. {
  32511. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32512. if (! newClip.isEmpty())
  32513. {
  32514. if (c->isOpaque())
  32515. {
  32516. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32517. }
  32518. else
  32519. {
  32520. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32521. c->getX() + deltaX,
  32522. c->getY() + deltaY);
  32523. }
  32524. }
  32525. }
  32526. }
  32527. }
  32528. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32529. {
  32530. result.clear();
  32531. const Rectangle<int> unclipped (getUnclippedArea());
  32532. if (! unclipped.isEmpty())
  32533. {
  32534. result.add (unclipped);
  32535. if (includeSiblings)
  32536. {
  32537. const Component* const c = getTopLevelComponent();
  32538. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32539. c->getLocalBounds(), this);
  32540. }
  32541. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32542. result.consolidate();
  32543. }
  32544. }
  32545. void Component::subtractObscuredRegions (RectangleList& result,
  32546. const Point<int>& delta,
  32547. const Rectangle<int>& clipRect,
  32548. const Component* const compToAvoid) const
  32549. {
  32550. for (int i = childComponentList_.size(); --i >= 0;)
  32551. {
  32552. const Component* const c = childComponentList_.getUnchecked(i);
  32553. if (c != compToAvoid && c->isVisible())
  32554. {
  32555. if (c->isOpaque())
  32556. {
  32557. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32558. childBounds.translate (delta.getX(), delta.getY());
  32559. result.subtract (childBounds);
  32560. }
  32561. else
  32562. {
  32563. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32564. newClip.translate (-c->getX(), -c->getY());
  32565. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32566. newClip, compToAvoid);
  32567. }
  32568. }
  32569. }
  32570. }
  32571. void Component::mouseEnter (const MouseEvent&)
  32572. {
  32573. // base class does nothing
  32574. }
  32575. void Component::mouseExit (const MouseEvent&)
  32576. {
  32577. // base class does nothing
  32578. }
  32579. void Component::mouseDown (const MouseEvent&)
  32580. {
  32581. // base class does nothing
  32582. }
  32583. void Component::mouseUp (const MouseEvent&)
  32584. {
  32585. // base class does nothing
  32586. }
  32587. void Component::mouseDrag (const MouseEvent&)
  32588. {
  32589. // base class does nothing
  32590. }
  32591. void Component::mouseMove (const MouseEvent&)
  32592. {
  32593. // base class does nothing
  32594. }
  32595. void Component::mouseDoubleClick (const MouseEvent&)
  32596. {
  32597. // base class does nothing
  32598. }
  32599. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32600. {
  32601. // the base class just passes this event up to its parent..
  32602. if (parentComponent_ != 0)
  32603. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32604. wheelIncrementX, wheelIncrementY);
  32605. }
  32606. void Component::resized()
  32607. {
  32608. // base class does nothing
  32609. }
  32610. void Component::moved()
  32611. {
  32612. // base class does nothing
  32613. }
  32614. void Component::childBoundsChanged (Component*)
  32615. {
  32616. // base class does nothing
  32617. }
  32618. void Component::parentSizeChanged()
  32619. {
  32620. // base class does nothing
  32621. }
  32622. void Component::addComponentListener (ComponentListener* const newListener)
  32623. {
  32624. jassert (isValidComponent());
  32625. componentListeners.add (newListener);
  32626. }
  32627. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32628. {
  32629. jassert (isValidComponent());
  32630. componentListeners.remove (listenerToRemove);
  32631. }
  32632. void Component::inputAttemptWhenModal()
  32633. {
  32634. bringModalComponentToFront();
  32635. getLookAndFeel().playAlertSound();
  32636. }
  32637. bool Component::canModalEventBeSentToComponent (const Component*)
  32638. {
  32639. return false;
  32640. }
  32641. void Component::internalModalInputAttempt()
  32642. {
  32643. Component* const current = getCurrentlyModalComponent();
  32644. if (current != 0)
  32645. current->inputAttemptWhenModal();
  32646. }
  32647. void Component::paint (Graphics&)
  32648. {
  32649. // all painting is done in the subclasses
  32650. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32651. }
  32652. void Component::paintOverChildren (Graphics&)
  32653. {
  32654. // all painting is done in the subclasses
  32655. }
  32656. void Component::handleMessage (const Message& message)
  32657. {
  32658. if (message.intParameter1 == exitModalStateMessage)
  32659. {
  32660. exitModalState (message.intParameter2);
  32661. }
  32662. else if (message.intParameter1 == customCommandMessage)
  32663. {
  32664. handleCommandMessage (message.intParameter2);
  32665. }
  32666. }
  32667. void Component::postCommandMessage (const int commandId)
  32668. {
  32669. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32670. }
  32671. void Component::handleCommandMessage (int)
  32672. {
  32673. // used by subclasses
  32674. }
  32675. void Component::addMouseListener (MouseListener* const newListener,
  32676. const bool wantsEventsForAllNestedChildComponents)
  32677. {
  32678. // if component methods are being called from threads other than the message
  32679. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32680. checkMessageManagerIsLocked
  32681. if (mouseListeners_ == 0)
  32682. mouseListeners_ = new Array<MouseListener*>();
  32683. if (! mouseListeners_->contains (newListener))
  32684. {
  32685. if (wantsEventsForAllNestedChildComponents)
  32686. {
  32687. mouseListeners_->insert (0, newListener);
  32688. ++numDeepMouseListeners;
  32689. }
  32690. else
  32691. {
  32692. mouseListeners_->add (newListener);
  32693. }
  32694. }
  32695. }
  32696. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32697. {
  32698. // if component methods are being called from threads other than the message
  32699. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32700. checkMessageManagerIsLocked
  32701. if (mouseListeners_ != 0)
  32702. {
  32703. const int index = mouseListeners_->indexOf (listenerToRemove);
  32704. if (index >= 0)
  32705. {
  32706. if (index < numDeepMouseListeners)
  32707. --numDeepMouseListeners;
  32708. mouseListeners_->remove (index);
  32709. }
  32710. }
  32711. }
  32712. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32713. {
  32714. if (isCurrentlyBlockedByAnotherModalComponent())
  32715. {
  32716. // if something else is modal, always just show a normal mouse cursor
  32717. source.showMouseCursor (MouseCursor::NormalCursor);
  32718. return;
  32719. }
  32720. if (! flags.mouseInsideFlag)
  32721. {
  32722. flags.mouseInsideFlag = true;
  32723. flags.mouseOverFlag = true;
  32724. flags.draggingFlag = false;
  32725. BailOutChecker checker (this);
  32726. if (flags.repaintOnMouseActivityFlag)
  32727. repaint();
  32728. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32729. this, this, time, relativePos,
  32730. time, 0, false);
  32731. mouseEnter (me);
  32732. if (checker.shouldBailOut())
  32733. return;
  32734. Desktop::getInstance().resetTimer();
  32735. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32736. if (checker.shouldBailOut())
  32737. return;
  32738. if (mouseListeners_ != 0)
  32739. {
  32740. for (int i = mouseListeners_->size(); --i >= 0;)
  32741. {
  32742. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32743. if (checker.shouldBailOut())
  32744. return;
  32745. i = jmin (i, mouseListeners_->size());
  32746. }
  32747. }
  32748. Component* p = parentComponent_;
  32749. while (p != 0)
  32750. {
  32751. if (p->numDeepMouseListeners > 0)
  32752. {
  32753. BailOutChecker checker2 (this, p);
  32754. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32755. {
  32756. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32757. if (checker2.shouldBailOut())
  32758. return;
  32759. i = jmin (i, p->numDeepMouseListeners);
  32760. }
  32761. }
  32762. p = p->parentComponent_;
  32763. }
  32764. }
  32765. }
  32766. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32767. {
  32768. BailOutChecker checker (this);
  32769. if (flags.draggingFlag)
  32770. {
  32771. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32772. if (checker.shouldBailOut())
  32773. return;
  32774. }
  32775. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32776. {
  32777. flags.mouseInsideFlag = false;
  32778. flags.mouseOverFlag = false;
  32779. flags.draggingFlag = false;
  32780. if (flags.repaintOnMouseActivityFlag)
  32781. repaint();
  32782. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32783. this, this, time, relativePos,
  32784. time, 0, false);
  32785. mouseExit (me);
  32786. if (checker.shouldBailOut())
  32787. return;
  32788. Desktop::getInstance().resetTimer();
  32789. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32790. if (checker.shouldBailOut())
  32791. return;
  32792. if (mouseListeners_ != 0)
  32793. {
  32794. for (int i = mouseListeners_->size(); --i >= 0;)
  32795. {
  32796. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32797. if (checker.shouldBailOut())
  32798. return;
  32799. i = jmin (i, mouseListeners_->size());
  32800. }
  32801. }
  32802. Component* p = parentComponent_;
  32803. while (p != 0)
  32804. {
  32805. if (p->numDeepMouseListeners > 0)
  32806. {
  32807. BailOutChecker checker2 (this, p);
  32808. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32809. {
  32810. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32811. if (checker2.shouldBailOut())
  32812. return;
  32813. i = jmin (i, p->numDeepMouseListeners);
  32814. }
  32815. }
  32816. p = p->parentComponent_;
  32817. }
  32818. }
  32819. }
  32820. class InternalDragRepeater : public Timer
  32821. {
  32822. public:
  32823. InternalDragRepeater()
  32824. {}
  32825. ~InternalDragRepeater()
  32826. {
  32827. clearSingletonInstance();
  32828. }
  32829. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32830. void timerCallback()
  32831. {
  32832. Desktop& desktop = Desktop::getInstance();
  32833. int numMiceDown = 0;
  32834. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32835. {
  32836. MouseInputSource* const source = desktop.getMouseSource(i);
  32837. if (source->isDragging())
  32838. {
  32839. source->triggerFakeMove();
  32840. ++numMiceDown;
  32841. }
  32842. }
  32843. if (numMiceDown == 0)
  32844. deleteInstance();
  32845. }
  32846. juce_UseDebuggingNewOperator
  32847. private:
  32848. InternalDragRepeater (const InternalDragRepeater&);
  32849. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32850. };
  32851. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32852. void Component::beginDragAutoRepeat (const int interval)
  32853. {
  32854. if (interval > 0)
  32855. {
  32856. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32857. InternalDragRepeater::getInstance()->startTimer (interval);
  32858. }
  32859. else
  32860. {
  32861. InternalDragRepeater::deleteInstance();
  32862. }
  32863. }
  32864. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32865. {
  32866. Desktop& desktop = Desktop::getInstance();
  32867. BailOutChecker checker (this);
  32868. if (isCurrentlyBlockedByAnotherModalComponent())
  32869. {
  32870. internalModalInputAttempt();
  32871. if (checker.shouldBailOut())
  32872. return;
  32873. // If processing the input attempt has exited the modal loop, we'll allow the event
  32874. // to be delivered..
  32875. if (isCurrentlyBlockedByAnotherModalComponent())
  32876. {
  32877. // allow blocked mouse-events to go to global listeners..
  32878. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32879. this, this, time, relativePos, time,
  32880. source.getNumberOfMultipleClicks(), false);
  32881. desktop.resetTimer();
  32882. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32883. return;
  32884. }
  32885. }
  32886. {
  32887. Component* c = this;
  32888. while (c != 0)
  32889. {
  32890. if (c->isBroughtToFrontOnMouseClick())
  32891. {
  32892. c->toFront (true);
  32893. if (checker.shouldBailOut())
  32894. return;
  32895. }
  32896. c = c->parentComponent_;
  32897. }
  32898. }
  32899. if (! flags.dontFocusOnMouseClickFlag)
  32900. {
  32901. grabFocusInternal (focusChangedByMouseClick);
  32902. if (checker.shouldBailOut())
  32903. return;
  32904. }
  32905. flags.draggingFlag = true;
  32906. flags.mouseOverFlag = true;
  32907. if (flags.repaintOnMouseActivityFlag)
  32908. repaint();
  32909. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32910. this, this, time, relativePos, time,
  32911. source.getNumberOfMultipleClicks(), false);
  32912. mouseDown (me);
  32913. if (checker.shouldBailOut())
  32914. return;
  32915. desktop.resetTimer();
  32916. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32917. if (checker.shouldBailOut())
  32918. return;
  32919. if (mouseListeners_ != 0)
  32920. {
  32921. for (int i = mouseListeners_->size(); --i >= 0;)
  32922. {
  32923. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32924. if (checker.shouldBailOut())
  32925. return;
  32926. i = jmin (i, mouseListeners_->size());
  32927. }
  32928. }
  32929. Component* p = parentComponent_;
  32930. while (p != 0)
  32931. {
  32932. if (p->numDeepMouseListeners > 0)
  32933. {
  32934. BailOutChecker checker2 (this, p);
  32935. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32936. {
  32937. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32938. if (checker2.shouldBailOut())
  32939. return;
  32940. i = jmin (i, p->numDeepMouseListeners);
  32941. }
  32942. }
  32943. p = p->parentComponent_;
  32944. }
  32945. }
  32946. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32947. {
  32948. if (flags.draggingFlag)
  32949. {
  32950. Desktop& desktop = Desktop::getInstance();
  32951. flags.draggingFlag = false;
  32952. BailOutChecker checker (this);
  32953. if (flags.repaintOnMouseActivityFlag)
  32954. repaint();
  32955. const MouseEvent me (source, relativePos,
  32956. oldModifiers, this, this, time,
  32957. globalPositionToRelative (source.getLastMouseDownPosition()),
  32958. source.getLastMouseDownTime(),
  32959. source.getNumberOfMultipleClicks(),
  32960. source.hasMouseMovedSignificantlySincePressed());
  32961. mouseUp (me);
  32962. if (checker.shouldBailOut())
  32963. return;
  32964. desktop.resetTimer();
  32965. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32966. if (checker.shouldBailOut())
  32967. return;
  32968. if (mouseListeners_ != 0)
  32969. {
  32970. for (int i = mouseListeners_->size(); --i >= 0;)
  32971. {
  32972. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32973. if (checker.shouldBailOut())
  32974. return;
  32975. i = jmin (i, mouseListeners_->size());
  32976. }
  32977. }
  32978. {
  32979. Component* p = parentComponent_;
  32980. while (p != 0)
  32981. {
  32982. if (p->numDeepMouseListeners > 0)
  32983. {
  32984. BailOutChecker checker2 (this, p);
  32985. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32986. {
  32987. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32988. if (checker2.shouldBailOut())
  32989. return;
  32990. i = jmin (i, p->numDeepMouseListeners);
  32991. }
  32992. }
  32993. p = p->parentComponent_;
  32994. }
  32995. }
  32996. // check for double-click
  32997. if (me.getNumberOfClicks() >= 2)
  32998. {
  32999. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33000. mouseDoubleClick (me);
  33001. if (checker.shouldBailOut())
  33002. return;
  33003. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33004. if (checker.shouldBailOut())
  33005. return;
  33006. for (int i = numListeners; --i >= 0;)
  33007. {
  33008. if (checker.shouldBailOut())
  33009. return;
  33010. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33011. if (ml != 0)
  33012. ml->mouseDoubleClick (me);
  33013. }
  33014. if (checker.shouldBailOut())
  33015. return;
  33016. Component* p = parentComponent_;
  33017. while (p != 0)
  33018. {
  33019. if (p->numDeepMouseListeners > 0)
  33020. {
  33021. BailOutChecker checker2 (this, p);
  33022. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33023. {
  33024. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33025. if (checker2.shouldBailOut())
  33026. return;
  33027. i = jmin (i, p->numDeepMouseListeners);
  33028. }
  33029. }
  33030. p = p->parentComponent_;
  33031. }
  33032. }
  33033. }
  33034. }
  33035. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33036. {
  33037. if (flags.draggingFlag)
  33038. {
  33039. Desktop& desktop = Desktop::getInstance();
  33040. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33041. BailOutChecker checker (this);
  33042. const MouseEvent me (source, relativePos,
  33043. source.getCurrentModifiers(), this, this, time,
  33044. globalPositionToRelative (source.getLastMouseDownPosition()),
  33045. source.getLastMouseDownTime(),
  33046. source.getNumberOfMultipleClicks(),
  33047. source.hasMouseMovedSignificantlySincePressed());
  33048. mouseDrag (me);
  33049. if (checker.shouldBailOut())
  33050. return;
  33051. desktop.resetTimer();
  33052. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33053. if (checker.shouldBailOut())
  33054. return;
  33055. if (mouseListeners_ != 0)
  33056. {
  33057. for (int i = mouseListeners_->size(); --i >= 0;)
  33058. {
  33059. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33060. if (checker.shouldBailOut())
  33061. return;
  33062. i = jmin (i, mouseListeners_->size());
  33063. }
  33064. }
  33065. Component* p = parentComponent_;
  33066. while (p != 0)
  33067. {
  33068. if (p->numDeepMouseListeners > 0)
  33069. {
  33070. BailOutChecker checker2 (this, p);
  33071. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33072. {
  33073. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33074. if (checker2.shouldBailOut())
  33075. return;
  33076. i = jmin (i, p->numDeepMouseListeners);
  33077. }
  33078. }
  33079. p = p->parentComponent_;
  33080. }
  33081. }
  33082. }
  33083. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33084. {
  33085. Desktop& desktop = Desktop::getInstance();
  33086. BailOutChecker checker (this);
  33087. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33088. this, this, time, relativePos,
  33089. time, 0, false);
  33090. if (isCurrentlyBlockedByAnotherModalComponent())
  33091. {
  33092. // allow blocked mouse-events to go to global listeners..
  33093. desktop.sendMouseMove();
  33094. }
  33095. else
  33096. {
  33097. flags.mouseOverFlag = true;
  33098. mouseMove (me);
  33099. if (checker.shouldBailOut())
  33100. return;
  33101. desktop.resetTimer();
  33102. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33103. if (checker.shouldBailOut())
  33104. return;
  33105. if (mouseListeners_ != 0)
  33106. {
  33107. for (int i = mouseListeners_->size(); --i >= 0;)
  33108. {
  33109. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33110. if (checker.shouldBailOut())
  33111. return;
  33112. i = jmin (i, mouseListeners_->size());
  33113. }
  33114. }
  33115. Component* p = parentComponent_;
  33116. while (p != 0)
  33117. {
  33118. if (p->numDeepMouseListeners > 0)
  33119. {
  33120. BailOutChecker checker2 (this, p);
  33121. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33122. {
  33123. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33124. if (checker2.shouldBailOut())
  33125. return;
  33126. i = jmin (i, p->numDeepMouseListeners);
  33127. }
  33128. }
  33129. p = p->parentComponent_;
  33130. }
  33131. }
  33132. }
  33133. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33134. const Time& time, const float amountX, const float amountY)
  33135. {
  33136. Desktop& desktop = Desktop::getInstance();
  33137. BailOutChecker checker (this);
  33138. const float wheelIncrementX = amountX / 256.0f;
  33139. const float wheelIncrementY = amountY / 256.0f;
  33140. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33141. this, this, time, relativePos, time, 0, false);
  33142. if (isCurrentlyBlockedByAnotherModalComponent())
  33143. {
  33144. // allow blocked mouse-events to go to global listeners..
  33145. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33146. }
  33147. else
  33148. {
  33149. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33150. if (checker.shouldBailOut())
  33151. return;
  33152. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33153. if (checker.shouldBailOut())
  33154. return;
  33155. if (mouseListeners_ != 0)
  33156. {
  33157. for (int i = mouseListeners_->size(); --i >= 0;)
  33158. {
  33159. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33160. if (checker.shouldBailOut())
  33161. return;
  33162. i = jmin (i, mouseListeners_->size());
  33163. }
  33164. }
  33165. Component* p = parentComponent_;
  33166. while (p != 0)
  33167. {
  33168. if (p->numDeepMouseListeners > 0)
  33169. {
  33170. BailOutChecker checker2 (this, p);
  33171. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33172. {
  33173. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33174. if (checker2.shouldBailOut())
  33175. return;
  33176. i = jmin (i, p->numDeepMouseListeners);
  33177. }
  33178. }
  33179. p = p->parentComponent_;
  33180. }
  33181. }
  33182. }
  33183. void Component::sendFakeMouseMove() const
  33184. {
  33185. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33186. }
  33187. void Component::broughtToFront()
  33188. {
  33189. }
  33190. void Component::internalBroughtToFront()
  33191. {
  33192. if (! isValidComponent())
  33193. return;
  33194. if (flags.hasHeavyweightPeerFlag)
  33195. Desktop::getInstance().componentBroughtToFront (this);
  33196. BailOutChecker checker (this);
  33197. broughtToFront();
  33198. if (checker.shouldBailOut())
  33199. return;
  33200. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33201. if (checker.shouldBailOut())
  33202. return;
  33203. // When brought to the front and there's a modal component blocking this one,
  33204. // we need to bring the modal one to the front instead..
  33205. Component* const cm = getCurrentlyModalComponent();
  33206. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33207. bringModalComponentToFront();
  33208. }
  33209. void Component::focusGained (FocusChangeType)
  33210. {
  33211. // base class does nothing
  33212. }
  33213. void Component::internalFocusGain (const FocusChangeType cause)
  33214. {
  33215. SafePointer<Component> safePointer (this);
  33216. focusGained (cause);
  33217. if (safePointer != 0)
  33218. internalChildFocusChange (cause);
  33219. }
  33220. void Component::focusLost (FocusChangeType)
  33221. {
  33222. // base class does nothing
  33223. }
  33224. void Component::internalFocusLoss (const FocusChangeType cause)
  33225. {
  33226. SafePointer<Component> safePointer (this);
  33227. focusLost (focusChangedDirectly);
  33228. if (safePointer != 0)
  33229. internalChildFocusChange (cause);
  33230. }
  33231. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33232. {
  33233. // base class does nothing
  33234. }
  33235. void Component::internalChildFocusChange (FocusChangeType cause)
  33236. {
  33237. const bool childIsNowFocused = hasKeyboardFocus (true);
  33238. if (flags.childCompFocusedFlag != childIsNowFocused)
  33239. {
  33240. flags.childCompFocusedFlag = childIsNowFocused;
  33241. SafePointer<Component> safePointer (this);
  33242. focusOfChildComponentChanged (cause);
  33243. if (safePointer == 0)
  33244. return;
  33245. }
  33246. if (parentComponent_ != 0)
  33247. parentComponent_->internalChildFocusChange (cause);
  33248. }
  33249. bool Component::isEnabled() const throw()
  33250. {
  33251. return (! flags.isDisabledFlag)
  33252. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33253. }
  33254. void Component::setEnabled (const bool shouldBeEnabled)
  33255. {
  33256. if (flags.isDisabledFlag == shouldBeEnabled)
  33257. {
  33258. flags.isDisabledFlag = ! shouldBeEnabled;
  33259. // if any parent components are disabled, setting our flag won't make a difference,
  33260. // so no need to send a change message
  33261. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33262. sendEnablementChangeMessage();
  33263. }
  33264. }
  33265. void Component::sendEnablementChangeMessage()
  33266. {
  33267. SafePointer<Component> safePointer (this);
  33268. enablementChanged();
  33269. if (safePointer == 0)
  33270. return;
  33271. for (int i = getNumChildComponents(); --i >= 0;)
  33272. {
  33273. Component* const c = getChildComponent (i);
  33274. if (c != 0)
  33275. {
  33276. c->sendEnablementChangeMessage();
  33277. if (safePointer == 0)
  33278. return;
  33279. }
  33280. }
  33281. }
  33282. void Component::enablementChanged()
  33283. {
  33284. }
  33285. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33286. {
  33287. flags.wantsFocusFlag = wantsFocus;
  33288. }
  33289. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33290. {
  33291. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33292. }
  33293. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33294. {
  33295. return ! flags.dontFocusOnMouseClickFlag;
  33296. }
  33297. bool Component::getWantsKeyboardFocus() const throw()
  33298. {
  33299. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33300. }
  33301. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33302. {
  33303. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33304. }
  33305. bool Component::isFocusContainer() const throw()
  33306. {
  33307. return flags.isFocusContainerFlag;
  33308. }
  33309. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33310. int Component::getExplicitFocusOrder() const
  33311. {
  33312. return properties [juce_explicitFocusOrderId];
  33313. }
  33314. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33315. {
  33316. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33317. }
  33318. KeyboardFocusTraverser* Component::createFocusTraverser()
  33319. {
  33320. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33321. return new KeyboardFocusTraverser();
  33322. return parentComponent_->createFocusTraverser();
  33323. }
  33324. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33325. {
  33326. // give the focus to this component
  33327. if (currentlyFocusedComponent != this)
  33328. {
  33329. JUCE_TRY
  33330. {
  33331. // get the focus onto our desktop window
  33332. ComponentPeer* const peer = getPeer();
  33333. if (peer != 0)
  33334. {
  33335. SafePointer<Component> safePointer (this);
  33336. peer->grabFocus();
  33337. if (peer->isFocused() && currentlyFocusedComponent != this)
  33338. {
  33339. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  33340. currentlyFocusedComponent = this;
  33341. Desktop::getInstance().triggerFocusCallback();
  33342. // call this after setting currentlyFocusedComponent so that the one that's
  33343. // losing it has a chance to see where focus is going
  33344. if (componentLosingFocus != 0)
  33345. componentLosingFocus->internalFocusLoss (cause);
  33346. if (currentlyFocusedComponent == this)
  33347. {
  33348. focusGained (cause);
  33349. if (safePointer != 0)
  33350. internalChildFocusChange (cause);
  33351. }
  33352. }
  33353. }
  33354. }
  33355. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33356. catch (const std::exception& e)
  33357. {
  33358. currentlyFocusedComponent = 0;
  33359. Desktop::getInstance().triggerFocusCallback();
  33360. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33361. }
  33362. catch (...)
  33363. {
  33364. currentlyFocusedComponent = 0;
  33365. Desktop::getInstance().triggerFocusCallback();
  33366. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33367. }
  33368. #endif
  33369. }
  33370. }
  33371. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33372. {
  33373. if (isShowing())
  33374. {
  33375. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33376. {
  33377. takeKeyboardFocus (cause);
  33378. }
  33379. else
  33380. {
  33381. if (isParentOf (currentlyFocusedComponent)
  33382. && currentlyFocusedComponent->isShowing())
  33383. {
  33384. // do nothing if the focused component is actually a child of ours..
  33385. }
  33386. else
  33387. {
  33388. // find the default child component..
  33389. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33390. if (traverser != 0)
  33391. {
  33392. Component* const defaultComp = traverser->getDefaultComponent (this);
  33393. traverser = 0;
  33394. if (defaultComp != 0)
  33395. {
  33396. defaultComp->grabFocusInternal (cause, false);
  33397. return;
  33398. }
  33399. }
  33400. if (canTryParent && parentComponent_ != 0)
  33401. {
  33402. // if no children want it and we're allowed to try our parent comp,
  33403. // then pass up to parent, which will try our siblings.
  33404. parentComponent_->grabFocusInternal (cause, true);
  33405. }
  33406. }
  33407. }
  33408. }
  33409. }
  33410. void Component::grabKeyboardFocus()
  33411. {
  33412. // if component methods are being called from threads other than the message
  33413. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33414. checkMessageManagerIsLocked
  33415. grabFocusInternal (focusChangedDirectly);
  33416. }
  33417. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33418. {
  33419. // if component methods are being called from threads other than the message
  33420. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33421. checkMessageManagerIsLocked
  33422. if (parentComponent_ != 0)
  33423. {
  33424. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33425. if (traverser != 0)
  33426. {
  33427. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33428. : traverser->getPreviousComponent (this);
  33429. traverser = 0;
  33430. if (nextComp != 0)
  33431. {
  33432. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33433. {
  33434. SafePointer<Component> nextCompPointer (nextComp);
  33435. internalModalInputAttempt();
  33436. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33437. return;
  33438. }
  33439. nextComp->grabFocusInternal (focusChangedByTabKey);
  33440. return;
  33441. }
  33442. }
  33443. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33444. }
  33445. }
  33446. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33447. {
  33448. return (currentlyFocusedComponent == this)
  33449. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33450. }
  33451. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33452. {
  33453. return currentlyFocusedComponent;
  33454. }
  33455. void Component::giveAwayFocus()
  33456. {
  33457. // use a copy so we can clear the value before the call
  33458. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  33459. currentlyFocusedComponent = 0;
  33460. Desktop::getInstance().triggerFocusCallback();
  33461. if (componentLosingFocus != 0)
  33462. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33463. }
  33464. bool Component::isMouseOver() const throw()
  33465. {
  33466. return flags.mouseOverFlag;
  33467. }
  33468. bool Component::isMouseButtonDown() const throw()
  33469. {
  33470. return flags.draggingFlag;
  33471. }
  33472. bool Component::isMouseOverOrDragging() const throw()
  33473. {
  33474. return flags.mouseOverFlag || flags.draggingFlag;
  33475. }
  33476. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33477. {
  33478. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33479. }
  33480. const Point<int> Component::getMouseXYRelative() const
  33481. {
  33482. return globalPositionToRelative (Desktop::getMousePosition());
  33483. }
  33484. const Rectangle<int> Component::getParentMonitorArea() const
  33485. {
  33486. return Desktop::getInstance()
  33487. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  33488. }
  33489. void Component::addKeyListener (KeyListener* const newListener)
  33490. {
  33491. if (keyListeners_ == 0)
  33492. keyListeners_ = new Array <KeyListener*>();
  33493. keyListeners_->addIfNotAlreadyThere (newListener);
  33494. }
  33495. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33496. {
  33497. if (keyListeners_ != 0)
  33498. keyListeners_->removeValue (listenerToRemove);
  33499. }
  33500. bool Component::keyPressed (const KeyPress&)
  33501. {
  33502. return false;
  33503. }
  33504. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33505. {
  33506. return false;
  33507. }
  33508. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33509. {
  33510. if (parentComponent_ != 0)
  33511. parentComponent_->modifierKeysChanged (modifiers);
  33512. }
  33513. void Component::internalModifierKeysChanged()
  33514. {
  33515. sendFakeMouseMove();
  33516. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33517. }
  33518. ComponentPeer* Component::getPeer() const
  33519. {
  33520. if (flags.hasHeavyweightPeerFlag)
  33521. return ComponentPeer::getPeerFor (this);
  33522. else if (parentComponent_ != 0)
  33523. return parentComponent_->getPeer();
  33524. else
  33525. return 0;
  33526. }
  33527. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33528. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33529. {
  33530. jassert (component1 != 0);
  33531. }
  33532. bool Component::BailOutChecker::shouldBailOut() const throw()
  33533. {
  33534. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33535. }
  33536. END_JUCE_NAMESPACE
  33537. /*** End of inlined file: juce_Component.cpp ***/
  33538. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33539. BEGIN_JUCE_NAMESPACE
  33540. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33541. void ComponentListener::componentBroughtToFront (Component&) {}
  33542. void ComponentListener::componentVisibilityChanged (Component&) {}
  33543. void ComponentListener::componentChildrenChanged (Component&) {}
  33544. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33545. void ComponentListener::componentNameChanged (Component&) {}
  33546. void ComponentListener::componentBeingDeleted (Component&) {}
  33547. END_JUCE_NAMESPACE
  33548. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33549. /*** Start of inlined file: juce_Desktop.cpp ***/
  33550. BEGIN_JUCE_NAMESPACE
  33551. Desktop::Desktop()
  33552. : mouseClickCounter (0),
  33553. kioskModeComponent (0)
  33554. {
  33555. createMouseInputSources();
  33556. refreshMonitorSizes();
  33557. }
  33558. Desktop::~Desktop()
  33559. {
  33560. jassert (instance == this);
  33561. instance = 0;
  33562. // doh! If you don't delete all your windows before exiting, you're going to
  33563. // be leaking memory!
  33564. jassert (desktopComponents.size() == 0);
  33565. }
  33566. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33567. {
  33568. if (instance == 0)
  33569. instance = new Desktop();
  33570. return *instance;
  33571. }
  33572. Desktop* Desktop::instance = 0;
  33573. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33574. const bool clipToWorkArea);
  33575. void Desktop::refreshMonitorSizes()
  33576. {
  33577. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33578. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33579. monitorCoordsClipped.clear();
  33580. monitorCoordsUnclipped.clear();
  33581. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33582. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33583. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33584. if (oldClipped != monitorCoordsClipped
  33585. || oldUnclipped != monitorCoordsUnclipped)
  33586. {
  33587. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33588. {
  33589. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33590. if (p != 0)
  33591. p->handleScreenSizeChange();
  33592. }
  33593. }
  33594. }
  33595. int Desktop::getNumDisplayMonitors() const throw()
  33596. {
  33597. return monitorCoordsClipped.size();
  33598. }
  33599. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33600. {
  33601. return clippedToWorkArea ? monitorCoordsClipped [index]
  33602. : monitorCoordsUnclipped [index];
  33603. }
  33604. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33605. {
  33606. RectangleList rl;
  33607. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33608. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33609. return rl;
  33610. }
  33611. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33612. {
  33613. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33614. }
  33615. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33616. {
  33617. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33618. double bestDistance = 1.0e10;
  33619. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33620. {
  33621. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33622. if (rect.contains (position))
  33623. return rect;
  33624. const double distance = rect.getCentre().getDistanceFrom (position);
  33625. if (distance < bestDistance)
  33626. {
  33627. bestDistance = distance;
  33628. best = rect;
  33629. }
  33630. }
  33631. return best;
  33632. }
  33633. int Desktop::getNumComponents() const throw()
  33634. {
  33635. return desktopComponents.size();
  33636. }
  33637. Component* Desktop::getComponent (const int index) const throw()
  33638. {
  33639. return desktopComponents [index];
  33640. }
  33641. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33642. {
  33643. for (int i = desktopComponents.size(); --i >= 0;)
  33644. {
  33645. Component* const c = desktopComponents.getUnchecked(i);
  33646. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33647. if (c->contains (relative.getX(), relative.getY()))
  33648. return c->getComponentAt (relative.getX(), relative.getY());
  33649. }
  33650. return 0;
  33651. }
  33652. void Desktop::addDesktopComponent (Component* const c)
  33653. {
  33654. jassert (c != 0);
  33655. jassert (! desktopComponents.contains (c));
  33656. desktopComponents.addIfNotAlreadyThere (c);
  33657. }
  33658. void Desktop::removeDesktopComponent (Component* const c)
  33659. {
  33660. desktopComponents.removeValue (c);
  33661. }
  33662. void Desktop::componentBroughtToFront (Component* const c)
  33663. {
  33664. const int index = desktopComponents.indexOf (c);
  33665. jassert (index >= 0);
  33666. if (index >= 0)
  33667. {
  33668. int newIndex = -1;
  33669. if (! c->isAlwaysOnTop())
  33670. {
  33671. newIndex = desktopComponents.size();
  33672. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33673. --newIndex;
  33674. --newIndex;
  33675. }
  33676. desktopComponents.move (index, newIndex);
  33677. }
  33678. }
  33679. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33680. {
  33681. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33682. }
  33683. int Desktop::getMouseButtonClickCounter() throw()
  33684. {
  33685. return getInstance().mouseClickCounter;
  33686. }
  33687. void Desktop::incrementMouseClickCounter() throw()
  33688. {
  33689. ++mouseClickCounter;
  33690. }
  33691. int Desktop::getNumDraggingMouseSources() const throw()
  33692. {
  33693. int num = 0;
  33694. for (int i = mouseSources.size(); --i >= 0;)
  33695. if (mouseSources.getUnchecked(i)->isDragging())
  33696. ++num;
  33697. return num;
  33698. }
  33699. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33700. {
  33701. int num = 0;
  33702. for (int i = mouseSources.size(); --i >= 0;)
  33703. {
  33704. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33705. if (mi->isDragging())
  33706. {
  33707. if (index == num)
  33708. return mi;
  33709. ++num;
  33710. }
  33711. }
  33712. return 0;
  33713. }
  33714. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33715. {
  33716. focusListeners.add (listener);
  33717. }
  33718. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33719. {
  33720. focusListeners.remove (listener);
  33721. }
  33722. void Desktop::triggerFocusCallback()
  33723. {
  33724. triggerAsyncUpdate();
  33725. }
  33726. void Desktop::handleAsyncUpdate()
  33727. {
  33728. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33729. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33730. }
  33731. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33732. {
  33733. mouseListeners.add (listener);
  33734. resetTimer();
  33735. }
  33736. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33737. {
  33738. mouseListeners.remove (listener);
  33739. resetTimer();
  33740. }
  33741. void Desktop::timerCallback()
  33742. {
  33743. if (lastFakeMouseMove != getMousePosition())
  33744. sendMouseMove();
  33745. }
  33746. void Desktop::sendMouseMove()
  33747. {
  33748. if (! mouseListeners.isEmpty())
  33749. {
  33750. startTimer (20);
  33751. lastFakeMouseMove = getMousePosition();
  33752. Component* const target = findComponentAt (lastFakeMouseMove);
  33753. if (target != 0)
  33754. {
  33755. Component::BailOutChecker checker (target);
  33756. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33757. const Time now (Time::getCurrentTime());
  33758. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33759. target, target, now, pos, now, 0, false);
  33760. if (me.mods.isAnyMouseButtonDown())
  33761. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33762. else
  33763. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33764. }
  33765. }
  33766. }
  33767. void Desktop::resetTimer()
  33768. {
  33769. if (mouseListeners.size() == 0)
  33770. stopTimer();
  33771. else
  33772. startTimer (100);
  33773. lastFakeMouseMove = getMousePosition();
  33774. }
  33775. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33776. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33777. {
  33778. if (kioskModeComponent != componentToUse)
  33779. {
  33780. // agh! Don't delete a component without first stopping it being the kiosk comp
  33781. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33782. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33783. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33784. if (kioskModeComponent->isValidComponent())
  33785. {
  33786. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33787. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33788. }
  33789. kioskModeComponent = componentToUse;
  33790. if (kioskModeComponent != 0)
  33791. {
  33792. jassert (kioskModeComponent->isValidComponent());
  33793. // Only components that are already on the desktop can be put into kiosk mode!
  33794. jassert (kioskModeComponent->isOnDesktop());
  33795. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33796. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33797. }
  33798. }
  33799. }
  33800. END_JUCE_NAMESPACE
  33801. /*** End of inlined file: juce_Desktop.cpp ***/
  33802. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  33803. BEGIN_JUCE_NAMESPACE
  33804. class ModalComponentManager::ModalItem : public ComponentListener
  33805. {
  33806. public:
  33807. ModalItem (Component* const comp, Callback* const callback)
  33808. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  33809. {
  33810. if (callback != 0)
  33811. callbacks.add (callback);
  33812. jassert (comp != 0);
  33813. component->addComponentListener (this);
  33814. }
  33815. ~ModalItem()
  33816. {
  33817. if (! isDeleted)
  33818. component->removeComponentListener (this);
  33819. }
  33820. void componentBeingDeleted (Component&)
  33821. {
  33822. isDeleted = true;
  33823. cancel();
  33824. }
  33825. void componentVisibilityChanged (Component&)
  33826. {
  33827. if (! component->isShowing())
  33828. cancel();
  33829. }
  33830. void componentParentHierarchyChanged (Component&)
  33831. {
  33832. if (! component->isShowing())
  33833. cancel();
  33834. }
  33835. void cancel()
  33836. {
  33837. if (isActive)
  33838. {
  33839. isActive = false;
  33840. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  33841. }
  33842. }
  33843. Component* component;
  33844. OwnedArray<Callback> callbacks;
  33845. int returnValue;
  33846. bool isActive, isDeleted;
  33847. private:
  33848. ModalItem (const ModalItem&);
  33849. ModalItem& operator= (const ModalItem&);
  33850. };
  33851. ModalComponentManager::ModalComponentManager()
  33852. {
  33853. }
  33854. ModalComponentManager::~ModalComponentManager()
  33855. {
  33856. clearSingletonInstance();
  33857. }
  33858. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  33859. void ModalComponentManager::startModal (Component* component, Callback* callback)
  33860. {
  33861. if (component != 0)
  33862. stack.add (new ModalItem (component, callback));
  33863. }
  33864. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  33865. {
  33866. if (callback != 0)
  33867. {
  33868. ScopedPointer<Callback> callbackDeleter (callback);
  33869. for (int i = stack.size(); --i >= 0;)
  33870. {
  33871. ModalItem* const item = stack.getUnchecked(i);
  33872. if (item->component == component)
  33873. {
  33874. item->callbacks.add (callback);
  33875. callbackDeleter.release();
  33876. break;
  33877. }
  33878. }
  33879. }
  33880. }
  33881. void ModalComponentManager::endModal (Component* component)
  33882. {
  33883. for (int i = stack.size(); --i >= 0;)
  33884. {
  33885. ModalItem* const item = stack.getUnchecked(i);
  33886. if (item->component == component)
  33887. item->cancel();
  33888. }
  33889. }
  33890. void ModalComponentManager::endModal (Component* component, int returnValue)
  33891. {
  33892. for (int i = stack.size(); --i >= 0;)
  33893. {
  33894. ModalItem* const item = stack.getUnchecked(i);
  33895. if (item->component == component)
  33896. {
  33897. item->returnValue = returnValue;
  33898. item->cancel();
  33899. }
  33900. }
  33901. }
  33902. int ModalComponentManager::getNumModalComponents() const
  33903. {
  33904. int n = 0;
  33905. for (int i = 0; i < stack.size(); ++i)
  33906. if (stack.getUnchecked(i)->isActive)
  33907. ++n;
  33908. return n;
  33909. }
  33910. Component* ModalComponentManager::getModalComponent (const int index) const
  33911. {
  33912. int n = 0;
  33913. for (int i = stack.size(); --i >= 0;)
  33914. {
  33915. const ModalItem* const item = stack.getUnchecked(i);
  33916. if (item->isActive)
  33917. if (n++ == index)
  33918. return item->component;
  33919. }
  33920. return 0;
  33921. }
  33922. bool ModalComponentManager::isModal (Component* const comp) const
  33923. {
  33924. for (int i = stack.size(); --i >= 0;)
  33925. {
  33926. const ModalItem* const item = stack.getUnchecked(i);
  33927. if (item->isActive && item->component == comp)
  33928. return true;
  33929. }
  33930. return false;
  33931. }
  33932. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  33933. {
  33934. return comp == getModalComponent (0);
  33935. }
  33936. void ModalComponentManager::handleAsyncUpdate()
  33937. {
  33938. for (int i = stack.size(); --i >= 0;)
  33939. {
  33940. const ModalItem* const item = stack.getUnchecked(i);
  33941. if (! item->isActive)
  33942. {
  33943. for (int j = item->callbacks.size(); --j >= 0;)
  33944. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  33945. stack.remove (i);
  33946. }
  33947. }
  33948. }
  33949. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  33950. {
  33951. public:
  33952. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  33953. ~ReturnValueRetriever() {}
  33954. void modalStateFinished (int returnValue)
  33955. {
  33956. finished = true;
  33957. value = returnValue;
  33958. }
  33959. private:
  33960. int& value;
  33961. bool& finished;
  33962. ReturnValueRetriever (const ReturnValueRetriever&);
  33963. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  33964. };
  33965. int ModalComponentManager::runEventLoopForCurrentComponent()
  33966. {
  33967. // This can only be run from the message thread!
  33968. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  33969. Component* currentlyModal = getModalComponent (0);
  33970. if (currentlyModal == 0)
  33971. return 0;
  33972. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  33973. int returnValue = 0;
  33974. bool finished = false;
  33975. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  33976. JUCE_TRY
  33977. {
  33978. while (! finished)
  33979. {
  33980. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  33981. break;
  33982. }
  33983. }
  33984. JUCE_CATCH_EXCEPTION
  33985. if (prevFocused != 0)
  33986. prevFocused->grabKeyboardFocus();
  33987. return returnValue;
  33988. }
  33989. END_JUCE_NAMESPACE
  33990. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  33991. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33992. BEGIN_JUCE_NAMESPACE
  33993. ArrowButton::ArrowButton (const String& name,
  33994. float arrowDirectionInRadians,
  33995. const Colour& arrowColour)
  33996. : Button (name),
  33997. colour (arrowColour)
  33998. {
  33999. path.lineTo (0.0f, 1.0f);
  34000. path.lineTo (1.0f, 0.5f);
  34001. path.closeSubPath();
  34002. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34003. 0.5f, 0.5f));
  34004. setComponentEffect (&shadow);
  34005. buttonStateChanged();
  34006. }
  34007. ArrowButton::~ArrowButton()
  34008. {
  34009. }
  34010. void ArrowButton::paintButton (Graphics& g,
  34011. bool /*isMouseOverButton*/,
  34012. bool /*isButtonDown*/)
  34013. {
  34014. g.setColour (colour);
  34015. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34016. (float) offset,
  34017. (float) (getWidth() - 3),
  34018. (float) (getHeight() - 3),
  34019. false));
  34020. }
  34021. void ArrowButton::buttonStateChanged()
  34022. {
  34023. offset = (isDown()) ? 1 : 0;
  34024. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34025. 0.3f, -1, 0);
  34026. }
  34027. END_JUCE_NAMESPACE
  34028. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34029. /*** Start of inlined file: juce_Button.cpp ***/
  34030. BEGIN_JUCE_NAMESPACE
  34031. class Button::RepeatTimer : public Timer
  34032. {
  34033. public:
  34034. RepeatTimer (Button& owner_) : owner (owner_) {}
  34035. void timerCallback() { owner.repeatTimerCallback(); }
  34036. juce_UseDebuggingNewOperator
  34037. private:
  34038. Button& owner;
  34039. RepeatTimer (const RepeatTimer&);
  34040. RepeatTimer& operator= (const RepeatTimer&);
  34041. };
  34042. Button::Button (const String& name)
  34043. : Component (name),
  34044. text (name),
  34045. buttonPressTime (0),
  34046. lastTimeCallbackTime (0),
  34047. commandManagerToUse (0),
  34048. autoRepeatDelay (-1),
  34049. autoRepeatSpeed (0),
  34050. autoRepeatMinimumDelay (-1),
  34051. radioGroupId (0),
  34052. commandID (0),
  34053. connectedEdgeFlags (0),
  34054. buttonState (buttonNormal),
  34055. lastToggleState (false),
  34056. clickTogglesState (false),
  34057. needsToRelease (false),
  34058. needsRepainting (false),
  34059. isKeyDown (false),
  34060. triggerOnMouseDown (false),
  34061. generateTooltip (false)
  34062. {
  34063. setWantsKeyboardFocus (true);
  34064. isOn.addListener (this);
  34065. }
  34066. Button::~Button()
  34067. {
  34068. isOn.removeListener (this);
  34069. if (commandManagerToUse != 0)
  34070. commandManagerToUse->removeListener (this);
  34071. repeatTimer = 0;
  34072. clearShortcuts();
  34073. }
  34074. void Button::setButtonText (const String& newText)
  34075. {
  34076. if (text != newText)
  34077. {
  34078. text = newText;
  34079. repaint();
  34080. }
  34081. }
  34082. void Button::setTooltip (const String& newTooltip)
  34083. {
  34084. SettableTooltipClient::setTooltip (newTooltip);
  34085. generateTooltip = false;
  34086. }
  34087. const String Button::getTooltip()
  34088. {
  34089. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34090. {
  34091. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34092. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34093. for (int i = 0; i < keyPresses.size(); ++i)
  34094. {
  34095. const String key (keyPresses.getReference(i).getTextDescription());
  34096. tt << " [";
  34097. if (key.length() == 1)
  34098. tt << TRANS("shortcut") << ": '" << key << "']";
  34099. else
  34100. tt << key << ']';
  34101. }
  34102. return tt;
  34103. }
  34104. return SettableTooltipClient::getTooltip();
  34105. }
  34106. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34107. {
  34108. if (connectedEdgeFlags != connectedEdgeFlags_)
  34109. {
  34110. connectedEdgeFlags = connectedEdgeFlags_;
  34111. repaint();
  34112. }
  34113. }
  34114. void Button::setToggleState (const bool shouldBeOn,
  34115. const bool sendChangeNotification)
  34116. {
  34117. if (shouldBeOn != lastToggleState)
  34118. {
  34119. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34120. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34121. lastToggleState = shouldBeOn;
  34122. repaint();
  34123. if (sendChangeNotification)
  34124. {
  34125. Component::SafePointer<Component> deletionWatcher (this);
  34126. sendClickMessage (ModifierKeys());
  34127. if (deletionWatcher == 0)
  34128. return;
  34129. }
  34130. if (lastToggleState)
  34131. turnOffOtherButtonsInGroup (sendChangeNotification);
  34132. }
  34133. }
  34134. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34135. {
  34136. clickTogglesState = shouldToggle;
  34137. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34138. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34139. // it is that this button represents, and the button will update its state to reflect this
  34140. // in the applicationCommandListChanged() method.
  34141. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34142. }
  34143. bool Button::getClickingTogglesState() const throw()
  34144. {
  34145. return clickTogglesState;
  34146. }
  34147. void Button::valueChanged (Value& value)
  34148. {
  34149. if (value.refersToSameSourceAs (isOn))
  34150. setToggleState (isOn.getValue(), true);
  34151. }
  34152. void Button::setRadioGroupId (const int newGroupId)
  34153. {
  34154. if (radioGroupId != newGroupId)
  34155. {
  34156. radioGroupId = newGroupId;
  34157. if (lastToggleState)
  34158. turnOffOtherButtonsInGroup (true);
  34159. }
  34160. }
  34161. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34162. {
  34163. Component* const p = getParentComponent();
  34164. if (p != 0 && radioGroupId != 0)
  34165. {
  34166. Component::SafePointer<Component> deletionWatcher (this);
  34167. for (int i = p->getNumChildComponents(); --i >= 0;)
  34168. {
  34169. Component* const c = p->getChildComponent (i);
  34170. if (c != this)
  34171. {
  34172. Button* const b = dynamic_cast <Button*> (c);
  34173. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34174. {
  34175. b->setToggleState (false, sendChangeNotification);
  34176. if (deletionWatcher == 0)
  34177. return;
  34178. }
  34179. }
  34180. }
  34181. }
  34182. }
  34183. void Button::enablementChanged()
  34184. {
  34185. updateState (0);
  34186. repaint();
  34187. }
  34188. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34189. {
  34190. ButtonState state = buttonNormal;
  34191. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34192. {
  34193. Point<int> mousePos;
  34194. if (e == 0)
  34195. mousePos = getMouseXYRelative();
  34196. else
  34197. mousePos = e->getEventRelativeTo (this).getPosition();
  34198. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34199. const bool down = isMouseButtonDown();
  34200. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34201. state = buttonDown;
  34202. else if (over)
  34203. state = buttonOver;
  34204. }
  34205. setState (state);
  34206. return state;
  34207. }
  34208. void Button::setState (const ButtonState newState)
  34209. {
  34210. if (buttonState != newState)
  34211. {
  34212. buttonState = newState;
  34213. repaint();
  34214. if (buttonState == buttonDown)
  34215. {
  34216. buttonPressTime = Time::getApproximateMillisecondCounter();
  34217. lastTimeCallbackTime = buttonPressTime;
  34218. }
  34219. sendStateMessage();
  34220. }
  34221. }
  34222. bool Button::isDown() const throw()
  34223. {
  34224. return buttonState == buttonDown;
  34225. }
  34226. bool Button::isOver() const throw()
  34227. {
  34228. return buttonState != buttonNormal;
  34229. }
  34230. void Button::buttonStateChanged()
  34231. {
  34232. }
  34233. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34234. {
  34235. const uint32 now = Time::getApproximateMillisecondCounter();
  34236. return now > buttonPressTime ? now - buttonPressTime : 0;
  34237. }
  34238. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34239. {
  34240. triggerOnMouseDown = isTriggeredOnMouseDown;
  34241. }
  34242. void Button::clicked()
  34243. {
  34244. }
  34245. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34246. {
  34247. clicked();
  34248. }
  34249. static const int clickMessageId = 0x2f3f4f99;
  34250. void Button::triggerClick()
  34251. {
  34252. postCommandMessage (clickMessageId);
  34253. }
  34254. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34255. {
  34256. if (clickTogglesState)
  34257. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34258. sendClickMessage (modifiers);
  34259. }
  34260. void Button::flashButtonState()
  34261. {
  34262. if (isEnabled())
  34263. {
  34264. needsToRelease = true;
  34265. setState (buttonDown);
  34266. getRepeatTimer().startTimer (100);
  34267. }
  34268. }
  34269. void Button::handleCommandMessage (int commandId)
  34270. {
  34271. if (commandId == clickMessageId)
  34272. {
  34273. if (isEnabled())
  34274. {
  34275. flashButtonState();
  34276. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34277. }
  34278. }
  34279. else
  34280. {
  34281. Component::handleCommandMessage (commandId);
  34282. }
  34283. }
  34284. void Button::addButtonListener (Listener* const newListener)
  34285. {
  34286. buttonListeners.add (newListener);
  34287. }
  34288. void Button::removeButtonListener (Listener* const listener)
  34289. {
  34290. buttonListeners.remove (listener);
  34291. }
  34292. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34293. {
  34294. Component::BailOutChecker checker (this);
  34295. if (commandManagerToUse != 0 && commandID != 0)
  34296. {
  34297. ApplicationCommandTarget::InvocationInfo info (commandID);
  34298. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34299. info.originatingComponent = this;
  34300. commandManagerToUse->invoke (info, true);
  34301. }
  34302. clicked (modifiers);
  34303. if (! checker.shouldBailOut())
  34304. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34305. }
  34306. void Button::sendStateMessage()
  34307. {
  34308. Component::BailOutChecker checker (this);
  34309. buttonStateChanged();
  34310. if (! checker.shouldBailOut())
  34311. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34312. }
  34313. void Button::paint (Graphics& g)
  34314. {
  34315. if (needsToRelease && isEnabled())
  34316. {
  34317. needsToRelease = false;
  34318. needsRepainting = true;
  34319. }
  34320. paintButton (g, isOver(), isDown());
  34321. }
  34322. void Button::mouseEnter (const MouseEvent& e)
  34323. {
  34324. updateState (&e);
  34325. }
  34326. void Button::mouseExit (const MouseEvent& e)
  34327. {
  34328. updateState (&e);
  34329. }
  34330. void Button::mouseDown (const MouseEvent& e)
  34331. {
  34332. updateState (&e);
  34333. if (isDown())
  34334. {
  34335. if (autoRepeatDelay >= 0)
  34336. getRepeatTimer().startTimer (autoRepeatDelay);
  34337. if (triggerOnMouseDown)
  34338. internalClickCallback (e.mods);
  34339. }
  34340. }
  34341. void Button::mouseUp (const MouseEvent& e)
  34342. {
  34343. const bool wasDown = isDown();
  34344. updateState (&e);
  34345. if (wasDown && isOver() && ! triggerOnMouseDown)
  34346. internalClickCallback (e.mods);
  34347. }
  34348. void Button::mouseDrag (const MouseEvent& e)
  34349. {
  34350. const ButtonState oldState = buttonState;
  34351. updateState (&e);
  34352. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34353. getRepeatTimer().startTimer (autoRepeatSpeed);
  34354. }
  34355. void Button::focusGained (FocusChangeType)
  34356. {
  34357. updateState (0);
  34358. repaint();
  34359. }
  34360. void Button::focusLost (FocusChangeType)
  34361. {
  34362. updateState (0);
  34363. repaint();
  34364. }
  34365. void Button::setVisible (bool shouldBeVisible)
  34366. {
  34367. if (shouldBeVisible != isVisible())
  34368. {
  34369. Component::setVisible (shouldBeVisible);
  34370. if (! shouldBeVisible)
  34371. needsToRelease = false;
  34372. updateState (0);
  34373. }
  34374. else
  34375. {
  34376. Component::setVisible (shouldBeVisible);
  34377. }
  34378. }
  34379. void Button::parentHierarchyChanged()
  34380. {
  34381. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34382. if (newKeySource != keySource.getComponent())
  34383. {
  34384. if (keySource != 0)
  34385. keySource->removeKeyListener (this);
  34386. keySource = newKeySource;
  34387. if (keySource != 0)
  34388. keySource->addKeyListener (this);
  34389. }
  34390. }
  34391. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34392. const int commandID_,
  34393. const bool generateTooltip_)
  34394. {
  34395. commandID = commandID_;
  34396. generateTooltip = generateTooltip_;
  34397. if (commandManagerToUse != commandManagerToUse_)
  34398. {
  34399. if (commandManagerToUse != 0)
  34400. commandManagerToUse->removeListener (this);
  34401. commandManagerToUse = commandManagerToUse_;
  34402. if (commandManagerToUse != 0)
  34403. commandManagerToUse->addListener (this);
  34404. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34405. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34406. // it is that this button represents, and the button will update its state to reflect this
  34407. // in the applicationCommandListChanged() method.
  34408. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34409. }
  34410. if (commandManagerToUse != 0)
  34411. applicationCommandListChanged();
  34412. else
  34413. setEnabled (true);
  34414. }
  34415. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34416. {
  34417. if (info.commandID == commandID
  34418. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34419. {
  34420. flashButtonState();
  34421. }
  34422. }
  34423. void Button::applicationCommandListChanged()
  34424. {
  34425. if (commandManagerToUse != 0)
  34426. {
  34427. ApplicationCommandInfo info (0);
  34428. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34429. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34430. if (target != 0)
  34431. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34432. }
  34433. }
  34434. void Button::addShortcut (const KeyPress& key)
  34435. {
  34436. if (key.isValid())
  34437. {
  34438. jassert (! isRegisteredForShortcut (key)); // already registered!
  34439. shortcuts.add (key);
  34440. parentHierarchyChanged();
  34441. }
  34442. }
  34443. void Button::clearShortcuts()
  34444. {
  34445. shortcuts.clear();
  34446. parentHierarchyChanged();
  34447. }
  34448. bool Button::isShortcutPressed() const
  34449. {
  34450. if (! isCurrentlyBlockedByAnotherModalComponent())
  34451. {
  34452. for (int i = shortcuts.size(); --i >= 0;)
  34453. if (shortcuts.getReference(i).isCurrentlyDown())
  34454. return true;
  34455. }
  34456. return false;
  34457. }
  34458. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34459. {
  34460. for (int i = shortcuts.size(); --i >= 0;)
  34461. if (key == shortcuts.getReference(i))
  34462. return true;
  34463. return false;
  34464. }
  34465. bool Button::keyStateChanged (const bool, Component*)
  34466. {
  34467. if (! isEnabled())
  34468. return false;
  34469. const bool wasDown = isKeyDown;
  34470. isKeyDown = isShortcutPressed();
  34471. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34472. getRepeatTimer().startTimer (autoRepeatDelay);
  34473. updateState (0);
  34474. if (isEnabled() && wasDown && ! isKeyDown)
  34475. {
  34476. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34477. // (return immediately - this button may now have been deleted)
  34478. return true;
  34479. }
  34480. return wasDown || isKeyDown;
  34481. }
  34482. bool Button::keyPressed (const KeyPress&, Component*)
  34483. {
  34484. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34485. return isShortcutPressed();
  34486. }
  34487. bool Button::keyPressed (const KeyPress& key)
  34488. {
  34489. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34490. {
  34491. triggerClick();
  34492. return true;
  34493. }
  34494. return false;
  34495. }
  34496. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34497. const int repeatMillisecs,
  34498. const int minimumDelayInMillisecs) throw()
  34499. {
  34500. autoRepeatDelay = initialDelayMillisecs;
  34501. autoRepeatSpeed = repeatMillisecs;
  34502. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34503. }
  34504. void Button::repeatTimerCallback()
  34505. {
  34506. if (needsRepainting)
  34507. {
  34508. getRepeatTimer().stopTimer();
  34509. updateState (0);
  34510. needsRepainting = false;
  34511. }
  34512. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34513. {
  34514. int repeatSpeed = autoRepeatSpeed;
  34515. if (autoRepeatMinimumDelay >= 0)
  34516. {
  34517. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34518. timeHeldDown *= timeHeldDown;
  34519. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34520. }
  34521. repeatSpeed = jmax (1, repeatSpeed);
  34522. getRepeatTimer().startTimer (repeatSpeed);
  34523. const uint32 now = Time::getApproximateMillisecondCounter();
  34524. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34525. lastTimeCallbackTime = now;
  34526. Component::SafePointer<Component> deletionWatcher (this);
  34527. for (int i = numTimesToCallback; --i >= 0;)
  34528. {
  34529. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34530. if (deletionWatcher == 0 || ! isDown())
  34531. return;
  34532. }
  34533. }
  34534. else if (! needsToRelease)
  34535. {
  34536. getRepeatTimer().stopTimer();
  34537. }
  34538. }
  34539. Button::RepeatTimer& Button::getRepeatTimer()
  34540. {
  34541. if (repeatTimer == 0)
  34542. repeatTimer = new RepeatTimer (*this);
  34543. return *repeatTimer;
  34544. }
  34545. END_JUCE_NAMESPACE
  34546. /*** End of inlined file: juce_Button.cpp ***/
  34547. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34548. BEGIN_JUCE_NAMESPACE
  34549. DrawableButton::DrawableButton (const String& name,
  34550. const DrawableButton::ButtonStyle buttonStyle)
  34551. : Button (name),
  34552. style (buttonStyle),
  34553. edgeIndent (3)
  34554. {
  34555. if (buttonStyle == ImageOnButtonBackground)
  34556. {
  34557. backgroundOff = Colour (0xffbbbbff);
  34558. backgroundOn = Colour (0xff3333ff);
  34559. }
  34560. else
  34561. {
  34562. backgroundOff = Colours::transparentBlack;
  34563. backgroundOn = Colour (0xaabbbbff);
  34564. }
  34565. }
  34566. DrawableButton::~DrawableButton()
  34567. {
  34568. deleteImages();
  34569. }
  34570. void DrawableButton::deleteImages()
  34571. {
  34572. }
  34573. void DrawableButton::setImages (const Drawable* normal,
  34574. const Drawable* over,
  34575. const Drawable* down,
  34576. const Drawable* disabled,
  34577. const Drawable* normalOn,
  34578. const Drawable* overOn,
  34579. const Drawable* downOn,
  34580. const Drawable* disabledOn)
  34581. {
  34582. deleteImages();
  34583. jassert (normal != 0); // you really need to give it at least a normal image..
  34584. if (normal != 0)
  34585. normalImage = normal->createCopy();
  34586. if (over != 0)
  34587. overImage = over->createCopy();
  34588. if (down != 0)
  34589. downImage = down->createCopy();
  34590. if (disabled != 0)
  34591. disabledImage = disabled->createCopy();
  34592. if (normalOn != 0)
  34593. normalImageOn = normalOn->createCopy();
  34594. if (overOn != 0)
  34595. overImageOn = overOn->createCopy();
  34596. if (downOn != 0)
  34597. downImageOn = downOn->createCopy();
  34598. if (disabledOn != 0)
  34599. disabledImageOn = disabledOn->createCopy();
  34600. repaint();
  34601. }
  34602. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34603. {
  34604. if (style != newStyle)
  34605. {
  34606. style = newStyle;
  34607. repaint();
  34608. }
  34609. }
  34610. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34611. const Colour& toggledOnColour)
  34612. {
  34613. if (backgroundOff != toggledOffColour
  34614. || backgroundOn != toggledOnColour)
  34615. {
  34616. backgroundOff = toggledOffColour;
  34617. backgroundOn = toggledOnColour;
  34618. repaint();
  34619. }
  34620. }
  34621. const Colour& DrawableButton::getBackgroundColour() const throw()
  34622. {
  34623. return getToggleState() ? backgroundOn
  34624. : backgroundOff;
  34625. }
  34626. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34627. {
  34628. edgeIndent = numPixelsIndent;
  34629. repaint();
  34630. }
  34631. void DrawableButton::paintButton (Graphics& g,
  34632. bool isMouseOverButton,
  34633. bool isButtonDown)
  34634. {
  34635. Rectangle<int> imageSpace;
  34636. if (style == ImageOnButtonBackground)
  34637. {
  34638. const int insetX = getWidth() / 4;
  34639. const int insetY = getHeight() / 4;
  34640. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34641. getLookAndFeel().drawButtonBackground (g, *this,
  34642. getBackgroundColour(),
  34643. isMouseOverButton,
  34644. isButtonDown);
  34645. }
  34646. else
  34647. {
  34648. g.fillAll (getBackgroundColour());
  34649. const int textH = (style == ImageAboveTextLabel)
  34650. ? jmin (16, proportionOfHeight (0.25f))
  34651. : 0;
  34652. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34653. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34654. imageSpace.setBounds (indentX, indentY,
  34655. getWidth() - indentX * 2,
  34656. getHeight() - indentY * 2 - textH);
  34657. if (textH > 0)
  34658. {
  34659. g.setFont ((float) textH);
  34660. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34661. g.drawFittedText (getButtonText(),
  34662. 2, getHeight() - textH - 1,
  34663. getWidth() - 4, textH,
  34664. Justification::centred, 1);
  34665. }
  34666. }
  34667. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34668. g.setOpacity (1.0f);
  34669. const Drawable* imageToDraw = 0;
  34670. if (isEnabled())
  34671. {
  34672. imageToDraw = getCurrentImage();
  34673. }
  34674. else
  34675. {
  34676. imageToDraw = getToggleState() ? disabledImageOn
  34677. : disabledImage;
  34678. if (imageToDraw == 0)
  34679. {
  34680. g.setOpacity (0.4f);
  34681. imageToDraw = getNormalImage();
  34682. }
  34683. }
  34684. if (imageToDraw != 0)
  34685. {
  34686. if (style == ImageRaw)
  34687. {
  34688. imageToDraw->draw (g, 1.0f);
  34689. }
  34690. else
  34691. {
  34692. imageToDraw->drawWithin (g,
  34693. imageSpace.getX(),
  34694. imageSpace.getY(),
  34695. imageSpace.getWidth(),
  34696. imageSpace.getHeight(),
  34697. RectanglePlacement::centred,
  34698. 1.0f);
  34699. }
  34700. }
  34701. }
  34702. const Drawable* DrawableButton::getCurrentImage() const throw()
  34703. {
  34704. if (isDown())
  34705. return getDownImage();
  34706. if (isOver())
  34707. return getOverImage();
  34708. return getNormalImage();
  34709. }
  34710. const Drawable* DrawableButton::getNormalImage() const throw()
  34711. {
  34712. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34713. : normalImage;
  34714. }
  34715. const Drawable* DrawableButton::getOverImage() const throw()
  34716. {
  34717. const Drawable* d = normalImage;
  34718. if (getToggleState())
  34719. {
  34720. if (overImageOn != 0)
  34721. d = overImageOn;
  34722. else if (normalImageOn != 0)
  34723. d = normalImageOn;
  34724. else if (overImage != 0)
  34725. d = overImage;
  34726. }
  34727. else
  34728. {
  34729. if (overImage != 0)
  34730. d = overImage;
  34731. }
  34732. return d;
  34733. }
  34734. const Drawable* DrawableButton::getDownImage() const throw()
  34735. {
  34736. const Drawable* d = normalImage;
  34737. if (getToggleState())
  34738. {
  34739. if (downImageOn != 0)
  34740. d = downImageOn;
  34741. else if (overImageOn != 0)
  34742. d = overImageOn;
  34743. else if (normalImageOn != 0)
  34744. d = normalImageOn;
  34745. else if (downImage != 0)
  34746. d = downImage;
  34747. else
  34748. d = getOverImage();
  34749. }
  34750. else
  34751. {
  34752. if (downImage != 0)
  34753. d = downImage;
  34754. else
  34755. d = getOverImage();
  34756. }
  34757. return d;
  34758. }
  34759. END_JUCE_NAMESPACE
  34760. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34761. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34762. BEGIN_JUCE_NAMESPACE
  34763. HyperlinkButton::HyperlinkButton (const String& linkText,
  34764. const URL& linkURL)
  34765. : Button (linkText),
  34766. url (linkURL),
  34767. font (14.0f, Font::underlined),
  34768. resizeFont (true),
  34769. justification (Justification::centred)
  34770. {
  34771. setMouseCursor (MouseCursor::PointingHandCursor);
  34772. setTooltip (linkURL.toString (false));
  34773. }
  34774. HyperlinkButton::~HyperlinkButton()
  34775. {
  34776. }
  34777. void HyperlinkButton::setFont (const Font& newFont,
  34778. const bool resizeToMatchComponentHeight,
  34779. const Justification& justificationType)
  34780. {
  34781. font = newFont;
  34782. resizeFont = resizeToMatchComponentHeight;
  34783. justification = justificationType;
  34784. repaint();
  34785. }
  34786. void HyperlinkButton::setURL (const URL& newURL) throw()
  34787. {
  34788. url = newURL;
  34789. setTooltip (newURL.toString (false));
  34790. }
  34791. const Font HyperlinkButton::getFontToUse() const
  34792. {
  34793. Font f (font);
  34794. if (resizeFont)
  34795. f.setHeight (getHeight() * 0.7f);
  34796. return f;
  34797. }
  34798. void HyperlinkButton::changeWidthToFitText()
  34799. {
  34800. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34801. }
  34802. void HyperlinkButton::colourChanged()
  34803. {
  34804. repaint();
  34805. }
  34806. void HyperlinkButton::clicked()
  34807. {
  34808. if (url.isWellFormed())
  34809. url.launchInDefaultBrowser();
  34810. }
  34811. void HyperlinkButton::paintButton (Graphics& g,
  34812. bool isMouseOverButton,
  34813. bool isButtonDown)
  34814. {
  34815. const Colour textColour (findColour (textColourId));
  34816. if (isEnabled())
  34817. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34818. : textColour);
  34819. else
  34820. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34821. g.setFont (getFontToUse());
  34822. g.drawText (getButtonText(),
  34823. 2, 0, getWidth() - 2, getHeight(),
  34824. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34825. true);
  34826. }
  34827. END_JUCE_NAMESPACE
  34828. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34829. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34830. BEGIN_JUCE_NAMESPACE
  34831. ImageButton::ImageButton (const String& text_)
  34832. : Button (text_),
  34833. scaleImageToFit (true),
  34834. preserveProportions (true),
  34835. alphaThreshold (0),
  34836. imageX (0),
  34837. imageY (0),
  34838. imageW (0),
  34839. imageH (0),
  34840. normalImage (0),
  34841. overImage (0),
  34842. downImage (0)
  34843. {
  34844. }
  34845. ImageButton::~ImageButton()
  34846. {
  34847. }
  34848. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34849. const bool rescaleImagesWhenButtonSizeChanges,
  34850. const bool preserveImageProportions,
  34851. const Image& normalImage_,
  34852. const float imageOpacityWhenNormal,
  34853. const Colour& overlayColourWhenNormal,
  34854. const Image& overImage_,
  34855. const float imageOpacityWhenOver,
  34856. const Colour& overlayColourWhenOver,
  34857. const Image& downImage_,
  34858. const float imageOpacityWhenDown,
  34859. const Colour& overlayColourWhenDown,
  34860. const float hitTestAlphaThreshold)
  34861. {
  34862. normalImage = normalImage_;
  34863. overImage = overImage_;
  34864. downImage = downImage_;
  34865. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34866. {
  34867. imageW = normalImage.getWidth();
  34868. imageH = normalImage.getHeight();
  34869. setSize (imageW, imageH);
  34870. }
  34871. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34872. preserveProportions = preserveImageProportions;
  34873. normalOpacity = imageOpacityWhenNormal;
  34874. normalOverlay = overlayColourWhenNormal;
  34875. overOpacity = imageOpacityWhenOver;
  34876. overOverlay = overlayColourWhenOver;
  34877. downOpacity = imageOpacityWhenDown;
  34878. downOverlay = overlayColourWhenDown;
  34879. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34880. repaint();
  34881. }
  34882. const Image ImageButton::getCurrentImage() const
  34883. {
  34884. if (isDown() || getToggleState())
  34885. return getDownImage();
  34886. if (isOver())
  34887. return getOverImage();
  34888. return getNormalImage();
  34889. }
  34890. const Image ImageButton::getNormalImage() const
  34891. {
  34892. return normalImage;
  34893. }
  34894. const Image ImageButton::getOverImage() const
  34895. {
  34896. return overImage.isValid() ? overImage
  34897. : normalImage;
  34898. }
  34899. const Image ImageButton::getDownImage() const
  34900. {
  34901. return downImage.isValid() ? downImage
  34902. : getOverImage();
  34903. }
  34904. void ImageButton::paintButton (Graphics& g,
  34905. bool isMouseOverButton,
  34906. bool isButtonDown)
  34907. {
  34908. if (! isEnabled())
  34909. {
  34910. isMouseOverButton = false;
  34911. isButtonDown = false;
  34912. }
  34913. Image im (getCurrentImage());
  34914. if (im.isValid())
  34915. {
  34916. const int iw = im.getWidth();
  34917. const int ih = im.getHeight();
  34918. imageW = getWidth();
  34919. imageH = getHeight();
  34920. imageX = (imageW - iw) >> 1;
  34921. imageY = (imageH - ih) >> 1;
  34922. if (scaleImageToFit)
  34923. {
  34924. if (preserveProportions)
  34925. {
  34926. int newW, newH;
  34927. const float imRatio = ih / (float)iw;
  34928. const float destRatio = imageH / (float)imageW;
  34929. if (imRatio > destRatio)
  34930. {
  34931. newW = roundToInt (imageH / imRatio);
  34932. newH = imageH;
  34933. }
  34934. else
  34935. {
  34936. newW = imageW;
  34937. newH = roundToInt (imageW * imRatio);
  34938. }
  34939. imageX = (imageW - newW) / 2;
  34940. imageY = (imageH - newH) / 2;
  34941. imageW = newW;
  34942. imageH = newH;
  34943. }
  34944. else
  34945. {
  34946. imageX = 0;
  34947. imageY = 0;
  34948. }
  34949. }
  34950. if (! scaleImageToFit)
  34951. {
  34952. imageW = iw;
  34953. imageH = ih;
  34954. }
  34955. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34956. isButtonDown ? downOverlay
  34957. : (isMouseOverButton ? overOverlay
  34958. : normalOverlay),
  34959. isButtonDown ? downOpacity
  34960. : (isMouseOverButton ? overOpacity
  34961. : normalOpacity),
  34962. *this);
  34963. }
  34964. }
  34965. bool ImageButton::hitTest (int x, int y)
  34966. {
  34967. if (alphaThreshold == 0)
  34968. return true;
  34969. Image im (getCurrentImage());
  34970. return im.isNull() || (imageW > 0 && imageH > 0
  34971. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34972. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34973. }
  34974. END_JUCE_NAMESPACE
  34975. /*** End of inlined file: juce_ImageButton.cpp ***/
  34976. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34977. BEGIN_JUCE_NAMESPACE
  34978. ShapeButton::ShapeButton (const String& text_,
  34979. const Colour& normalColour_,
  34980. const Colour& overColour_,
  34981. const Colour& downColour_)
  34982. : Button (text_),
  34983. normalColour (normalColour_),
  34984. overColour (overColour_),
  34985. downColour (downColour_),
  34986. maintainShapeProportions (false),
  34987. outlineWidth (0.0f)
  34988. {
  34989. }
  34990. ShapeButton::~ShapeButton()
  34991. {
  34992. }
  34993. void ShapeButton::setColours (const Colour& newNormalColour,
  34994. const Colour& newOverColour,
  34995. const Colour& newDownColour)
  34996. {
  34997. normalColour = newNormalColour;
  34998. overColour = newOverColour;
  34999. downColour = newDownColour;
  35000. }
  35001. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35002. const float newOutlineWidth)
  35003. {
  35004. outlineColour = newOutlineColour;
  35005. outlineWidth = newOutlineWidth;
  35006. }
  35007. void ShapeButton::setShape (const Path& newShape,
  35008. const bool resizeNowToFitThisShape,
  35009. const bool maintainShapeProportions_,
  35010. const bool hasShadow)
  35011. {
  35012. shape = newShape;
  35013. maintainShapeProportions = maintainShapeProportions_;
  35014. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35015. setComponentEffect ((hasShadow) ? &shadow : 0);
  35016. if (resizeNowToFitThisShape)
  35017. {
  35018. Rectangle<float> bounds (shape.getBounds());
  35019. if (hasShadow)
  35020. bounds.expand (4.0f, 4.0f);
  35021. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35022. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35023. 1 + (int) (bounds.getHeight() + outlineWidth));
  35024. }
  35025. }
  35026. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35027. {
  35028. if (! isEnabled())
  35029. {
  35030. isMouseOverButton = false;
  35031. isButtonDown = false;
  35032. }
  35033. g.setColour ((isButtonDown) ? downColour
  35034. : (isMouseOverButton) ? overColour
  35035. : normalColour);
  35036. int w = getWidth();
  35037. int h = getHeight();
  35038. if (getComponentEffect() != 0)
  35039. {
  35040. w -= 4;
  35041. h -= 4;
  35042. }
  35043. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35044. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35045. w - offset - outlineWidth,
  35046. h - offset - outlineWidth,
  35047. maintainShapeProportions));
  35048. g.fillPath (shape, trans);
  35049. if (outlineWidth > 0.0f)
  35050. {
  35051. g.setColour (outlineColour);
  35052. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35053. }
  35054. }
  35055. END_JUCE_NAMESPACE
  35056. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35057. /*** Start of inlined file: juce_TextButton.cpp ***/
  35058. BEGIN_JUCE_NAMESPACE
  35059. TextButton::TextButton (const String& name,
  35060. const String& toolTip)
  35061. : Button (name)
  35062. {
  35063. setTooltip (toolTip);
  35064. }
  35065. TextButton::~TextButton()
  35066. {
  35067. }
  35068. void TextButton::paintButton (Graphics& g,
  35069. bool isMouseOverButton,
  35070. bool isButtonDown)
  35071. {
  35072. getLookAndFeel().drawButtonBackground (g, *this,
  35073. findColour (getToggleState() ? buttonOnColourId
  35074. : buttonColourId),
  35075. isMouseOverButton,
  35076. isButtonDown);
  35077. getLookAndFeel().drawButtonText (g, *this,
  35078. isMouseOverButton,
  35079. isButtonDown);
  35080. }
  35081. void TextButton::colourChanged()
  35082. {
  35083. repaint();
  35084. }
  35085. const Font TextButton::getFont()
  35086. {
  35087. return Font (jmin (15.0f, getHeight() * 0.6f));
  35088. }
  35089. void TextButton::changeWidthToFitText (const int newHeight)
  35090. {
  35091. if (newHeight >= 0)
  35092. setSize (jmax (1, getWidth()), newHeight);
  35093. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35094. getHeight());
  35095. }
  35096. END_JUCE_NAMESPACE
  35097. /*** End of inlined file: juce_TextButton.cpp ***/
  35098. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35099. BEGIN_JUCE_NAMESPACE
  35100. ToggleButton::ToggleButton (const String& buttonText)
  35101. : Button (buttonText)
  35102. {
  35103. setClickingTogglesState (true);
  35104. }
  35105. ToggleButton::~ToggleButton()
  35106. {
  35107. }
  35108. void ToggleButton::paintButton (Graphics& g,
  35109. bool isMouseOverButton,
  35110. bool isButtonDown)
  35111. {
  35112. getLookAndFeel().drawToggleButton (g, *this,
  35113. isMouseOverButton,
  35114. isButtonDown);
  35115. }
  35116. void ToggleButton::changeWidthToFitText()
  35117. {
  35118. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35119. }
  35120. void ToggleButton::colourChanged()
  35121. {
  35122. repaint();
  35123. }
  35124. END_JUCE_NAMESPACE
  35125. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35126. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35127. BEGIN_JUCE_NAMESPACE
  35128. ToolbarButton::ToolbarButton (const int itemId_,
  35129. const String& buttonText,
  35130. Drawable* const normalImage_,
  35131. Drawable* const toggledOnImage_)
  35132. : ToolbarItemComponent (itemId_, buttonText, true),
  35133. normalImage (normalImage_),
  35134. toggledOnImage (toggledOnImage_)
  35135. {
  35136. jassert (normalImage_ != 0);
  35137. }
  35138. ToolbarButton::~ToolbarButton()
  35139. {
  35140. }
  35141. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35142. bool /*isToolbarVertical*/,
  35143. int& preferredSize,
  35144. int& minSize, int& maxSize)
  35145. {
  35146. preferredSize = minSize = maxSize = toolbarDepth;
  35147. return true;
  35148. }
  35149. void ToolbarButton::paintButtonArea (Graphics& g,
  35150. int width, int height,
  35151. bool /*isMouseOver*/,
  35152. bool /*isMouseDown*/)
  35153. {
  35154. Drawable* d = normalImage;
  35155. if (getToggleState() && toggledOnImage != 0)
  35156. d = toggledOnImage;
  35157. if (! isEnabled())
  35158. {
  35159. Image im (Image::ARGB, width, height, true);
  35160. {
  35161. Graphics g2 (im);
  35162. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35163. }
  35164. im.desaturate();
  35165. g.drawImageAt (im, 0, 0);
  35166. }
  35167. else
  35168. {
  35169. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35170. }
  35171. }
  35172. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35173. {
  35174. }
  35175. END_JUCE_NAMESPACE
  35176. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35177. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35178. BEGIN_JUCE_NAMESPACE
  35179. class CodeDocumentLine
  35180. {
  35181. public:
  35182. CodeDocumentLine (const juce_wchar* const line_,
  35183. const int lineLength_,
  35184. const int numNewLineChars,
  35185. const int lineStartInFile_)
  35186. : line (line_, lineLength_),
  35187. lineStartInFile (lineStartInFile_),
  35188. lineLength (lineLength_),
  35189. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35190. {
  35191. }
  35192. ~CodeDocumentLine()
  35193. {
  35194. }
  35195. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35196. {
  35197. const juce_wchar* const t = text;
  35198. int pos = 0;
  35199. while (t [pos] != 0)
  35200. {
  35201. const int startOfLine = pos;
  35202. int numNewLineChars = 0;
  35203. while (t[pos] != 0)
  35204. {
  35205. if (t[pos] == '\r')
  35206. {
  35207. ++numNewLineChars;
  35208. ++pos;
  35209. if (t[pos] == '\n')
  35210. {
  35211. ++numNewLineChars;
  35212. ++pos;
  35213. }
  35214. break;
  35215. }
  35216. if (t[pos] == '\n')
  35217. {
  35218. ++numNewLineChars;
  35219. ++pos;
  35220. break;
  35221. }
  35222. ++pos;
  35223. }
  35224. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35225. numNewLineChars, startOfLine));
  35226. }
  35227. jassert (pos == text.length());
  35228. }
  35229. bool endsWithLineBreak() const throw()
  35230. {
  35231. return lineLengthWithoutNewLines != lineLength;
  35232. }
  35233. void updateLength() throw()
  35234. {
  35235. lineLengthWithoutNewLines = lineLength = line.length();
  35236. while (lineLengthWithoutNewLines > 0
  35237. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35238. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35239. {
  35240. --lineLengthWithoutNewLines;
  35241. }
  35242. }
  35243. String line;
  35244. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35245. };
  35246. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35247. : document (document_),
  35248. currentLine (document_->lines[0]),
  35249. line (0),
  35250. position (0)
  35251. {
  35252. }
  35253. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35254. : document (other.document),
  35255. currentLine (other.currentLine),
  35256. line (other.line),
  35257. position (other.position)
  35258. {
  35259. }
  35260. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35261. {
  35262. document = other.document;
  35263. currentLine = other.currentLine;
  35264. line = other.line;
  35265. position = other.position;
  35266. return *this;
  35267. }
  35268. CodeDocument::Iterator::~Iterator() throw()
  35269. {
  35270. }
  35271. juce_wchar CodeDocument::Iterator::nextChar()
  35272. {
  35273. if (currentLine == 0)
  35274. return 0;
  35275. jassert (currentLine == document->lines.getUnchecked (line));
  35276. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35277. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35278. {
  35279. ++line;
  35280. currentLine = document->lines [line];
  35281. }
  35282. return result;
  35283. }
  35284. void CodeDocument::Iterator::skip()
  35285. {
  35286. if (currentLine != 0)
  35287. {
  35288. jassert (currentLine == document->lines.getUnchecked (line));
  35289. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35290. {
  35291. ++line;
  35292. currentLine = document->lines [line];
  35293. }
  35294. }
  35295. }
  35296. void CodeDocument::Iterator::skipToEndOfLine()
  35297. {
  35298. if (currentLine != 0)
  35299. {
  35300. jassert (currentLine == document->lines.getUnchecked (line));
  35301. ++line;
  35302. currentLine = document->lines [line];
  35303. if (currentLine != 0)
  35304. position = currentLine->lineStartInFile;
  35305. else
  35306. position = document->getNumCharacters();
  35307. }
  35308. }
  35309. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35310. {
  35311. if (currentLine == 0)
  35312. return 0;
  35313. jassert (currentLine == document->lines.getUnchecked (line));
  35314. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35315. }
  35316. void CodeDocument::Iterator::skipWhitespace()
  35317. {
  35318. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35319. skip();
  35320. }
  35321. bool CodeDocument::Iterator::isEOF() const throw()
  35322. {
  35323. return currentLine == 0;
  35324. }
  35325. CodeDocument::Position::Position() throw()
  35326. : owner (0), characterPos (0), line (0),
  35327. indexInLine (0), positionMaintained (false)
  35328. {
  35329. }
  35330. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35331. const int line_, const int indexInLine_) throw()
  35332. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35333. characterPos (0), line (line_),
  35334. indexInLine (indexInLine_), positionMaintained (false)
  35335. {
  35336. setLineAndIndex (line_, indexInLine_);
  35337. }
  35338. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35339. const int characterPos_) throw()
  35340. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35341. positionMaintained (false)
  35342. {
  35343. setPosition (characterPos_);
  35344. }
  35345. CodeDocument::Position::Position (const Position& other) throw()
  35346. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35347. indexInLine (other.indexInLine), positionMaintained (false)
  35348. {
  35349. jassert (*this == other);
  35350. }
  35351. CodeDocument::Position::~Position() throw()
  35352. {
  35353. setPositionMaintained (false);
  35354. }
  35355. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35356. {
  35357. if (this != &other)
  35358. {
  35359. const bool wasPositionMaintained = positionMaintained;
  35360. if (owner != other.owner)
  35361. setPositionMaintained (false);
  35362. owner = other.owner;
  35363. line = other.line;
  35364. indexInLine = other.indexInLine;
  35365. characterPos = other.characterPos;
  35366. setPositionMaintained (wasPositionMaintained);
  35367. jassert (*this == other);
  35368. }
  35369. return *this;
  35370. }
  35371. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35372. {
  35373. jassert ((characterPos == other.characterPos)
  35374. == (line == other.line && indexInLine == other.indexInLine));
  35375. return characterPos == other.characterPos
  35376. && line == other.line
  35377. && indexInLine == other.indexInLine
  35378. && owner == other.owner;
  35379. }
  35380. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35381. {
  35382. return ! operator== (other);
  35383. }
  35384. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35385. {
  35386. jassert (owner != 0);
  35387. if (owner->lines.size() == 0)
  35388. {
  35389. line = 0;
  35390. indexInLine = 0;
  35391. characterPos = 0;
  35392. }
  35393. else
  35394. {
  35395. if (newLine >= owner->lines.size())
  35396. {
  35397. line = owner->lines.size() - 1;
  35398. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35399. jassert (l != 0);
  35400. indexInLine = l->lineLengthWithoutNewLines;
  35401. characterPos = l->lineStartInFile + indexInLine;
  35402. }
  35403. else
  35404. {
  35405. line = jmax (0, newLine);
  35406. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35407. jassert (l != 0);
  35408. if (l->lineLengthWithoutNewLines > 0)
  35409. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35410. else
  35411. indexInLine = 0;
  35412. characterPos = l->lineStartInFile + indexInLine;
  35413. }
  35414. }
  35415. }
  35416. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35417. {
  35418. jassert (owner != 0);
  35419. line = 0;
  35420. indexInLine = 0;
  35421. characterPos = 0;
  35422. if (newPosition > 0)
  35423. {
  35424. int lineStart = 0;
  35425. int lineEnd = owner->lines.size();
  35426. for (;;)
  35427. {
  35428. if (lineEnd - lineStart < 4)
  35429. {
  35430. for (int i = lineStart; i < lineEnd; ++i)
  35431. {
  35432. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35433. int index = newPosition - l->lineStartInFile;
  35434. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35435. {
  35436. line = i;
  35437. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35438. characterPos = l->lineStartInFile + indexInLine;
  35439. }
  35440. }
  35441. break;
  35442. }
  35443. else
  35444. {
  35445. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35446. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35447. if (newPosition >= mid->lineStartInFile)
  35448. lineStart = midIndex;
  35449. else
  35450. lineEnd = midIndex;
  35451. }
  35452. }
  35453. }
  35454. }
  35455. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35456. {
  35457. jassert (owner != 0);
  35458. if (characterDelta == 1)
  35459. {
  35460. setPosition (getPosition());
  35461. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35462. if (line < owner->lines.size())
  35463. {
  35464. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35465. if (indexInLine + characterDelta < l->lineLength
  35466. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35467. ++characterDelta;
  35468. }
  35469. }
  35470. setPosition (characterPos + characterDelta);
  35471. }
  35472. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35473. {
  35474. CodeDocument::Position p (*this);
  35475. p.moveBy (characterDelta);
  35476. return p;
  35477. }
  35478. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35479. {
  35480. CodeDocument::Position p (*this);
  35481. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35482. return p;
  35483. }
  35484. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35485. {
  35486. const CodeDocumentLine* const l = owner->lines [line];
  35487. return l == 0 ? 0 : l->line [getIndexInLine()];
  35488. }
  35489. const String CodeDocument::Position::getLineText() const throw()
  35490. {
  35491. const CodeDocumentLine* const l = owner->lines [line];
  35492. return l == 0 ? String::empty : l->line;
  35493. }
  35494. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35495. {
  35496. if (isMaintained != positionMaintained)
  35497. {
  35498. positionMaintained = isMaintained;
  35499. if (owner != 0)
  35500. {
  35501. if (isMaintained)
  35502. {
  35503. jassert (! owner->positionsToMaintain.contains (this));
  35504. owner->positionsToMaintain.add (this);
  35505. }
  35506. else
  35507. {
  35508. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35509. jassert (owner->positionsToMaintain.contains (this));
  35510. owner->positionsToMaintain.removeValue (this);
  35511. }
  35512. }
  35513. }
  35514. }
  35515. CodeDocument::CodeDocument()
  35516. : undoManager (std::numeric_limits<int>::max(), 10000),
  35517. currentActionIndex (0),
  35518. indexOfSavedState (-1),
  35519. maximumLineLength (-1),
  35520. newLineChars ("\r\n")
  35521. {
  35522. }
  35523. CodeDocument::~CodeDocument()
  35524. {
  35525. }
  35526. const String CodeDocument::getAllContent() const throw()
  35527. {
  35528. return getTextBetween (Position (this, 0),
  35529. Position (this, lines.size(), 0));
  35530. }
  35531. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35532. {
  35533. if (end.getPosition() <= start.getPosition())
  35534. return String::empty;
  35535. const int startLine = start.getLineNumber();
  35536. const int endLine = end.getLineNumber();
  35537. if (startLine == endLine)
  35538. {
  35539. CodeDocumentLine* const line = lines [startLine];
  35540. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35541. }
  35542. String result;
  35543. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35544. String::Concatenator concatenator (result);
  35545. const int maxLine = jmin (lines.size() - 1, endLine);
  35546. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35547. {
  35548. const CodeDocumentLine* line = lines.getUnchecked(i);
  35549. int len = line->lineLength;
  35550. if (i == startLine)
  35551. {
  35552. const int index = start.getIndexInLine();
  35553. concatenator.append (line->line.substring (index, len));
  35554. }
  35555. else if (i == endLine)
  35556. {
  35557. len = end.getIndexInLine();
  35558. concatenator.append (line->line.substring (0, len));
  35559. }
  35560. else
  35561. {
  35562. concatenator.append (line->line);
  35563. }
  35564. }
  35565. return result;
  35566. }
  35567. int CodeDocument::getNumCharacters() const throw()
  35568. {
  35569. const CodeDocumentLine* const lastLine = lines.getLast();
  35570. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35571. }
  35572. const String CodeDocument::getLine (const int lineIndex) const throw()
  35573. {
  35574. const CodeDocumentLine* const line = lines [lineIndex];
  35575. return (line == 0) ? String::empty : line->line;
  35576. }
  35577. int CodeDocument::getMaximumLineLength() throw()
  35578. {
  35579. if (maximumLineLength < 0)
  35580. {
  35581. maximumLineLength = 0;
  35582. for (int i = lines.size(); --i >= 0;)
  35583. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35584. }
  35585. return maximumLineLength;
  35586. }
  35587. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35588. {
  35589. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35590. }
  35591. void CodeDocument::insertText (const Position& position, const String& text)
  35592. {
  35593. insert (text, position.getPosition(), true);
  35594. }
  35595. void CodeDocument::replaceAllContent (const String& newContent)
  35596. {
  35597. remove (0, getNumCharacters(), true);
  35598. insert (newContent, 0, true);
  35599. }
  35600. bool CodeDocument::loadFromStream (InputStream& stream)
  35601. {
  35602. replaceAllContent (stream.readEntireStreamAsString());
  35603. setSavePoint();
  35604. clearUndoHistory();
  35605. return true;
  35606. }
  35607. bool CodeDocument::writeToStream (OutputStream& stream)
  35608. {
  35609. for (int i = 0; i < lines.size(); ++i)
  35610. {
  35611. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35612. const char* utf8 = temp.toUTF8();
  35613. if (! stream.write (utf8, (int) strlen (utf8)))
  35614. return false;
  35615. }
  35616. return true;
  35617. }
  35618. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35619. {
  35620. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35621. newLineChars = newLine;
  35622. }
  35623. void CodeDocument::newTransaction()
  35624. {
  35625. undoManager.beginNewTransaction (String::empty);
  35626. }
  35627. void CodeDocument::undo()
  35628. {
  35629. newTransaction();
  35630. undoManager.undo();
  35631. }
  35632. void CodeDocument::redo()
  35633. {
  35634. undoManager.redo();
  35635. }
  35636. void CodeDocument::clearUndoHistory()
  35637. {
  35638. undoManager.clearUndoHistory();
  35639. }
  35640. void CodeDocument::setSavePoint() throw()
  35641. {
  35642. indexOfSavedState = currentActionIndex;
  35643. }
  35644. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35645. {
  35646. return currentActionIndex != indexOfSavedState;
  35647. }
  35648. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35649. {
  35650. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35651. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35652. }
  35653. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35654. {
  35655. Position p (position);
  35656. const int maxDistance = 256;
  35657. int i = 0;
  35658. while (i < maxDistance
  35659. && CharacterFunctions::isWhitespace (p.getCharacter())
  35660. && (i == 0 || (p.getCharacter() != '\n'
  35661. && p.getCharacter() != '\r')))
  35662. {
  35663. ++i;
  35664. p.moveBy (1);
  35665. }
  35666. if (i == 0)
  35667. {
  35668. const int type = getCodeCharacterCategory (p.getCharacter());
  35669. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35670. {
  35671. ++i;
  35672. p.moveBy (1);
  35673. }
  35674. while (i < maxDistance
  35675. && CharacterFunctions::isWhitespace (p.getCharacter())
  35676. && (i == 0 || (p.getCharacter() != '\n'
  35677. && p.getCharacter() != '\r')))
  35678. {
  35679. ++i;
  35680. p.moveBy (1);
  35681. }
  35682. }
  35683. return p;
  35684. }
  35685. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35686. {
  35687. Position p (position);
  35688. const int maxDistance = 256;
  35689. int i = 0;
  35690. bool stoppedAtLineStart = false;
  35691. while (i < maxDistance)
  35692. {
  35693. const juce_wchar c = p.movedBy (-1).getCharacter();
  35694. if (c == '\r' || c == '\n')
  35695. {
  35696. stoppedAtLineStart = true;
  35697. if (i > 0)
  35698. break;
  35699. }
  35700. if (! CharacterFunctions::isWhitespace (c))
  35701. break;
  35702. p.moveBy (-1);
  35703. ++i;
  35704. }
  35705. if (i < maxDistance && ! stoppedAtLineStart)
  35706. {
  35707. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35708. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35709. {
  35710. p.moveBy (-1);
  35711. ++i;
  35712. }
  35713. }
  35714. return p;
  35715. }
  35716. void CodeDocument::checkLastLineStatus()
  35717. {
  35718. while (lines.size() > 0
  35719. && lines.getLast()->lineLength == 0
  35720. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35721. {
  35722. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35723. lines.removeLast();
  35724. }
  35725. const CodeDocumentLine* const lastLine = lines.getLast();
  35726. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35727. {
  35728. // check that there's an empty line at the end if the preceding one ends in a newline..
  35729. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35730. }
  35731. }
  35732. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35733. {
  35734. listeners.add (listener);
  35735. }
  35736. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35737. {
  35738. listeners.remove (listener);
  35739. }
  35740. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35741. {
  35742. Position startPos (this, startLine, 0);
  35743. Position endPos (this, endLine, 0);
  35744. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  35745. }
  35746. class CodeDocumentInsertAction : public UndoableAction
  35747. {
  35748. CodeDocument& owner;
  35749. const String text;
  35750. int insertPos;
  35751. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35752. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35753. public:
  35754. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35755. : owner (owner_),
  35756. text (text_),
  35757. insertPos (insertPos_)
  35758. {
  35759. }
  35760. ~CodeDocumentInsertAction() {}
  35761. bool perform()
  35762. {
  35763. owner.currentActionIndex++;
  35764. owner.insert (text, insertPos, false);
  35765. return true;
  35766. }
  35767. bool undo()
  35768. {
  35769. owner.currentActionIndex--;
  35770. owner.remove (insertPos, insertPos + text.length(), false);
  35771. return true;
  35772. }
  35773. int getSizeInUnits() { return text.length() + 32; }
  35774. };
  35775. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35776. {
  35777. if (text.isEmpty())
  35778. return;
  35779. if (undoable)
  35780. {
  35781. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35782. }
  35783. else
  35784. {
  35785. Position pos (this, insertPos);
  35786. const int firstAffectedLine = pos.getLineNumber();
  35787. int lastAffectedLine = firstAffectedLine + 1;
  35788. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35789. String textInsideOriginalLine (text);
  35790. if (firstLine != 0)
  35791. {
  35792. const int index = pos.getIndexInLine();
  35793. textInsideOriginalLine = firstLine->line.substring (0, index)
  35794. + textInsideOriginalLine
  35795. + firstLine->line.substring (index);
  35796. }
  35797. maximumLineLength = -1;
  35798. Array <CodeDocumentLine*> newLines;
  35799. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35800. jassert (newLines.size() > 0);
  35801. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35802. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35803. lines.set (firstAffectedLine, newFirstLine);
  35804. if (newLines.size() > 1)
  35805. {
  35806. for (int i = 1; i < newLines.size(); ++i)
  35807. {
  35808. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35809. lines.insert (firstAffectedLine + i, l);
  35810. }
  35811. lastAffectedLine = lines.size();
  35812. }
  35813. int i, lineStart = newFirstLine->lineStartInFile;
  35814. for (i = firstAffectedLine; i < lines.size(); ++i)
  35815. {
  35816. CodeDocumentLine* const l = lines.getUnchecked (i);
  35817. l->lineStartInFile = lineStart;
  35818. lineStart += l->lineLength;
  35819. }
  35820. checkLastLineStatus();
  35821. const int newTextLength = text.length();
  35822. for (i = 0; i < positionsToMaintain.size(); ++i)
  35823. {
  35824. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35825. if (p->getPosition() >= insertPos)
  35826. p->setPosition (p->getPosition() + newTextLength);
  35827. }
  35828. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35829. }
  35830. }
  35831. class CodeDocumentDeleteAction : public UndoableAction
  35832. {
  35833. CodeDocument& owner;
  35834. int startPos, endPos;
  35835. String removedText;
  35836. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35837. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35838. public:
  35839. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35840. : owner (owner_),
  35841. startPos (startPos_),
  35842. endPos (endPos_)
  35843. {
  35844. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35845. CodeDocument::Position (&owner, endPos));
  35846. }
  35847. ~CodeDocumentDeleteAction() {}
  35848. bool perform()
  35849. {
  35850. owner.currentActionIndex++;
  35851. owner.remove (startPos, endPos, false);
  35852. return true;
  35853. }
  35854. bool undo()
  35855. {
  35856. owner.currentActionIndex--;
  35857. owner.insert (removedText, startPos, false);
  35858. return true;
  35859. }
  35860. int getSizeInUnits() { return removedText.length() + 32; }
  35861. };
  35862. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35863. {
  35864. if (endPos <= startPos)
  35865. return;
  35866. if (undoable)
  35867. {
  35868. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35869. }
  35870. else
  35871. {
  35872. Position startPosition (this, startPos);
  35873. Position endPosition (this, endPos);
  35874. maximumLineLength = -1;
  35875. const int firstAffectedLine = startPosition.getLineNumber();
  35876. const int endLine = endPosition.getLineNumber();
  35877. int lastAffectedLine = firstAffectedLine + 1;
  35878. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35879. if (firstAffectedLine == endLine)
  35880. {
  35881. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35882. + firstLine->line.substring (endPosition.getIndexInLine());
  35883. firstLine->updateLength();
  35884. }
  35885. else
  35886. {
  35887. lastAffectedLine = lines.size();
  35888. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35889. jassert (lastLine != 0);
  35890. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35891. + lastLine->line.substring (endPosition.getIndexInLine());
  35892. firstLine->updateLength();
  35893. int numLinesToRemove = endLine - firstAffectedLine;
  35894. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35895. }
  35896. int i;
  35897. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35898. {
  35899. CodeDocumentLine* const l = lines.getUnchecked (i);
  35900. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35901. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35902. }
  35903. checkLastLineStatus();
  35904. const int totalChars = getNumCharacters();
  35905. for (i = 0; i < positionsToMaintain.size(); ++i)
  35906. {
  35907. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35908. if (p->getPosition() > startPosition.getPosition())
  35909. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35910. if (p->getPosition() > totalChars)
  35911. p->setPosition (totalChars);
  35912. }
  35913. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35914. }
  35915. }
  35916. END_JUCE_NAMESPACE
  35917. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35918. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35919. BEGIN_JUCE_NAMESPACE
  35920. class CodeEditorComponent::CaretComponent : public Component,
  35921. public Timer
  35922. {
  35923. public:
  35924. CaretComponent (CodeEditorComponent& owner_)
  35925. : owner (owner_)
  35926. {
  35927. setAlwaysOnTop (true);
  35928. setInterceptsMouseClicks (false, false);
  35929. }
  35930. ~CaretComponent()
  35931. {
  35932. }
  35933. void paint (Graphics& g)
  35934. {
  35935. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35936. }
  35937. void timerCallback()
  35938. {
  35939. setVisible (shouldBeShown() && ! isVisible());
  35940. }
  35941. void updatePosition()
  35942. {
  35943. startTimer (400);
  35944. setVisible (shouldBeShown());
  35945. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35946. }
  35947. private:
  35948. CodeEditorComponent& owner;
  35949. CaretComponent (const CaretComponent&);
  35950. CaretComponent& operator= (const CaretComponent&);
  35951. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35952. };
  35953. class CodeEditorComponent::CodeEditorLine
  35954. {
  35955. public:
  35956. CodeEditorLine() throw()
  35957. : highlightColumnStart (0), highlightColumnEnd (0)
  35958. {
  35959. }
  35960. ~CodeEditorLine() throw()
  35961. {
  35962. }
  35963. bool update (CodeDocument& document, int lineNum,
  35964. CodeDocument::Iterator& source,
  35965. CodeTokeniser* analyser, const int spacesPerTab,
  35966. const CodeDocument::Position& selectionStart,
  35967. const CodeDocument::Position& selectionEnd)
  35968. {
  35969. Array <SyntaxToken> newTokens;
  35970. newTokens.ensureStorageAllocated (8);
  35971. if (analyser == 0)
  35972. {
  35973. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35974. }
  35975. else if (lineNum < document.getNumLines())
  35976. {
  35977. const CodeDocument::Position pos (&document, lineNum, 0);
  35978. createTokens (pos.getPosition(), pos.getLineText(),
  35979. source, analyser, newTokens);
  35980. }
  35981. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35982. int newHighlightStart = 0;
  35983. int newHighlightEnd = 0;
  35984. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35985. {
  35986. const String line (document.getLine (lineNum));
  35987. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35988. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35989. line, spacesPerTab);
  35990. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35991. line, spacesPerTab);
  35992. }
  35993. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35994. {
  35995. highlightColumnStart = newHighlightStart;
  35996. highlightColumnEnd = newHighlightEnd;
  35997. }
  35998. else
  35999. {
  36000. if (tokens.size() == newTokens.size())
  36001. {
  36002. bool allTheSame = true;
  36003. for (int i = newTokens.size(); --i >= 0;)
  36004. {
  36005. if (tokens.getReference(i) != newTokens.getReference(i))
  36006. {
  36007. allTheSame = false;
  36008. break;
  36009. }
  36010. }
  36011. if (allTheSame)
  36012. return false;
  36013. }
  36014. }
  36015. tokens.swapWithArray (newTokens);
  36016. return true;
  36017. }
  36018. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36019. float x, const int y, const int baselineOffset, const int lineHeight,
  36020. const Colour& highlightColour) const throw()
  36021. {
  36022. if (highlightColumnStart < highlightColumnEnd)
  36023. {
  36024. g.setColour (highlightColour);
  36025. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36026. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36027. }
  36028. int lastType = std::numeric_limits<int>::min();
  36029. for (int i = 0; i < tokens.size(); ++i)
  36030. {
  36031. SyntaxToken& token = tokens.getReference(i);
  36032. if (lastType != token.tokenType)
  36033. {
  36034. lastType = token.tokenType;
  36035. g.setColour (owner.getColourForTokenType (lastType));
  36036. }
  36037. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36038. if (i < tokens.size() - 1)
  36039. {
  36040. if (token.width < 0)
  36041. token.width = font.getStringWidthFloat (token.text);
  36042. x += token.width;
  36043. }
  36044. }
  36045. }
  36046. private:
  36047. struct SyntaxToken
  36048. {
  36049. String text;
  36050. int tokenType;
  36051. float width;
  36052. SyntaxToken (const String& text_, const int type) throw()
  36053. : text (text_), tokenType (type), width (-1.0f)
  36054. {
  36055. }
  36056. bool operator!= (const SyntaxToken& other) const throw()
  36057. {
  36058. return text != other.text || tokenType != other.tokenType;
  36059. }
  36060. };
  36061. Array <SyntaxToken> tokens;
  36062. int highlightColumnStart, highlightColumnEnd;
  36063. static void createTokens (int startPosition, const String& lineText,
  36064. CodeDocument::Iterator& source,
  36065. CodeTokeniser* analyser,
  36066. Array <SyntaxToken>& newTokens)
  36067. {
  36068. CodeDocument::Iterator lastIterator (source);
  36069. const int lineLength = lineText.length();
  36070. for (;;)
  36071. {
  36072. int tokenType = analyser->readNextToken (source);
  36073. int tokenStart = lastIterator.getPosition();
  36074. int tokenEnd = source.getPosition();
  36075. if (tokenEnd <= tokenStart)
  36076. break;
  36077. tokenEnd -= startPosition;
  36078. if (tokenEnd > 0)
  36079. {
  36080. tokenStart -= startPosition;
  36081. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36082. tokenType));
  36083. if (tokenEnd >= lineLength)
  36084. break;
  36085. }
  36086. lastIterator = source;
  36087. }
  36088. source = lastIterator;
  36089. }
  36090. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  36091. {
  36092. int x = 0;
  36093. for (int i = 0; i < tokens.size(); ++i)
  36094. {
  36095. SyntaxToken& t = tokens.getReference(i);
  36096. for (;;)
  36097. {
  36098. int tabPos = t.text.indexOfChar ('\t');
  36099. if (tabPos < 0)
  36100. break;
  36101. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36102. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36103. }
  36104. x += t.text.length();
  36105. }
  36106. }
  36107. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36108. {
  36109. jassert (index <= line.length());
  36110. int col = 0;
  36111. for (int i = 0; i < index; ++i)
  36112. {
  36113. if (line[i] != '\t')
  36114. ++col;
  36115. else
  36116. col += spacesPerTab - (col % spacesPerTab);
  36117. }
  36118. return col;
  36119. }
  36120. };
  36121. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36122. CodeTokeniser* const codeTokeniser_)
  36123. : document (document_),
  36124. firstLineOnScreen (0),
  36125. gutter (5),
  36126. spacesPerTab (4),
  36127. lineHeight (0),
  36128. linesOnScreen (0),
  36129. columnsOnScreen (0),
  36130. scrollbarThickness (16),
  36131. columnToTryToMaintain (-1),
  36132. useSpacesForTabs (false),
  36133. xOffset (0),
  36134. codeTokeniser (codeTokeniser_)
  36135. {
  36136. caretPos = CodeDocument::Position (&document_, 0, 0);
  36137. caretPos.setPositionMaintained (true);
  36138. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36139. selectionStart.setPositionMaintained (true);
  36140. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36141. selectionEnd.setPositionMaintained (true);
  36142. setOpaque (true);
  36143. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36144. setWantsKeyboardFocus (true);
  36145. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36146. verticalScrollBar->setSingleStepSize (1.0);
  36147. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36148. horizontalScrollBar->setSingleStepSize (1.0);
  36149. addAndMakeVisible (caret = new CaretComponent (*this));
  36150. Font f (12.0f);
  36151. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36152. setFont (f);
  36153. resetToDefaultColours();
  36154. verticalScrollBar->addListener (this);
  36155. horizontalScrollBar->addListener (this);
  36156. document.addListener (this);
  36157. }
  36158. CodeEditorComponent::~CodeEditorComponent()
  36159. {
  36160. document.removeListener (this);
  36161. deleteAllChildren();
  36162. }
  36163. void CodeEditorComponent::loadContent (const String& newContent)
  36164. {
  36165. clearCachedIterators (0);
  36166. document.replaceAllContent (newContent);
  36167. document.clearUndoHistory();
  36168. document.setSavePoint();
  36169. caretPos.setPosition (0);
  36170. selectionStart.setPosition (0);
  36171. selectionEnd.setPosition (0);
  36172. scrollToLine (0);
  36173. }
  36174. bool CodeEditorComponent::isTextInputActive() const
  36175. {
  36176. return true;
  36177. }
  36178. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36179. const CodeDocument::Position& affectedTextEnd)
  36180. {
  36181. clearCachedIterators (affectedTextStart.getLineNumber());
  36182. triggerAsyncUpdate();
  36183. caret->updatePosition();
  36184. columnToTryToMaintain = -1;
  36185. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36186. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36187. deselectAll();
  36188. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36189. || caretPos.getPosition() < affectedTextStart.getPosition())
  36190. moveCaretTo (affectedTextStart, false);
  36191. updateScrollBars();
  36192. }
  36193. void CodeEditorComponent::resized()
  36194. {
  36195. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36196. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36197. lines.clear();
  36198. rebuildLineTokens();
  36199. caret->updatePosition();
  36200. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36201. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36202. updateScrollBars();
  36203. }
  36204. void CodeEditorComponent::paint (Graphics& g)
  36205. {
  36206. handleUpdateNowIfNeeded();
  36207. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36208. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36209. g.setFont (font);
  36210. const int baselineOffset = (int) font.getAscent();
  36211. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36212. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36213. const Rectangle<int> clip (g.getClipBounds());
  36214. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36215. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36216. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36217. {
  36218. lines.getUnchecked(j)->draw (*this, g, font,
  36219. (float) (gutter - xOffset * charWidth),
  36220. lineHeight * j, baselineOffset, lineHeight,
  36221. highlightColour);
  36222. }
  36223. }
  36224. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36225. {
  36226. if (scrollbarThickness != thickness)
  36227. {
  36228. scrollbarThickness = thickness;
  36229. resized();
  36230. }
  36231. }
  36232. void CodeEditorComponent::handleAsyncUpdate()
  36233. {
  36234. rebuildLineTokens();
  36235. }
  36236. void CodeEditorComponent::rebuildLineTokens()
  36237. {
  36238. cancelPendingUpdate();
  36239. const int numNeeded = linesOnScreen + 1;
  36240. int minLineToRepaint = numNeeded;
  36241. int maxLineToRepaint = 0;
  36242. if (numNeeded != lines.size())
  36243. {
  36244. lines.clear();
  36245. for (int i = numNeeded; --i >= 0;)
  36246. lines.add (new CodeEditorLine());
  36247. minLineToRepaint = 0;
  36248. maxLineToRepaint = numNeeded;
  36249. }
  36250. jassert (numNeeded == lines.size());
  36251. CodeDocument::Iterator source (&document);
  36252. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36253. for (int i = 0; i < numNeeded; ++i)
  36254. {
  36255. CodeEditorLine* const line = lines.getUnchecked(i);
  36256. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36257. selectionStart, selectionEnd))
  36258. {
  36259. minLineToRepaint = jmin (minLineToRepaint, i);
  36260. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36261. }
  36262. }
  36263. if (minLineToRepaint <= maxLineToRepaint)
  36264. {
  36265. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36266. verticalScrollBar->getX() - gutter,
  36267. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36268. }
  36269. }
  36270. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36271. {
  36272. caretPos = newPos;
  36273. columnToTryToMaintain = -1;
  36274. if (highlighting)
  36275. {
  36276. if (dragType == notDragging)
  36277. {
  36278. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36279. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36280. dragType = draggingSelectionStart;
  36281. else
  36282. dragType = draggingSelectionEnd;
  36283. }
  36284. if (dragType == draggingSelectionStart)
  36285. {
  36286. selectionStart = caretPos;
  36287. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36288. {
  36289. const CodeDocument::Position temp (selectionStart);
  36290. selectionStart = selectionEnd;
  36291. selectionEnd = temp;
  36292. dragType = draggingSelectionEnd;
  36293. }
  36294. }
  36295. else
  36296. {
  36297. selectionEnd = caretPos;
  36298. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36299. {
  36300. const CodeDocument::Position temp (selectionStart);
  36301. selectionStart = selectionEnd;
  36302. selectionEnd = temp;
  36303. dragType = draggingSelectionStart;
  36304. }
  36305. }
  36306. triggerAsyncUpdate();
  36307. }
  36308. else
  36309. {
  36310. deselectAll();
  36311. }
  36312. caret->updatePosition();
  36313. scrollToKeepCaretOnScreen();
  36314. updateScrollBars();
  36315. }
  36316. void CodeEditorComponent::deselectAll()
  36317. {
  36318. if (selectionStart != selectionEnd)
  36319. triggerAsyncUpdate();
  36320. selectionStart = caretPos;
  36321. selectionEnd = caretPos;
  36322. }
  36323. void CodeEditorComponent::updateScrollBars()
  36324. {
  36325. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36326. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36327. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36328. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36329. }
  36330. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36331. {
  36332. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36333. newFirstLineOnScreen);
  36334. if (newFirstLineOnScreen != firstLineOnScreen)
  36335. {
  36336. firstLineOnScreen = newFirstLineOnScreen;
  36337. caret->updatePosition();
  36338. updateCachedIterators (firstLineOnScreen);
  36339. triggerAsyncUpdate();
  36340. }
  36341. }
  36342. void CodeEditorComponent::scrollToColumnInternal (double column)
  36343. {
  36344. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36345. if (xOffset != newOffset)
  36346. {
  36347. xOffset = newOffset;
  36348. caret->updatePosition();
  36349. repaint();
  36350. }
  36351. }
  36352. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36353. {
  36354. scrollToLineInternal (newFirstLineOnScreen);
  36355. updateScrollBars();
  36356. }
  36357. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36358. {
  36359. scrollToColumnInternal (newFirstColumnOnScreen);
  36360. updateScrollBars();
  36361. }
  36362. void CodeEditorComponent::scrollBy (int deltaLines)
  36363. {
  36364. scrollToLine (firstLineOnScreen + deltaLines);
  36365. }
  36366. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36367. {
  36368. if (caretPos.getLineNumber() < firstLineOnScreen)
  36369. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36370. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36371. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36372. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36373. if (column >= xOffset + columnsOnScreen - 1)
  36374. scrollToColumn (column + 1 - columnsOnScreen);
  36375. else if (column < xOffset)
  36376. scrollToColumn (column);
  36377. }
  36378. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36379. {
  36380. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36381. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36382. roundToInt (charWidth),
  36383. lineHeight);
  36384. }
  36385. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36386. {
  36387. const int line = y / lineHeight + firstLineOnScreen;
  36388. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36389. const int index = columnToIndex (line, column);
  36390. return CodeDocument::Position (&document, line, index);
  36391. }
  36392. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36393. {
  36394. document.deleteSection (selectionStart, selectionEnd);
  36395. if (newText.isNotEmpty())
  36396. document.insertText (caretPos, newText);
  36397. scrollToKeepCaretOnScreen();
  36398. }
  36399. void CodeEditorComponent::insertTabAtCaret()
  36400. {
  36401. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36402. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36403. {
  36404. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36405. }
  36406. if (useSpacesForTabs)
  36407. {
  36408. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36409. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36410. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36411. }
  36412. else
  36413. {
  36414. insertTextAtCaret ("\t");
  36415. }
  36416. }
  36417. void CodeEditorComponent::cut()
  36418. {
  36419. insertTextAtCaret (String::empty);
  36420. }
  36421. void CodeEditorComponent::copy()
  36422. {
  36423. newTransaction();
  36424. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36425. if (selection.isNotEmpty())
  36426. SystemClipboard::copyTextToClipboard (selection);
  36427. }
  36428. void CodeEditorComponent::copyThenCut()
  36429. {
  36430. copy();
  36431. cut();
  36432. newTransaction();
  36433. }
  36434. void CodeEditorComponent::paste()
  36435. {
  36436. newTransaction();
  36437. const String clip (SystemClipboard::getTextFromClipboard());
  36438. if (clip.isNotEmpty())
  36439. insertTextAtCaret (clip);
  36440. newTransaction();
  36441. }
  36442. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36443. {
  36444. newTransaction();
  36445. if (moveInWholeWordSteps)
  36446. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36447. else
  36448. moveCaretTo (caretPos.movedBy (-1), selecting);
  36449. }
  36450. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36451. {
  36452. newTransaction();
  36453. if (moveInWholeWordSteps)
  36454. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36455. else
  36456. moveCaretTo (caretPos.movedBy (1), selecting);
  36457. }
  36458. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36459. {
  36460. CodeDocument::Position pos (caretPos);
  36461. const int newLineNum = pos.getLineNumber() + delta;
  36462. if (columnToTryToMaintain < 0)
  36463. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36464. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36465. const int colToMaintain = columnToTryToMaintain;
  36466. moveCaretTo (pos, selecting);
  36467. columnToTryToMaintain = colToMaintain;
  36468. }
  36469. void CodeEditorComponent::cursorDown (const bool selecting)
  36470. {
  36471. newTransaction();
  36472. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36473. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36474. else
  36475. moveLineDelta (1, selecting);
  36476. }
  36477. void CodeEditorComponent::cursorUp (const bool selecting)
  36478. {
  36479. newTransaction();
  36480. if (caretPos.getLineNumber() == 0)
  36481. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36482. else
  36483. moveLineDelta (-1, selecting);
  36484. }
  36485. void CodeEditorComponent::pageDown (const bool selecting)
  36486. {
  36487. newTransaction();
  36488. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36489. moveLineDelta (linesOnScreen, selecting);
  36490. }
  36491. void CodeEditorComponent::pageUp (const bool selecting)
  36492. {
  36493. newTransaction();
  36494. scrollBy (-linesOnScreen);
  36495. moveLineDelta (-linesOnScreen, selecting);
  36496. }
  36497. void CodeEditorComponent::scrollUp()
  36498. {
  36499. newTransaction();
  36500. scrollBy (1);
  36501. if (caretPos.getLineNumber() < firstLineOnScreen)
  36502. moveLineDelta (1, false);
  36503. }
  36504. void CodeEditorComponent::scrollDown()
  36505. {
  36506. newTransaction();
  36507. scrollBy (-1);
  36508. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36509. moveLineDelta (-1, false);
  36510. }
  36511. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36512. {
  36513. newTransaction();
  36514. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36515. }
  36516. static int findFirstNonWhitespaceChar (const String& line) throw()
  36517. {
  36518. const int len = line.length();
  36519. for (int i = 0; i < len; ++i)
  36520. if (! CharacterFunctions::isWhitespace (line [i]))
  36521. return i;
  36522. return 0;
  36523. }
  36524. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36525. {
  36526. newTransaction();
  36527. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36528. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36529. index = 0;
  36530. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36531. }
  36532. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36533. {
  36534. newTransaction();
  36535. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36536. }
  36537. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36538. {
  36539. newTransaction();
  36540. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36541. }
  36542. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36543. {
  36544. if (moveInWholeWordSteps)
  36545. {
  36546. cut(); // in case something is already highlighted
  36547. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36548. }
  36549. else
  36550. {
  36551. if (selectionStart == selectionEnd)
  36552. selectionStart.moveBy (-1);
  36553. }
  36554. cut();
  36555. }
  36556. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36557. {
  36558. if (moveInWholeWordSteps)
  36559. {
  36560. cut(); // in case something is already highlighted
  36561. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36562. }
  36563. else
  36564. {
  36565. if (selectionStart == selectionEnd)
  36566. selectionEnd.moveBy (1);
  36567. else
  36568. newTransaction();
  36569. }
  36570. cut();
  36571. }
  36572. void CodeEditorComponent::selectAll()
  36573. {
  36574. newTransaction();
  36575. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36576. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36577. }
  36578. void CodeEditorComponent::undo()
  36579. {
  36580. document.undo();
  36581. scrollToKeepCaretOnScreen();
  36582. }
  36583. void CodeEditorComponent::redo()
  36584. {
  36585. document.redo();
  36586. scrollToKeepCaretOnScreen();
  36587. }
  36588. void CodeEditorComponent::newTransaction()
  36589. {
  36590. document.newTransaction();
  36591. startTimer (600);
  36592. }
  36593. void CodeEditorComponent::timerCallback()
  36594. {
  36595. newTransaction();
  36596. }
  36597. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36598. {
  36599. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36600. }
  36601. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36602. {
  36603. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36604. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36605. }
  36606. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36607. {
  36608. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36609. CodeDocument::Position (&document, range.getEnd()));
  36610. }
  36611. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36612. {
  36613. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36614. const bool shiftDown = key.getModifiers().isShiftDown();
  36615. if (key.isKeyCode (KeyPress::leftKey))
  36616. {
  36617. cursorLeft (moveInWholeWordSteps, shiftDown);
  36618. }
  36619. else if (key.isKeyCode (KeyPress::rightKey))
  36620. {
  36621. cursorRight (moveInWholeWordSteps, shiftDown);
  36622. }
  36623. else if (key.isKeyCode (KeyPress::upKey))
  36624. {
  36625. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36626. scrollDown();
  36627. #if JUCE_MAC
  36628. else if (key.getModifiers().isCommandDown())
  36629. goToStartOfDocument (shiftDown);
  36630. #endif
  36631. else
  36632. cursorUp (shiftDown);
  36633. }
  36634. else if (key.isKeyCode (KeyPress::downKey))
  36635. {
  36636. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36637. scrollUp();
  36638. #if JUCE_MAC
  36639. else if (key.getModifiers().isCommandDown())
  36640. goToEndOfDocument (shiftDown);
  36641. #endif
  36642. else
  36643. cursorDown (shiftDown);
  36644. }
  36645. else if (key.isKeyCode (KeyPress::pageDownKey))
  36646. {
  36647. pageDown (shiftDown);
  36648. }
  36649. else if (key.isKeyCode (KeyPress::pageUpKey))
  36650. {
  36651. pageUp (shiftDown);
  36652. }
  36653. else if (key.isKeyCode (KeyPress::homeKey))
  36654. {
  36655. if (moveInWholeWordSteps)
  36656. goToStartOfDocument (shiftDown);
  36657. else
  36658. goToStartOfLine (shiftDown);
  36659. }
  36660. else if (key.isKeyCode (KeyPress::endKey))
  36661. {
  36662. if (moveInWholeWordSteps)
  36663. goToEndOfDocument (shiftDown);
  36664. else
  36665. goToEndOfLine (shiftDown);
  36666. }
  36667. else if (key.isKeyCode (KeyPress::backspaceKey))
  36668. {
  36669. backspace (moveInWholeWordSteps);
  36670. }
  36671. else if (key.isKeyCode (KeyPress::deleteKey))
  36672. {
  36673. deleteForward (moveInWholeWordSteps);
  36674. }
  36675. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36676. {
  36677. copy();
  36678. }
  36679. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36680. {
  36681. copyThenCut();
  36682. }
  36683. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36684. {
  36685. paste();
  36686. }
  36687. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36688. {
  36689. undo();
  36690. }
  36691. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36692. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36693. {
  36694. redo();
  36695. }
  36696. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36697. {
  36698. selectAll();
  36699. }
  36700. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36701. {
  36702. insertTabAtCaret();
  36703. }
  36704. else if (key == KeyPress::returnKey)
  36705. {
  36706. newTransaction();
  36707. insertTextAtCaret (document.getNewLineCharacters());
  36708. }
  36709. else if (key.isKeyCode (KeyPress::escapeKey))
  36710. {
  36711. newTransaction();
  36712. }
  36713. else if (key.getTextCharacter() >= ' ')
  36714. {
  36715. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36716. }
  36717. else
  36718. {
  36719. return false;
  36720. }
  36721. return true;
  36722. }
  36723. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36724. {
  36725. newTransaction();
  36726. dragType = notDragging;
  36727. if (! e.mods.isPopupMenu())
  36728. {
  36729. beginDragAutoRepeat (100);
  36730. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36731. }
  36732. else
  36733. {
  36734. /*PopupMenu m;
  36735. addPopupMenuItems (m, &e);
  36736. const int result = m.show();
  36737. if (result != 0)
  36738. performPopupMenuAction (result);
  36739. */
  36740. }
  36741. }
  36742. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36743. {
  36744. if (! e.mods.isPopupMenu())
  36745. moveCaretTo (getPositionAt (e.x, e.y), true);
  36746. }
  36747. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36748. {
  36749. newTransaction();
  36750. beginDragAutoRepeat (0);
  36751. dragType = notDragging;
  36752. }
  36753. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36754. {
  36755. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36756. CodeDocument::Position tokenEnd (tokenStart);
  36757. if (e.getNumberOfClicks() > 2)
  36758. {
  36759. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36760. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36761. }
  36762. else
  36763. {
  36764. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36765. tokenEnd.moveBy (1);
  36766. tokenStart = tokenEnd;
  36767. while (tokenStart.getIndexInLine() > 0
  36768. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36769. tokenStart.moveBy (-1);
  36770. }
  36771. moveCaretTo (tokenEnd, false);
  36772. moveCaretTo (tokenStart, true);
  36773. }
  36774. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36775. {
  36776. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36777. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36778. {
  36779. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36780. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36781. }
  36782. else
  36783. {
  36784. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36785. }
  36786. }
  36787. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36788. {
  36789. if (scrollBarThatHasMoved == verticalScrollBar)
  36790. scrollToLineInternal ((int) newRangeStart);
  36791. else
  36792. scrollToColumnInternal (newRangeStart);
  36793. }
  36794. void CodeEditorComponent::focusGained (FocusChangeType)
  36795. {
  36796. caret->updatePosition();
  36797. }
  36798. void CodeEditorComponent::focusLost (FocusChangeType)
  36799. {
  36800. caret->updatePosition();
  36801. }
  36802. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36803. {
  36804. useSpacesForTabs = insertSpaces;
  36805. if (spacesPerTab != numSpaces)
  36806. {
  36807. spacesPerTab = numSpaces;
  36808. triggerAsyncUpdate();
  36809. }
  36810. }
  36811. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36812. {
  36813. const String line (document.getLine (lineNum));
  36814. jassert (index <= line.length());
  36815. int col = 0;
  36816. for (int i = 0; i < index; ++i)
  36817. {
  36818. if (line[i] != '\t')
  36819. ++col;
  36820. else
  36821. col += getTabSize() - (col % getTabSize());
  36822. }
  36823. return col;
  36824. }
  36825. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36826. {
  36827. const String line (document.getLine (lineNum));
  36828. const int lineLength = line.length();
  36829. int i, col = 0;
  36830. for (i = 0; i < lineLength; ++i)
  36831. {
  36832. if (line[i] != '\t')
  36833. ++col;
  36834. else
  36835. col += getTabSize() - (col % getTabSize());
  36836. if (col > column)
  36837. break;
  36838. }
  36839. return i;
  36840. }
  36841. void CodeEditorComponent::setFont (const Font& newFont)
  36842. {
  36843. font = newFont;
  36844. charWidth = font.getStringWidthFloat ("0");
  36845. lineHeight = roundToInt (font.getHeight());
  36846. resized();
  36847. }
  36848. void CodeEditorComponent::resetToDefaultColours()
  36849. {
  36850. coloursForTokenCategories.clear();
  36851. if (codeTokeniser != 0)
  36852. {
  36853. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36854. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36855. }
  36856. }
  36857. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36858. {
  36859. jassert (tokenType < 256);
  36860. while (coloursForTokenCategories.size() < tokenType)
  36861. coloursForTokenCategories.add (Colours::black);
  36862. coloursForTokenCategories.set (tokenType, colour);
  36863. repaint();
  36864. }
  36865. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36866. {
  36867. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36868. return findColour (CodeEditorComponent::defaultTextColourId);
  36869. return coloursForTokenCategories.getReference (tokenType);
  36870. }
  36871. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36872. {
  36873. int i;
  36874. for (i = cachedIterators.size(); --i >= 0;)
  36875. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36876. break;
  36877. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36878. }
  36879. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36880. {
  36881. const int maxNumCachedPositions = 5000;
  36882. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36883. if (cachedIterators.size() == 0)
  36884. cachedIterators.add (new CodeDocument::Iterator (&document));
  36885. if (codeTokeniser == 0)
  36886. return;
  36887. for (;;)
  36888. {
  36889. CodeDocument::Iterator* last = cachedIterators.getLast();
  36890. if (last->getLine() >= maxLineNum)
  36891. break;
  36892. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36893. cachedIterators.add (t);
  36894. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36895. for (;;)
  36896. {
  36897. codeTokeniser->readNextToken (*t);
  36898. if (t->getLine() >= targetLine)
  36899. break;
  36900. if (t->isEOF())
  36901. return;
  36902. }
  36903. }
  36904. }
  36905. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36906. {
  36907. if (codeTokeniser == 0)
  36908. return;
  36909. for (int i = cachedIterators.size(); --i >= 0;)
  36910. {
  36911. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36912. if (t->getPosition() <= position)
  36913. {
  36914. source = *t;
  36915. break;
  36916. }
  36917. }
  36918. while (source.getPosition() < position)
  36919. {
  36920. const CodeDocument::Iterator original (source);
  36921. codeTokeniser->readNextToken (source);
  36922. if (source.getPosition() > position || source.isEOF())
  36923. {
  36924. source = original;
  36925. break;
  36926. }
  36927. }
  36928. }
  36929. END_JUCE_NAMESPACE
  36930. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36931. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36932. BEGIN_JUCE_NAMESPACE
  36933. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36934. {
  36935. }
  36936. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36937. {
  36938. }
  36939. namespace CppTokeniser
  36940. {
  36941. static bool isIdentifierStart (const juce_wchar c) throw()
  36942. {
  36943. return CharacterFunctions::isLetter (c)
  36944. || c == '_' || c == '@';
  36945. }
  36946. static bool isIdentifierBody (const juce_wchar c) throw()
  36947. {
  36948. return CharacterFunctions::isLetterOrDigit (c)
  36949. || c == '_' || c == '@';
  36950. }
  36951. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36952. {
  36953. static const juce_wchar* const keywords2Char[] =
  36954. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36955. static const juce_wchar* const keywords3Char[] =
  36956. { 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 };
  36957. static const juce_wchar* const keywords4Char[] =
  36958. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36959. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36960. static const juce_wchar* const keywords5Char[] =
  36961. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36962. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36963. static const juce_wchar* const keywords6Char[] =
  36964. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36965. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36966. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36967. static const juce_wchar* const keywordsOther[] =
  36968. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36969. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36970. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36971. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36972. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36973. const juce_wchar* const* k;
  36974. switch (tokenLength)
  36975. {
  36976. case 2: k = keywords2Char; break;
  36977. case 3: k = keywords3Char; break;
  36978. case 4: k = keywords4Char; break;
  36979. case 5: k = keywords5Char; break;
  36980. case 6: k = keywords6Char; break;
  36981. default:
  36982. if (tokenLength < 2 || tokenLength > 16)
  36983. return false;
  36984. k = keywordsOther;
  36985. break;
  36986. }
  36987. int i = 0;
  36988. while (k[i] != 0)
  36989. {
  36990. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36991. return true;
  36992. ++i;
  36993. }
  36994. return false;
  36995. }
  36996. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36997. {
  36998. int tokenLength = 0;
  36999. juce_wchar possibleIdentifier [19];
  37000. while (isIdentifierBody (source.peekNextChar()))
  37001. {
  37002. const juce_wchar c = source.nextChar();
  37003. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37004. possibleIdentifier [tokenLength] = c;
  37005. ++tokenLength;
  37006. }
  37007. if (tokenLength > 1 && tokenLength <= 16)
  37008. {
  37009. possibleIdentifier [tokenLength] = 0;
  37010. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37011. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37012. }
  37013. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37014. }
  37015. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37016. {
  37017. const juce_wchar c = source.peekNextChar();
  37018. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37019. source.skip();
  37020. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37021. return false;
  37022. return true;
  37023. }
  37024. static bool isHexDigit (const juce_wchar c) throw()
  37025. {
  37026. return (c >= '0' && c <= '9')
  37027. || (c >= 'a' && c <= 'f')
  37028. || (c >= 'A' && c <= 'F');
  37029. }
  37030. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37031. {
  37032. if (source.nextChar() != '0')
  37033. return false;
  37034. juce_wchar c = source.nextChar();
  37035. if (c != 'x' && c != 'X')
  37036. return false;
  37037. int numDigits = 0;
  37038. while (isHexDigit (source.peekNextChar()))
  37039. {
  37040. ++numDigits;
  37041. source.skip();
  37042. }
  37043. if (numDigits == 0)
  37044. return false;
  37045. return skipNumberSuffix (source);
  37046. }
  37047. static bool isOctalDigit (const juce_wchar c) throw()
  37048. {
  37049. return c >= '0' && c <= '7';
  37050. }
  37051. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37052. {
  37053. if (source.nextChar() != '0')
  37054. return false;
  37055. if (! isOctalDigit (source.nextChar()))
  37056. return false;
  37057. while (isOctalDigit (source.peekNextChar()))
  37058. source.skip();
  37059. return skipNumberSuffix (source);
  37060. }
  37061. static bool isDecimalDigit (const juce_wchar c) throw()
  37062. {
  37063. return c >= '0' && c <= '9';
  37064. }
  37065. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37066. {
  37067. int numChars = 0;
  37068. while (isDecimalDigit (source.peekNextChar()))
  37069. {
  37070. ++numChars;
  37071. source.skip();
  37072. }
  37073. if (numChars == 0)
  37074. return false;
  37075. return skipNumberSuffix (source);
  37076. }
  37077. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37078. {
  37079. int numDigits = 0;
  37080. while (isDecimalDigit (source.peekNextChar()))
  37081. {
  37082. source.skip();
  37083. ++numDigits;
  37084. }
  37085. const bool hasPoint = (source.peekNextChar() == '.');
  37086. if (hasPoint)
  37087. {
  37088. source.skip();
  37089. while (isDecimalDigit (source.peekNextChar()))
  37090. {
  37091. source.skip();
  37092. ++numDigits;
  37093. }
  37094. }
  37095. if (numDigits == 0)
  37096. return false;
  37097. juce_wchar c = source.peekNextChar();
  37098. const bool hasExponent = (c == 'e' || c == 'E');
  37099. if (hasExponent)
  37100. {
  37101. source.skip();
  37102. c = source.peekNextChar();
  37103. if (c == '+' || c == '-')
  37104. source.skip();
  37105. int numExpDigits = 0;
  37106. while (isDecimalDigit (source.peekNextChar()))
  37107. {
  37108. source.skip();
  37109. ++numExpDigits;
  37110. }
  37111. if (numExpDigits == 0)
  37112. return false;
  37113. }
  37114. c = source.peekNextChar();
  37115. if (c == 'f' || c == 'F')
  37116. source.skip();
  37117. else if (! (hasExponent || hasPoint))
  37118. return false;
  37119. return true;
  37120. }
  37121. static int parseNumber (CodeDocument::Iterator& source)
  37122. {
  37123. const CodeDocument::Iterator original (source);
  37124. if (parseFloatLiteral (source))
  37125. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37126. source = original;
  37127. if (parseHexLiteral (source))
  37128. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37129. source = original;
  37130. if (parseOctalLiteral (source))
  37131. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37132. source = original;
  37133. if (parseDecimalLiteral (source))
  37134. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37135. source = original;
  37136. source.skip();
  37137. return CPlusPlusCodeTokeniser::tokenType_error;
  37138. }
  37139. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37140. {
  37141. const juce_wchar quote = source.nextChar();
  37142. for (;;)
  37143. {
  37144. const juce_wchar c = source.nextChar();
  37145. if (c == quote || c == 0)
  37146. break;
  37147. if (c == '\\')
  37148. source.skip();
  37149. }
  37150. }
  37151. static void skipComment (CodeDocument::Iterator& source) throw()
  37152. {
  37153. bool lastWasStar = false;
  37154. for (;;)
  37155. {
  37156. const juce_wchar c = source.nextChar();
  37157. if (c == 0 || (c == '/' && lastWasStar))
  37158. break;
  37159. lastWasStar = (c == '*');
  37160. }
  37161. }
  37162. }
  37163. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37164. {
  37165. int result = tokenType_error;
  37166. source.skipWhitespace();
  37167. juce_wchar firstChar = source.peekNextChar();
  37168. switch (firstChar)
  37169. {
  37170. case 0:
  37171. source.skip();
  37172. break;
  37173. case '0':
  37174. case '1':
  37175. case '2':
  37176. case '3':
  37177. case '4':
  37178. case '5':
  37179. case '6':
  37180. case '7':
  37181. case '8':
  37182. case '9':
  37183. result = CppTokeniser::parseNumber (source);
  37184. break;
  37185. case '.':
  37186. result = CppTokeniser::parseNumber (source);
  37187. if (result == tokenType_error)
  37188. result = tokenType_punctuation;
  37189. break;
  37190. case ',':
  37191. case ';':
  37192. case ':':
  37193. source.skip();
  37194. result = tokenType_punctuation;
  37195. break;
  37196. case '(':
  37197. case ')':
  37198. case '{':
  37199. case '}':
  37200. case '[':
  37201. case ']':
  37202. source.skip();
  37203. result = tokenType_bracket;
  37204. break;
  37205. case '"':
  37206. case '\'':
  37207. CppTokeniser::skipQuotedString (source);
  37208. result = tokenType_stringLiteral;
  37209. break;
  37210. case '+':
  37211. result = tokenType_operator;
  37212. source.skip();
  37213. if (source.peekNextChar() == '+')
  37214. source.skip();
  37215. else if (source.peekNextChar() == '=')
  37216. source.skip();
  37217. break;
  37218. case '-':
  37219. source.skip();
  37220. result = CppTokeniser::parseNumber (source);
  37221. if (result == tokenType_error)
  37222. {
  37223. result = tokenType_operator;
  37224. if (source.peekNextChar() == '-')
  37225. source.skip();
  37226. else if (source.peekNextChar() == '=')
  37227. source.skip();
  37228. }
  37229. break;
  37230. case '*':
  37231. case '%':
  37232. case '=':
  37233. case '!':
  37234. result = tokenType_operator;
  37235. source.skip();
  37236. if (source.peekNextChar() == '=')
  37237. source.skip();
  37238. break;
  37239. case '/':
  37240. result = tokenType_operator;
  37241. source.skip();
  37242. if (source.peekNextChar() == '=')
  37243. {
  37244. source.skip();
  37245. }
  37246. else if (source.peekNextChar() == '/')
  37247. {
  37248. result = tokenType_comment;
  37249. source.skipToEndOfLine();
  37250. }
  37251. else if (source.peekNextChar() == '*')
  37252. {
  37253. source.skip();
  37254. result = tokenType_comment;
  37255. CppTokeniser::skipComment (source);
  37256. }
  37257. break;
  37258. case '?':
  37259. case '~':
  37260. source.skip();
  37261. result = tokenType_operator;
  37262. break;
  37263. case '<':
  37264. source.skip();
  37265. result = tokenType_operator;
  37266. if (source.peekNextChar() == '=')
  37267. {
  37268. source.skip();
  37269. }
  37270. else if (source.peekNextChar() == '<')
  37271. {
  37272. source.skip();
  37273. if (source.peekNextChar() == '=')
  37274. source.skip();
  37275. }
  37276. break;
  37277. case '>':
  37278. source.skip();
  37279. result = tokenType_operator;
  37280. if (source.peekNextChar() == '=')
  37281. {
  37282. source.skip();
  37283. }
  37284. else if (source.peekNextChar() == '<')
  37285. {
  37286. source.skip();
  37287. if (source.peekNextChar() == '=')
  37288. source.skip();
  37289. }
  37290. break;
  37291. case '|':
  37292. source.skip();
  37293. result = tokenType_operator;
  37294. if (source.peekNextChar() == '=')
  37295. {
  37296. source.skip();
  37297. }
  37298. else if (source.peekNextChar() == '|')
  37299. {
  37300. source.skip();
  37301. if (source.peekNextChar() == '=')
  37302. source.skip();
  37303. }
  37304. break;
  37305. case '&':
  37306. source.skip();
  37307. result = tokenType_operator;
  37308. if (source.peekNextChar() == '=')
  37309. {
  37310. source.skip();
  37311. }
  37312. else if (source.peekNextChar() == '&')
  37313. {
  37314. source.skip();
  37315. if (source.peekNextChar() == '=')
  37316. source.skip();
  37317. }
  37318. break;
  37319. case '^':
  37320. source.skip();
  37321. result = tokenType_operator;
  37322. if (source.peekNextChar() == '=')
  37323. {
  37324. source.skip();
  37325. }
  37326. else if (source.peekNextChar() == '^')
  37327. {
  37328. source.skip();
  37329. if (source.peekNextChar() == '=')
  37330. source.skip();
  37331. }
  37332. break;
  37333. case '#':
  37334. result = tokenType_preprocessor;
  37335. source.skipToEndOfLine();
  37336. break;
  37337. default:
  37338. if (CppTokeniser::isIdentifierStart (firstChar))
  37339. result = CppTokeniser::parseIdentifier (source);
  37340. else
  37341. source.skip();
  37342. break;
  37343. }
  37344. return result;
  37345. }
  37346. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37347. {
  37348. const char* const types[] =
  37349. {
  37350. "Error",
  37351. "Comment",
  37352. "C++ keyword",
  37353. "Identifier",
  37354. "Integer literal",
  37355. "Float literal",
  37356. "String literal",
  37357. "Operator",
  37358. "Bracket",
  37359. "Punctuation",
  37360. "Preprocessor line",
  37361. 0
  37362. };
  37363. return StringArray (types);
  37364. }
  37365. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37366. {
  37367. const uint32 colours[] =
  37368. {
  37369. 0xffcc0000, // error
  37370. 0xff00aa00, // comment
  37371. 0xff0000cc, // keyword
  37372. 0xff000000, // identifier
  37373. 0xff880000, // int literal
  37374. 0xff885500, // float literal
  37375. 0xff990099, // string literal
  37376. 0xff225500, // operator
  37377. 0xff000055, // bracket
  37378. 0xff004400, // punctuation
  37379. 0xff660000 // preprocessor
  37380. };
  37381. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37382. return Colour (colours [tokenType]);
  37383. return Colours::black;
  37384. }
  37385. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37386. {
  37387. return CppTokeniser::isReservedKeyword (token, token.length());
  37388. }
  37389. END_JUCE_NAMESPACE
  37390. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37391. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37392. BEGIN_JUCE_NAMESPACE
  37393. ComboBox::ComboBox (const String& name)
  37394. : Component (name),
  37395. lastCurrentId (0),
  37396. isButtonDown (false),
  37397. separatorPending (false),
  37398. menuActive (false),
  37399. label (0)
  37400. {
  37401. noChoicesMessage = TRANS("(no choices)");
  37402. setRepaintsOnMouseActivity (true);
  37403. lookAndFeelChanged();
  37404. currentId.addListener (this);
  37405. }
  37406. ComboBox::~ComboBox()
  37407. {
  37408. currentId.removeListener (this);
  37409. if (menuActive)
  37410. PopupMenu::dismissAllActiveMenus();
  37411. label = 0;
  37412. deleteAllChildren();
  37413. }
  37414. void ComboBox::setEditableText (const bool isEditable)
  37415. {
  37416. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37417. {
  37418. label->setEditable (isEditable, isEditable, false);
  37419. setWantsKeyboardFocus (! isEditable);
  37420. resized();
  37421. }
  37422. }
  37423. bool ComboBox::isTextEditable() const throw()
  37424. {
  37425. return label->isEditable();
  37426. }
  37427. void ComboBox::setJustificationType (const Justification& justification) throw()
  37428. {
  37429. label->setJustificationType (justification);
  37430. }
  37431. const Justification ComboBox::getJustificationType() const throw()
  37432. {
  37433. return label->getJustificationType();
  37434. }
  37435. void ComboBox::setTooltip (const String& newTooltip)
  37436. {
  37437. SettableTooltipClient::setTooltip (newTooltip);
  37438. label->setTooltip (newTooltip);
  37439. }
  37440. void ComboBox::addItem (const String& newItemText,
  37441. const int newItemId) throw()
  37442. {
  37443. // you can't add empty strings to the list..
  37444. jassert (newItemText.isNotEmpty());
  37445. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37446. jassert (newItemId != 0);
  37447. // you shouldn't use duplicate item IDs!
  37448. jassert (getItemForId (newItemId) == 0);
  37449. if (newItemText.isNotEmpty() && newItemId != 0)
  37450. {
  37451. if (separatorPending)
  37452. {
  37453. separatorPending = false;
  37454. ItemInfo* const item = new ItemInfo();
  37455. item->itemId = 0;
  37456. item->isEnabled = false;
  37457. item->isHeading = false;
  37458. items.add (item);
  37459. }
  37460. ItemInfo* const item = new ItemInfo();
  37461. item->name = newItemText;
  37462. item->itemId = newItemId;
  37463. item->isEnabled = true;
  37464. item->isHeading = false;
  37465. items.add (item);
  37466. }
  37467. }
  37468. void ComboBox::addSeparator() throw()
  37469. {
  37470. separatorPending = (items.size() > 0);
  37471. }
  37472. void ComboBox::addSectionHeading (const String& headingName) throw()
  37473. {
  37474. // you can't add empty strings to the list..
  37475. jassert (headingName.isNotEmpty());
  37476. if (headingName.isNotEmpty())
  37477. {
  37478. if (separatorPending)
  37479. {
  37480. separatorPending = false;
  37481. ItemInfo* const item = new ItemInfo();
  37482. item->itemId = 0;
  37483. item->isEnabled = false;
  37484. item->isHeading = false;
  37485. items.add (item);
  37486. }
  37487. ItemInfo* const item = new ItemInfo();
  37488. item->name = headingName;
  37489. item->itemId = 0;
  37490. item->isEnabled = true;
  37491. item->isHeading = true;
  37492. items.add (item);
  37493. }
  37494. }
  37495. void ComboBox::setItemEnabled (const int itemId,
  37496. const bool shouldBeEnabled) throw()
  37497. {
  37498. ItemInfo* const item = getItemForId (itemId);
  37499. if (item != 0)
  37500. item->isEnabled = shouldBeEnabled;
  37501. }
  37502. void ComboBox::changeItemText (const int itemId,
  37503. const String& newText) throw()
  37504. {
  37505. ItemInfo* const item = getItemForId (itemId);
  37506. jassert (item != 0);
  37507. if (item != 0)
  37508. item->name = newText;
  37509. }
  37510. void ComboBox::clear (const bool dontSendChangeMessage)
  37511. {
  37512. items.clear();
  37513. separatorPending = false;
  37514. if (! label->isEditable())
  37515. setSelectedItemIndex (-1, dontSendChangeMessage);
  37516. }
  37517. bool ComboBox::ItemInfo::isSeparator() const throw()
  37518. {
  37519. return name.isEmpty();
  37520. }
  37521. bool ComboBox::ItemInfo::isRealItem() const throw()
  37522. {
  37523. return ! (isHeading || name.isEmpty());
  37524. }
  37525. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37526. {
  37527. if (itemId != 0)
  37528. {
  37529. for (int i = items.size(); --i >= 0;)
  37530. if (items.getUnchecked(i)->itemId == itemId)
  37531. return items.getUnchecked(i);
  37532. }
  37533. return 0;
  37534. }
  37535. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37536. {
  37537. int n = 0;
  37538. for (int i = 0; i < items.size(); ++i)
  37539. {
  37540. ItemInfo* const item = items.getUnchecked(i);
  37541. if (item->isRealItem())
  37542. if (n++ == index)
  37543. return item;
  37544. }
  37545. return 0;
  37546. }
  37547. int ComboBox::getNumItems() const throw()
  37548. {
  37549. int n = 0;
  37550. for (int i = items.size(); --i >= 0;)
  37551. if (items.getUnchecked(i)->isRealItem())
  37552. ++n;
  37553. return n;
  37554. }
  37555. const String ComboBox::getItemText (const int index) const throw()
  37556. {
  37557. const ItemInfo* const item = getItemForIndex (index);
  37558. if (item != 0)
  37559. return item->name;
  37560. return String::empty;
  37561. }
  37562. int ComboBox::getItemId (const int index) const throw()
  37563. {
  37564. const ItemInfo* const item = getItemForIndex (index);
  37565. return (item != 0) ? item->itemId : 0;
  37566. }
  37567. int ComboBox::indexOfItemId (const int itemId) const throw()
  37568. {
  37569. int n = 0;
  37570. for (int i = 0; i < items.size(); ++i)
  37571. {
  37572. const ItemInfo* const item = items.getUnchecked(i);
  37573. if (item->isRealItem())
  37574. {
  37575. if (item->itemId == itemId)
  37576. return n;
  37577. ++n;
  37578. }
  37579. }
  37580. return -1;
  37581. }
  37582. int ComboBox::getSelectedItemIndex() const throw()
  37583. {
  37584. int index = indexOfItemId (currentId.getValue());
  37585. if (getText() != getItemText (index))
  37586. index = -1;
  37587. return index;
  37588. }
  37589. void ComboBox::setSelectedItemIndex (const int index,
  37590. const bool dontSendChangeMessage) throw()
  37591. {
  37592. setSelectedId (getItemId (index), dontSendChangeMessage);
  37593. }
  37594. int ComboBox::getSelectedId() const throw()
  37595. {
  37596. const ItemInfo* const item = getItemForId (currentId.getValue());
  37597. return (item != 0 && getText() == item->name)
  37598. ? item->itemId
  37599. : 0;
  37600. }
  37601. void ComboBox::setSelectedId (const int newItemId,
  37602. const bool dontSendChangeMessage) throw()
  37603. {
  37604. const ItemInfo* const item = getItemForId (newItemId);
  37605. const String newItemText (item != 0 ? item->name : String::empty);
  37606. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37607. {
  37608. if (! dontSendChangeMessage)
  37609. triggerAsyncUpdate();
  37610. label->setText (newItemText, false);
  37611. lastCurrentId = newItemId;
  37612. currentId = newItemId;
  37613. repaint(); // for the benefit of the 'none selected' text
  37614. }
  37615. }
  37616. void ComboBox::valueChanged (Value&)
  37617. {
  37618. if (lastCurrentId != (int) currentId.getValue())
  37619. setSelectedId (currentId.getValue(), false);
  37620. }
  37621. const String ComboBox::getText() const throw()
  37622. {
  37623. return label->getText();
  37624. }
  37625. void ComboBox::setText (const String& newText,
  37626. const bool dontSendChangeMessage) throw()
  37627. {
  37628. for (int i = items.size(); --i >= 0;)
  37629. {
  37630. const ItemInfo* const item = items.getUnchecked(i);
  37631. if (item->isRealItem()
  37632. && item->name == newText)
  37633. {
  37634. setSelectedId (item->itemId, dontSendChangeMessage);
  37635. return;
  37636. }
  37637. }
  37638. lastCurrentId = 0;
  37639. currentId = 0;
  37640. if (label->getText() != newText)
  37641. {
  37642. label->setText (newText, false);
  37643. if (! dontSendChangeMessage)
  37644. triggerAsyncUpdate();
  37645. }
  37646. repaint();
  37647. }
  37648. void ComboBox::showEditor()
  37649. {
  37650. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37651. label->showEditor();
  37652. }
  37653. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37654. {
  37655. if (textWhenNothingSelected != newMessage)
  37656. {
  37657. textWhenNothingSelected = newMessage;
  37658. repaint();
  37659. }
  37660. }
  37661. const String ComboBox::getTextWhenNothingSelected() const throw()
  37662. {
  37663. return textWhenNothingSelected;
  37664. }
  37665. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37666. {
  37667. noChoicesMessage = newMessage;
  37668. }
  37669. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37670. {
  37671. return noChoicesMessage;
  37672. }
  37673. void ComboBox::paint (Graphics& g)
  37674. {
  37675. getLookAndFeel().drawComboBox (g,
  37676. getWidth(),
  37677. getHeight(),
  37678. isButtonDown,
  37679. label->getRight(),
  37680. 0,
  37681. getWidth() - label->getRight(),
  37682. getHeight(),
  37683. *this);
  37684. if (textWhenNothingSelected.isNotEmpty()
  37685. && label->getText().isEmpty()
  37686. && ! label->isBeingEdited())
  37687. {
  37688. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37689. g.setFont (label->getFont());
  37690. g.drawFittedText (textWhenNothingSelected,
  37691. label->getX() + 2, label->getY() + 1,
  37692. label->getWidth() - 4, label->getHeight() - 2,
  37693. label->getJustificationType(),
  37694. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37695. }
  37696. }
  37697. void ComboBox::resized()
  37698. {
  37699. if (getHeight() > 0 && getWidth() > 0)
  37700. getLookAndFeel().positionComboBoxText (*this, *label);
  37701. }
  37702. void ComboBox::enablementChanged()
  37703. {
  37704. repaint();
  37705. }
  37706. void ComboBox::lookAndFeelChanged()
  37707. {
  37708. repaint();
  37709. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37710. if (label != 0)
  37711. {
  37712. newLabel->setEditable (label->isEditable());
  37713. newLabel->setJustificationType (label->getJustificationType());
  37714. newLabel->setTooltip (label->getTooltip());
  37715. newLabel->setText (label->getText(), false);
  37716. }
  37717. label = newLabel;
  37718. addAndMakeVisible (newLabel);
  37719. newLabel->addListener (this);
  37720. newLabel->addMouseListener (this, false);
  37721. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37722. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37723. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37724. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37725. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37726. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37727. resized();
  37728. }
  37729. void ComboBox::colourChanged()
  37730. {
  37731. lookAndFeelChanged();
  37732. }
  37733. bool ComboBox::keyPressed (const KeyPress& key)
  37734. {
  37735. bool used = false;
  37736. if (key.isKeyCode (KeyPress::upKey)
  37737. || key.isKeyCode (KeyPress::leftKey))
  37738. {
  37739. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37740. used = true;
  37741. }
  37742. else if (key.isKeyCode (KeyPress::downKey)
  37743. || key.isKeyCode (KeyPress::rightKey))
  37744. {
  37745. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37746. used = true;
  37747. }
  37748. else if (key.isKeyCode (KeyPress::returnKey))
  37749. {
  37750. showPopup();
  37751. used = true;
  37752. }
  37753. return used;
  37754. }
  37755. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37756. {
  37757. // only forward key events that aren't used by this component
  37758. return isKeyDown
  37759. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37760. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37761. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37762. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37763. }
  37764. void ComboBox::focusGained (FocusChangeType)
  37765. {
  37766. repaint();
  37767. }
  37768. void ComboBox::focusLost (FocusChangeType)
  37769. {
  37770. repaint();
  37771. }
  37772. void ComboBox::labelTextChanged (Label*)
  37773. {
  37774. triggerAsyncUpdate();
  37775. }
  37776. class ComboBox::Callback : public ModalComponentManager::Callback
  37777. {
  37778. public:
  37779. Callback (ComboBox* const box_)
  37780. : box (box_)
  37781. {
  37782. }
  37783. void modalStateFinished (int returnValue)
  37784. {
  37785. if (box != 0)
  37786. {
  37787. box->menuActive = false;
  37788. if (returnValue != 0)
  37789. box->setSelectedId (returnValue);
  37790. }
  37791. }
  37792. private:
  37793. Component::SafePointer<ComboBox> box;
  37794. Callback (const Callback&);
  37795. Callback& operator= (const Callback&);
  37796. };
  37797. void ComboBox::showPopup()
  37798. {
  37799. if (! menuActive)
  37800. {
  37801. const int selectedId = getSelectedId();
  37802. PopupMenu menu;
  37803. menu.setLookAndFeel (&getLookAndFeel());
  37804. for (int i = 0; i < items.size(); ++i)
  37805. {
  37806. const ItemInfo* const item = items.getUnchecked(i);
  37807. if (item->isSeparator())
  37808. menu.addSeparator();
  37809. else if (item->isHeading)
  37810. menu.addSectionHeader (item->name);
  37811. else
  37812. menu.addItem (item->itemId, item->name,
  37813. item->isEnabled, item->itemId == selectedId);
  37814. }
  37815. if (items.size() == 0)
  37816. menu.addItem (1, noChoicesMessage, false);
  37817. menuActive = true;
  37818. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  37819. new Callback (this));
  37820. }
  37821. }
  37822. void ComboBox::mouseDown (const MouseEvent& e)
  37823. {
  37824. beginDragAutoRepeat (300);
  37825. isButtonDown = isEnabled();
  37826. if (isButtonDown
  37827. && (e.eventComponent == this || ! label->isEditable()))
  37828. {
  37829. showPopup();
  37830. }
  37831. }
  37832. void ComboBox::mouseDrag (const MouseEvent& e)
  37833. {
  37834. beginDragAutoRepeat (50);
  37835. if (isButtonDown && ! e.mouseWasClicked())
  37836. showPopup();
  37837. }
  37838. void ComboBox::mouseUp (const MouseEvent& e2)
  37839. {
  37840. if (isButtonDown)
  37841. {
  37842. isButtonDown = false;
  37843. repaint();
  37844. const MouseEvent e (e2.getEventRelativeTo (this));
  37845. if (reallyContains (e.x, e.y, true)
  37846. && (e2.eventComponent == this || ! label->isEditable()))
  37847. {
  37848. showPopup();
  37849. }
  37850. }
  37851. }
  37852. void ComboBox::addListener (Listener* const listener) throw()
  37853. {
  37854. listeners.add (listener);
  37855. }
  37856. void ComboBox::removeListener (Listener* const listener) throw()
  37857. {
  37858. listeners.remove (listener);
  37859. }
  37860. void ComboBox::handleAsyncUpdate()
  37861. {
  37862. Component::BailOutChecker checker (this);
  37863. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  37864. }
  37865. END_JUCE_NAMESPACE
  37866. /*** End of inlined file: juce_ComboBox.cpp ***/
  37867. /*** Start of inlined file: juce_Label.cpp ***/
  37868. BEGIN_JUCE_NAMESPACE
  37869. Label::Label (const String& componentName,
  37870. const String& labelText)
  37871. : Component (componentName),
  37872. textValue (labelText),
  37873. lastTextValue (labelText),
  37874. font (15.0f),
  37875. justification (Justification::centredLeft),
  37876. ownerComponent (0),
  37877. horizontalBorderSize (5),
  37878. verticalBorderSize (1),
  37879. minimumHorizontalScale (0.7f),
  37880. editSingleClick (false),
  37881. editDoubleClick (false),
  37882. lossOfFocusDiscardsChanges (false)
  37883. {
  37884. setColour (TextEditor::textColourId, Colours::black);
  37885. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37886. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37887. textValue.addListener (this);
  37888. }
  37889. Label::~Label()
  37890. {
  37891. textValue.removeListener (this);
  37892. if (ownerComponent != 0)
  37893. ownerComponent->removeComponentListener (this);
  37894. editor = 0;
  37895. }
  37896. void Label::setText (const String& newText,
  37897. const bool broadcastChangeMessage)
  37898. {
  37899. hideEditor (true);
  37900. if (lastTextValue != newText)
  37901. {
  37902. lastTextValue = newText;
  37903. textValue = newText;
  37904. repaint();
  37905. textWasChanged();
  37906. if (ownerComponent != 0)
  37907. componentMovedOrResized (*ownerComponent, true, true);
  37908. if (broadcastChangeMessage)
  37909. callChangeListeners();
  37910. }
  37911. }
  37912. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37913. {
  37914. return (returnActiveEditorContents && isBeingEdited())
  37915. ? editor->getText()
  37916. : textValue.toString();
  37917. }
  37918. void Label::valueChanged (Value&)
  37919. {
  37920. if (lastTextValue != textValue.toString())
  37921. setText (textValue.toString(), true);
  37922. }
  37923. void Label::setFont (const Font& newFont) throw()
  37924. {
  37925. if (font != newFont)
  37926. {
  37927. font = newFont;
  37928. repaint();
  37929. }
  37930. }
  37931. const Font& Label::getFont() const throw()
  37932. {
  37933. return font;
  37934. }
  37935. void Label::setEditable (const bool editOnSingleClick,
  37936. const bool editOnDoubleClick,
  37937. const bool lossOfFocusDiscardsChanges_) throw()
  37938. {
  37939. editSingleClick = editOnSingleClick;
  37940. editDoubleClick = editOnDoubleClick;
  37941. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37942. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37943. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37944. }
  37945. void Label::setJustificationType (const Justification& newJustification) throw()
  37946. {
  37947. if (justification != newJustification)
  37948. {
  37949. justification = newJustification;
  37950. repaint();
  37951. }
  37952. }
  37953. void Label::setBorderSize (int h, int v)
  37954. {
  37955. if (horizontalBorderSize != h || verticalBorderSize != v)
  37956. {
  37957. horizontalBorderSize = h;
  37958. verticalBorderSize = v;
  37959. repaint();
  37960. }
  37961. }
  37962. Component* Label::getAttachedComponent() const
  37963. {
  37964. return static_cast<Component*> (ownerComponent);
  37965. }
  37966. void Label::attachToComponent (Component* owner,
  37967. const bool onLeft)
  37968. {
  37969. if (ownerComponent != 0)
  37970. ownerComponent->removeComponentListener (this);
  37971. ownerComponent = owner;
  37972. leftOfOwnerComp = onLeft;
  37973. if (ownerComponent != 0)
  37974. {
  37975. setVisible (owner->isVisible());
  37976. ownerComponent->addComponentListener (this);
  37977. componentParentHierarchyChanged (*ownerComponent);
  37978. componentMovedOrResized (*ownerComponent, true, true);
  37979. }
  37980. }
  37981. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37982. {
  37983. if (leftOfOwnerComp)
  37984. {
  37985. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37986. component.getHeight());
  37987. setTopRightPosition (component.getX(), component.getY());
  37988. }
  37989. else
  37990. {
  37991. setSize (component.getWidth(),
  37992. 8 + roundToInt (getFont().getHeight()));
  37993. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37994. }
  37995. }
  37996. void Label::componentParentHierarchyChanged (Component& component)
  37997. {
  37998. if (component.getParentComponent() != 0)
  37999. component.getParentComponent()->addChildComponent (this);
  38000. }
  38001. void Label::componentVisibilityChanged (Component& component)
  38002. {
  38003. setVisible (component.isVisible());
  38004. }
  38005. void Label::textWasEdited()
  38006. {
  38007. }
  38008. void Label::textWasChanged()
  38009. {
  38010. }
  38011. void Label::showEditor()
  38012. {
  38013. if (editor == 0)
  38014. {
  38015. addAndMakeVisible (editor = createEditorComponent());
  38016. editor->setText (getText(), false);
  38017. editor->addListener (this);
  38018. editor->grabKeyboardFocus();
  38019. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38020. editor->addListener (this);
  38021. resized();
  38022. repaint();
  38023. editorShown (editor);
  38024. enterModalState (false);
  38025. editor->grabKeyboardFocus();
  38026. }
  38027. }
  38028. void Label::editorShown (TextEditor* /*editorComponent*/)
  38029. {
  38030. }
  38031. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38032. {
  38033. }
  38034. bool Label::updateFromTextEditorContents()
  38035. {
  38036. jassert (editor != 0);
  38037. const String newText (editor->getText());
  38038. if (textValue.toString() != newText)
  38039. {
  38040. lastTextValue = newText;
  38041. textValue = newText;
  38042. repaint();
  38043. textWasChanged();
  38044. if (ownerComponent != 0)
  38045. componentMovedOrResized (*ownerComponent, true, true);
  38046. return true;
  38047. }
  38048. return false;
  38049. }
  38050. void Label::hideEditor (const bool discardCurrentEditorContents)
  38051. {
  38052. if (editor != 0)
  38053. {
  38054. Component::SafePointer<Component> deletionChecker (this);
  38055. editorAboutToBeHidden (editor);
  38056. const bool changed = (! discardCurrentEditorContents)
  38057. && updateFromTextEditorContents();
  38058. editor = 0;
  38059. repaint();
  38060. if (changed)
  38061. textWasEdited();
  38062. if (deletionChecker != 0)
  38063. exitModalState (0);
  38064. if (changed && deletionChecker != 0)
  38065. callChangeListeners();
  38066. }
  38067. }
  38068. void Label::inputAttemptWhenModal()
  38069. {
  38070. if (editor != 0)
  38071. {
  38072. if (lossOfFocusDiscardsChanges)
  38073. textEditorEscapeKeyPressed (*editor);
  38074. else
  38075. textEditorReturnKeyPressed (*editor);
  38076. }
  38077. }
  38078. bool Label::isBeingEdited() const throw()
  38079. {
  38080. return editor != 0;
  38081. }
  38082. TextEditor* Label::createEditorComponent()
  38083. {
  38084. TextEditor* const ed = new TextEditor (getName());
  38085. ed->setFont (font);
  38086. // copy these colours from our own settings..
  38087. const int cols[] = { TextEditor::backgroundColourId,
  38088. TextEditor::textColourId,
  38089. TextEditor::highlightColourId,
  38090. TextEditor::highlightedTextColourId,
  38091. TextEditor::caretColourId,
  38092. TextEditor::outlineColourId,
  38093. TextEditor::focusedOutlineColourId,
  38094. TextEditor::shadowColourId };
  38095. for (int i = 0; i < numElementsInArray (cols); ++i)
  38096. ed->setColour (cols[i], findColour (cols[i]));
  38097. return ed;
  38098. }
  38099. void Label::paint (Graphics& g)
  38100. {
  38101. getLookAndFeel().drawLabel (g, *this);
  38102. }
  38103. void Label::mouseUp (const MouseEvent& e)
  38104. {
  38105. if (editSingleClick
  38106. && e.mouseWasClicked()
  38107. && contains (e.x, e.y)
  38108. && ! e.mods.isPopupMenu())
  38109. {
  38110. showEditor();
  38111. }
  38112. }
  38113. void Label::mouseDoubleClick (const MouseEvent& e)
  38114. {
  38115. if (editDoubleClick && ! e.mods.isPopupMenu())
  38116. showEditor();
  38117. }
  38118. void Label::resized()
  38119. {
  38120. if (editor != 0)
  38121. editor->setBoundsInset (BorderSize (0));
  38122. }
  38123. void Label::focusGained (FocusChangeType cause)
  38124. {
  38125. if (editSingleClick && cause == focusChangedByTabKey)
  38126. showEditor();
  38127. }
  38128. void Label::enablementChanged()
  38129. {
  38130. repaint();
  38131. }
  38132. void Label::colourChanged()
  38133. {
  38134. repaint();
  38135. }
  38136. void Label::setMinimumHorizontalScale (const float newScale)
  38137. {
  38138. if (minimumHorizontalScale != newScale)
  38139. {
  38140. minimumHorizontalScale = newScale;
  38141. repaint();
  38142. }
  38143. }
  38144. // We'll use a custom focus traverser here to make sure focus goes from the
  38145. // text editor to another component rather than back to the label itself.
  38146. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38147. {
  38148. public:
  38149. LabelKeyboardFocusTraverser() {}
  38150. Component* getNextComponent (Component* current)
  38151. {
  38152. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38153. ? current->getParentComponent() : current);
  38154. }
  38155. Component* getPreviousComponent (Component* current)
  38156. {
  38157. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38158. ? current->getParentComponent() : current);
  38159. }
  38160. };
  38161. KeyboardFocusTraverser* Label::createFocusTraverser()
  38162. {
  38163. return new LabelKeyboardFocusTraverser();
  38164. }
  38165. void Label::addListener (Listener* const listener) throw()
  38166. {
  38167. listeners.add (listener);
  38168. }
  38169. void Label::removeListener (Listener* const listener) throw()
  38170. {
  38171. listeners.remove (listener);
  38172. }
  38173. void Label::callChangeListeners()
  38174. {
  38175. Component::BailOutChecker checker (this);
  38176. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38177. }
  38178. void Label::textEditorTextChanged (TextEditor& ed)
  38179. {
  38180. if (editor != 0)
  38181. {
  38182. jassert (&ed == editor);
  38183. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38184. {
  38185. if (lossOfFocusDiscardsChanges)
  38186. textEditorEscapeKeyPressed (ed);
  38187. else
  38188. textEditorReturnKeyPressed (ed);
  38189. }
  38190. }
  38191. }
  38192. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38193. {
  38194. if (editor != 0)
  38195. {
  38196. jassert (&ed == editor);
  38197. (void) ed;
  38198. const bool changed = updateFromTextEditorContents();
  38199. hideEditor (true);
  38200. if (changed)
  38201. {
  38202. Component::SafePointer<Component> deletionChecker (this);
  38203. textWasEdited();
  38204. if (deletionChecker != 0)
  38205. callChangeListeners();
  38206. }
  38207. }
  38208. }
  38209. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38210. {
  38211. if (editor != 0)
  38212. {
  38213. jassert (&ed == editor);
  38214. (void) ed;
  38215. editor->setText (textValue.toString(), false);
  38216. hideEditor (true);
  38217. }
  38218. }
  38219. void Label::textEditorFocusLost (TextEditor& ed)
  38220. {
  38221. textEditorTextChanged (ed);
  38222. }
  38223. END_JUCE_NAMESPACE
  38224. /*** End of inlined file: juce_Label.cpp ***/
  38225. /*** Start of inlined file: juce_ListBox.cpp ***/
  38226. BEGIN_JUCE_NAMESPACE
  38227. class ListBoxRowComponent : public Component,
  38228. public TooltipClient
  38229. {
  38230. public:
  38231. ListBoxRowComponent (ListBox& owner_)
  38232. : owner (owner_),
  38233. row (-1),
  38234. selected (false),
  38235. isDragging (false)
  38236. {
  38237. }
  38238. ~ListBoxRowComponent()
  38239. {
  38240. deleteAllChildren();
  38241. }
  38242. void paint (Graphics& g)
  38243. {
  38244. if (owner.getModel() != 0)
  38245. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38246. }
  38247. void update (const int row_, const bool selected_)
  38248. {
  38249. if (row != row_ || selected != selected_)
  38250. {
  38251. repaint();
  38252. row = row_;
  38253. selected = selected_;
  38254. }
  38255. if (owner.getModel() != 0)
  38256. {
  38257. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38258. if (customComp != 0)
  38259. {
  38260. addAndMakeVisible (customComp);
  38261. customComp->setBounds (getLocalBounds());
  38262. for (int i = getNumChildComponents(); --i >= 0;)
  38263. if (getChildComponent (i) != customComp)
  38264. delete getChildComponent (i);
  38265. }
  38266. else
  38267. {
  38268. deleteAllChildren();
  38269. }
  38270. }
  38271. }
  38272. void mouseDown (const MouseEvent& e)
  38273. {
  38274. isDragging = false;
  38275. selectRowOnMouseUp = false;
  38276. if (isEnabled())
  38277. {
  38278. if (! selected)
  38279. {
  38280. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38281. if (owner.getModel() != 0)
  38282. owner.getModel()->listBoxItemClicked (row, e);
  38283. }
  38284. else
  38285. {
  38286. selectRowOnMouseUp = true;
  38287. }
  38288. }
  38289. }
  38290. void mouseUp (const MouseEvent& e)
  38291. {
  38292. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38293. {
  38294. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38295. if (owner.getModel() != 0)
  38296. owner.getModel()->listBoxItemClicked (row, e);
  38297. }
  38298. }
  38299. void mouseDoubleClick (const MouseEvent& e)
  38300. {
  38301. if (owner.getModel() != 0 && isEnabled())
  38302. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38303. }
  38304. void mouseDrag (const MouseEvent& e)
  38305. {
  38306. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38307. {
  38308. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38309. if (selectedRows.size() > 0)
  38310. {
  38311. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38312. if (dragDescription.isNotEmpty())
  38313. {
  38314. isDragging = true;
  38315. owner.startDragAndDrop (e, dragDescription);
  38316. }
  38317. }
  38318. }
  38319. }
  38320. void resized()
  38321. {
  38322. if (getNumChildComponents() > 0)
  38323. getChildComponent(0)->setBounds (getLocalBounds());
  38324. }
  38325. const String getTooltip()
  38326. {
  38327. if (owner.getModel() != 0)
  38328. return owner.getModel()->getTooltipForRow (row);
  38329. return String::empty;
  38330. }
  38331. juce_UseDebuggingNewOperator
  38332. bool neededFlag;
  38333. private:
  38334. ListBox& owner;
  38335. int row;
  38336. bool selected, isDragging, selectRowOnMouseUp;
  38337. ListBoxRowComponent (const ListBoxRowComponent&);
  38338. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38339. };
  38340. class ListViewport : public Viewport
  38341. {
  38342. public:
  38343. int firstIndex, firstWholeIndex, lastWholeIndex;
  38344. bool hasUpdated;
  38345. ListViewport (ListBox& owner_)
  38346. : owner (owner_)
  38347. {
  38348. setWantsKeyboardFocus (false);
  38349. setViewedComponent (new Component());
  38350. getViewedComponent()->addMouseListener (this, false);
  38351. getViewedComponent()->setWantsKeyboardFocus (false);
  38352. }
  38353. ~ListViewport()
  38354. {
  38355. getViewedComponent()->removeMouseListener (this);
  38356. getViewedComponent()->deleteAllChildren();
  38357. }
  38358. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38359. {
  38360. return static_cast <ListBoxRowComponent*>
  38361. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38362. }
  38363. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38364. {
  38365. const int index = getIndexOfChildComponent (rowComponent);
  38366. const int num = getViewedComponent()->getNumChildComponents();
  38367. for (int i = num; --i >= 0;)
  38368. if (((firstIndex + i) % jmax (1, num)) == index)
  38369. return firstIndex + i;
  38370. return -1;
  38371. }
  38372. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38373. {
  38374. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38375. ? getComponentForRow (row) : 0;
  38376. }
  38377. void visibleAreaChanged (int, int, int, int)
  38378. {
  38379. updateVisibleArea (true);
  38380. if (owner.getModel() != 0)
  38381. owner.getModel()->listWasScrolled();
  38382. }
  38383. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38384. {
  38385. hasUpdated = false;
  38386. const int newX = getViewedComponent()->getX();
  38387. int newY = getViewedComponent()->getY();
  38388. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38389. const int newH = owner.totalItems * owner.getRowHeight();
  38390. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38391. newY = getMaximumVisibleHeight() - newH;
  38392. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38393. if (makeSureItUpdatesContent && ! hasUpdated)
  38394. updateContents();
  38395. }
  38396. void updateContents()
  38397. {
  38398. hasUpdated = true;
  38399. const int rowHeight = owner.getRowHeight();
  38400. if (rowHeight > 0)
  38401. {
  38402. const int y = getViewPositionY();
  38403. const int w = getViewedComponent()->getWidth();
  38404. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38405. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38406. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38407. jassert (numNeeded >= 0);
  38408. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38409. {
  38410. Component* const rowToRemove
  38411. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38412. delete rowToRemove;
  38413. }
  38414. firstIndex = y / rowHeight;
  38415. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38416. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38417. for (int i = 0; i < numNeeded; ++i)
  38418. {
  38419. const int row = i + firstIndex;
  38420. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38421. if (rowComp != 0)
  38422. {
  38423. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38424. rowComp->update (row, owner.isRowSelected (row));
  38425. }
  38426. }
  38427. }
  38428. if (owner.headerComponent != 0)
  38429. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38430. owner.outlineThickness,
  38431. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38432. getViewedComponent()->getWidth()),
  38433. owner.headerComponent->getHeight());
  38434. }
  38435. void paint (Graphics& g)
  38436. {
  38437. if (isOpaque())
  38438. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38439. }
  38440. bool keyPressed (const KeyPress& key)
  38441. {
  38442. if (key.isKeyCode (KeyPress::upKey)
  38443. || key.isKeyCode (KeyPress::downKey)
  38444. || key.isKeyCode (KeyPress::pageUpKey)
  38445. || key.isKeyCode (KeyPress::pageDownKey)
  38446. || key.isKeyCode (KeyPress::homeKey)
  38447. || key.isKeyCode (KeyPress::endKey))
  38448. {
  38449. // we want to avoid these keypresses going to the viewport, and instead allow
  38450. // them to pass up to our listbox..
  38451. return false;
  38452. }
  38453. return Viewport::keyPressed (key);
  38454. }
  38455. juce_UseDebuggingNewOperator
  38456. private:
  38457. ListBox& owner;
  38458. ListViewport (const ListViewport&);
  38459. ListViewport& operator= (const ListViewport&);
  38460. };
  38461. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38462. : Component (name),
  38463. model (model_),
  38464. totalItems (0),
  38465. rowHeight (22),
  38466. minimumRowWidth (0),
  38467. outlineThickness (0),
  38468. lastRowSelected (-1),
  38469. mouseMoveSelects (false),
  38470. multipleSelection (false),
  38471. hasDoneInitialUpdate (false)
  38472. {
  38473. addAndMakeVisible (viewport = new ListViewport (*this));
  38474. setWantsKeyboardFocus (true);
  38475. colourChanged();
  38476. }
  38477. ListBox::~ListBox()
  38478. {
  38479. headerComponent = 0;
  38480. viewport = 0;
  38481. }
  38482. void ListBox::setModel (ListBoxModel* const newModel)
  38483. {
  38484. if (model != newModel)
  38485. {
  38486. model = newModel;
  38487. updateContent();
  38488. }
  38489. }
  38490. void ListBox::setMultipleSelectionEnabled (bool b)
  38491. {
  38492. multipleSelection = b;
  38493. }
  38494. void ListBox::setMouseMoveSelectsRows (bool b)
  38495. {
  38496. mouseMoveSelects = b;
  38497. if (b)
  38498. addMouseListener (this, true);
  38499. }
  38500. void ListBox::paint (Graphics& g)
  38501. {
  38502. if (! hasDoneInitialUpdate)
  38503. updateContent();
  38504. g.fillAll (findColour (backgroundColourId));
  38505. }
  38506. void ListBox::paintOverChildren (Graphics& g)
  38507. {
  38508. if (outlineThickness > 0)
  38509. {
  38510. g.setColour (findColour (outlineColourId));
  38511. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38512. }
  38513. }
  38514. void ListBox::resized()
  38515. {
  38516. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38517. outlineThickness,
  38518. outlineThickness,
  38519. outlineThickness));
  38520. viewport->setSingleStepSizes (20, getRowHeight());
  38521. viewport->updateVisibleArea (false);
  38522. }
  38523. void ListBox::visibilityChanged()
  38524. {
  38525. viewport->updateVisibleArea (true);
  38526. }
  38527. Viewport* ListBox::getViewport() const throw()
  38528. {
  38529. return viewport;
  38530. }
  38531. void ListBox::updateContent()
  38532. {
  38533. hasDoneInitialUpdate = true;
  38534. totalItems = (model != 0) ? model->getNumRows() : 0;
  38535. bool selectionChanged = false;
  38536. if (selected [selected.size() - 1] >= totalItems)
  38537. {
  38538. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38539. lastRowSelected = getSelectedRow (0);
  38540. selectionChanged = true;
  38541. }
  38542. viewport->updateVisibleArea (isVisible());
  38543. viewport->resized();
  38544. if (selectionChanged && model != 0)
  38545. model->selectedRowsChanged (lastRowSelected);
  38546. }
  38547. void ListBox::selectRow (const int row,
  38548. bool dontScroll,
  38549. bool deselectOthersFirst)
  38550. {
  38551. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38552. }
  38553. void ListBox::selectRowInternal (const int row,
  38554. bool dontScroll,
  38555. bool deselectOthersFirst,
  38556. bool isMouseClick)
  38557. {
  38558. if (! multipleSelection)
  38559. deselectOthersFirst = true;
  38560. if ((! isRowSelected (row))
  38561. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38562. {
  38563. if (((unsigned int) row) < (unsigned int) totalItems)
  38564. {
  38565. if (deselectOthersFirst)
  38566. selected.clear();
  38567. selected.addRange (Range<int> (row, row + 1));
  38568. if (getHeight() == 0 || getWidth() == 0)
  38569. dontScroll = true;
  38570. viewport->hasUpdated = false;
  38571. if (row < viewport->firstWholeIndex && ! dontScroll)
  38572. {
  38573. viewport->setViewPosition (viewport->getViewPositionX(),
  38574. row * getRowHeight());
  38575. }
  38576. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38577. {
  38578. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38579. if (row >= lastRowSelected + rowsOnScreen
  38580. && rowsOnScreen < totalItems - 1
  38581. && ! isMouseClick)
  38582. {
  38583. viewport->setViewPosition (viewport->getViewPositionX(),
  38584. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38585. * getRowHeight());
  38586. }
  38587. else
  38588. {
  38589. viewport->setViewPosition (viewport->getViewPositionX(),
  38590. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38591. }
  38592. }
  38593. if (! viewport->hasUpdated)
  38594. viewport->updateContents();
  38595. lastRowSelected = row;
  38596. model->selectedRowsChanged (row);
  38597. }
  38598. else
  38599. {
  38600. if (deselectOthersFirst)
  38601. deselectAllRows();
  38602. }
  38603. }
  38604. }
  38605. void ListBox::deselectRow (const int row)
  38606. {
  38607. if (selected.contains (row))
  38608. {
  38609. selected.removeRange (Range <int> (row, row + 1));
  38610. if (row == lastRowSelected)
  38611. lastRowSelected = getSelectedRow (0);
  38612. viewport->updateContents();
  38613. model->selectedRowsChanged (lastRowSelected);
  38614. }
  38615. }
  38616. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38617. const bool sendNotificationEventToModel)
  38618. {
  38619. selected = setOfRowsToBeSelected;
  38620. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38621. if (! isRowSelected (lastRowSelected))
  38622. lastRowSelected = getSelectedRow (0);
  38623. viewport->updateContents();
  38624. if ((model != 0) && sendNotificationEventToModel)
  38625. model->selectedRowsChanged (lastRowSelected);
  38626. }
  38627. const SparseSet<int> ListBox::getSelectedRows() const
  38628. {
  38629. return selected;
  38630. }
  38631. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38632. {
  38633. if (multipleSelection && (firstRow != lastRow))
  38634. {
  38635. const int numRows = totalItems - 1;
  38636. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38637. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38638. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38639. jmax (firstRow, lastRow) + 1));
  38640. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38641. }
  38642. selectRowInternal (lastRow, false, false, true);
  38643. }
  38644. void ListBox::flipRowSelection (const int row)
  38645. {
  38646. if (isRowSelected (row))
  38647. deselectRow (row);
  38648. else
  38649. selectRowInternal (row, false, false, true);
  38650. }
  38651. void ListBox::deselectAllRows()
  38652. {
  38653. if (! selected.isEmpty())
  38654. {
  38655. selected.clear();
  38656. lastRowSelected = -1;
  38657. viewport->updateContents();
  38658. if (model != 0)
  38659. model->selectedRowsChanged (lastRowSelected);
  38660. }
  38661. }
  38662. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38663. const ModifierKeys& mods)
  38664. {
  38665. if (multipleSelection && mods.isCommandDown())
  38666. {
  38667. flipRowSelection (row);
  38668. }
  38669. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38670. {
  38671. selectRangeOfRows (lastRowSelected, row);
  38672. }
  38673. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38674. {
  38675. selectRowInternal (row, false, true, true);
  38676. }
  38677. }
  38678. int ListBox::getNumSelectedRows() const
  38679. {
  38680. return selected.size();
  38681. }
  38682. int ListBox::getSelectedRow (const int index) const
  38683. {
  38684. return (((unsigned int) index) < (unsigned int) selected.size())
  38685. ? selected [index] : -1;
  38686. }
  38687. bool ListBox::isRowSelected (const int row) const
  38688. {
  38689. return selected.contains (row);
  38690. }
  38691. int ListBox::getLastRowSelected() const
  38692. {
  38693. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38694. }
  38695. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38696. {
  38697. if (((unsigned int) x) < (unsigned int) getWidth())
  38698. {
  38699. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38700. if (((unsigned int) row) < (unsigned int) totalItems)
  38701. return row;
  38702. }
  38703. return -1;
  38704. }
  38705. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38706. {
  38707. if (((unsigned int) x) < (unsigned int) getWidth())
  38708. {
  38709. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38710. return jlimit (0, totalItems, row);
  38711. }
  38712. return -1;
  38713. }
  38714. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38715. {
  38716. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38717. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38718. }
  38719. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38720. {
  38721. return viewport->getRowNumberOfComponent (rowComponent);
  38722. }
  38723. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38724. const bool relativeToComponentTopLeft) const throw()
  38725. {
  38726. int y = viewport->getY() + rowHeight * rowNumber;
  38727. if (relativeToComponentTopLeft)
  38728. y -= viewport->getViewPositionY();
  38729. return Rectangle<int> (viewport->getX(), y,
  38730. viewport->getViewedComponent()->getWidth(), rowHeight);
  38731. }
  38732. void ListBox::setVerticalPosition (const double proportion)
  38733. {
  38734. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38735. viewport->setViewPosition (viewport->getViewPositionX(),
  38736. jmax (0, roundToInt (proportion * offscreen)));
  38737. }
  38738. double ListBox::getVerticalPosition() const
  38739. {
  38740. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38741. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38742. : 0;
  38743. }
  38744. int ListBox::getVisibleRowWidth() const throw()
  38745. {
  38746. return viewport->getViewWidth();
  38747. }
  38748. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38749. {
  38750. if (row < viewport->firstWholeIndex)
  38751. {
  38752. viewport->setViewPosition (viewport->getViewPositionX(),
  38753. row * getRowHeight());
  38754. }
  38755. else if (row >= viewport->lastWholeIndex)
  38756. {
  38757. viewport->setViewPosition (viewport->getViewPositionX(),
  38758. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38759. }
  38760. }
  38761. bool ListBox::keyPressed (const KeyPress& key)
  38762. {
  38763. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38764. const bool multiple = multipleSelection
  38765. && (lastRowSelected >= 0)
  38766. && (key.getModifiers().isShiftDown()
  38767. || key.getModifiers().isCtrlDown()
  38768. || key.getModifiers().isCommandDown());
  38769. if (key.isKeyCode (KeyPress::upKey))
  38770. {
  38771. if (multiple)
  38772. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38773. else
  38774. selectRow (jmax (0, lastRowSelected - 1));
  38775. }
  38776. else if (key.isKeyCode (KeyPress::returnKey)
  38777. && isRowSelected (lastRowSelected))
  38778. {
  38779. if (model != 0)
  38780. model->returnKeyPressed (lastRowSelected);
  38781. }
  38782. else if (key.isKeyCode (KeyPress::pageUpKey))
  38783. {
  38784. if (multiple)
  38785. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38786. else
  38787. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38788. }
  38789. else if (key.isKeyCode (KeyPress::pageDownKey))
  38790. {
  38791. if (multiple)
  38792. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38793. else
  38794. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38795. }
  38796. else if (key.isKeyCode (KeyPress::homeKey))
  38797. {
  38798. if (multiple && key.getModifiers().isShiftDown())
  38799. selectRangeOfRows (lastRowSelected, 0);
  38800. else
  38801. selectRow (0);
  38802. }
  38803. else if (key.isKeyCode (KeyPress::endKey))
  38804. {
  38805. if (multiple && key.getModifiers().isShiftDown())
  38806. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38807. else
  38808. selectRow (totalItems - 1);
  38809. }
  38810. else if (key.isKeyCode (KeyPress::downKey))
  38811. {
  38812. if (multiple)
  38813. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38814. else
  38815. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38816. }
  38817. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38818. && isRowSelected (lastRowSelected))
  38819. {
  38820. if (model != 0)
  38821. model->deleteKeyPressed (lastRowSelected);
  38822. }
  38823. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38824. {
  38825. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38826. }
  38827. else
  38828. {
  38829. return false;
  38830. }
  38831. return true;
  38832. }
  38833. bool ListBox::keyStateChanged (const bool isKeyDown)
  38834. {
  38835. return isKeyDown
  38836. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38837. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38838. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38839. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38840. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38841. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38842. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38843. }
  38844. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38845. {
  38846. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38847. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38848. }
  38849. void ListBox::mouseMove (const MouseEvent& e)
  38850. {
  38851. if (mouseMoveSelects)
  38852. {
  38853. const MouseEvent e2 (e.getEventRelativeTo (this));
  38854. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38855. }
  38856. }
  38857. void ListBox::mouseExit (const MouseEvent& e)
  38858. {
  38859. mouseMove (e);
  38860. }
  38861. void ListBox::mouseUp (const MouseEvent& e)
  38862. {
  38863. if (e.mouseWasClicked() && model != 0)
  38864. model->backgroundClicked();
  38865. }
  38866. void ListBox::setRowHeight (const int newHeight)
  38867. {
  38868. rowHeight = jmax (1, newHeight);
  38869. viewport->setSingleStepSizes (20, rowHeight);
  38870. updateContent();
  38871. }
  38872. int ListBox::getNumRowsOnScreen() const throw()
  38873. {
  38874. return viewport->getMaximumVisibleHeight() / rowHeight;
  38875. }
  38876. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38877. {
  38878. minimumRowWidth = newMinimumWidth;
  38879. updateContent();
  38880. }
  38881. int ListBox::getVisibleContentWidth() const throw()
  38882. {
  38883. return viewport->getMaximumVisibleWidth();
  38884. }
  38885. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38886. {
  38887. return viewport->getVerticalScrollBar();
  38888. }
  38889. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38890. {
  38891. return viewport->getHorizontalScrollBar();
  38892. }
  38893. void ListBox::colourChanged()
  38894. {
  38895. setOpaque (findColour (backgroundColourId).isOpaque());
  38896. viewport->setOpaque (isOpaque());
  38897. repaint();
  38898. }
  38899. void ListBox::setOutlineThickness (const int outlineThickness_)
  38900. {
  38901. outlineThickness = outlineThickness_;
  38902. resized();
  38903. }
  38904. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38905. {
  38906. if (newHeaderComponent != headerComponent)
  38907. {
  38908. headerComponent = newHeaderComponent;
  38909. addAndMakeVisible (newHeaderComponent);
  38910. ListBox::resized();
  38911. }
  38912. }
  38913. void ListBox::repaintRow (const int rowNumber) throw()
  38914. {
  38915. repaint (getRowPosition (rowNumber, true));
  38916. }
  38917. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38918. {
  38919. Rectangle<int> imageArea;
  38920. const int firstRow = getRowContainingPosition (0, 0);
  38921. int i;
  38922. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38923. {
  38924. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38925. if (rowComp != 0 && isRowSelected (firstRow + i))
  38926. {
  38927. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38928. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38929. imageArea = imageArea.getUnion (rowRect);
  38930. }
  38931. }
  38932. imageArea = imageArea.getIntersection (getLocalBounds());
  38933. imageX = imageArea.getX();
  38934. imageY = imageArea.getY();
  38935. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38936. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38937. {
  38938. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38939. if (rowComp != 0 && isRowSelected (firstRow + i))
  38940. {
  38941. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38942. Graphics g (snapshot);
  38943. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38944. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38945. rowComp->paintEntireComponent (g);
  38946. }
  38947. }
  38948. return snapshot;
  38949. }
  38950. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38951. {
  38952. DragAndDropContainer* const dragContainer
  38953. = DragAndDropContainer::findParentDragContainerFor (this);
  38954. if (dragContainer != 0)
  38955. {
  38956. int x, y;
  38957. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38958. dragImage.multiplyAllAlphas (0.6f);
  38959. MouseEvent e2 (e.getEventRelativeTo (this));
  38960. const Point<int> p (x - e2.x, y - e2.y);
  38961. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38962. }
  38963. else
  38964. {
  38965. // to be able to do a drag-and-drop operation, the listbox needs to
  38966. // be inside a component which is also a DragAndDropContainer.
  38967. jassertfalse;
  38968. }
  38969. }
  38970. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38971. {
  38972. (void) existingComponentToUpdate;
  38973. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38974. return 0;
  38975. }
  38976. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38977. {
  38978. }
  38979. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38980. {
  38981. }
  38982. void ListBoxModel::backgroundClicked()
  38983. {
  38984. }
  38985. void ListBoxModel::selectedRowsChanged (int)
  38986. {
  38987. }
  38988. void ListBoxModel::deleteKeyPressed (int)
  38989. {
  38990. }
  38991. void ListBoxModel::returnKeyPressed (int)
  38992. {
  38993. }
  38994. void ListBoxModel::listWasScrolled()
  38995. {
  38996. }
  38997. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38998. {
  38999. return String::empty;
  39000. }
  39001. const String ListBoxModel::getTooltipForRow (int)
  39002. {
  39003. return String::empty;
  39004. }
  39005. END_JUCE_NAMESPACE
  39006. /*** End of inlined file: juce_ListBox.cpp ***/
  39007. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39008. BEGIN_JUCE_NAMESPACE
  39009. ProgressBar::ProgressBar (double& progress_)
  39010. : progress (progress_),
  39011. displayPercentage (true),
  39012. lastCallbackTime (0)
  39013. {
  39014. currentValue = jlimit (0.0, 1.0, progress);
  39015. }
  39016. ProgressBar::~ProgressBar()
  39017. {
  39018. }
  39019. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39020. {
  39021. displayPercentage = shouldDisplayPercentage;
  39022. repaint();
  39023. }
  39024. void ProgressBar::setTextToDisplay (const String& text)
  39025. {
  39026. displayPercentage = false;
  39027. displayedMessage = text;
  39028. }
  39029. void ProgressBar::lookAndFeelChanged()
  39030. {
  39031. setOpaque (findColour (backgroundColourId).isOpaque());
  39032. }
  39033. void ProgressBar::colourChanged()
  39034. {
  39035. lookAndFeelChanged();
  39036. }
  39037. void ProgressBar::paint (Graphics& g)
  39038. {
  39039. String text;
  39040. if (displayPercentage)
  39041. {
  39042. if (currentValue >= 0 && currentValue <= 1.0)
  39043. text << roundToInt (currentValue * 100.0) << '%';
  39044. }
  39045. else
  39046. {
  39047. text = displayedMessage;
  39048. }
  39049. getLookAndFeel().drawProgressBar (g, *this,
  39050. getWidth(), getHeight(),
  39051. currentValue, text);
  39052. }
  39053. void ProgressBar::visibilityChanged()
  39054. {
  39055. if (isVisible())
  39056. startTimer (30);
  39057. else
  39058. stopTimer();
  39059. }
  39060. void ProgressBar::timerCallback()
  39061. {
  39062. double newProgress = progress;
  39063. const uint32 now = Time::getMillisecondCounter();
  39064. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39065. lastCallbackTime = now;
  39066. if (currentValue != newProgress
  39067. || newProgress < 0 || newProgress >= 1.0
  39068. || currentMessage != displayedMessage)
  39069. {
  39070. if (currentValue < newProgress
  39071. && newProgress >= 0 && newProgress < 1.0
  39072. && currentValue >= 0 && currentValue < 1.0)
  39073. {
  39074. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39075. newProgress);
  39076. }
  39077. currentValue = newProgress;
  39078. currentMessage = displayedMessage;
  39079. repaint();
  39080. }
  39081. }
  39082. END_JUCE_NAMESPACE
  39083. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39084. /*** Start of inlined file: juce_Slider.cpp ***/
  39085. BEGIN_JUCE_NAMESPACE
  39086. class SliderPopupDisplayComponent : public BubbleComponent
  39087. {
  39088. public:
  39089. SliderPopupDisplayComponent (Slider* const owner_)
  39090. : owner (owner_),
  39091. font (15.0f, Font::bold)
  39092. {
  39093. setAlwaysOnTop (true);
  39094. }
  39095. ~SliderPopupDisplayComponent()
  39096. {
  39097. }
  39098. void paintContent (Graphics& g, int w, int h)
  39099. {
  39100. g.setFont (font);
  39101. g.setColour (Colours::black);
  39102. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39103. }
  39104. void getContentSize (int& w, int& h)
  39105. {
  39106. w = font.getStringWidth (text) + 18;
  39107. h = (int) (font.getHeight() * 1.6f);
  39108. }
  39109. void updatePosition (const String& newText)
  39110. {
  39111. if (text != newText)
  39112. {
  39113. text = newText;
  39114. repaint();
  39115. }
  39116. BubbleComponent::setPosition (owner);
  39117. }
  39118. juce_UseDebuggingNewOperator
  39119. private:
  39120. Slider* owner;
  39121. Font font;
  39122. String text;
  39123. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39124. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39125. };
  39126. Slider::Slider (const String& name)
  39127. : Component (name),
  39128. lastCurrentValue (0),
  39129. lastValueMin (0),
  39130. lastValueMax (0),
  39131. minimum (0),
  39132. maximum (10),
  39133. interval (0),
  39134. skewFactor (1.0),
  39135. velocityModeSensitivity (1.0),
  39136. velocityModeOffset (0.0),
  39137. velocityModeThreshold (1),
  39138. rotaryStart (float_Pi * 1.2f),
  39139. rotaryEnd (float_Pi * 2.8f),
  39140. numDecimalPlaces (7),
  39141. sliderRegionStart (0),
  39142. sliderRegionSize (1),
  39143. sliderBeingDragged (-1),
  39144. pixelsForFullDragExtent (250),
  39145. style (LinearHorizontal),
  39146. textBoxPos (TextBoxLeft),
  39147. textBoxWidth (80),
  39148. textBoxHeight (20),
  39149. incDecButtonMode (incDecButtonsNotDraggable),
  39150. editableText (true),
  39151. doubleClickToValue (false),
  39152. isVelocityBased (false),
  39153. userKeyOverridesVelocity (true),
  39154. rotaryStop (true),
  39155. incDecButtonsSideBySide (false),
  39156. sendChangeOnlyOnRelease (false),
  39157. popupDisplayEnabled (false),
  39158. menuEnabled (false),
  39159. menuShown (false),
  39160. scrollWheelEnabled (true),
  39161. snapsToMousePos (true),
  39162. valueBox (0),
  39163. incButton (0),
  39164. decButton (0),
  39165. popupDisplay (0),
  39166. parentForPopupDisplay (0)
  39167. {
  39168. setWantsKeyboardFocus (false);
  39169. setRepaintsOnMouseActivity (true);
  39170. lookAndFeelChanged();
  39171. updateText();
  39172. currentValue.addListener (this);
  39173. valueMin.addListener (this);
  39174. valueMax.addListener (this);
  39175. }
  39176. Slider::~Slider()
  39177. {
  39178. currentValue.removeListener (this);
  39179. valueMin.removeListener (this);
  39180. valueMax.removeListener (this);
  39181. popupDisplay = 0;
  39182. deleteAllChildren();
  39183. }
  39184. void Slider::handleAsyncUpdate()
  39185. {
  39186. cancelPendingUpdate();
  39187. Component::BailOutChecker checker (this);
  39188. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39189. }
  39190. void Slider::sendDragStart()
  39191. {
  39192. startedDragging();
  39193. Component::BailOutChecker checker (this);
  39194. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39195. }
  39196. void Slider::sendDragEnd()
  39197. {
  39198. stoppedDragging();
  39199. sliderBeingDragged = -1;
  39200. Component::BailOutChecker checker (this);
  39201. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39202. }
  39203. void Slider::addListener (Listener* const listener)
  39204. {
  39205. listeners.add (listener);
  39206. }
  39207. void Slider::removeListener (Listener* const listener)
  39208. {
  39209. listeners.remove (listener);
  39210. }
  39211. void Slider::setSliderStyle (const SliderStyle newStyle)
  39212. {
  39213. if (style != newStyle)
  39214. {
  39215. style = newStyle;
  39216. repaint();
  39217. lookAndFeelChanged();
  39218. }
  39219. }
  39220. void Slider::setRotaryParameters (const float startAngleRadians,
  39221. const float endAngleRadians,
  39222. const bool stopAtEnd)
  39223. {
  39224. // make sure the values are sensible..
  39225. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39226. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39227. jassert (rotaryStart < rotaryEnd);
  39228. rotaryStart = startAngleRadians;
  39229. rotaryEnd = endAngleRadians;
  39230. rotaryStop = stopAtEnd;
  39231. }
  39232. void Slider::setVelocityBasedMode (const bool velBased)
  39233. {
  39234. isVelocityBased = velBased;
  39235. }
  39236. void Slider::setVelocityModeParameters (const double sensitivity,
  39237. const int threshold,
  39238. const double offset,
  39239. const bool userCanPressKeyToSwapMode)
  39240. {
  39241. jassert (threshold >= 0);
  39242. jassert (sensitivity > 0);
  39243. jassert (offset >= 0);
  39244. velocityModeSensitivity = sensitivity;
  39245. velocityModeOffset = offset;
  39246. velocityModeThreshold = threshold;
  39247. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39248. }
  39249. void Slider::setSkewFactor (const double factor)
  39250. {
  39251. skewFactor = factor;
  39252. }
  39253. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39254. {
  39255. if (maximum > minimum)
  39256. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39257. / (maximum - minimum));
  39258. }
  39259. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39260. {
  39261. jassert (distanceForFullScaleDrag > 0);
  39262. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39263. }
  39264. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39265. {
  39266. if (incDecButtonMode != mode)
  39267. {
  39268. incDecButtonMode = mode;
  39269. lookAndFeelChanged();
  39270. }
  39271. }
  39272. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39273. const bool isReadOnly,
  39274. const int textEntryBoxWidth,
  39275. const int textEntryBoxHeight)
  39276. {
  39277. if (textBoxPos != newPosition
  39278. || editableText != (! isReadOnly)
  39279. || textBoxWidth != textEntryBoxWidth
  39280. || textBoxHeight != textEntryBoxHeight)
  39281. {
  39282. textBoxPos = newPosition;
  39283. editableText = ! isReadOnly;
  39284. textBoxWidth = textEntryBoxWidth;
  39285. textBoxHeight = textEntryBoxHeight;
  39286. repaint();
  39287. lookAndFeelChanged();
  39288. }
  39289. }
  39290. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39291. {
  39292. editableText = shouldBeEditable;
  39293. if (valueBox != 0)
  39294. valueBox->setEditable (shouldBeEditable && isEnabled());
  39295. }
  39296. void Slider::showTextBox()
  39297. {
  39298. jassert (editableText); // this should probably be avoided in read-only sliders.
  39299. if (valueBox != 0)
  39300. valueBox->showEditor();
  39301. }
  39302. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39303. {
  39304. if (valueBox != 0)
  39305. {
  39306. valueBox->hideEditor (discardCurrentEditorContents);
  39307. if (discardCurrentEditorContents)
  39308. updateText();
  39309. }
  39310. }
  39311. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39312. {
  39313. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39314. }
  39315. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39316. {
  39317. snapsToMousePos = shouldSnapToMouse;
  39318. }
  39319. void Slider::setPopupDisplayEnabled (const bool enabled,
  39320. Component* const parentComponentToUse)
  39321. {
  39322. popupDisplayEnabled = enabled;
  39323. parentForPopupDisplay = parentComponentToUse;
  39324. }
  39325. void Slider::colourChanged()
  39326. {
  39327. lookAndFeelChanged();
  39328. }
  39329. void Slider::lookAndFeelChanged()
  39330. {
  39331. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39332. : getTextFromValue (currentValue.getValue()));
  39333. deleteAllChildren();
  39334. valueBox = 0;
  39335. LookAndFeel& lf = getLookAndFeel();
  39336. if (textBoxPos != NoTextBox)
  39337. {
  39338. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39339. valueBox->setWantsKeyboardFocus (false);
  39340. valueBox->setText (previousTextBoxContent, false);
  39341. valueBox->setEditable (editableText && isEnabled());
  39342. valueBox->addListener (this);
  39343. if (style == LinearBar)
  39344. valueBox->addMouseListener (this, false);
  39345. valueBox->setTooltip (getTooltip());
  39346. }
  39347. if (style == IncDecButtons)
  39348. {
  39349. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39350. incButton->addButtonListener (this);
  39351. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39352. decButton->addButtonListener (this);
  39353. if (incDecButtonMode != incDecButtonsNotDraggable)
  39354. {
  39355. incButton->addMouseListener (this, false);
  39356. decButton->addMouseListener (this, false);
  39357. }
  39358. else
  39359. {
  39360. incButton->setRepeatSpeed (300, 100, 20);
  39361. incButton->addMouseListener (decButton, false);
  39362. decButton->setRepeatSpeed (300, 100, 20);
  39363. decButton->addMouseListener (incButton, false);
  39364. }
  39365. incButton->setTooltip (getTooltip());
  39366. decButton->setTooltip (getTooltip());
  39367. }
  39368. setComponentEffect (lf.getSliderEffect());
  39369. resized();
  39370. repaint();
  39371. }
  39372. void Slider::setRange (const double newMin,
  39373. const double newMax,
  39374. const double newInt)
  39375. {
  39376. if (minimum != newMin
  39377. || maximum != newMax
  39378. || interval != newInt)
  39379. {
  39380. minimum = newMin;
  39381. maximum = newMax;
  39382. interval = newInt;
  39383. // figure out the number of DPs needed to display all values at this
  39384. // interval setting.
  39385. numDecimalPlaces = 7;
  39386. if (newInt != 0)
  39387. {
  39388. int v = abs ((int) (newInt * 10000000));
  39389. while ((v % 10) == 0)
  39390. {
  39391. --numDecimalPlaces;
  39392. v /= 10;
  39393. }
  39394. }
  39395. // keep the current values inside the new range..
  39396. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39397. {
  39398. setValue (getValue(), false, false);
  39399. }
  39400. else
  39401. {
  39402. setMinValue (getMinValue(), false, false);
  39403. setMaxValue (getMaxValue(), false, false);
  39404. }
  39405. updateText();
  39406. }
  39407. }
  39408. void Slider::triggerChangeMessage (const bool synchronous)
  39409. {
  39410. if (synchronous)
  39411. handleAsyncUpdate();
  39412. else
  39413. triggerAsyncUpdate();
  39414. valueChanged();
  39415. }
  39416. void Slider::valueChanged (Value& value)
  39417. {
  39418. if (value.refersToSameSourceAs (currentValue))
  39419. {
  39420. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39421. setValue (currentValue.getValue(), false, false);
  39422. }
  39423. else if (value.refersToSameSourceAs (valueMin))
  39424. setMinValue (valueMin.getValue(), false, false, true);
  39425. else if (value.refersToSameSourceAs (valueMax))
  39426. setMaxValue (valueMax.getValue(), false, false, true);
  39427. }
  39428. double Slider::getValue() const
  39429. {
  39430. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39431. // methods to get the two values.
  39432. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39433. return currentValue.getValue();
  39434. }
  39435. void Slider::setValue (double newValue,
  39436. const bool sendUpdateMessage,
  39437. const bool sendMessageSynchronously)
  39438. {
  39439. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39440. // methods to set the two values.
  39441. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39442. newValue = constrainedValue (newValue);
  39443. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39444. {
  39445. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39446. newValue = jlimit ((double) valueMin.getValue(),
  39447. (double) valueMax.getValue(),
  39448. newValue);
  39449. }
  39450. if (newValue != lastCurrentValue)
  39451. {
  39452. if (valueBox != 0)
  39453. valueBox->hideEditor (true);
  39454. lastCurrentValue = newValue;
  39455. currentValue = newValue;
  39456. updateText();
  39457. repaint();
  39458. if (popupDisplay != 0)
  39459. {
  39460. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39461. ->updatePosition (getTextFromValue (newValue));
  39462. popupDisplay->repaint();
  39463. }
  39464. if (sendUpdateMessage)
  39465. triggerChangeMessage (sendMessageSynchronously);
  39466. }
  39467. }
  39468. double Slider::getMinValue() const
  39469. {
  39470. // The minimum value only applies to sliders that are in two- or three-value mode.
  39471. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39472. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39473. return valueMin.getValue();
  39474. }
  39475. double Slider::getMaxValue() const
  39476. {
  39477. // The maximum value only applies to sliders that are in two- or three-value mode.
  39478. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39479. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39480. return valueMax.getValue();
  39481. }
  39482. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39483. {
  39484. // The minimum value only applies to sliders that are in two- or three-value mode.
  39485. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39486. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39487. newValue = constrainedValue (newValue);
  39488. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39489. {
  39490. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39491. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39492. newValue = jmin ((double) valueMax.getValue(), newValue);
  39493. }
  39494. else
  39495. {
  39496. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39497. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39498. newValue = jmin (lastCurrentValue, newValue);
  39499. }
  39500. if (lastValueMin != newValue)
  39501. {
  39502. lastValueMin = newValue;
  39503. valueMin = newValue;
  39504. repaint();
  39505. if (popupDisplay != 0)
  39506. {
  39507. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39508. ->updatePosition (getTextFromValue (newValue));
  39509. popupDisplay->repaint();
  39510. }
  39511. if (sendUpdateMessage)
  39512. triggerChangeMessage (sendMessageSynchronously);
  39513. }
  39514. }
  39515. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39516. {
  39517. // The maximum value only applies to sliders that are in two- or three-value mode.
  39518. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39519. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39520. newValue = constrainedValue (newValue);
  39521. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39522. {
  39523. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39524. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39525. newValue = jmax ((double) valueMin.getValue(), newValue);
  39526. }
  39527. else
  39528. {
  39529. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39530. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39531. newValue = jmax (lastCurrentValue, newValue);
  39532. }
  39533. if (lastValueMax != newValue)
  39534. {
  39535. lastValueMax = newValue;
  39536. valueMax = newValue;
  39537. repaint();
  39538. if (popupDisplay != 0)
  39539. {
  39540. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39541. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39542. popupDisplay->repaint();
  39543. }
  39544. if (sendUpdateMessage)
  39545. triggerChangeMessage (sendMessageSynchronously);
  39546. }
  39547. }
  39548. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39549. const double valueToSetOnDoubleClick)
  39550. {
  39551. doubleClickToValue = isDoubleClickEnabled;
  39552. doubleClickReturnValue = valueToSetOnDoubleClick;
  39553. }
  39554. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39555. {
  39556. isEnabled_ = doubleClickToValue;
  39557. return doubleClickReturnValue;
  39558. }
  39559. void Slider::updateText()
  39560. {
  39561. if (valueBox != 0)
  39562. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39563. }
  39564. void Slider::setTextValueSuffix (const String& suffix)
  39565. {
  39566. if (textSuffix != suffix)
  39567. {
  39568. textSuffix = suffix;
  39569. updateText();
  39570. }
  39571. }
  39572. const String Slider::getTextValueSuffix() const
  39573. {
  39574. return textSuffix;
  39575. }
  39576. const String Slider::getTextFromValue (double v)
  39577. {
  39578. if (getNumDecimalPlacesToDisplay() > 0)
  39579. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39580. else
  39581. return String (roundToInt (v)) + getTextValueSuffix();
  39582. }
  39583. double Slider::getValueFromText (const String& text)
  39584. {
  39585. String t (text.trimStart());
  39586. if (t.endsWith (textSuffix))
  39587. t = t.substring (0, t.length() - textSuffix.length());
  39588. while (t.startsWithChar ('+'))
  39589. t = t.substring (1).trimStart();
  39590. return t.initialSectionContainingOnly ("0123456789.,-")
  39591. .getDoubleValue();
  39592. }
  39593. double Slider::proportionOfLengthToValue (double proportion)
  39594. {
  39595. if (skewFactor != 1.0 && proportion > 0.0)
  39596. proportion = exp (log (proportion) / skewFactor);
  39597. return minimum + (maximum - minimum) * proportion;
  39598. }
  39599. double Slider::valueToProportionOfLength (double value)
  39600. {
  39601. const double n = (value - minimum) / (maximum - minimum);
  39602. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39603. }
  39604. double Slider::snapValue (double attemptedValue, const bool)
  39605. {
  39606. return attemptedValue;
  39607. }
  39608. void Slider::startedDragging()
  39609. {
  39610. }
  39611. void Slider::stoppedDragging()
  39612. {
  39613. }
  39614. void Slider::valueChanged()
  39615. {
  39616. }
  39617. void Slider::enablementChanged()
  39618. {
  39619. repaint();
  39620. }
  39621. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39622. {
  39623. menuEnabled = menuEnabled_;
  39624. }
  39625. void Slider::setScrollWheelEnabled (const bool enabled)
  39626. {
  39627. scrollWheelEnabled = enabled;
  39628. }
  39629. void Slider::labelTextChanged (Label* label)
  39630. {
  39631. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39632. if (newValue != (double) currentValue.getValue())
  39633. {
  39634. sendDragStart();
  39635. setValue (newValue, true, true);
  39636. sendDragEnd();
  39637. }
  39638. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39639. }
  39640. void Slider::buttonClicked (Button* button)
  39641. {
  39642. if (style == IncDecButtons)
  39643. {
  39644. sendDragStart();
  39645. if (button == incButton)
  39646. setValue (snapValue (getValue() + interval, false), true, true);
  39647. else if (button == decButton)
  39648. setValue (snapValue (getValue() - interval, false), true, true);
  39649. sendDragEnd();
  39650. }
  39651. }
  39652. double Slider::constrainedValue (double value) const
  39653. {
  39654. if (interval > 0)
  39655. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39656. if (value <= minimum || maximum <= minimum)
  39657. value = minimum;
  39658. else if (value >= maximum)
  39659. value = maximum;
  39660. return value;
  39661. }
  39662. float Slider::getLinearSliderPos (const double value)
  39663. {
  39664. double sliderPosProportional;
  39665. if (maximum > minimum)
  39666. {
  39667. if (value < minimum)
  39668. {
  39669. sliderPosProportional = 0.0;
  39670. }
  39671. else if (value > maximum)
  39672. {
  39673. sliderPosProportional = 1.0;
  39674. }
  39675. else
  39676. {
  39677. sliderPosProportional = valueToProportionOfLength (value);
  39678. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39679. }
  39680. }
  39681. else
  39682. {
  39683. sliderPosProportional = 0.5;
  39684. }
  39685. if (isVertical() || style == IncDecButtons)
  39686. sliderPosProportional = 1.0 - sliderPosProportional;
  39687. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39688. }
  39689. bool Slider::isHorizontal() const
  39690. {
  39691. return style == LinearHorizontal
  39692. || style == LinearBar
  39693. || style == TwoValueHorizontal
  39694. || style == ThreeValueHorizontal;
  39695. }
  39696. bool Slider::isVertical() const
  39697. {
  39698. return style == LinearVertical
  39699. || style == TwoValueVertical
  39700. || style == ThreeValueVertical;
  39701. }
  39702. bool Slider::incDecDragDirectionIsHorizontal() const
  39703. {
  39704. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39705. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39706. }
  39707. float Slider::getPositionOfValue (const double value)
  39708. {
  39709. if (isHorizontal() || isVertical())
  39710. {
  39711. return getLinearSliderPos (value);
  39712. }
  39713. else
  39714. {
  39715. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39716. return 0.0f;
  39717. }
  39718. }
  39719. void Slider::paint (Graphics& g)
  39720. {
  39721. if (style != IncDecButtons)
  39722. {
  39723. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39724. {
  39725. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39726. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39727. getLookAndFeel().drawRotarySlider (g,
  39728. sliderRect.getX(),
  39729. sliderRect.getY(),
  39730. sliderRect.getWidth(),
  39731. sliderRect.getHeight(),
  39732. sliderPos,
  39733. rotaryStart, rotaryEnd,
  39734. *this);
  39735. }
  39736. else
  39737. {
  39738. getLookAndFeel().drawLinearSlider (g,
  39739. sliderRect.getX(),
  39740. sliderRect.getY(),
  39741. sliderRect.getWidth(),
  39742. sliderRect.getHeight(),
  39743. getLinearSliderPos (lastCurrentValue),
  39744. getLinearSliderPos (lastValueMin),
  39745. getLinearSliderPos (lastValueMax),
  39746. style,
  39747. *this);
  39748. }
  39749. if (style == LinearBar && valueBox == 0)
  39750. {
  39751. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39752. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39753. }
  39754. }
  39755. }
  39756. void Slider::resized()
  39757. {
  39758. int minXSpace = 0;
  39759. int minYSpace = 0;
  39760. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39761. minXSpace = 30;
  39762. else
  39763. minYSpace = 15;
  39764. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39765. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39766. if (style == LinearBar)
  39767. {
  39768. if (valueBox != 0)
  39769. valueBox->setBounds (getLocalBounds());
  39770. }
  39771. else
  39772. {
  39773. if (textBoxPos == NoTextBox)
  39774. {
  39775. sliderRect = getLocalBounds();
  39776. }
  39777. else if (textBoxPos == TextBoxLeft)
  39778. {
  39779. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39780. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39781. }
  39782. else if (textBoxPos == TextBoxRight)
  39783. {
  39784. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39785. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39786. }
  39787. else if (textBoxPos == TextBoxAbove)
  39788. {
  39789. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39790. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39791. }
  39792. else if (textBoxPos == TextBoxBelow)
  39793. {
  39794. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39795. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39796. }
  39797. }
  39798. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39799. if (style == LinearBar)
  39800. {
  39801. const int barIndent = 1;
  39802. sliderRegionStart = barIndent;
  39803. sliderRegionSize = getWidth() - barIndent * 2;
  39804. sliderRect.setBounds (sliderRegionStart, barIndent,
  39805. sliderRegionSize, getHeight() - barIndent * 2);
  39806. }
  39807. else if (isHorizontal())
  39808. {
  39809. sliderRegionStart = sliderRect.getX() + indent;
  39810. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39811. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39812. sliderRegionSize, sliderRect.getHeight());
  39813. }
  39814. else if (isVertical())
  39815. {
  39816. sliderRegionStart = sliderRect.getY() + indent;
  39817. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39818. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39819. sliderRect.getWidth(), sliderRegionSize);
  39820. }
  39821. else
  39822. {
  39823. sliderRegionStart = 0;
  39824. sliderRegionSize = 100;
  39825. }
  39826. if (style == IncDecButtons)
  39827. {
  39828. Rectangle<int> buttonRect (sliderRect);
  39829. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39830. buttonRect.expand (-2, 0);
  39831. else
  39832. buttonRect.expand (0, -2);
  39833. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39834. if (incDecButtonsSideBySide)
  39835. {
  39836. decButton->setBounds (buttonRect.getX(),
  39837. buttonRect.getY(),
  39838. buttonRect.getWidth() / 2,
  39839. buttonRect.getHeight());
  39840. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39841. incButton->setBounds (buttonRect.getCentreX(),
  39842. buttonRect.getY(),
  39843. buttonRect.getWidth() / 2,
  39844. buttonRect.getHeight());
  39845. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39846. }
  39847. else
  39848. {
  39849. incButton->setBounds (buttonRect.getX(),
  39850. buttonRect.getY(),
  39851. buttonRect.getWidth(),
  39852. buttonRect.getHeight() / 2);
  39853. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39854. decButton->setBounds (buttonRect.getX(),
  39855. buttonRect.getCentreY(),
  39856. buttonRect.getWidth(),
  39857. buttonRect.getHeight() / 2);
  39858. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39859. }
  39860. }
  39861. }
  39862. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39863. {
  39864. repaint();
  39865. }
  39866. void Slider::mouseDown (const MouseEvent& e)
  39867. {
  39868. mouseWasHidden = false;
  39869. incDecDragged = false;
  39870. mouseXWhenLastDragged = e.x;
  39871. mouseYWhenLastDragged = e.y;
  39872. mouseDragStartX = e.getMouseDownX();
  39873. mouseDragStartY = e.getMouseDownY();
  39874. if (isEnabled())
  39875. {
  39876. if (e.mods.isPopupMenu() && menuEnabled)
  39877. {
  39878. menuShown = true;
  39879. PopupMenu m;
  39880. m.setLookAndFeel (&getLookAndFeel());
  39881. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39882. m.addSeparator();
  39883. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39884. {
  39885. PopupMenu rotaryMenu;
  39886. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39887. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39888. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39889. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39890. }
  39891. const int r = m.show();
  39892. if (r == 1)
  39893. {
  39894. setVelocityBasedMode (! isVelocityBased);
  39895. }
  39896. else if (r == 2)
  39897. {
  39898. setSliderStyle (Rotary);
  39899. }
  39900. else if (r == 3)
  39901. {
  39902. setSliderStyle (RotaryHorizontalDrag);
  39903. }
  39904. else if (r == 4)
  39905. {
  39906. setSliderStyle (RotaryVerticalDrag);
  39907. }
  39908. }
  39909. else if (maximum > minimum)
  39910. {
  39911. menuShown = false;
  39912. if (valueBox != 0)
  39913. valueBox->hideEditor (true);
  39914. sliderBeingDragged = 0;
  39915. if (style == TwoValueHorizontal
  39916. || style == TwoValueVertical
  39917. || style == ThreeValueHorizontal
  39918. || style == ThreeValueVertical)
  39919. {
  39920. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39921. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39922. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39923. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39924. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39925. {
  39926. if (maxPosDistance <= minPosDistance)
  39927. sliderBeingDragged = 2;
  39928. else
  39929. sliderBeingDragged = 1;
  39930. }
  39931. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39932. {
  39933. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39934. sliderBeingDragged = 1;
  39935. else if (normalPosDistance >= maxPosDistance)
  39936. sliderBeingDragged = 2;
  39937. }
  39938. }
  39939. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39940. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39941. * valueToProportionOfLength (currentValue.getValue());
  39942. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39943. : ((sliderBeingDragged == 1) ? valueMin
  39944. : currentValue)).getValue();
  39945. valueOnMouseDown = valueWhenLastDragged;
  39946. if (popupDisplayEnabled)
  39947. {
  39948. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39949. popupDisplay = popup;
  39950. if (parentForPopupDisplay != 0)
  39951. {
  39952. parentForPopupDisplay->addChildComponent (popup);
  39953. }
  39954. else
  39955. {
  39956. popup->addToDesktop (0);
  39957. }
  39958. popup->setVisible (true);
  39959. }
  39960. sendDragStart();
  39961. mouseDrag (e);
  39962. }
  39963. }
  39964. }
  39965. void Slider::mouseUp (const MouseEvent&)
  39966. {
  39967. if (isEnabled()
  39968. && (! menuShown)
  39969. && (maximum > minimum)
  39970. && (style != IncDecButtons || incDecDragged))
  39971. {
  39972. restoreMouseIfHidden();
  39973. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39974. triggerChangeMessage (false);
  39975. sendDragEnd();
  39976. popupDisplay = 0;
  39977. if (style == IncDecButtons)
  39978. {
  39979. incButton->setState (Button::buttonNormal);
  39980. decButton->setState (Button::buttonNormal);
  39981. }
  39982. }
  39983. }
  39984. void Slider::restoreMouseIfHidden()
  39985. {
  39986. if (mouseWasHidden)
  39987. {
  39988. mouseWasHidden = false;
  39989. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39990. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39991. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39992. : ((sliderBeingDragged == 1) ? getMinValue()
  39993. : (double) currentValue.getValue());
  39994. Point<int> mousePos;
  39995. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39996. {
  39997. mousePos = Desktop::getLastMouseDownPosition();
  39998. if (style == RotaryHorizontalDrag)
  39999. {
  40000. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40001. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40002. }
  40003. else
  40004. {
  40005. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40006. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40007. }
  40008. }
  40009. else
  40010. {
  40011. const int pixelPos = (int) getLinearSliderPos (pos);
  40012. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40013. isVertical() ? pixelPos : (getHeight() / 2)));
  40014. }
  40015. Desktop::setMousePosition (mousePos);
  40016. }
  40017. }
  40018. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40019. {
  40020. if (isEnabled()
  40021. && style != IncDecButtons
  40022. && style != Rotary
  40023. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40024. {
  40025. restoreMouseIfHidden();
  40026. }
  40027. }
  40028. static double smallestAngleBetween (double a1, double a2)
  40029. {
  40030. return jmin (std::abs (a1 - a2),
  40031. std::abs (a1 + double_Pi * 2.0 - a2),
  40032. std::abs (a2 + double_Pi * 2.0 - a1));
  40033. }
  40034. void Slider::mouseDrag (const MouseEvent& e)
  40035. {
  40036. if (isEnabled()
  40037. && (! menuShown)
  40038. && (maximum > minimum))
  40039. {
  40040. if (style == Rotary)
  40041. {
  40042. int dx = e.x - sliderRect.getCentreX();
  40043. int dy = e.y - sliderRect.getCentreY();
  40044. if (dx * dx + dy * dy > 25)
  40045. {
  40046. double angle = std::atan2 ((double) dx, (double) -dy);
  40047. while (angle < 0.0)
  40048. angle += double_Pi * 2.0;
  40049. if (rotaryStop && ! e.mouseWasClicked())
  40050. {
  40051. if (std::abs (angle - lastAngle) > double_Pi)
  40052. {
  40053. if (angle >= lastAngle)
  40054. angle -= double_Pi * 2.0;
  40055. else
  40056. angle += double_Pi * 2.0;
  40057. }
  40058. if (angle >= lastAngle)
  40059. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40060. else
  40061. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40062. }
  40063. else
  40064. {
  40065. while (angle < rotaryStart)
  40066. angle += double_Pi * 2.0;
  40067. if (angle > rotaryEnd)
  40068. {
  40069. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40070. angle = rotaryStart;
  40071. else
  40072. angle = rotaryEnd;
  40073. }
  40074. }
  40075. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40076. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40077. lastAngle = angle;
  40078. }
  40079. }
  40080. else
  40081. {
  40082. if (style == LinearBar && e.mouseWasClicked()
  40083. && valueBox != 0 && valueBox->isEditable())
  40084. return;
  40085. if (style == IncDecButtons && ! incDecDragged)
  40086. {
  40087. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40088. return;
  40089. incDecDragged = true;
  40090. mouseDragStartX = e.x;
  40091. mouseDragStartY = e.y;
  40092. }
  40093. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40094. : false))
  40095. || ((maximum - minimum) / sliderRegionSize < interval))
  40096. {
  40097. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40098. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40099. if (style == RotaryHorizontalDrag
  40100. || style == RotaryVerticalDrag
  40101. || style == IncDecButtons
  40102. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40103. && ! snapsToMousePos))
  40104. {
  40105. const int mouseDiff = (style == RotaryHorizontalDrag
  40106. || style == LinearHorizontal
  40107. || style == LinearBar
  40108. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40109. ? e.x - mouseDragStartX
  40110. : mouseDragStartY - e.y;
  40111. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40112. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40113. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40114. if (style == IncDecButtons)
  40115. {
  40116. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40117. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40118. }
  40119. }
  40120. else
  40121. {
  40122. if (isVertical())
  40123. scaledMousePos = 1.0 - scaledMousePos;
  40124. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40125. }
  40126. }
  40127. else
  40128. {
  40129. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40130. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40131. ? e.x - mouseXWhenLastDragged
  40132. : e.y - mouseYWhenLastDragged;
  40133. const double maxSpeed = jmax (200, sliderRegionSize);
  40134. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40135. if (speed != 0)
  40136. {
  40137. speed = 0.2 * velocityModeSensitivity
  40138. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40139. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40140. / maxSpeed))));
  40141. if (mouseDiff < 0)
  40142. speed = -speed;
  40143. if (isVertical() || style == RotaryVerticalDrag
  40144. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40145. speed = -speed;
  40146. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40147. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40148. e.source.enableUnboundedMouseMovement (true, false);
  40149. mouseWasHidden = true;
  40150. }
  40151. }
  40152. }
  40153. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40154. if (sliderBeingDragged == 0)
  40155. {
  40156. setValue (snapValue (valueWhenLastDragged, true),
  40157. ! sendChangeOnlyOnRelease, true);
  40158. }
  40159. else if (sliderBeingDragged == 1)
  40160. {
  40161. setMinValue (snapValue (valueWhenLastDragged, true),
  40162. ! sendChangeOnlyOnRelease, false, true);
  40163. if (e.mods.isShiftDown())
  40164. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40165. else
  40166. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40167. }
  40168. else
  40169. {
  40170. jassert (sliderBeingDragged == 2);
  40171. setMaxValue (snapValue (valueWhenLastDragged, true),
  40172. ! sendChangeOnlyOnRelease, false, true);
  40173. if (e.mods.isShiftDown())
  40174. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40175. else
  40176. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40177. }
  40178. mouseXWhenLastDragged = e.x;
  40179. mouseYWhenLastDragged = e.y;
  40180. }
  40181. }
  40182. void Slider::mouseDoubleClick (const MouseEvent&)
  40183. {
  40184. if (doubleClickToValue
  40185. && isEnabled()
  40186. && style != IncDecButtons
  40187. && minimum <= doubleClickReturnValue
  40188. && maximum >= doubleClickReturnValue)
  40189. {
  40190. sendDragStart();
  40191. setValue (doubleClickReturnValue, true, true);
  40192. sendDragEnd();
  40193. }
  40194. }
  40195. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40196. {
  40197. if (scrollWheelEnabled && isEnabled()
  40198. && style != TwoValueHorizontal
  40199. && style != TwoValueVertical)
  40200. {
  40201. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40202. {
  40203. if (valueBox != 0)
  40204. valueBox->hideEditor (false);
  40205. const double value = (double) currentValue.getValue();
  40206. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40207. const double currentPos = valueToProportionOfLength (value);
  40208. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40209. double delta = (newValue != value)
  40210. ? jmax (std::abs (newValue - value), interval) : 0;
  40211. if (value > newValue)
  40212. delta = -delta;
  40213. sendDragStart();
  40214. setValue (snapValue (value + delta, false), true, true);
  40215. sendDragEnd();
  40216. }
  40217. }
  40218. else
  40219. {
  40220. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40221. }
  40222. }
  40223. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40224. {
  40225. }
  40226. void SliderListener::sliderDragEnded (Slider*)
  40227. {
  40228. }
  40229. END_JUCE_NAMESPACE
  40230. /*** End of inlined file: juce_Slider.cpp ***/
  40231. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40232. BEGIN_JUCE_NAMESPACE
  40233. class DragOverlayComp : public Component
  40234. {
  40235. public:
  40236. DragOverlayComp (const Image& image_)
  40237. : image (image_)
  40238. {
  40239. image.duplicateIfShared();
  40240. image.multiplyAllAlphas (0.8f);
  40241. setAlwaysOnTop (true);
  40242. }
  40243. ~DragOverlayComp()
  40244. {
  40245. }
  40246. void paint (Graphics& g)
  40247. {
  40248. g.drawImageAt (image, 0, 0);
  40249. }
  40250. private:
  40251. Image image;
  40252. DragOverlayComp (const DragOverlayComp&);
  40253. DragOverlayComp& operator= (const DragOverlayComp&);
  40254. };
  40255. TableHeaderComponent::TableHeaderComponent()
  40256. : columnsChanged (false),
  40257. columnsResized (false),
  40258. sortChanged (false),
  40259. menuActive (true),
  40260. stretchToFit (false),
  40261. columnIdBeingResized (0),
  40262. columnIdBeingDragged (0),
  40263. columnIdUnderMouse (0),
  40264. lastDeliberateWidth (0)
  40265. {
  40266. }
  40267. TableHeaderComponent::~TableHeaderComponent()
  40268. {
  40269. dragOverlayComp = 0;
  40270. }
  40271. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40272. {
  40273. menuActive = hasMenu;
  40274. }
  40275. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40276. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40277. {
  40278. if (onlyCountVisibleColumns)
  40279. {
  40280. int num = 0;
  40281. for (int i = columns.size(); --i >= 0;)
  40282. if (columns.getUnchecked(i)->isVisible())
  40283. ++num;
  40284. return num;
  40285. }
  40286. else
  40287. {
  40288. return columns.size();
  40289. }
  40290. }
  40291. const String TableHeaderComponent::getColumnName (const int columnId) const
  40292. {
  40293. const ColumnInfo* const ci = getInfoForId (columnId);
  40294. return ci != 0 ? ci->name : String::empty;
  40295. }
  40296. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40297. {
  40298. ColumnInfo* const ci = getInfoForId (columnId);
  40299. if (ci != 0 && ci->name != newName)
  40300. {
  40301. ci->name = newName;
  40302. sendColumnsChanged();
  40303. }
  40304. }
  40305. void TableHeaderComponent::addColumn (const String& columnName,
  40306. const int columnId,
  40307. const int width,
  40308. const int minimumWidth,
  40309. const int maximumWidth,
  40310. const int propertyFlags,
  40311. const int insertIndex)
  40312. {
  40313. // can't have a duplicate or null ID!
  40314. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40315. jassert (width > 0);
  40316. ColumnInfo* const ci = new ColumnInfo();
  40317. ci->name = columnName;
  40318. ci->id = columnId;
  40319. ci->width = width;
  40320. ci->lastDeliberateWidth = width;
  40321. ci->minimumWidth = minimumWidth;
  40322. ci->maximumWidth = maximumWidth;
  40323. if (ci->maximumWidth < 0)
  40324. ci->maximumWidth = std::numeric_limits<int>::max();
  40325. jassert (ci->maximumWidth >= ci->minimumWidth);
  40326. ci->propertyFlags = propertyFlags;
  40327. columns.insert (insertIndex, ci);
  40328. sendColumnsChanged();
  40329. }
  40330. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40331. {
  40332. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40333. if (index >= 0)
  40334. {
  40335. columns.remove (index);
  40336. sortChanged = true;
  40337. sendColumnsChanged();
  40338. }
  40339. }
  40340. void TableHeaderComponent::removeAllColumns()
  40341. {
  40342. if (columns.size() > 0)
  40343. {
  40344. columns.clear();
  40345. sendColumnsChanged();
  40346. }
  40347. }
  40348. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40349. {
  40350. const int currentIndex = getIndexOfColumnId (columnId, false);
  40351. newIndex = visibleIndexToTotalIndex (newIndex);
  40352. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40353. {
  40354. columns.move (currentIndex, newIndex);
  40355. sendColumnsChanged();
  40356. }
  40357. }
  40358. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40359. {
  40360. const ColumnInfo* const ci = getInfoForId (columnId);
  40361. return ci != 0 ? ci->width : 0;
  40362. }
  40363. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40364. {
  40365. ColumnInfo* const ci = getInfoForId (columnId);
  40366. if (ci != 0 && ci->width != newWidth)
  40367. {
  40368. const int numColumns = getNumColumns (true);
  40369. ci->lastDeliberateWidth = ci->width
  40370. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40371. if (stretchToFit)
  40372. {
  40373. const int index = getIndexOfColumnId (columnId, true) + 1;
  40374. if (((unsigned int) index) < (unsigned int) numColumns)
  40375. {
  40376. const int x = getColumnPosition (index).getX();
  40377. if (lastDeliberateWidth == 0)
  40378. lastDeliberateWidth = getTotalWidth();
  40379. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40380. }
  40381. }
  40382. repaint();
  40383. columnsResized = true;
  40384. triggerAsyncUpdate();
  40385. }
  40386. }
  40387. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40388. {
  40389. int n = 0;
  40390. for (int i = 0; i < columns.size(); ++i)
  40391. {
  40392. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40393. {
  40394. if (columns.getUnchecked(i)->id == columnId)
  40395. return n;
  40396. ++n;
  40397. }
  40398. }
  40399. return -1;
  40400. }
  40401. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40402. {
  40403. if (onlyCountVisibleColumns)
  40404. index = visibleIndexToTotalIndex (index);
  40405. const ColumnInfo* const ci = columns [index];
  40406. return (ci != 0) ? ci->id : 0;
  40407. }
  40408. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40409. {
  40410. int x = 0, width = 0, n = 0;
  40411. for (int i = 0; i < columns.size(); ++i)
  40412. {
  40413. x += width;
  40414. if (columns.getUnchecked(i)->isVisible())
  40415. {
  40416. width = columns.getUnchecked(i)->width;
  40417. if (n++ == index)
  40418. break;
  40419. }
  40420. else
  40421. {
  40422. width = 0;
  40423. }
  40424. }
  40425. return Rectangle<int> (x, 0, width, getHeight());
  40426. }
  40427. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40428. {
  40429. if (xToFind >= 0)
  40430. {
  40431. int x = 0;
  40432. for (int i = 0; i < columns.size(); ++i)
  40433. {
  40434. const ColumnInfo* const ci = columns.getUnchecked(i);
  40435. if (ci->isVisible())
  40436. {
  40437. x += ci->width;
  40438. if (xToFind < x)
  40439. return ci->id;
  40440. }
  40441. }
  40442. }
  40443. return 0;
  40444. }
  40445. int TableHeaderComponent::getTotalWidth() const
  40446. {
  40447. int w = 0;
  40448. for (int i = columns.size(); --i >= 0;)
  40449. if (columns.getUnchecked(i)->isVisible())
  40450. w += columns.getUnchecked(i)->width;
  40451. return w;
  40452. }
  40453. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40454. {
  40455. stretchToFit = shouldStretchToFit;
  40456. lastDeliberateWidth = getTotalWidth();
  40457. resized();
  40458. }
  40459. bool TableHeaderComponent::isStretchToFitActive() const
  40460. {
  40461. return stretchToFit;
  40462. }
  40463. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40464. {
  40465. if (stretchToFit && getWidth() > 0
  40466. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40467. {
  40468. lastDeliberateWidth = targetTotalWidth;
  40469. resizeColumnsToFit (0, targetTotalWidth);
  40470. }
  40471. }
  40472. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40473. {
  40474. targetTotalWidth = jmax (targetTotalWidth, 0);
  40475. StretchableObjectResizer sor;
  40476. int i;
  40477. for (i = firstColumnIndex; i < columns.size(); ++i)
  40478. {
  40479. ColumnInfo* const ci = columns.getUnchecked(i);
  40480. if (ci->isVisible())
  40481. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40482. }
  40483. sor.resizeToFit (targetTotalWidth);
  40484. int visIndex = 0;
  40485. for (i = firstColumnIndex; i < columns.size(); ++i)
  40486. {
  40487. ColumnInfo* const ci = columns.getUnchecked(i);
  40488. if (ci->isVisible())
  40489. {
  40490. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40491. (int) std::floor (sor.getItemSize (visIndex++)));
  40492. if (newWidth != ci->width)
  40493. {
  40494. ci->width = newWidth;
  40495. repaint();
  40496. columnsResized = true;
  40497. triggerAsyncUpdate();
  40498. }
  40499. }
  40500. }
  40501. }
  40502. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40503. {
  40504. ColumnInfo* const ci = getInfoForId (columnId);
  40505. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40506. {
  40507. if (shouldBeVisible)
  40508. ci->propertyFlags |= visible;
  40509. else
  40510. ci->propertyFlags &= ~visible;
  40511. sendColumnsChanged();
  40512. resized();
  40513. }
  40514. }
  40515. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40516. {
  40517. const ColumnInfo* const ci = getInfoForId (columnId);
  40518. return ci != 0 && ci->isVisible();
  40519. }
  40520. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40521. {
  40522. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40523. {
  40524. for (int i = columns.size(); --i >= 0;)
  40525. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40526. ColumnInfo* const ci = getInfoForId (columnId);
  40527. if (ci != 0)
  40528. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40529. reSortTable();
  40530. }
  40531. }
  40532. int TableHeaderComponent::getSortColumnId() const
  40533. {
  40534. for (int i = columns.size(); --i >= 0;)
  40535. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40536. return columns.getUnchecked(i)->id;
  40537. return 0;
  40538. }
  40539. bool TableHeaderComponent::isSortedForwards() const
  40540. {
  40541. for (int i = columns.size(); --i >= 0;)
  40542. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40543. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40544. return true;
  40545. }
  40546. void TableHeaderComponent::reSortTable()
  40547. {
  40548. sortChanged = true;
  40549. repaint();
  40550. triggerAsyncUpdate();
  40551. }
  40552. const String TableHeaderComponent::toString() const
  40553. {
  40554. String s;
  40555. XmlElement doc ("TABLELAYOUT");
  40556. doc.setAttribute ("sortedCol", getSortColumnId());
  40557. doc.setAttribute ("sortForwards", isSortedForwards());
  40558. for (int i = 0; i < columns.size(); ++i)
  40559. {
  40560. const ColumnInfo* const ci = columns.getUnchecked (i);
  40561. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40562. e->setAttribute ("id", ci->id);
  40563. e->setAttribute ("visible", ci->isVisible());
  40564. e->setAttribute ("width", ci->width);
  40565. }
  40566. return doc.createDocument (String::empty, true, false);
  40567. }
  40568. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40569. {
  40570. XmlDocument doc (storedVersion);
  40571. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40572. int index = 0;
  40573. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40574. {
  40575. forEachXmlChildElement (*storedXml, col)
  40576. {
  40577. const int tabId = col->getIntAttribute ("id");
  40578. ColumnInfo* const ci = getInfoForId (tabId);
  40579. if (ci != 0)
  40580. {
  40581. columns.move (columns.indexOf (ci), index);
  40582. ci->width = col->getIntAttribute ("width");
  40583. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40584. }
  40585. ++index;
  40586. }
  40587. columnsResized = true;
  40588. sendColumnsChanged();
  40589. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40590. storedXml->getBoolAttribute ("sortForwards", true));
  40591. }
  40592. }
  40593. void TableHeaderComponent::addListener (Listener* const newListener)
  40594. {
  40595. listeners.addIfNotAlreadyThere (newListener);
  40596. }
  40597. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  40598. {
  40599. listeners.removeValue (listenerToRemove);
  40600. }
  40601. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40602. {
  40603. const ColumnInfo* const ci = getInfoForId (columnId);
  40604. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40605. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40606. }
  40607. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40608. {
  40609. for (int i = 0; i < columns.size(); ++i)
  40610. {
  40611. const ColumnInfo* const ci = columns.getUnchecked(i);
  40612. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40613. menu.addItem (ci->id, ci->name,
  40614. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40615. isColumnVisible (ci->id));
  40616. }
  40617. }
  40618. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40619. {
  40620. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40621. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40622. }
  40623. void TableHeaderComponent::paint (Graphics& g)
  40624. {
  40625. LookAndFeel& lf = getLookAndFeel();
  40626. lf.drawTableHeaderBackground (g, *this);
  40627. const Rectangle<int> clip (g.getClipBounds());
  40628. int x = 0;
  40629. for (int i = 0; i < columns.size(); ++i)
  40630. {
  40631. const ColumnInfo* const ci = columns.getUnchecked(i);
  40632. if (ci->isVisible())
  40633. {
  40634. if (x + ci->width > clip.getX()
  40635. && (ci->id != columnIdBeingDragged
  40636. || dragOverlayComp == 0
  40637. || ! dragOverlayComp->isVisible()))
  40638. {
  40639. g.saveState();
  40640. g.setOrigin (x, 0);
  40641. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40642. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40643. ci->id == columnIdUnderMouse,
  40644. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40645. ci->propertyFlags);
  40646. g.restoreState();
  40647. }
  40648. x += ci->width;
  40649. if (x >= clip.getRight())
  40650. break;
  40651. }
  40652. }
  40653. }
  40654. void TableHeaderComponent::resized()
  40655. {
  40656. }
  40657. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40658. {
  40659. updateColumnUnderMouse (e.x, e.y);
  40660. }
  40661. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40662. {
  40663. updateColumnUnderMouse (e.x, e.y);
  40664. }
  40665. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40666. {
  40667. updateColumnUnderMouse (e.x, e.y);
  40668. }
  40669. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40670. {
  40671. repaint();
  40672. columnIdBeingResized = 0;
  40673. columnIdBeingDragged = 0;
  40674. if (columnIdUnderMouse != 0)
  40675. {
  40676. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40677. if (e.mods.isPopupMenu())
  40678. columnClicked (columnIdUnderMouse, e.mods);
  40679. }
  40680. if (menuActive && e.mods.isPopupMenu())
  40681. showColumnChooserMenu (columnIdUnderMouse);
  40682. }
  40683. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40684. {
  40685. if (columnIdBeingResized == 0
  40686. && columnIdBeingDragged == 0
  40687. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40688. {
  40689. dragOverlayComp = 0;
  40690. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40691. if (columnIdBeingResized != 0)
  40692. {
  40693. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40694. initialColumnWidth = ci->width;
  40695. }
  40696. else
  40697. {
  40698. beginDrag (e);
  40699. }
  40700. }
  40701. if (columnIdBeingResized != 0)
  40702. {
  40703. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40704. if (ci != 0)
  40705. {
  40706. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40707. initialColumnWidth + e.getDistanceFromDragStartX());
  40708. if (stretchToFit)
  40709. {
  40710. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40711. int minWidthOnRight = 0;
  40712. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40713. if (columns.getUnchecked (i)->isVisible())
  40714. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40715. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40716. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40717. }
  40718. setColumnWidth (columnIdBeingResized, w);
  40719. }
  40720. }
  40721. else if (columnIdBeingDragged != 0)
  40722. {
  40723. if (e.y >= -50 && e.y < getHeight() + 50)
  40724. {
  40725. if (dragOverlayComp != 0)
  40726. {
  40727. dragOverlayComp->setVisible (true);
  40728. dragOverlayComp->setBounds (jlimit (0,
  40729. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40730. e.x - draggingColumnOffset),
  40731. 0,
  40732. dragOverlayComp->getWidth(),
  40733. getHeight());
  40734. for (int i = columns.size(); --i >= 0;)
  40735. {
  40736. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40737. int newIndex = currentIndex;
  40738. if (newIndex > 0)
  40739. {
  40740. // if the previous column isn't draggable, we can't move our column
  40741. // past it, because that'd change the undraggable column's position..
  40742. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40743. if ((previous->propertyFlags & draggable) != 0)
  40744. {
  40745. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40746. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40747. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40748. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40749. {
  40750. --newIndex;
  40751. }
  40752. }
  40753. }
  40754. if (newIndex < columns.size() - 1)
  40755. {
  40756. // if the next column isn't draggable, we can't move our column
  40757. // past it, because that'd change the undraggable column's position..
  40758. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40759. if ((nextCol->propertyFlags & draggable) != 0)
  40760. {
  40761. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40762. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40763. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40764. > abs (dragOverlayComp->getRight() - rightOfNext))
  40765. {
  40766. ++newIndex;
  40767. }
  40768. }
  40769. }
  40770. if (newIndex != currentIndex)
  40771. moveColumn (columnIdBeingDragged, newIndex);
  40772. else
  40773. break;
  40774. }
  40775. }
  40776. }
  40777. else
  40778. {
  40779. endDrag (draggingColumnOriginalIndex);
  40780. }
  40781. }
  40782. }
  40783. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40784. {
  40785. if (columnIdBeingDragged == 0)
  40786. {
  40787. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40788. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40789. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40790. {
  40791. columnIdBeingDragged = 0;
  40792. }
  40793. else
  40794. {
  40795. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40796. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40797. const int temp = columnIdBeingDragged;
  40798. columnIdBeingDragged = 0;
  40799. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40800. columnIdBeingDragged = temp;
  40801. dragOverlayComp->setBounds (columnRect);
  40802. for (int i = listeners.size(); --i >= 0;)
  40803. {
  40804. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40805. i = jmin (i, listeners.size() - 1);
  40806. }
  40807. }
  40808. }
  40809. }
  40810. void TableHeaderComponent::endDrag (const int finalIndex)
  40811. {
  40812. if (columnIdBeingDragged != 0)
  40813. {
  40814. moveColumn (columnIdBeingDragged, finalIndex);
  40815. columnIdBeingDragged = 0;
  40816. repaint();
  40817. for (int i = listeners.size(); --i >= 0;)
  40818. {
  40819. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40820. i = jmin (i, listeners.size() - 1);
  40821. }
  40822. }
  40823. }
  40824. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40825. {
  40826. mouseDrag (e);
  40827. for (int i = columns.size(); --i >= 0;)
  40828. if (columns.getUnchecked (i)->isVisible())
  40829. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40830. columnIdBeingResized = 0;
  40831. repaint();
  40832. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40833. updateColumnUnderMouse (e.x, e.y);
  40834. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40835. columnClicked (columnIdUnderMouse, e.mods);
  40836. dragOverlayComp = 0;
  40837. }
  40838. const MouseCursor TableHeaderComponent::getMouseCursor()
  40839. {
  40840. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40841. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40842. return Component::getMouseCursor();
  40843. }
  40844. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40845. {
  40846. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40847. }
  40848. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40849. {
  40850. for (int i = columns.size(); --i >= 0;)
  40851. if (columns.getUnchecked(i)->id == id)
  40852. return columns.getUnchecked(i);
  40853. return 0;
  40854. }
  40855. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40856. {
  40857. int n = 0;
  40858. for (int i = 0; i < columns.size(); ++i)
  40859. {
  40860. if (columns.getUnchecked(i)->isVisible())
  40861. {
  40862. if (n == visibleIndex)
  40863. return i;
  40864. ++n;
  40865. }
  40866. }
  40867. return -1;
  40868. }
  40869. void TableHeaderComponent::sendColumnsChanged()
  40870. {
  40871. if (stretchToFit && lastDeliberateWidth > 0)
  40872. resizeAllColumnsToFit (lastDeliberateWidth);
  40873. repaint();
  40874. columnsChanged = true;
  40875. triggerAsyncUpdate();
  40876. }
  40877. void TableHeaderComponent::handleAsyncUpdate()
  40878. {
  40879. const bool changed = columnsChanged || sortChanged;
  40880. const bool sized = columnsResized || changed;
  40881. const bool sorted = sortChanged;
  40882. columnsChanged = false;
  40883. columnsResized = false;
  40884. sortChanged = false;
  40885. if (sorted)
  40886. {
  40887. for (int i = listeners.size(); --i >= 0;)
  40888. {
  40889. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40890. i = jmin (i, listeners.size() - 1);
  40891. }
  40892. }
  40893. if (changed)
  40894. {
  40895. for (int i = listeners.size(); --i >= 0;)
  40896. {
  40897. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40898. i = jmin (i, listeners.size() - 1);
  40899. }
  40900. }
  40901. if (sized)
  40902. {
  40903. for (int i = listeners.size(); --i >= 0;)
  40904. {
  40905. listeners.getUnchecked(i)->tableColumnsResized (this);
  40906. i = jmin (i, listeners.size() - 1);
  40907. }
  40908. }
  40909. }
  40910. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40911. {
  40912. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40913. {
  40914. const int draggableDistance = 3;
  40915. int x = 0;
  40916. for (int i = 0; i < columns.size(); ++i)
  40917. {
  40918. const ColumnInfo* const ci = columns.getUnchecked(i);
  40919. if (ci->isVisible())
  40920. {
  40921. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40922. && (ci->propertyFlags & resizable) != 0)
  40923. return ci->id;
  40924. x += ci->width;
  40925. }
  40926. }
  40927. }
  40928. return 0;
  40929. }
  40930. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40931. {
  40932. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40933. ? getColumnIdAtX (x) : 0;
  40934. if (newCol != columnIdUnderMouse)
  40935. {
  40936. columnIdUnderMouse = newCol;
  40937. repaint();
  40938. }
  40939. }
  40940. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40941. {
  40942. PopupMenu m;
  40943. addMenuItems (m, columnIdClicked);
  40944. if (m.getNumItems() > 0)
  40945. {
  40946. m.setLookAndFeel (&getLookAndFeel());
  40947. const int result = m.show();
  40948. if (result != 0)
  40949. reactToMenuItem (result, columnIdClicked);
  40950. }
  40951. }
  40952. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40953. {
  40954. }
  40955. END_JUCE_NAMESPACE
  40956. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40957. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40958. BEGIN_JUCE_NAMESPACE
  40959. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40960. class TableListRowComp : public Component,
  40961. public TooltipClient
  40962. {
  40963. public:
  40964. TableListRowComp (TableListBox& owner_)
  40965. : owner (owner_),
  40966. row (-1),
  40967. isSelected (false)
  40968. {
  40969. }
  40970. ~TableListRowComp()
  40971. {
  40972. deleteAllChildren();
  40973. }
  40974. void paint (Graphics& g)
  40975. {
  40976. TableListBoxModel* const model = owner.getModel();
  40977. if (model != 0)
  40978. {
  40979. const TableHeaderComponent* const header = owner.getHeader();
  40980. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40981. const int numColumns = header->getNumColumns (true);
  40982. for (int i = 0; i < numColumns; ++i)
  40983. {
  40984. if (! columnsWithComponents [i])
  40985. {
  40986. const int columnId = header->getColumnIdOfIndex (i, true);
  40987. Rectangle<int> columnRect (header->getColumnPosition (i));
  40988. columnRect.setSize (columnRect.getWidth(), getHeight());
  40989. g.saveState();
  40990. g.reduceClipRegion (columnRect);
  40991. g.setOrigin (columnRect.getX(), 0);
  40992. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40993. g.restoreState();
  40994. }
  40995. }
  40996. }
  40997. }
  40998. void update (const int newRow, const bool isNowSelected)
  40999. {
  41000. if (newRow != row || isNowSelected != isSelected)
  41001. {
  41002. row = newRow;
  41003. isSelected = isNowSelected;
  41004. repaint();
  41005. }
  41006. if (row < owner.getNumRows())
  41007. {
  41008. jassert (row >= 0);
  41009. const Identifier tagPropertyName ("_tableLastUseNum");
  41010. const int newTag = Random::getSystemRandom().nextInt();
  41011. const TableHeaderComponent* const header = owner.getHeader();
  41012. const int numColumns = header->getNumColumns (true);
  41013. int i;
  41014. columnsWithComponents.clear();
  41015. if (owner.getModel() != 0)
  41016. {
  41017. for (i = 0; i < numColumns; ++i)
  41018. {
  41019. const int columnId = header->getColumnIdOfIndex (i, true);
  41020. Component* const newComp
  41021. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41022. findChildComponentForColumn (columnId));
  41023. if (newComp != 0)
  41024. {
  41025. addAndMakeVisible (newComp);
  41026. newComp->getProperties().set (tagPropertyName, newTag);
  41027. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41028. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41029. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41030. columnsWithComponents.setBit (i);
  41031. }
  41032. }
  41033. }
  41034. for (i = getNumChildComponents(); --i >= 0;)
  41035. {
  41036. Component* const c = getChildComponent (i);
  41037. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41038. delete c;
  41039. }
  41040. }
  41041. else
  41042. {
  41043. columnsWithComponents.clear();
  41044. deleteAllChildren();
  41045. }
  41046. }
  41047. void resized()
  41048. {
  41049. for (int i = getNumChildComponents(); --i >= 0;)
  41050. {
  41051. Component* const c = getChildComponent (i);
  41052. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41053. if (columnId != 0)
  41054. {
  41055. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41056. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41057. }
  41058. }
  41059. }
  41060. void mouseDown (const MouseEvent& e)
  41061. {
  41062. isDragging = false;
  41063. selectRowOnMouseUp = false;
  41064. if (isEnabled())
  41065. {
  41066. if (! isSelected)
  41067. {
  41068. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41069. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41070. if (columnId != 0 && owner.getModel() != 0)
  41071. owner.getModel()->cellClicked (row, columnId, e);
  41072. }
  41073. else
  41074. {
  41075. selectRowOnMouseUp = true;
  41076. }
  41077. }
  41078. }
  41079. void mouseDrag (const MouseEvent& e)
  41080. {
  41081. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41082. {
  41083. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41084. if (selectedRows.size() > 0)
  41085. {
  41086. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41087. if (dragDescription.isNotEmpty())
  41088. {
  41089. isDragging = true;
  41090. owner.startDragAndDrop (e, dragDescription);
  41091. }
  41092. }
  41093. }
  41094. }
  41095. void mouseUp (const MouseEvent& e)
  41096. {
  41097. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41098. {
  41099. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41100. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41101. if (columnId != 0 && owner.getModel() != 0)
  41102. owner.getModel()->cellClicked (row, columnId, e);
  41103. }
  41104. }
  41105. void mouseDoubleClick (const MouseEvent& e)
  41106. {
  41107. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41108. if (columnId != 0 && owner.getModel() != 0)
  41109. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41110. }
  41111. const String getTooltip()
  41112. {
  41113. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41114. if (columnId != 0 && owner.getModel() != 0)
  41115. return owner.getModel()->getCellTooltip (row, columnId);
  41116. return String::empty;
  41117. }
  41118. Component* findChildComponentForColumn (const int columnId) const
  41119. {
  41120. for (int i = getNumChildComponents(); --i >= 0;)
  41121. {
  41122. Component* const c = getChildComponent (i);
  41123. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41124. return c;
  41125. }
  41126. return 0;
  41127. }
  41128. juce_UseDebuggingNewOperator
  41129. private:
  41130. TableListBox& owner;
  41131. int row;
  41132. bool isSelected, isDragging, selectRowOnMouseUp;
  41133. BigInteger columnsWithComponents;
  41134. TableListRowComp (const TableListRowComp&);
  41135. TableListRowComp& operator= (const TableListRowComp&);
  41136. };
  41137. class TableListBoxHeader : public TableHeaderComponent
  41138. {
  41139. public:
  41140. TableListBoxHeader (TableListBox& owner_)
  41141. : owner (owner_)
  41142. {
  41143. }
  41144. ~TableListBoxHeader()
  41145. {
  41146. }
  41147. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41148. {
  41149. if (owner.isAutoSizeMenuOptionShown())
  41150. {
  41151. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41152. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41153. menu.addSeparator();
  41154. }
  41155. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41156. }
  41157. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41158. {
  41159. if (menuReturnId == 0xf836743)
  41160. {
  41161. owner.autoSizeColumn (columnIdClicked);
  41162. }
  41163. else if (menuReturnId == 0xf836744)
  41164. {
  41165. owner.autoSizeAllColumns();
  41166. }
  41167. else
  41168. {
  41169. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41170. }
  41171. }
  41172. juce_UseDebuggingNewOperator
  41173. private:
  41174. TableListBox& owner;
  41175. TableListBoxHeader (const TableListBoxHeader&);
  41176. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41177. };
  41178. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41179. : ListBox (name, 0),
  41180. model (model_),
  41181. autoSizeOptionsShown (true)
  41182. {
  41183. ListBox::model = this;
  41184. header = new TableListBoxHeader (*this);
  41185. header->setSize (100, 28);
  41186. header->addListener (this);
  41187. setHeaderComponent (header);
  41188. }
  41189. TableListBox::~TableListBox()
  41190. {
  41191. header = 0;
  41192. }
  41193. void TableListBox::setModel (TableListBoxModel* const newModel)
  41194. {
  41195. if (model != newModel)
  41196. {
  41197. model = newModel;
  41198. updateContent();
  41199. }
  41200. }
  41201. int TableListBox::getHeaderHeight() const
  41202. {
  41203. return header->getHeight();
  41204. }
  41205. void TableListBox::setHeaderHeight (const int newHeight)
  41206. {
  41207. header->setSize (header->getWidth(), newHeight);
  41208. resized();
  41209. }
  41210. void TableListBox::autoSizeColumn (const int columnId)
  41211. {
  41212. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41213. if (width > 0)
  41214. header->setColumnWidth (columnId, width);
  41215. }
  41216. void TableListBox::autoSizeAllColumns()
  41217. {
  41218. for (int i = 0; i < header->getNumColumns (true); ++i)
  41219. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41220. }
  41221. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41222. {
  41223. autoSizeOptionsShown = shouldBeShown;
  41224. }
  41225. bool TableListBox::isAutoSizeMenuOptionShown() const
  41226. {
  41227. return autoSizeOptionsShown;
  41228. }
  41229. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41230. const int rowNumber,
  41231. const bool relativeToComponentTopLeft) const
  41232. {
  41233. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41234. if (relativeToComponentTopLeft)
  41235. headerCell.translate (header->getX(), 0);
  41236. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41237. return Rectangle<int> (headerCell.getX(), row.getY(),
  41238. headerCell.getWidth(), row.getHeight());
  41239. }
  41240. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41241. {
  41242. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41243. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41244. }
  41245. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41246. {
  41247. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41248. if (scrollbar != 0)
  41249. {
  41250. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41251. double x = scrollbar->getCurrentRangeStart();
  41252. const double w = scrollbar->getCurrentRangeSize();
  41253. if (pos.getX() < x)
  41254. x = pos.getX();
  41255. else if (pos.getRight() > x + w)
  41256. x += jmax (0.0, pos.getRight() - (x + w));
  41257. scrollbar->setCurrentRangeStart (x);
  41258. }
  41259. }
  41260. int TableListBox::getNumRows()
  41261. {
  41262. return model != 0 ? model->getNumRows() : 0;
  41263. }
  41264. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41265. {
  41266. }
  41267. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41268. {
  41269. if (existingComponentToUpdate == 0)
  41270. existingComponentToUpdate = new TableListRowComp (*this);
  41271. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41272. return existingComponentToUpdate;
  41273. }
  41274. void TableListBox::selectedRowsChanged (int row)
  41275. {
  41276. if (model != 0)
  41277. model->selectedRowsChanged (row);
  41278. }
  41279. void TableListBox::deleteKeyPressed (int row)
  41280. {
  41281. if (model != 0)
  41282. model->deleteKeyPressed (row);
  41283. }
  41284. void TableListBox::returnKeyPressed (int row)
  41285. {
  41286. if (model != 0)
  41287. model->returnKeyPressed (row);
  41288. }
  41289. void TableListBox::backgroundClicked()
  41290. {
  41291. if (model != 0)
  41292. model->backgroundClicked();
  41293. }
  41294. void TableListBox::listWasScrolled()
  41295. {
  41296. if (model != 0)
  41297. model->listWasScrolled();
  41298. }
  41299. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41300. {
  41301. setMinimumContentWidth (header->getTotalWidth());
  41302. repaint();
  41303. updateColumnComponents();
  41304. }
  41305. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41306. {
  41307. setMinimumContentWidth (header->getTotalWidth());
  41308. repaint();
  41309. updateColumnComponents();
  41310. }
  41311. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41312. {
  41313. if (model != 0)
  41314. model->sortOrderChanged (header->getSortColumnId(),
  41315. header->isSortedForwards());
  41316. }
  41317. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41318. {
  41319. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41320. repaint();
  41321. }
  41322. void TableListBox::resized()
  41323. {
  41324. ListBox::resized();
  41325. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41326. setMinimumContentWidth (header->getTotalWidth());
  41327. }
  41328. void TableListBox::updateColumnComponents() const
  41329. {
  41330. const int firstRow = getRowContainingPosition (0, 0);
  41331. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41332. {
  41333. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41334. if (rowComp != 0)
  41335. rowComp->resized();
  41336. }
  41337. }
  41338. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41339. {
  41340. }
  41341. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41342. {
  41343. }
  41344. void TableListBoxModel::backgroundClicked()
  41345. {
  41346. }
  41347. void TableListBoxModel::sortOrderChanged (int, const bool)
  41348. {
  41349. }
  41350. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41351. {
  41352. return 0;
  41353. }
  41354. void TableListBoxModel::selectedRowsChanged (int)
  41355. {
  41356. }
  41357. void TableListBoxModel::deleteKeyPressed (int)
  41358. {
  41359. }
  41360. void TableListBoxModel::returnKeyPressed (int)
  41361. {
  41362. }
  41363. void TableListBoxModel::listWasScrolled()
  41364. {
  41365. }
  41366. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41367. {
  41368. return String::empty;
  41369. }
  41370. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41371. {
  41372. return String::empty;
  41373. }
  41374. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41375. {
  41376. (void) existingComponentToUpdate;
  41377. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41378. return 0;
  41379. }
  41380. END_JUCE_NAMESPACE
  41381. /*** End of inlined file: juce_TableListBox.cpp ***/
  41382. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41383. BEGIN_JUCE_NAMESPACE
  41384. // a word or space that can't be broken down any further
  41385. struct TextAtom
  41386. {
  41387. String atomText;
  41388. float width;
  41389. uint16 numChars;
  41390. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41391. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41392. const String getText (const juce_wchar passwordCharacter) const
  41393. {
  41394. if (passwordCharacter == 0)
  41395. return atomText;
  41396. else
  41397. return String::repeatedString (String::charToString (passwordCharacter),
  41398. atomText.length());
  41399. }
  41400. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41401. {
  41402. if (passwordCharacter == 0)
  41403. return atomText.substring (0, numChars);
  41404. else if (isNewLine())
  41405. return String::empty;
  41406. else
  41407. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41408. }
  41409. };
  41410. // a run of text with a single font and colour
  41411. class TextEditor::UniformTextSection
  41412. {
  41413. public:
  41414. UniformTextSection (const String& text,
  41415. const Font& font_,
  41416. const Colour& colour_,
  41417. const juce_wchar passwordCharacter)
  41418. : font (font_),
  41419. colour (colour_)
  41420. {
  41421. initialiseAtoms (text, passwordCharacter);
  41422. }
  41423. UniformTextSection (const UniformTextSection& other)
  41424. : font (other.font),
  41425. colour (other.colour)
  41426. {
  41427. atoms.ensureStorageAllocated (other.atoms.size());
  41428. for (int i = 0; i < other.atoms.size(); ++i)
  41429. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41430. }
  41431. ~UniformTextSection()
  41432. {
  41433. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41434. }
  41435. void clear()
  41436. {
  41437. for (int i = atoms.size(); --i >= 0;)
  41438. delete getAtom(i);
  41439. atoms.clear();
  41440. }
  41441. int getNumAtoms() const
  41442. {
  41443. return atoms.size();
  41444. }
  41445. TextAtom* getAtom (const int index) const throw()
  41446. {
  41447. return atoms.getUnchecked (index);
  41448. }
  41449. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41450. {
  41451. if (other.atoms.size() > 0)
  41452. {
  41453. TextAtom* const lastAtom = atoms.getLast();
  41454. int i = 0;
  41455. if (lastAtom != 0)
  41456. {
  41457. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41458. {
  41459. TextAtom* const first = other.getAtom(0);
  41460. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41461. {
  41462. lastAtom->atomText += first->atomText;
  41463. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41464. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41465. delete first;
  41466. ++i;
  41467. }
  41468. }
  41469. }
  41470. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41471. while (i < other.atoms.size())
  41472. {
  41473. atoms.add (other.getAtom(i));
  41474. ++i;
  41475. }
  41476. }
  41477. }
  41478. UniformTextSection* split (const int indexToBreakAt,
  41479. const juce_wchar passwordCharacter)
  41480. {
  41481. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41482. font, colour,
  41483. passwordCharacter);
  41484. int index = 0;
  41485. for (int i = 0; i < atoms.size(); ++i)
  41486. {
  41487. TextAtom* const atom = getAtom(i);
  41488. const int nextIndex = index + atom->numChars;
  41489. if (index == indexToBreakAt)
  41490. {
  41491. int j;
  41492. for (j = i; j < atoms.size(); ++j)
  41493. section2->atoms.add (getAtom (j));
  41494. for (j = atoms.size(); --j >= i;)
  41495. atoms.remove (j);
  41496. break;
  41497. }
  41498. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41499. {
  41500. TextAtom* const secondAtom = new TextAtom();
  41501. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41502. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41503. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41504. section2->atoms.add (secondAtom);
  41505. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41506. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41507. atom->numChars = (uint16) (indexToBreakAt - index);
  41508. int j;
  41509. for (j = i + 1; j < atoms.size(); ++j)
  41510. section2->atoms.add (getAtom (j));
  41511. for (j = atoms.size(); --j > i;)
  41512. atoms.remove (j);
  41513. break;
  41514. }
  41515. index = nextIndex;
  41516. }
  41517. return section2;
  41518. }
  41519. void appendAllText (String::Concatenator& concatenator) const
  41520. {
  41521. for (int i = 0; i < atoms.size(); ++i)
  41522. concatenator.append (getAtom(i)->atomText);
  41523. }
  41524. void appendSubstring (String::Concatenator& concatenator,
  41525. const Range<int>& range) const
  41526. {
  41527. int index = 0;
  41528. for (int i = 0; i < atoms.size(); ++i)
  41529. {
  41530. const TextAtom* const atom = getAtom (i);
  41531. const int nextIndex = index + atom->numChars;
  41532. if (range.getStart() < nextIndex)
  41533. {
  41534. if (range.getEnd() <= index)
  41535. break;
  41536. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41537. if (! r.isEmpty())
  41538. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41539. }
  41540. index = nextIndex;
  41541. }
  41542. }
  41543. int getTotalLength() const
  41544. {
  41545. int total = 0;
  41546. for (int i = atoms.size(); --i >= 0;)
  41547. total += getAtom(i)->numChars;
  41548. return total;
  41549. }
  41550. void setFont (const Font& newFont,
  41551. const juce_wchar passwordCharacter)
  41552. {
  41553. if (font != newFont)
  41554. {
  41555. font = newFont;
  41556. for (int i = atoms.size(); --i >= 0;)
  41557. {
  41558. TextAtom* const atom = atoms.getUnchecked(i);
  41559. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41560. }
  41561. }
  41562. }
  41563. juce_UseDebuggingNewOperator
  41564. Font font;
  41565. Colour colour;
  41566. private:
  41567. Array <TextAtom*> atoms;
  41568. void initialiseAtoms (const String& textToParse,
  41569. const juce_wchar passwordCharacter)
  41570. {
  41571. int i = 0;
  41572. const int len = textToParse.length();
  41573. const juce_wchar* const text = textToParse;
  41574. while (i < len)
  41575. {
  41576. int start = i;
  41577. // create a whitespace atom unless it starts with non-ws
  41578. if (CharacterFunctions::isWhitespace (text[i])
  41579. && text[i] != '\r'
  41580. && text[i] != '\n')
  41581. {
  41582. while (i < len
  41583. && CharacterFunctions::isWhitespace (text[i])
  41584. && text[i] != '\r'
  41585. && text[i] != '\n')
  41586. {
  41587. ++i;
  41588. }
  41589. }
  41590. else
  41591. {
  41592. if (text[i] == '\r')
  41593. {
  41594. ++i;
  41595. if ((i < len) && (text[i] == '\n'))
  41596. {
  41597. ++start;
  41598. ++i;
  41599. }
  41600. }
  41601. else if (text[i] == '\n')
  41602. {
  41603. ++i;
  41604. }
  41605. else
  41606. {
  41607. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41608. ++i;
  41609. }
  41610. }
  41611. TextAtom* const atom = new TextAtom();
  41612. atom->atomText = String (text + start, i - start);
  41613. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41614. atom->numChars = (uint16) (i - start);
  41615. atoms.add (atom);
  41616. }
  41617. }
  41618. UniformTextSection& operator= (const UniformTextSection& other);
  41619. };
  41620. class TextEditor::Iterator
  41621. {
  41622. public:
  41623. Iterator (const Array <UniformTextSection*>& sections_,
  41624. const float wordWrapWidth_,
  41625. const juce_wchar passwordCharacter_)
  41626. : indexInText (0),
  41627. lineY (0),
  41628. lineHeight (0),
  41629. maxDescent (0),
  41630. atomX (0),
  41631. atomRight (0),
  41632. atom (0),
  41633. currentSection (0),
  41634. sections (sections_),
  41635. sectionIndex (0),
  41636. atomIndex (0),
  41637. wordWrapWidth (wordWrapWidth_),
  41638. passwordCharacter (passwordCharacter_)
  41639. {
  41640. jassert (wordWrapWidth_ > 0);
  41641. if (sections.size() > 0)
  41642. {
  41643. currentSection = sections.getUnchecked (sectionIndex);
  41644. if (currentSection != 0)
  41645. beginNewLine();
  41646. }
  41647. }
  41648. Iterator (const Iterator& other)
  41649. : indexInText (other.indexInText),
  41650. lineY (other.lineY),
  41651. lineHeight (other.lineHeight),
  41652. maxDescent (other.maxDescent),
  41653. atomX (other.atomX),
  41654. atomRight (other.atomRight),
  41655. atom (other.atom),
  41656. currentSection (other.currentSection),
  41657. sections (other.sections),
  41658. sectionIndex (other.sectionIndex),
  41659. atomIndex (other.atomIndex),
  41660. wordWrapWidth (other.wordWrapWidth),
  41661. passwordCharacter (other.passwordCharacter),
  41662. tempAtom (other.tempAtom)
  41663. {
  41664. }
  41665. ~Iterator()
  41666. {
  41667. }
  41668. bool next()
  41669. {
  41670. if (atom == &tempAtom)
  41671. {
  41672. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41673. if (numRemaining > 0)
  41674. {
  41675. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41676. atomX = 0;
  41677. if (tempAtom.numChars > 0)
  41678. lineY += lineHeight;
  41679. indexInText += tempAtom.numChars;
  41680. GlyphArrangement g;
  41681. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41682. int split;
  41683. for (split = 0; split < g.getNumGlyphs(); ++split)
  41684. if (shouldWrap (g.getGlyph (split).getRight()))
  41685. break;
  41686. if (split > 0 && split <= numRemaining)
  41687. {
  41688. tempAtom.numChars = (uint16) split;
  41689. tempAtom.width = g.getGlyph (split - 1).getRight();
  41690. atomRight = atomX + tempAtom.width;
  41691. return true;
  41692. }
  41693. }
  41694. }
  41695. bool forceNewLine = false;
  41696. if (sectionIndex >= sections.size())
  41697. {
  41698. moveToEndOfLastAtom();
  41699. return false;
  41700. }
  41701. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41702. {
  41703. if (atomIndex >= currentSection->getNumAtoms())
  41704. {
  41705. if (++sectionIndex >= sections.size())
  41706. {
  41707. moveToEndOfLastAtom();
  41708. return false;
  41709. }
  41710. atomIndex = 0;
  41711. currentSection = sections.getUnchecked (sectionIndex);
  41712. }
  41713. else
  41714. {
  41715. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41716. if (! lastAtom->isWhitespace())
  41717. {
  41718. // handle the case where the last atom in a section is actually part of the same
  41719. // word as the first atom of the next section...
  41720. float right = atomRight + lastAtom->width;
  41721. float lineHeight2 = lineHeight;
  41722. float maxDescent2 = maxDescent;
  41723. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41724. {
  41725. const UniformTextSection* const s = sections.getUnchecked (section);
  41726. if (s->getNumAtoms() == 0)
  41727. break;
  41728. const TextAtom* const nextAtom = s->getAtom (0);
  41729. if (nextAtom->isWhitespace())
  41730. break;
  41731. right += nextAtom->width;
  41732. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41733. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41734. if (shouldWrap (right))
  41735. {
  41736. lineHeight = lineHeight2;
  41737. maxDescent = maxDescent2;
  41738. forceNewLine = true;
  41739. break;
  41740. }
  41741. if (s->getNumAtoms() > 1)
  41742. break;
  41743. }
  41744. }
  41745. }
  41746. }
  41747. if (atom != 0)
  41748. {
  41749. atomX = atomRight;
  41750. indexInText += atom->numChars;
  41751. if (atom->isNewLine())
  41752. beginNewLine();
  41753. }
  41754. atom = currentSection->getAtom (atomIndex);
  41755. atomRight = atomX + atom->width;
  41756. ++atomIndex;
  41757. if (shouldWrap (atomRight) || forceNewLine)
  41758. {
  41759. if (atom->isWhitespace())
  41760. {
  41761. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41762. atomRight = jmin (atomRight, wordWrapWidth);
  41763. }
  41764. else
  41765. {
  41766. atomRight = atom->width;
  41767. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41768. {
  41769. tempAtom = *atom;
  41770. tempAtom.width = 0;
  41771. tempAtom.numChars = 0;
  41772. atom = &tempAtom;
  41773. if (atomX > 0)
  41774. beginNewLine();
  41775. return next();
  41776. }
  41777. beginNewLine();
  41778. return true;
  41779. }
  41780. }
  41781. return true;
  41782. }
  41783. void beginNewLine()
  41784. {
  41785. atomX = 0;
  41786. lineY += lineHeight;
  41787. int tempSectionIndex = sectionIndex;
  41788. int tempAtomIndex = atomIndex;
  41789. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41790. lineHeight = section->font.getHeight();
  41791. maxDescent = section->font.getDescent();
  41792. float x = (atom != 0) ? atom->width : 0;
  41793. while (! shouldWrap (x))
  41794. {
  41795. if (tempSectionIndex >= sections.size())
  41796. break;
  41797. bool checkSize = false;
  41798. if (tempAtomIndex >= section->getNumAtoms())
  41799. {
  41800. if (++tempSectionIndex >= sections.size())
  41801. break;
  41802. tempAtomIndex = 0;
  41803. section = sections.getUnchecked (tempSectionIndex);
  41804. checkSize = true;
  41805. }
  41806. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41807. if (nextAtom == 0)
  41808. break;
  41809. x += nextAtom->width;
  41810. if (shouldWrap (x) || nextAtom->isNewLine())
  41811. break;
  41812. if (checkSize)
  41813. {
  41814. lineHeight = jmax (lineHeight, section->font.getHeight());
  41815. maxDescent = jmax (maxDescent, section->font.getDescent());
  41816. }
  41817. ++tempAtomIndex;
  41818. }
  41819. }
  41820. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41821. {
  41822. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41823. {
  41824. if (lastSection != currentSection)
  41825. {
  41826. lastSection = currentSection;
  41827. g.setColour (currentSection->colour);
  41828. g.setFont (currentSection->font);
  41829. }
  41830. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41831. GlyphArrangement ga;
  41832. ga.addLineOfText (currentSection->font,
  41833. atom->getTrimmedText (passwordCharacter),
  41834. atomX,
  41835. (float) roundToInt (lineY + lineHeight - maxDescent));
  41836. ga.draw (g);
  41837. }
  41838. }
  41839. void drawSelection (Graphics& g,
  41840. const Range<int>& selection) const
  41841. {
  41842. const int startX = roundToInt (indexToX (selection.getStart()));
  41843. const int endX = roundToInt (indexToX (selection.getEnd()));
  41844. const int y = roundToInt (lineY);
  41845. const int nextY = roundToInt (lineY + lineHeight);
  41846. g.fillRect (startX, y, endX - startX, nextY - y);
  41847. }
  41848. void drawSelectedText (Graphics& g,
  41849. const Range<int>& selection,
  41850. const Colour& selectedTextColour) const
  41851. {
  41852. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41853. {
  41854. GlyphArrangement ga;
  41855. ga.addLineOfText (currentSection->font,
  41856. atom->getTrimmedText (passwordCharacter),
  41857. atomX,
  41858. (float) roundToInt (lineY + lineHeight - maxDescent));
  41859. if (selection.getEnd() < indexInText + atom->numChars)
  41860. {
  41861. GlyphArrangement ga2 (ga);
  41862. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41863. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41864. g.setColour (currentSection->colour);
  41865. ga2.draw (g);
  41866. }
  41867. if (selection.getStart() > indexInText)
  41868. {
  41869. GlyphArrangement ga2 (ga);
  41870. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41871. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41872. g.setColour (currentSection->colour);
  41873. ga2.draw (g);
  41874. }
  41875. g.setColour (selectedTextColour);
  41876. ga.draw (g);
  41877. }
  41878. }
  41879. float indexToX (const int indexToFind) const
  41880. {
  41881. if (indexToFind <= indexInText)
  41882. return atomX;
  41883. if (indexToFind >= indexInText + atom->numChars)
  41884. return atomRight;
  41885. GlyphArrangement g;
  41886. g.addLineOfText (currentSection->font,
  41887. atom->getText (passwordCharacter),
  41888. atomX, 0.0f);
  41889. if (indexToFind - indexInText >= g.getNumGlyphs())
  41890. return atomRight;
  41891. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41892. }
  41893. int xToIndex (const float xToFind) const
  41894. {
  41895. if (xToFind <= atomX || atom->isNewLine())
  41896. return indexInText;
  41897. if (xToFind >= atomRight)
  41898. return indexInText + atom->numChars;
  41899. GlyphArrangement g;
  41900. g.addLineOfText (currentSection->font,
  41901. atom->getText (passwordCharacter),
  41902. atomX, 0.0f);
  41903. int j;
  41904. for (j = 0; j < g.getNumGlyphs(); ++j)
  41905. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41906. break;
  41907. return indexInText + j;
  41908. }
  41909. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41910. {
  41911. while (next())
  41912. {
  41913. if (indexInText + atom->numChars > index)
  41914. {
  41915. cx = indexToX (index);
  41916. cy = lineY;
  41917. lineHeight_ = lineHeight;
  41918. return true;
  41919. }
  41920. }
  41921. cx = atomX;
  41922. cy = lineY;
  41923. lineHeight_ = lineHeight;
  41924. return false;
  41925. }
  41926. juce_UseDebuggingNewOperator
  41927. int indexInText;
  41928. float lineY, lineHeight, maxDescent;
  41929. float atomX, atomRight;
  41930. const TextAtom* atom;
  41931. const UniformTextSection* currentSection;
  41932. private:
  41933. const Array <UniformTextSection*>& sections;
  41934. int sectionIndex, atomIndex;
  41935. const float wordWrapWidth;
  41936. const juce_wchar passwordCharacter;
  41937. TextAtom tempAtom;
  41938. Iterator& operator= (const Iterator&);
  41939. void moveToEndOfLastAtom()
  41940. {
  41941. if (atom != 0)
  41942. {
  41943. atomX = atomRight;
  41944. if (atom->isNewLine())
  41945. {
  41946. atomX = 0.0f;
  41947. lineY += lineHeight;
  41948. }
  41949. }
  41950. }
  41951. bool shouldWrap (const float x) const
  41952. {
  41953. return (x - 0.0001f) >= wordWrapWidth;
  41954. }
  41955. };
  41956. class TextEditor::InsertAction : public UndoableAction
  41957. {
  41958. TextEditor& owner;
  41959. const String text;
  41960. const int insertIndex, oldCaretPos, newCaretPos;
  41961. const Font font;
  41962. const Colour colour;
  41963. InsertAction (const InsertAction&);
  41964. InsertAction& operator= (const InsertAction&);
  41965. public:
  41966. InsertAction (TextEditor& owner_,
  41967. const String& text_,
  41968. const int insertIndex_,
  41969. const Font& font_,
  41970. const Colour& colour_,
  41971. const int oldCaretPos_,
  41972. const int newCaretPos_)
  41973. : owner (owner_),
  41974. text (text_),
  41975. insertIndex (insertIndex_),
  41976. oldCaretPos (oldCaretPos_),
  41977. newCaretPos (newCaretPos_),
  41978. font (font_),
  41979. colour (colour_)
  41980. {
  41981. }
  41982. ~InsertAction()
  41983. {
  41984. }
  41985. bool perform()
  41986. {
  41987. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41988. return true;
  41989. }
  41990. bool undo()
  41991. {
  41992. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41993. return true;
  41994. }
  41995. int getSizeInUnits()
  41996. {
  41997. return text.length() + 16;
  41998. }
  41999. };
  42000. class TextEditor::RemoveAction : public UndoableAction
  42001. {
  42002. TextEditor& owner;
  42003. const Range<int> range;
  42004. const int oldCaretPos, newCaretPos;
  42005. Array <UniformTextSection*> removedSections;
  42006. RemoveAction (const RemoveAction&);
  42007. RemoveAction& operator= (const RemoveAction&);
  42008. public:
  42009. RemoveAction (TextEditor& owner_,
  42010. const Range<int> range_,
  42011. const int oldCaretPos_,
  42012. const int newCaretPos_,
  42013. const Array <UniformTextSection*>& removedSections_)
  42014. : owner (owner_),
  42015. range (range_),
  42016. oldCaretPos (oldCaretPos_),
  42017. newCaretPos (newCaretPos_),
  42018. removedSections (removedSections_)
  42019. {
  42020. }
  42021. ~RemoveAction()
  42022. {
  42023. for (int i = removedSections.size(); --i >= 0;)
  42024. {
  42025. UniformTextSection* const section = removedSections.getUnchecked (i);
  42026. section->clear();
  42027. delete section;
  42028. }
  42029. }
  42030. bool perform()
  42031. {
  42032. owner.remove (range, 0, newCaretPos);
  42033. return true;
  42034. }
  42035. bool undo()
  42036. {
  42037. owner.reinsert (range.getStart(), removedSections);
  42038. owner.moveCursorTo (oldCaretPos, false);
  42039. return true;
  42040. }
  42041. int getSizeInUnits()
  42042. {
  42043. int n = 0;
  42044. for (int i = removedSections.size(); --i >= 0;)
  42045. n += removedSections.getUnchecked (i)->getTotalLength();
  42046. return n + 16;
  42047. }
  42048. };
  42049. class TextEditor::TextHolderComponent : public Component,
  42050. public Timer,
  42051. public Value::Listener
  42052. {
  42053. public:
  42054. TextHolderComponent (TextEditor& owner_)
  42055. : owner (owner_)
  42056. {
  42057. setWantsKeyboardFocus (false);
  42058. setInterceptsMouseClicks (false, true);
  42059. owner.getTextValue().addListener (this);
  42060. }
  42061. ~TextHolderComponent()
  42062. {
  42063. owner.getTextValue().removeListener (this);
  42064. }
  42065. void paint (Graphics& g)
  42066. {
  42067. owner.drawContent (g);
  42068. }
  42069. void timerCallback()
  42070. {
  42071. owner.timerCallbackInt();
  42072. }
  42073. const MouseCursor getMouseCursor()
  42074. {
  42075. return owner.getMouseCursor();
  42076. }
  42077. void valueChanged (Value&)
  42078. {
  42079. owner.textWasChangedByValue();
  42080. }
  42081. private:
  42082. TextEditor& owner;
  42083. TextHolderComponent (const TextHolderComponent&);
  42084. TextHolderComponent& operator= (const TextHolderComponent&);
  42085. };
  42086. class TextEditorViewport : public Viewport
  42087. {
  42088. public:
  42089. TextEditorViewport (TextEditor* const owner_)
  42090. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42091. {
  42092. }
  42093. ~TextEditorViewport()
  42094. {
  42095. }
  42096. void visibleAreaChanged (int, int, int, int)
  42097. {
  42098. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42099. // appear and disappear, causing the wrap width to change.
  42100. {
  42101. const float wordWrapWidth = owner->getWordWrapWidth();
  42102. if (wordWrapWidth != lastWordWrapWidth)
  42103. {
  42104. lastWordWrapWidth = wordWrapWidth;
  42105. rentrant = true;
  42106. owner->updateTextHolderSize();
  42107. rentrant = false;
  42108. }
  42109. }
  42110. }
  42111. private:
  42112. TextEditor* const owner;
  42113. float lastWordWrapWidth;
  42114. bool rentrant;
  42115. TextEditorViewport (const TextEditorViewport&);
  42116. TextEditorViewport& operator= (const TextEditorViewport&);
  42117. };
  42118. namespace TextEditorDefs
  42119. {
  42120. const int flashSpeedIntervalMs = 380;
  42121. const int textChangeMessageId = 0x10003001;
  42122. const int returnKeyMessageId = 0x10003002;
  42123. const int escapeKeyMessageId = 0x10003003;
  42124. const int focusLossMessageId = 0x10003004;
  42125. const int maxActionsPerTransaction = 100;
  42126. }
  42127. TextEditor::TextEditor (const String& name,
  42128. const juce_wchar passwordCharacter_)
  42129. : Component (name),
  42130. borderSize (1, 1, 1, 3),
  42131. readOnly (false),
  42132. multiline (false),
  42133. wordWrap (false),
  42134. returnKeyStartsNewLine (false),
  42135. caretVisible (true),
  42136. popupMenuEnabled (true),
  42137. selectAllTextWhenFocused (false),
  42138. scrollbarVisible (true),
  42139. wasFocused (false),
  42140. caretFlashState (true),
  42141. keepCursorOnScreen (true),
  42142. tabKeyUsed (false),
  42143. menuActive (false),
  42144. valueTextNeedsUpdating (false),
  42145. cursorX (0),
  42146. cursorY (0),
  42147. cursorHeight (0),
  42148. maxTextLength (0),
  42149. leftIndent (4),
  42150. topIndent (4),
  42151. lastTransactionTime (0),
  42152. currentFont (14.0f),
  42153. totalNumChars (0),
  42154. caretPosition (0),
  42155. passwordCharacter (passwordCharacter_),
  42156. dragType (notDragging)
  42157. {
  42158. setOpaque (true);
  42159. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42160. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42161. viewport->setWantsKeyboardFocus (false);
  42162. viewport->setScrollBarsShown (false, false);
  42163. setMouseCursor (MouseCursor::IBeamCursor);
  42164. setWantsKeyboardFocus (true);
  42165. }
  42166. TextEditor::~TextEditor()
  42167. {
  42168. textValue.referTo (Value());
  42169. clearInternal (0);
  42170. viewport = 0;
  42171. textHolder = 0;
  42172. }
  42173. void TextEditor::newTransaction()
  42174. {
  42175. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42176. undoManager.beginNewTransaction();
  42177. }
  42178. void TextEditor::doUndoRedo (const bool isRedo)
  42179. {
  42180. if (! isReadOnly())
  42181. {
  42182. if (isRedo ? undoManager.redo()
  42183. : undoManager.undo())
  42184. {
  42185. scrollToMakeSureCursorIsVisible();
  42186. repaint();
  42187. textChanged();
  42188. }
  42189. }
  42190. }
  42191. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42192. const bool shouldWordWrap)
  42193. {
  42194. if (multiline != shouldBeMultiLine
  42195. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42196. {
  42197. multiline = shouldBeMultiLine;
  42198. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42199. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42200. scrollbarVisible && multiline);
  42201. viewport->setViewPosition (0, 0);
  42202. resized();
  42203. scrollToMakeSureCursorIsVisible();
  42204. }
  42205. }
  42206. bool TextEditor::isMultiLine() const
  42207. {
  42208. return multiline;
  42209. }
  42210. void TextEditor::setScrollbarsShown (bool shown)
  42211. {
  42212. if (scrollbarVisible != shown)
  42213. {
  42214. scrollbarVisible = shown;
  42215. shown = shown && isMultiLine();
  42216. viewport->setScrollBarsShown (shown, shown);
  42217. }
  42218. }
  42219. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42220. {
  42221. if (readOnly != shouldBeReadOnly)
  42222. {
  42223. readOnly = shouldBeReadOnly;
  42224. enablementChanged();
  42225. }
  42226. }
  42227. bool TextEditor::isReadOnly() const
  42228. {
  42229. return readOnly || ! isEnabled();
  42230. }
  42231. bool TextEditor::isTextInputActive() const
  42232. {
  42233. return ! isReadOnly();
  42234. }
  42235. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42236. {
  42237. returnKeyStartsNewLine = shouldStartNewLine;
  42238. }
  42239. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42240. {
  42241. tabKeyUsed = shouldTabKeyBeUsed;
  42242. }
  42243. void TextEditor::setPopupMenuEnabled (const bool b)
  42244. {
  42245. popupMenuEnabled = b;
  42246. }
  42247. void TextEditor::setSelectAllWhenFocused (const bool b)
  42248. {
  42249. selectAllTextWhenFocused = b;
  42250. }
  42251. const Font TextEditor::getFont() const
  42252. {
  42253. return currentFont;
  42254. }
  42255. void TextEditor::setFont (const Font& newFont)
  42256. {
  42257. currentFont = newFont;
  42258. scrollToMakeSureCursorIsVisible();
  42259. }
  42260. void TextEditor::applyFontToAllText (const Font& newFont)
  42261. {
  42262. currentFont = newFont;
  42263. const Colour overallColour (findColour (textColourId));
  42264. for (int i = sections.size(); --i >= 0;)
  42265. {
  42266. UniformTextSection* const uts = sections.getUnchecked (i);
  42267. uts->setFont (newFont, passwordCharacter);
  42268. uts->colour = overallColour;
  42269. }
  42270. coalesceSimilarSections();
  42271. updateTextHolderSize();
  42272. scrollToMakeSureCursorIsVisible();
  42273. repaint();
  42274. }
  42275. void TextEditor::colourChanged()
  42276. {
  42277. setOpaque (findColour (backgroundColourId).isOpaque());
  42278. repaint();
  42279. }
  42280. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42281. {
  42282. caretVisible = shouldCaretBeVisible;
  42283. if (shouldCaretBeVisible)
  42284. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42285. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42286. : MouseCursor::NormalCursor);
  42287. }
  42288. void TextEditor::setInputRestrictions (const int maxLen,
  42289. const String& chars)
  42290. {
  42291. maxTextLength = jmax (0, maxLen);
  42292. allowedCharacters = chars;
  42293. }
  42294. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42295. {
  42296. textToShowWhenEmpty = text;
  42297. colourForTextWhenEmpty = colourToUse;
  42298. }
  42299. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42300. {
  42301. if (passwordCharacter != newPasswordCharacter)
  42302. {
  42303. passwordCharacter = newPasswordCharacter;
  42304. resized();
  42305. repaint();
  42306. }
  42307. }
  42308. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42309. {
  42310. viewport->setScrollBarThickness (newThicknessPixels);
  42311. }
  42312. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42313. {
  42314. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42315. }
  42316. void TextEditor::clear()
  42317. {
  42318. clearInternal (0);
  42319. updateTextHolderSize();
  42320. undoManager.clearUndoHistory();
  42321. }
  42322. void TextEditor::setText (const String& newText,
  42323. const bool sendTextChangeMessage)
  42324. {
  42325. const int newLength = newText.length();
  42326. if (newLength != getTotalNumChars() || getText() != newText)
  42327. {
  42328. const int oldCursorPos = caretPosition;
  42329. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42330. clearInternal (0);
  42331. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42332. // if you're adding text with line-feeds to a single-line text editor, it
  42333. // ain't gonna look right!
  42334. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42335. if (cursorWasAtEnd && ! isMultiLine())
  42336. moveCursorTo (getTotalNumChars(), false);
  42337. else
  42338. moveCursorTo (oldCursorPos, false);
  42339. if (sendTextChangeMessage)
  42340. textChanged();
  42341. updateTextHolderSize();
  42342. scrollToMakeSureCursorIsVisible();
  42343. undoManager.clearUndoHistory();
  42344. repaint();
  42345. }
  42346. }
  42347. Value& TextEditor::getTextValue()
  42348. {
  42349. if (valueTextNeedsUpdating)
  42350. {
  42351. valueTextNeedsUpdating = false;
  42352. textValue = getText();
  42353. }
  42354. return textValue;
  42355. }
  42356. void TextEditor::textWasChangedByValue()
  42357. {
  42358. if (textValue.getValueSource().getReferenceCount() > 1)
  42359. setText (textValue.getValue());
  42360. }
  42361. void TextEditor::textChanged()
  42362. {
  42363. updateTextHolderSize();
  42364. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42365. if (textValue.getValueSource().getReferenceCount() > 1)
  42366. {
  42367. valueTextNeedsUpdating = false;
  42368. textValue = getText();
  42369. }
  42370. }
  42371. void TextEditor::returnPressed()
  42372. {
  42373. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42374. }
  42375. void TextEditor::escapePressed()
  42376. {
  42377. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42378. }
  42379. void TextEditor::addListener (Listener* const newListener)
  42380. {
  42381. listeners.add (newListener);
  42382. }
  42383. void TextEditor::removeListener (Listener* const listenerToRemove)
  42384. {
  42385. listeners.remove (listenerToRemove);
  42386. }
  42387. void TextEditor::timerCallbackInt()
  42388. {
  42389. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42390. if (caretFlashState != newState)
  42391. {
  42392. caretFlashState = newState;
  42393. if (caretFlashState)
  42394. wasFocused = true;
  42395. if (caretVisible
  42396. && hasKeyboardFocus (false)
  42397. && ! isReadOnly())
  42398. {
  42399. repaintCaret();
  42400. }
  42401. }
  42402. const unsigned int now = Time::getApproximateMillisecondCounter();
  42403. if (now > lastTransactionTime + 200)
  42404. newTransaction();
  42405. }
  42406. void TextEditor::repaintCaret()
  42407. {
  42408. if (! findColour (caretColourId).isTransparent())
  42409. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42410. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42411. 4,
  42412. roundToInt (cursorHeight) + 2);
  42413. }
  42414. void TextEditor::repaintText (const Range<int>& range)
  42415. {
  42416. if (! range.isEmpty())
  42417. {
  42418. float x = 0, y = 0, lh = currentFont.getHeight();
  42419. const float wordWrapWidth = getWordWrapWidth();
  42420. if (wordWrapWidth > 0)
  42421. {
  42422. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42423. i.getCharPosition (range.getStart(), x, y, lh);
  42424. const int y1 = (int) y;
  42425. int y2;
  42426. if (range.getEnd() >= getTotalNumChars())
  42427. {
  42428. y2 = textHolder->getHeight();
  42429. }
  42430. else
  42431. {
  42432. i.getCharPosition (range.getEnd(), x, y, lh);
  42433. y2 = (int) (y + lh * 2.0f);
  42434. }
  42435. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42436. }
  42437. }
  42438. }
  42439. void TextEditor::moveCaret (int newCaretPos)
  42440. {
  42441. if (newCaretPos < 0)
  42442. newCaretPos = 0;
  42443. else if (newCaretPos > getTotalNumChars())
  42444. newCaretPos = getTotalNumChars();
  42445. if (newCaretPos != getCaretPosition())
  42446. {
  42447. repaintCaret();
  42448. caretFlashState = true;
  42449. caretPosition = newCaretPos;
  42450. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42451. scrollToMakeSureCursorIsVisible();
  42452. repaintCaret();
  42453. }
  42454. }
  42455. void TextEditor::setCaretPosition (const int newIndex)
  42456. {
  42457. moveCursorTo (newIndex, false);
  42458. }
  42459. int TextEditor::getCaretPosition() const
  42460. {
  42461. return caretPosition;
  42462. }
  42463. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42464. const int desiredCaretY)
  42465. {
  42466. updateCaretPosition();
  42467. int vx = roundToInt (cursorX) - desiredCaretX;
  42468. int vy = roundToInt (cursorY) - desiredCaretY;
  42469. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42470. {
  42471. vx += desiredCaretX - proportionOfWidth (0.2f);
  42472. }
  42473. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42474. {
  42475. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42476. }
  42477. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42478. if (! isMultiLine())
  42479. {
  42480. vy = viewport->getViewPositionY();
  42481. }
  42482. else
  42483. {
  42484. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42485. const int curH = roundToInt (cursorHeight);
  42486. if (desiredCaretY < 0)
  42487. {
  42488. vy = jmax (0, desiredCaretY + vy);
  42489. }
  42490. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42491. {
  42492. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42493. }
  42494. }
  42495. viewport->setViewPosition (vx, vy);
  42496. }
  42497. const Rectangle<int> TextEditor::getCaretRectangle()
  42498. {
  42499. updateCaretPosition();
  42500. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42501. roundToInt (cursorY) - viewport->getY(),
  42502. 1, roundToInt (cursorHeight));
  42503. }
  42504. float TextEditor::getWordWrapWidth() const
  42505. {
  42506. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42507. : 1.0e10f;
  42508. }
  42509. void TextEditor::updateTextHolderSize()
  42510. {
  42511. const float wordWrapWidth = getWordWrapWidth();
  42512. if (wordWrapWidth > 0)
  42513. {
  42514. float maxWidth = 0.0f;
  42515. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42516. while (i.next())
  42517. maxWidth = jmax (maxWidth, i.atomRight);
  42518. const int w = leftIndent + roundToInt (maxWidth);
  42519. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42520. currentFont.getHeight()));
  42521. textHolder->setSize (w + 1, h + 1);
  42522. }
  42523. }
  42524. int TextEditor::getTextWidth() const
  42525. {
  42526. return textHolder->getWidth();
  42527. }
  42528. int TextEditor::getTextHeight() const
  42529. {
  42530. return textHolder->getHeight();
  42531. }
  42532. void TextEditor::setIndents (const int newLeftIndent,
  42533. const int newTopIndent)
  42534. {
  42535. leftIndent = newLeftIndent;
  42536. topIndent = newTopIndent;
  42537. }
  42538. void TextEditor::setBorder (const BorderSize& border)
  42539. {
  42540. borderSize = border;
  42541. resized();
  42542. }
  42543. const BorderSize TextEditor::getBorder() const
  42544. {
  42545. return borderSize;
  42546. }
  42547. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42548. {
  42549. keepCursorOnScreen = shouldScrollToShowCursor;
  42550. }
  42551. void TextEditor::updateCaretPosition()
  42552. {
  42553. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42554. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42555. }
  42556. void TextEditor::scrollToMakeSureCursorIsVisible()
  42557. {
  42558. updateCaretPosition();
  42559. if (keepCursorOnScreen)
  42560. {
  42561. int x = viewport->getViewPositionX();
  42562. int y = viewport->getViewPositionY();
  42563. const int relativeCursorX = roundToInt (cursorX) - x;
  42564. const int relativeCursorY = roundToInt (cursorY) - y;
  42565. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42566. {
  42567. x += relativeCursorX - proportionOfWidth (0.2f);
  42568. }
  42569. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42570. {
  42571. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42572. }
  42573. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42574. if (! isMultiLine())
  42575. {
  42576. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42577. }
  42578. else
  42579. {
  42580. const int curH = roundToInt (cursorHeight);
  42581. if (relativeCursorY < 0)
  42582. {
  42583. y = jmax (0, relativeCursorY + y);
  42584. }
  42585. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42586. {
  42587. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42588. }
  42589. }
  42590. viewport->setViewPosition (x, y);
  42591. }
  42592. }
  42593. void TextEditor::moveCursorTo (const int newPosition,
  42594. const bool isSelecting)
  42595. {
  42596. if (isSelecting)
  42597. {
  42598. moveCaret (newPosition);
  42599. const Range<int> oldSelection (selection);
  42600. if (dragType == notDragging)
  42601. {
  42602. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42603. dragType = draggingSelectionStart;
  42604. else
  42605. dragType = draggingSelectionEnd;
  42606. }
  42607. if (dragType == draggingSelectionStart)
  42608. {
  42609. if (getCaretPosition() >= selection.getEnd())
  42610. dragType = draggingSelectionEnd;
  42611. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42612. }
  42613. else
  42614. {
  42615. if (getCaretPosition() < selection.getStart())
  42616. dragType = draggingSelectionStart;
  42617. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42618. }
  42619. repaintText (selection.getUnionWith (oldSelection));
  42620. }
  42621. else
  42622. {
  42623. dragType = notDragging;
  42624. repaintText (selection);
  42625. moveCaret (newPosition);
  42626. selection = Range<int>::emptyRange (getCaretPosition());
  42627. }
  42628. }
  42629. int TextEditor::getTextIndexAt (const int x,
  42630. const int y)
  42631. {
  42632. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42633. (float) (y + viewport->getViewPositionY() - topIndent));
  42634. }
  42635. void TextEditor::insertTextAtCaret (const String& newText_)
  42636. {
  42637. String newText (newText_);
  42638. if (allowedCharacters.isNotEmpty())
  42639. newText = newText.retainCharacters (allowedCharacters);
  42640. if ((! returnKeyStartsNewLine) && newText == "\n")
  42641. {
  42642. returnPressed();
  42643. return;
  42644. }
  42645. if (! isMultiLine())
  42646. newText = newText.replaceCharacters ("\r\n", " ");
  42647. else
  42648. newText = newText.replace ("\r\n", "\n");
  42649. const int newCaretPos = selection.getStart() + newText.length();
  42650. const int insertIndex = selection.getStart();
  42651. remove (selection, getUndoManager(),
  42652. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42653. if (maxTextLength > 0)
  42654. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42655. if (newText.isNotEmpty())
  42656. insert (newText,
  42657. insertIndex,
  42658. currentFont,
  42659. findColour (textColourId),
  42660. getUndoManager(),
  42661. newCaretPos);
  42662. textChanged();
  42663. }
  42664. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42665. {
  42666. moveCursorTo (newSelection.getStart(), false);
  42667. moveCursorTo (newSelection.getEnd(), true);
  42668. }
  42669. void TextEditor::copy()
  42670. {
  42671. if (passwordCharacter == 0)
  42672. {
  42673. const String selectedText (getHighlightedText());
  42674. if (selectedText.isNotEmpty())
  42675. SystemClipboard::copyTextToClipboard (selectedText);
  42676. }
  42677. }
  42678. void TextEditor::paste()
  42679. {
  42680. if (! isReadOnly())
  42681. {
  42682. const String clip (SystemClipboard::getTextFromClipboard());
  42683. if (clip.isNotEmpty())
  42684. insertTextAtCaret (clip);
  42685. }
  42686. }
  42687. void TextEditor::cut()
  42688. {
  42689. if (! isReadOnly())
  42690. {
  42691. moveCaret (selection.getEnd());
  42692. insertTextAtCaret (String::empty);
  42693. }
  42694. }
  42695. void TextEditor::drawContent (Graphics& g)
  42696. {
  42697. const float wordWrapWidth = getWordWrapWidth();
  42698. if (wordWrapWidth > 0)
  42699. {
  42700. g.setOrigin (leftIndent, topIndent);
  42701. const Rectangle<int> clip (g.getClipBounds());
  42702. Colour selectedTextColour;
  42703. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42704. while (i.lineY + 200.0 < clip.getY() && i.next())
  42705. {}
  42706. if (! selection.isEmpty())
  42707. {
  42708. g.setColour (findColour (highlightColourId)
  42709. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42710. selectedTextColour = findColour (highlightedTextColourId);
  42711. Iterator i2 (i);
  42712. while (i2.next() && i2.lineY < clip.getBottom())
  42713. {
  42714. if (i2.lineY + i2.lineHeight >= clip.getY()
  42715. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42716. {
  42717. i2.drawSelection (g, selection);
  42718. }
  42719. }
  42720. }
  42721. const UniformTextSection* lastSection = 0;
  42722. while (i.next() && i.lineY < clip.getBottom())
  42723. {
  42724. if (i.lineY + i.lineHeight >= clip.getY())
  42725. {
  42726. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42727. {
  42728. i.drawSelectedText (g, selection, selectedTextColour);
  42729. lastSection = 0;
  42730. }
  42731. else
  42732. {
  42733. i.draw (g, lastSection);
  42734. }
  42735. }
  42736. }
  42737. }
  42738. }
  42739. void TextEditor::paint (Graphics& g)
  42740. {
  42741. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42742. }
  42743. void TextEditor::paintOverChildren (Graphics& g)
  42744. {
  42745. if (caretFlashState
  42746. && hasKeyboardFocus (false)
  42747. && caretVisible
  42748. && ! isReadOnly())
  42749. {
  42750. g.setColour (findColour (caretColourId));
  42751. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42752. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42753. 2.0f, cursorHeight);
  42754. }
  42755. if (textToShowWhenEmpty.isNotEmpty()
  42756. && (! hasKeyboardFocus (false))
  42757. && getTotalNumChars() == 0)
  42758. {
  42759. g.setColour (colourForTextWhenEmpty);
  42760. g.setFont (getFont());
  42761. if (isMultiLine())
  42762. {
  42763. g.drawText (textToShowWhenEmpty,
  42764. 0, 0, getWidth(), getHeight(),
  42765. Justification::centred, true);
  42766. }
  42767. else
  42768. {
  42769. g.drawText (textToShowWhenEmpty,
  42770. leftIndent, topIndent,
  42771. viewport->getWidth() - leftIndent,
  42772. viewport->getHeight() - topIndent,
  42773. Justification::centredLeft, true);
  42774. }
  42775. }
  42776. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42777. }
  42778. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  42779. {
  42780. public:
  42781. TextEditorMenuPerformer (TextEditor* const editor_)
  42782. : editor (editor_)
  42783. {
  42784. }
  42785. void modalStateFinished (int returnValue)
  42786. {
  42787. if (editor != 0 && returnValue != 0)
  42788. editor->performPopupMenuAction (returnValue);
  42789. }
  42790. private:
  42791. Component::SafePointer<TextEditor> editor;
  42792. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  42793. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  42794. };
  42795. void TextEditor::mouseDown (const MouseEvent& e)
  42796. {
  42797. beginDragAutoRepeat (100);
  42798. newTransaction();
  42799. if (wasFocused || ! selectAllTextWhenFocused)
  42800. {
  42801. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42802. {
  42803. moveCursorTo (getTextIndexAt (e.x, e.y),
  42804. e.mods.isShiftDown());
  42805. }
  42806. else
  42807. {
  42808. PopupMenu m;
  42809. m.setLookAndFeel (&getLookAndFeel());
  42810. addPopupMenuItems (m, &e);
  42811. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  42812. }
  42813. }
  42814. }
  42815. void TextEditor::mouseDrag (const MouseEvent& e)
  42816. {
  42817. if (wasFocused || ! selectAllTextWhenFocused)
  42818. {
  42819. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42820. {
  42821. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42822. }
  42823. }
  42824. }
  42825. void TextEditor::mouseUp (const MouseEvent& e)
  42826. {
  42827. newTransaction();
  42828. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42829. if (wasFocused || ! selectAllTextWhenFocused)
  42830. {
  42831. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42832. {
  42833. moveCaret (getTextIndexAt (e.x, e.y));
  42834. }
  42835. }
  42836. wasFocused = true;
  42837. }
  42838. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42839. {
  42840. int tokenEnd = getTextIndexAt (e.x, e.y);
  42841. int tokenStart = tokenEnd;
  42842. if (e.getNumberOfClicks() > 3)
  42843. {
  42844. tokenStart = 0;
  42845. tokenEnd = getTotalNumChars();
  42846. }
  42847. else
  42848. {
  42849. const String t (getText());
  42850. const int totalLength = getTotalNumChars();
  42851. while (tokenEnd < totalLength)
  42852. {
  42853. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42854. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42855. ++tokenEnd;
  42856. else
  42857. break;
  42858. }
  42859. tokenStart = tokenEnd;
  42860. while (tokenStart > 0)
  42861. {
  42862. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42863. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42864. --tokenStart;
  42865. else
  42866. break;
  42867. }
  42868. if (e.getNumberOfClicks() > 2)
  42869. {
  42870. while (tokenEnd < totalLength)
  42871. {
  42872. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42873. ++tokenEnd;
  42874. else
  42875. break;
  42876. }
  42877. while (tokenStart > 0)
  42878. {
  42879. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42880. --tokenStart;
  42881. else
  42882. break;
  42883. }
  42884. }
  42885. }
  42886. moveCursorTo (tokenEnd, false);
  42887. moveCursorTo (tokenStart, true);
  42888. }
  42889. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42890. {
  42891. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42892. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42893. }
  42894. bool TextEditor::keyPressed (const KeyPress& key)
  42895. {
  42896. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42897. return false;
  42898. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42899. if (key.isKeyCode (KeyPress::leftKey)
  42900. || key.isKeyCode (KeyPress::upKey))
  42901. {
  42902. newTransaction();
  42903. int newPos;
  42904. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42905. newPos = indexAtPosition (cursorX, cursorY - 1);
  42906. else if (moveInWholeWordSteps)
  42907. newPos = findWordBreakBefore (getCaretPosition());
  42908. else
  42909. newPos = getCaretPosition() - 1;
  42910. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42911. }
  42912. else if (key.isKeyCode (KeyPress::rightKey)
  42913. || key.isKeyCode (KeyPress::downKey))
  42914. {
  42915. newTransaction();
  42916. int newPos;
  42917. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42918. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42919. else if (moveInWholeWordSteps)
  42920. newPos = findWordBreakAfter (getCaretPosition());
  42921. else
  42922. newPos = getCaretPosition() + 1;
  42923. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42924. }
  42925. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42926. {
  42927. newTransaction();
  42928. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42929. key.getModifiers().isShiftDown());
  42930. }
  42931. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42932. {
  42933. newTransaction();
  42934. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42935. key.getModifiers().isShiftDown());
  42936. }
  42937. else if (key.isKeyCode (KeyPress::homeKey))
  42938. {
  42939. newTransaction();
  42940. if (isMultiLine() && ! moveInWholeWordSteps)
  42941. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42942. key.getModifiers().isShiftDown());
  42943. else
  42944. moveCursorTo (0, key.getModifiers().isShiftDown());
  42945. }
  42946. else if (key.isKeyCode (KeyPress::endKey))
  42947. {
  42948. newTransaction();
  42949. if (isMultiLine() && ! moveInWholeWordSteps)
  42950. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42951. key.getModifiers().isShiftDown());
  42952. else
  42953. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42954. }
  42955. else if (key.isKeyCode (KeyPress::backspaceKey))
  42956. {
  42957. if (moveInWholeWordSteps)
  42958. {
  42959. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42960. }
  42961. else
  42962. {
  42963. if (selection.isEmpty() && selection.getStart() > 0)
  42964. selection.setStart (selection.getEnd() - 1);
  42965. }
  42966. cut();
  42967. }
  42968. else if (key.isKeyCode (KeyPress::deleteKey))
  42969. {
  42970. if (key.getModifiers().isShiftDown())
  42971. copy();
  42972. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42973. selection.setEnd (selection.getStart() + 1);
  42974. cut();
  42975. }
  42976. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42977. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42978. {
  42979. newTransaction();
  42980. copy();
  42981. }
  42982. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42983. {
  42984. newTransaction();
  42985. copy();
  42986. cut();
  42987. }
  42988. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42989. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42990. {
  42991. newTransaction();
  42992. paste();
  42993. }
  42994. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42995. {
  42996. newTransaction();
  42997. doUndoRedo (false);
  42998. }
  42999. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43000. {
  43001. newTransaction();
  43002. doUndoRedo (true);
  43003. }
  43004. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43005. {
  43006. newTransaction();
  43007. moveCursorTo (getTotalNumChars(), false);
  43008. moveCursorTo (0, true);
  43009. }
  43010. else if (key == KeyPress::returnKey)
  43011. {
  43012. newTransaction();
  43013. insertTextAtCaret ("\n");
  43014. }
  43015. else if (key.isKeyCode (KeyPress::escapeKey))
  43016. {
  43017. newTransaction();
  43018. moveCursorTo (getCaretPosition(), false);
  43019. escapePressed();
  43020. }
  43021. else if (key.getTextCharacter() >= ' '
  43022. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43023. {
  43024. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43025. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43026. }
  43027. else
  43028. {
  43029. return false;
  43030. }
  43031. return true;
  43032. }
  43033. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43034. {
  43035. if (! isKeyDown)
  43036. return false;
  43037. #if JUCE_WINDOWS
  43038. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43039. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43040. #endif
  43041. // (overridden to avoid forwarding key events to the parent)
  43042. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43043. }
  43044. const int baseMenuItemID = 0x7fff0000;
  43045. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43046. {
  43047. const bool writable = ! isReadOnly();
  43048. if (passwordCharacter == 0)
  43049. {
  43050. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43051. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43052. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43053. }
  43054. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43055. m.addSeparator();
  43056. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43057. m.addSeparator();
  43058. if (getUndoManager() != 0)
  43059. {
  43060. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43061. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43062. }
  43063. }
  43064. void TextEditor::performPopupMenuAction (const int menuItemID)
  43065. {
  43066. switch (menuItemID)
  43067. {
  43068. case baseMenuItemID + 1:
  43069. copy();
  43070. cut();
  43071. break;
  43072. case baseMenuItemID + 2:
  43073. copy();
  43074. break;
  43075. case baseMenuItemID + 3:
  43076. paste();
  43077. break;
  43078. case baseMenuItemID + 4:
  43079. cut();
  43080. break;
  43081. case baseMenuItemID + 5:
  43082. moveCursorTo (getTotalNumChars(), false);
  43083. moveCursorTo (0, true);
  43084. break;
  43085. case baseMenuItemID + 6:
  43086. doUndoRedo (false);
  43087. break;
  43088. case baseMenuItemID + 7:
  43089. doUndoRedo (true);
  43090. break;
  43091. default:
  43092. break;
  43093. }
  43094. }
  43095. void TextEditor::focusGained (FocusChangeType)
  43096. {
  43097. newTransaction();
  43098. caretFlashState = true;
  43099. if (selectAllTextWhenFocused)
  43100. {
  43101. moveCursorTo (0, false);
  43102. moveCursorTo (getTotalNumChars(), true);
  43103. }
  43104. repaint();
  43105. if (caretVisible)
  43106. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43107. ComponentPeer* const peer = getPeer();
  43108. if (peer != 0 && ! isReadOnly())
  43109. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43110. }
  43111. void TextEditor::focusLost (FocusChangeType)
  43112. {
  43113. newTransaction();
  43114. wasFocused = false;
  43115. textHolder->stopTimer();
  43116. caretFlashState = false;
  43117. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43118. repaint();
  43119. }
  43120. void TextEditor::resized()
  43121. {
  43122. viewport->setBoundsInset (borderSize);
  43123. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43124. updateTextHolderSize();
  43125. if (! isMultiLine())
  43126. {
  43127. scrollToMakeSureCursorIsVisible();
  43128. }
  43129. else
  43130. {
  43131. updateCaretPosition();
  43132. }
  43133. }
  43134. void TextEditor::handleCommandMessage (const int commandId)
  43135. {
  43136. Component::BailOutChecker checker (this);
  43137. switch (commandId)
  43138. {
  43139. case TextEditorDefs::textChangeMessageId:
  43140. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43141. break;
  43142. case TextEditorDefs::returnKeyMessageId:
  43143. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43144. break;
  43145. case TextEditorDefs::escapeKeyMessageId:
  43146. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43147. break;
  43148. case TextEditorDefs::focusLossMessageId:
  43149. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43150. break;
  43151. default:
  43152. jassertfalse;
  43153. break;
  43154. }
  43155. }
  43156. void TextEditor::enablementChanged()
  43157. {
  43158. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43159. : MouseCursor::IBeamCursor);
  43160. repaint();
  43161. }
  43162. UndoManager* TextEditor::getUndoManager() throw()
  43163. {
  43164. return isReadOnly() ? 0 : &undoManager;
  43165. }
  43166. void TextEditor::clearInternal (UndoManager* const um)
  43167. {
  43168. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43169. }
  43170. void TextEditor::insert (const String& text,
  43171. const int insertIndex,
  43172. const Font& font,
  43173. const Colour& colour,
  43174. UndoManager* const um,
  43175. const int caretPositionToMoveTo)
  43176. {
  43177. if (text.isNotEmpty())
  43178. {
  43179. if (um != 0)
  43180. {
  43181. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43182. newTransaction();
  43183. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43184. caretPosition, caretPositionToMoveTo));
  43185. }
  43186. else
  43187. {
  43188. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43189. // a line gets moved due to word wrap
  43190. int index = 0;
  43191. int nextIndex = 0;
  43192. for (int i = 0; i < sections.size(); ++i)
  43193. {
  43194. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43195. if (insertIndex == index)
  43196. {
  43197. sections.insert (i, new UniformTextSection (text,
  43198. font, colour,
  43199. passwordCharacter));
  43200. break;
  43201. }
  43202. else if (insertIndex > index && insertIndex < nextIndex)
  43203. {
  43204. splitSection (i, insertIndex - index);
  43205. sections.insert (i + 1, new UniformTextSection (text,
  43206. font, colour,
  43207. passwordCharacter));
  43208. break;
  43209. }
  43210. index = nextIndex;
  43211. }
  43212. if (nextIndex == insertIndex)
  43213. sections.add (new UniformTextSection (text,
  43214. font, colour,
  43215. passwordCharacter));
  43216. coalesceSimilarSections();
  43217. totalNumChars = -1;
  43218. valueTextNeedsUpdating = true;
  43219. moveCursorTo (caretPositionToMoveTo, false);
  43220. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43221. }
  43222. }
  43223. }
  43224. void TextEditor::reinsert (const int insertIndex,
  43225. const Array <UniformTextSection*>& sectionsToInsert)
  43226. {
  43227. int index = 0;
  43228. int nextIndex = 0;
  43229. for (int i = 0; i < sections.size(); ++i)
  43230. {
  43231. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43232. if (insertIndex == index)
  43233. {
  43234. for (int j = sectionsToInsert.size(); --j >= 0;)
  43235. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43236. break;
  43237. }
  43238. else if (insertIndex > index && insertIndex < nextIndex)
  43239. {
  43240. splitSection (i, insertIndex - index);
  43241. for (int j = sectionsToInsert.size(); --j >= 0;)
  43242. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43243. break;
  43244. }
  43245. index = nextIndex;
  43246. }
  43247. if (nextIndex == insertIndex)
  43248. {
  43249. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43250. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43251. }
  43252. coalesceSimilarSections();
  43253. totalNumChars = -1;
  43254. valueTextNeedsUpdating = true;
  43255. }
  43256. void TextEditor::remove (const Range<int>& range,
  43257. UndoManager* const um,
  43258. const int caretPositionToMoveTo)
  43259. {
  43260. if (! range.isEmpty())
  43261. {
  43262. int index = 0;
  43263. for (int i = 0; i < sections.size(); ++i)
  43264. {
  43265. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43266. if (range.getStart() > index && range.getStart() < nextIndex)
  43267. {
  43268. splitSection (i, range.getStart() - index);
  43269. --i;
  43270. }
  43271. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43272. {
  43273. splitSection (i, range.getEnd() - index);
  43274. --i;
  43275. }
  43276. else
  43277. {
  43278. index = nextIndex;
  43279. if (index > range.getEnd())
  43280. break;
  43281. }
  43282. }
  43283. index = 0;
  43284. if (um != 0)
  43285. {
  43286. Array <UniformTextSection*> removedSections;
  43287. for (int i = 0; i < sections.size(); ++i)
  43288. {
  43289. if (range.getEnd() <= range.getStart())
  43290. break;
  43291. UniformTextSection* const section = sections.getUnchecked (i);
  43292. const int nextIndex = index + section->getTotalLength();
  43293. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43294. removedSections.add (new UniformTextSection (*section));
  43295. index = nextIndex;
  43296. }
  43297. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43298. newTransaction();
  43299. um->perform (new RemoveAction (*this, range, caretPosition,
  43300. caretPositionToMoveTo, removedSections));
  43301. }
  43302. else
  43303. {
  43304. Range<int> remainingRange (range);
  43305. for (int i = 0; i < sections.size(); ++i)
  43306. {
  43307. UniformTextSection* const section = sections.getUnchecked (i);
  43308. const int nextIndex = index + section->getTotalLength();
  43309. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43310. {
  43311. sections.remove(i);
  43312. section->clear();
  43313. delete section;
  43314. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43315. if (remainingRange.isEmpty())
  43316. break;
  43317. --i;
  43318. }
  43319. else
  43320. {
  43321. index = nextIndex;
  43322. }
  43323. }
  43324. coalesceSimilarSections();
  43325. totalNumChars = -1;
  43326. valueTextNeedsUpdating = true;
  43327. moveCursorTo (caretPositionToMoveTo, false);
  43328. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43329. }
  43330. }
  43331. }
  43332. const String TextEditor::getText() const
  43333. {
  43334. String t;
  43335. t.preallocateStorage (getTotalNumChars());
  43336. String::Concatenator concatenator (t);
  43337. for (int i = 0; i < sections.size(); ++i)
  43338. sections.getUnchecked (i)->appendAllText (concatenator);
  43339. return t;
  43340. }
  43341. const String TextEditor::getTextInRange (const Range<int>& range) const
  43342. {
  43343. String t;
  43344. if (! range.isEmpty())
  43345. {
  43346. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43347. String::Concatenator concatenator (t);
  43348. int index = 0;
  43349. for (int i = 0; i < sections.size(); ++i)
  43350. {
  43351. const UniformTextSection* const s = sections.getUnchecked (i);
  43352. const int nextIndex = index + s->getTotalLength();
  43353. if (range.getStart() < nextIndex)
  43354. {
  43355. if (range.getEnd() <= index)
  43356. break;
  43357. s->appendSubstring (concatenator, range - index);
  43358. }
  43359. index = nextIndex;
  43360. }
  43361. }
  43362. return t;
  43363. }
  43364. const String TextEditor::getHighlightedText() const
  43365. {
  43366. return getTextInRange (selection);
  43367. }
  43368. int TextEditor::getTotalNumChars() const
  43369. {
  43370. if (totalNumChars < 0)
  43371. {
  43372. totalNumChars = 0;
  43373. for (int i = sections.size(); --i >= 0;)
  43374. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43375. }
  43376. return totalNumChars;
  43377. }
  43378. bool TextEditor::isEmpty() const
  43379. {
  43380. return getTotalNumChars() == 0;
  43381. }
  43382. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43383. {
  43384. const float wordWrapWidth = getWordWrapWidth();
  43385. if (wordWrapWidth > 0 && sections.size() > 0)
  43386. {
  43387. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43388. i.getCharPosition (index, cx, cy, lineHeight);
  43389. }
  43390. else
  43391. {
  43392. cx = cy = 0;
  43393. lineHeight = currentFont.getHeight();
  43394. }
  43395. }
  43396. int TextEditor::indexAtPosition (const float x, const float y)
  43397. {
  43398. const float wordWrapWidth = getWordWrapWidth();
  43399. if (wordWrapWidth > 0)
  43400. {
  43401. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43402. while (i.next())
  43403. {
  43404. if (i.lineY + i.lineHeight > y)
  43405. {
  43406. if (i.lineY > y)
  43407. return jmax (0, i.indexInText - 1);
  43408. if (i.atomX >= x)
  43409. return i.indexInText;
  43410. if (x < i.atomRight)
  43411. return i.xToIndex (x);
  43412. }
  43413. }
  43414. }
  43415. return getTotalNumChars();
  43416. }
  43417. static int getCharacterCategory (const juce_wchar character)
  43418. {
  43419. return CharacterFunctions::isLetterOrDigit (character)
  43420. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43421. }
  43422. int TextEditor::findWordBreakAfter (const int position) const
  43423. {
  43424. const String t (getTextInRange (Range<int> (position, position + 512)));
  43425. const int totalLength = t.length();
  43426. int i = 0;
  43427. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43428. ++i;
  43429. const int type = getCharacterCategory (t[i]);
  43430. while (i < totalLength && type == getCharacterCategory (t[i]))
  43431. ++i;
  43432. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43433. ++i;
  43434. return position + i;
  43435. }
  43436. int TextEditor::findWordBreakBefore (const int position) const
  43437. {
  43438. if (position <= 0)
  43439. return 0;
  43440. const int startOfBuffer = jmax (0, position - 512);
  43441. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43442. int i = position - startOfBuffer;
  43443. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43444. --i;
  43445. if (i > 0)
  43446. {
  43447. const int type = getCharacterCategory (t [i - 1]);
  43448. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43449. --i;
  43450. }
  43451. jassert (startOfBuffer + i >= 0);
  43452. return startOfBuffer + i;
  43453. }
  43454. void TextEditor::splitSection (const int sectionIndex,
  43455. const int charToSplitAt)
  43456. {
  43457. jassert (sections[sectionIndex] != 0);
  43458. sections.insert (sectionIndex + 1,
  43459. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43460. }
  43461. void TextEditor::coalesceSimilarSections()
  43462. {
  43463. for (int i = 0; i < sections.size() - 1; ++i)
  43464. {
  43465. UniformTextSection* const s1 = sections.getUnchecked (i);
  43466. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43467. if (s1->font == s2->font
  43468. && s1->colour == s2->colour)
  43469. {
  43470. s1->append (*s2, passwordCharacter);
  43471. sections.remove (i + 1);
  43472. delete s2;
  43473. --i;
  43474. }
  43475. }
  43476. }
  43477. END_JUCE_NAMESPACE
  43478. /*** End of inlined file: juce_TextEditor.cpp ***/
  43479. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43480. BEGIN_JUCE_NAMESPACE
  43481. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43482. class ToolbarSpacerComp : public ToolbarItemComponent
  43483. {
  43484. public:
  43485. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43486. : ToolbarItemComponent (itemId_, String::empty, false),
  43487. fixedSize (fixedSize_),
  43488. drawBar (drawBar_)
  43489. {
  43490. }
  43491. ~ToolbarSpacerComp()
  43492. {
  43493. }
  43494. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43495. int& preferredSize, int& minSize, int& maxSize)
  43496. {
  43497. if (fixedSize <= 0)
  43498. {
  43499. preferredSize = toolbarThickness * 2;
  43500. minSize = 4;
  43501. maxSize = 32768;
  43502. }
  43503. else
  43504. {
  43505. maxSize = roundToInt (toolbarThickness * fixedSize);
  43506. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43507. preferredSize = maxSize;
  43508. if (getEditingMode() == editableOnPalette)
  43509. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43510. }
  43511. return true;
  43512. }
  43513. void paintButtonArea (Graphics&, int, int, bool, bool)
  43514. {
  43515. }
  43516. void contentAreaChanged (const Rectangle<int>&)
  43517. {
  43518. }
  43519. int getResizeOrder() const throw()
  43520. {
  43521. return fixedSize <= 0 ? 0 : 1;
  43522. }
  43523. void paint (Graphics& g)
  43524. {
  43525. const int w = getWidth();
  43526. const int h = getHeight();
  43527. if (drawBar)
  43528. {
  43529. g.setColour (findColour (Toolbar::separatorColourId, true));
  43530. const float thickness = 0.2f;
  43531. if (isToolbarVertical())
  43532. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43533. else
  43534. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43535. }
  43536. if (getEditingMode() != normalMode && ! drawBar)
  43537. {
  43538. g.setColour (findColour (Toolbar::separatorColourId, true));
  43539. const int indentX = jmin (2, (w - 3) / 2);
  43540. const int indentY = jmin (2, (h - 3) / 2);
  43541. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43542. if (fixedSize <= 0)
  43543. {
  43544. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43545. if (isToolbarVertical())
  43546. {
  43547. x1 = w * 0.5f;
  43548. y1 = h * 0.4f;
  43549. x2 = x1;
  43550. y2 = indentX * 2.0f;
  43551. x3 = x1;
  43552. y3 = h * 0.6f;
  43553. x4 = x1;
  43554. y4 = h - y2;
  43555. hw = w * 0.15f;
  43556. hl = w * 0.2f;
  43557. }
  43558. else
  43559. {
  43560. x1 = w * 0.4f;
  43561. y1 = h * 0.5f;
  43562. x2 = indentX * 2.0f;
  43563. y2 = y1;
  43564. x3 = w * 0.6f;
  43565. y3 = y1;
  43566. x4 = w - x2;
  43567. y4 = y1;
  43568. hw = h * 0.15f;
  43569. hl = h * 0.2f;
  43570. }
  43571. Path p;
  43572. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43573. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43574. g.fillPath (p);
  43575. }
  43576. }
  43577. }
  43578. juce_UseDebuggingNewOperator
  43579. private:
  43580. const float fixedSize;
  43581. const bool drawBar;
  43582. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43583. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43584. };
  43585. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  43586. {
  43587. public:
  43588. MissingItemsComponent (Toolbar& owner_, const int height_)
  43589. : PopupMenuCustomComponent (true),
  43590. owner (owner_),
  43591. height (height_)
  43592. {
  43593. for (int i = owner_.items.size(); --i >= 0;)
  43594. {
  43595. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43596. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43597. {
  43598. oldIndexes.insert (0, i);
  43599. addAndMakeVisible (tc, 0);
  43600. }
  43601. }
  43602. layout (400);
  43603. }
  43604. ~MissingItemsComponent()
  43605. {
  43606. // deleting the toolbar while its menu it open??
  43607. jassert (owner.isValidComponent());
  43608. for (int i = 0; i < getNumChildComponents(); ++i)
  43609. {
  43610. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43611. if (tc != 0)
  43612. {
  43613. tc->setVisible (false);
  43614. const int index = oldIndexes.remove (i);
  43615. owner.addChildComponent (tc, index);
  43616. --i;
  43617. }
  43618. }
  43619. owner.resized();
  43620. }
  43621. void layout (const int preferredWidth)
  43622. {
  43623. const int indent = 8;
  43624. int x = indent;
  43625. int y = indent;
  43626. int maxX = 0;
  43627. for (int i = 0; i < getNumChildComponents(); ++i)
  43628. {
  43629. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43630. if (tc != 0)
  43631. {
  43632. int preferredSize = 1, minSize = 1, maxSize = 1;
  43633. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43634. {
  43635. if (x + preferredSize > preferredWidth && x > indent)
  43636. {
  43637. x = indent;
  43638. y += height;
  43639. }
  43640. tc->setBounds (x, y, preferredSize, height);
  43641. x += preferredSize;
  43642. maxX = jmax (maxX, x);
  43643. }
  43644. }
  43645. }
  43646. setSize (maxX + 8, y + height + 8);
  43647. }
  43648. void getIdealSize (int& idealWidth, int& idealHeight)
  43649. {
  43650. idealWidth = getWidth();
  43651. idealHeight = getHeight();
  43652. }
  43653. juce_UseDebuggingNewOperator
  43654. private:
  43655. Toolbar& owner;
  43656. const int height;
  43657. Array <int> oldIndexes;
  43658. MissingItemsComponent (const MissingItemsComponent&);
  43659. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43660. };
  43661. Toolbar::Toolbar()
  43662. : vertical (false),
  43663. isEditingActive (false),
  43664. toolbarStyle (Toolbar::iconsOnly)
  43665. {
  43666. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43667. missingItemsButton->setAlwaysOnTop (true);
  43668. missingItemsButton->addButtonListener (this);
  43669. }
  43670. Toolbar::~Toolbar()
  43671. {
  43672. animator.cancelAllAnimations (true);
  43673. deleteAllChildren();
  43674. }
  43675. void Toolbar::setVertical (const bool shouldBeVertical)
  43676. {
  43677. if (vertical != shouldBeVertical)
  43678. {
  43679. vertical = shouldBeVertical;
  43680. resized();
  43681. }
  43682. }
  43683. void Toolbar::clear()
  43684. {
  43685. for (int i = items.size(); --i >= 0;)
  43686. {
  43687. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43688. items.remove (i);
  43689. delete tc;
  43690. }
  43691. resized();
  43692. }
  43693. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43694. {
  43695. if (itemId == ToolbarItemFactory::separatorBarId)
  43696. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43697. else if (itemId == ToolbarItemFactory::spacerId)
  43698. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43699. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43700. return new ToolbarSpacerComp (itemId, 0, false);
  43701. return factory.createItem (itemId);
  43702. }
  43703. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43704. const int itemId,
  43705. const int insertIndex)
  43706. {
  43707. // An ID can't be zero - this might indicate a mistake somewhere?
  43708. jassert (itemId != 0);
  43709. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43710. if (tc != 0)
  43711. {
  43712. #if JUCE_DEBUG
  43713. Array <int> allowedIds;
  43714. factory.getAllToolbarItemIds (allowedIds);
  43715. // If your factory can create an item for a given ID, it must also return
  43716. // that ID from its getAllToolbarItemIds() method!
  43717. jassert (allowedIds.contains (itemId));
  43718. #endif
  43719. items.insert (insertIndex, tc);
  43720. addAndMakeVisible (tc, insertIndex);
  43721. }
  43722. }
  43723. void Toolbar::addItem (ToolbarItemFactory& factory,
  43724. const int itemId,
  43725. const int insertIndex)
  43726. {
  43727. addItemInternal (factory, itemId, insertIndex);
  43728. resized();
  43729. }
  43730. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43731. {
  43732. Array <int> ids;
  43733. factoryToUse.getDefaultItemSet (ids);
  43734. clear();
  43735. for (int i = 0; i < ids.size(); ++i)
  43736. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43737. resized();
  43738. }
  43739. void Toolbar::removeToolbarItem (const int itemIndex)
  43740. {
  43741. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43742. if (tc != 0)
  43743. {
  43744. items.removeValue (tc);
  43745. delete tc;
  43746. resized();
  43747. }
  43748. }
  43749. int Toolbar::getNumItems() const throw()
  43750. {
  43751. return items.size();
  43752. }
  43753. int Toolbar::getItemId (const int itemIndex) const throw()
  43754. {
  43755. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43756. return tc != 0 ? tc->getItemId() : 0;
  43757. }
  43758. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43759. {
  43760. return items [itemIndex];
  43761. }
  43762. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43763. {
  43764. for (;;)
  43765. {
  43766. index += delta;
  43767. ToolbarItemComponent* const tc = getItemComponent (index);
  43768. if (tc == 0)
  43769. break;
  43770. if (tc->isActive)
  43771. return tc;
  43772. }
  43773. return 0;
  43774. }
  43775. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43776. {
  43777. if (toolbarStyle != newStyle)
  43778. {
  43779. toolbarStyle = newStyle;
  43780. updateAllItemPositions (false);
  43781. }
  43782. }
  43783. const String Toolbar::toString() const
  43784. {
  43785. String s ("TB:");
  43786. for (int i = 0; i < getNumItems(); ++i)
  43787. s << getItemId(i) << ' ';
  43788. return s.trimEnd();
  43789. }
  43790. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43791. const String& savedVersion)
  43792. {
  43793. if (! savedVersion.startsWith ("TB:"))
  43794. return false;
  43795. StringArray tokens;
  43796. tokens.addTokens (savedVersion.substring (3), false);
  43797. clear();
  43798. for (int i = 0; i < tokens.size(); ++i)
  43799. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43800. resized();
  43801. return true;
  43802. }
  43803. void Toolbar::paint (Graphics& g)
  43804. {
  43805. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43806. }
  43807. int Toolbar::getThickness() const throw()
  43808. {
  43809. return vertical ? getWidth() : getHeight();
  43810. }
  43811. int Toolbar::getLength() const throw()
  43812. {
  43813. return vertical ? getHeight() : getWidth();
  43814. }
  43815. void Toolbar::setEditingActive (const bool active)
  43816. {
  43817. if (isEditingActive != active)
  43818. {
  43819. isEditingActive = active;
  43820. updateAllItemPositions (false);
  43821. }
  43822. }
  43823. void Toolbar::resized()
  43824. {
  43825. updateAllItemPositions (false);
  43826. }
  43827. void Toolbar::updateAllItemPositions (const bool animate)
  43828. {
  43829. if (getWidth() > 0 && getHeight() > 0)
  43830. {
  43831. StretchableObjectResizer resizer;
  43832. int i;
  43833. for (i = 0; i < items.size(); ++i)
  43834. {
  43835. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43836. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43837. : ToolbarItemComponent::normalMode);
  43838. tc->setStyle (toolbarStyle);
  43839. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43840. int preferredSize = 1, minSize = 1, maxSize = 1;
  43841. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43842. preferredSize, minSize, maxSize))
  43843. {
  43844. tc->isActive = true;
  43845. resizer.addItem (preferredSize, minSize, maxSize,
  43846. spacer != 0 ? spacer->getResizeOrder() : 2);
  43847. }
  43848. else
  43849. {
  43850. tc->isActive = false;
  43851. tc->setVisible (false);
  43852. }
  43853. }
  43854. resizer.resizeToFit (getLength());
  43855. int totalLength = 0;
  43856. for (i = 0; i < resizer.getNumItems(); ++i)
  43857. totalLength += (int) resizer.getItemSize (i);
  43858. const bool itemsOffTheEnd = totalLength > getLength();
  43859. const int extrasButtonSize = getThickness() / 2;
  43860. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43861. missingItemsButton->setVisible (itemsOffTheEnd);
  43862. missingItemsButton->setEnabled (! isEditingActive);
  43863. if (vertical)
  43864. missingItemsButton->setCentrePosition (getWidth() / 2,
  43865. getHeight() - 4 - extrasButtonSize / 2);
  43866. else
  43867. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43868. getHeight() / 2);
  43869. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43870. : missingItemsButton->getX()) - 4
  43871. : getLength();
  43872. int pos = 0, activeIndex = 0;
  43873. for (i = 0; i < items.size(); ++i)
  43874. {
  43875. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43876. if (tc->isActive)
  43877. {
  43878. const int size = (int) resizer.getItemSize (activeIndex++);
  43879. Rectangle<int> newBounds;
  43880. if (vertical)
  43881. newBounds.setBounds (0, pos, getWidth(), size);
  43882. else
  43883. newBounds.setBounds (pos, 0, size, getHeight());
  43884. if (animate)
  43885. {
  43886. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43887. }
  43888. else
  43889. {
  43890. animator.cancelAnimation (tc, false);
  43891. tc->setBounds (newBounds);
  43892. }
  43893. pos += size;
  43894. tc->setVisible (pos <= maxLength
  43895. && ((! tc->isBeingDragged)
  43896. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43897. }
  43898. }
  43899. }
  43900. }
  43901. void Toolbar::buttonClicked (Button*)
  43902. {
  43903. jassert (missingItemsButton->isShowing());
  43904. if (missingItemsButton->isShowing())
  43905. {
  43906. PopupMenu m;
  43907. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43908. m.showAt (missingItemsButton);
  43909. }
  43910. }
  43911. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43912. Component* /*sourceComponent*/)
  43913. {
  43914. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43915. }
  43916. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43917. {
  43918. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43919. if (tc != 0)
  43920. {
  43921. if (getNumItems() == 0)
  43922. {
  43923. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43924. {
  43925. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43926. if (palette != 0)
  43927. palette->replaceComponent (tc);
  43928. }
  43929. else
  43930. {
  43931. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43932. }
  43933. items.add (tc);
  43934. addChildComponent (tc);
  43935. updateAllItemPositions (false);
  43936. }
  43937. else
  43938. {
  43939. for (int i = getNumItems(); --i >= 0;)
  43940. {
  43941. int currentIndex = getIndexOfChildComponent (tc);
  43942. if (currentIndex < 0)
  43943. {
  43944. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43945. {
  43946. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43947. if (palette != 0)
  43948. palette->replaceComponent (tc);
  43949. }
  43950. else
  43951. {
  43952. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43953. }
  43954. items.add (tc);
  43955. addChildComponent (tc);
  43956. currentIndex = getIndexOfChildComponent (tc);
  43957. updateAllItemPositions (true);
  43958. }
  43959. int newIndex = currentIndex;
  43960. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43961. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43962. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43963. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43964. if (prev != 0)
  43965. {
  43966. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43967. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43968. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43969. {
  43970. newIndex = getIndexOfChildComponent (prev);
  43971. }
  43972. }
  43973. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43974. if (next != 0)
  43975. {
  43976. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43977. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43978. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43979. {
  43980. newIndex = getIndexOfChildComponent (next) + 1;
  43981. }
  43982. }
  43983. if (newIndex != currentIndex)
  43984. {
  43985. items.removeValue (tc);
  43986. removeChildComponent (tc);
  43987. addChildComponent (tc, newIndex);
  43988. items.insert (newIndex, tc);
  43989. updateAllItemPositions (true);
  43990. }
  43991. else
  43992. {
  43993. break;
  43994. }
  43995. }
  43996. }
  43997. }
  43998. }
  43999. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44000. {
  44001. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44002. if (tc != 0)
  44003. {
  44004. if (isParentOf (tc))
  44005. {
  44006. items.removeValue (tc);
  44007. removeChildComponent (tc);
  44008. updateAllItemPositions (true);
  44009. }
  44010. }
  44011. }
  44012. void Toolbar::itemDropped (const String&, Component*, int, int)
  44013. {
  44014. }
  44015. void Toolbar::mouseDown (const MouseEvent& e)
  44016. {
  44017. if (e.mods.isPopupMenu())
  44018. {
  44019. }
  44020. }
  44021. class ToolbarCustomisationDialog : public DialogWindow
  44022. {
  44023. public:
  44024. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44025. Toolbar* const toolbar_,
  44026. const int optionFlags)
  44027. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44028. toolbar (toolbar_)
  44029. {
  44030. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44031. setResizable (true, true);
  44032. setResizeLimits (400, 300, 1500, 1000);
  44033. positionNearBar();
  44034. }
  44035. ~ToolbarCustomisationDialog()
  44036. {
  44037. setContentComponent (0, true);
  44038. }
  44039. void closeButtonPressed()
  44040. {
  44041. setVisible (false);
  44042. }
  44043. bool canModalEventBeSentToComponent (const Component* comp)
  44044. {
  44045. return toolbar->isParentOf (comp);
  44046. }
  44047. void positionNearBar()
  44048. {
  44049. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44050. const int tbx = toolbar->getScreenX();
  44051. const int tby = toolbar->getScreenY();
  44052. const int gap = 8;
  44053. int x, y;
  44054. if (toolbar->isVertical())
  44055. {
  44056. y = tby;
  44057. if (tbx > screenSize.getCentreX())
  44058. x = tbx - getWidth() - gap;
  44059. else
  44060. x = tbx + toolbar->getWidth() + gap;
  44061. }
  44062. else
  44063. {
  44064. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44065. if (tby > screenSize.getCentreY())
  44066. y = tby - getHeight() - gap;
  44067. else
  44068. y = tby + toolbar->getHeight() + gap;
  44069. }
  44070. setTopLeftPosition (x, y);
  44071. }
  44072. private:
  44073. Toolbar* const toolbar;
  44074. class CustomiserPanel : public Component,
  44075. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44076. private ButtonListener
  44077. {
  44078. public:
  44079. CustomiserPanel (ToolbarItemFactory& factory_,
  44080. Toolbar* const toolbar_,
  44081. const int optionFlags)
  44082. : factory (factory_),
  44083. toolbar (toolbar_),
  44084. styleBox (0),
  44085. defaultButton (0)
  44086. {
  44087. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44088. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44089. | Toolbar::allowIconsWithTextChoice
  44090. | Toolbar::allowTextOnlyChoice)) != 0)
  44091. {
  44092. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44093. styleBox->setEditableText (false);
  44094. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44095. styleBox->addItem (TRANS("Show icons only"), 1);
  44096. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44097. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44098. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44099. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44100. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44101. styleBox->setSelectedId (1);
  44102. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44103. styleBox->setSelectedId (2);
  44104. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44105. styleBox->setSelectedId (3);
  44106. styleBox->addListener (this);
  44107. }
  44108. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44109. {
  44110. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44111. defaultButton->addButtonListener (this);
  44112. }
  44113. addAndMakeVisible (instructions = new Label (String::empty,
  44114. 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.")));
  44115. instructions->setFont (Font (13.0f));
  44116. setSize (500, 300);
  44117. }
  44118. ~CustomiserPanel()
  44119. {
  44120. deleteAllChildren();
  44121. }
  44122. void comboBoxChanged (ComboBox*)
  44123. {
  44124. if (styleBox->getSelectedId() == 1)
  44125. toolbar->setStyle (Toolbar::iconsOnly);
  44126. else if (styleBox->getSelectedId() == 2)
  44127. toolbar->setStyle (Toolbar::iconsWithText);
  44128. else if (styleBox->getSelectedId() == 3)
  44129. toolbar->setStyle (Toolbar::textOnly);
  44130. palette->resized(); // to make it update the styles
  44131. }
  44132. void buttonClicked (Button*)
  44133. {
  44134. toolbar->addDefaultItems (factory);
  44135. }
  44136. void paint (Graphics& g)
  44137. {
  44138. Colour background;
  44139. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44140. if (dw != 0)
  44141. background = dw->getBackgroundColour();
  44142. g.setColour (background.contrasting().withAlpha (0.3f));
  44143. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44144. }
  44145. void resized()
  44146. {
  44147. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44148. if (styleBox != 0)
  44149. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44150. if (defaultButton != 0)
  44151. {
  44152. defaultButton->changeWidthToFitText (22);
  44153. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44154. }
  44155. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44156. }
  44157. private:
  44158. ToolbarItemFactory& factory;
  44159. Toolbar* const toolbar;
  44160. Label* instructions;
  44161. ToolbarItemPalette* palette;
  44162. ComboBox* styleBox;
  44163. TextButton* defaultButton;
  44164. };
  44165. };
  44166. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44167. {
  44168. setEditingActive (true);
  44169. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44170. dw.runModalLoop();
  44171. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44172. setEditingActive (false);
  44173. }
  44174. END_JUCE_NAMESPACE
  44175. /*** End of inlined file: juce_Toolbar.cpp ***/
  44176. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44177. BEGIN_JUCE_NAMESPACE
  44178. ToolbarItemFactory::ToolbarItemFactory()
  44179. {
  44180. }
  44181. ToolbarItemFactory::~ToolbarItemFactory()
  44182. {
  44183. }
  44184. class ItemDragAndDropOverlayComponent : public Component
  44185. {
  44186. public:
  44187. ItemDragAndDropOverlayComponent()
  44188. : isDragging (false)
  44189. {
  44190. setAlwaysOnTop (true);
  44191. setRepaintsOnMouseActivity (true);
  44192. setMouseCursor (MouseCursor::DraggingHandCursor);
  44193. }
  44194. ~ItemDragAndDropOverlayComponent()
  44195. {
  44196. }
  44197. void paint (Graphics& g)
  44198. {
  44199. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44200. if (isMouseOverOrDragging()
  44201. && tc != 0
  44202. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44203. {
  44204. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44205. g.drawRect (0, 0, getWidth(), getHeight(),
  44206. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44207. }
  44208. }
  44209. void mouseDown (const MouseEvent& e)
  44210. {
  44211. isDragging = false;
  44212. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44213. if (tc != 0)
  44214. {
  44215. tc->dragOffsetX = e.x;
  44216. tc->dragOffsetY = e.y;
  44217. }
  44218. }
  44219. void mouseDrag (const MouseEvent& e)
  44220. {
  44221. if (! (isDragging || e.mouseWasClicked()))
  44222. {
  44223. isDragging = true;
  44224. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44225. if (dnd != 0)
  44226. {
  44227. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44228. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44229. if (tc != 0)
  44230. {
  44231. tc->isBeingDragged = true;
  44232. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44233. tc->setVisible (false);
  44234. }
  44235. }
  44236. }
  44237. }
  44238. void mouseUp (const MouseEvent&)
  44239. {
  44240. isDragging = false;
  44241. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44242. if (tc != 0)
  44243. {
  44244. tc->isBeingDragged = false;
  44245. Toolbar* const tb = tc->getToolbar();
  44246. if (tb != 0)
  44247. tb->updateAllItemPositions (true);
  44248. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44249. delete tc;
  44250. }
  44251. }
  44252. void parentSizeChanged()
  44253. {
  44254. setBounds (0, 0, getParentWidth(), getParentHeight());
  44255. }
  44256. juce_UseDebuggingNewOperator
  44257. private:
  44258. bool isDragging;
  44259. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44260. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44261. };
  44262. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44263. const String& labelText,
  44264. const bool isBeingUsedAsAButton_)
  44265. : Button (labelText),
  44266. itemId (itemId_),
  44267. mode (normalMode),
  44268. toolbarStyle (Toolbar::iconsOnly),
  44269. dragOffsetX (0),
  44270. dragOffsetY (0),
  44271. isActive (true),
  44272. isBeingDragged (false),
  44273. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44274. {
  44275. // Your item ID can't be 0!
  44276. jassert (itemId_ != 0);
  44277. }
  44278. ToolbarItemComponent::~ToolbarItemComponent()
  44279. {
  44280. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44281. overlayComp = 0;
  44282. }
  44283. Toolbar* ToolbarItemComponent::getToolbar() const
  44284. {
  44285. return dynamic_cast <Toolbar*> (getParentComponent());
  44286. }
  44287. bool ToolbarItemComponent::isToolbarVertical() const
  44288. {
  44289. const Toolbar* const t = getToolbar();
  44290. return t != 0 && t->isVertical();
  44291. }
  44292. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44293. {
  44294. if (toolbarStyle != newStyle)
  44295. {
  44296. toolbarStyle = newStyle;
  44297. repaint();
  44298. resized();
  44299. }
  44300. }
  44301. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44302. {
  44303. if (isBeingUsedAsAButton)
  44304. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44305. over, down, *this);
  44306. if (toolbarStyle != Toolbar::iconsOnly)
  44307. {
  44308. const int indent = contentArea.getX();
  44309. int y = indent;
  44310. int h = getHeight() - indent * 2;
  44311. if (toolbarStyle == Toolbar::iconsWithText)
  44312. {
  44313. y = contentArea.getBottom() + indent / 2;
  44314. h -= contentArea.getHeight();
  44315. }
  44316. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44317. getButtonText(), *this);
  44318. }
  44319. if (! contentArea.isEmpty())
  44320. {
  44321. g.saveState();
  44322. g.setOrigin (contentArea.getX(), contentArea.getY());
  44323. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44324. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44325. g.restoreState();
  44326. }
  44327. }
  44328. void ToolbarItemComponent::resized()
  44329. {
  44330. if (toolbarStyle != Toolbar::textOnly)
  44331. {
  44332. const int indent = jmin (proportionOfWidth (0.08f),
  44333. proportionOfHeight (0.08f));
  44334. contentArea = Rectangle<int> (indent, indent,
  44335. getWidth() - indent * 2,
  44336. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44337. : (getHeight() - indent * 2));
  44338. }
  44339. else
  44340. {
  44341. contentArea = Rectangle<int>();
  44342. }
  44343. contentAreaChanged (contentArea);
  44344. }
  44345. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44346. {
  44347. if (mode != newMode)
  44348. {
  44349. mode = newMode;
  44350. repaint();
  44351. if (mode == normalMode)
  44352. {
  44353. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44354. overlayComp = 0;
  44355. }
  44356. else if (overlayComp == 0)
  44357. {
  44358. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44359. overlayComp->parentSizeChanged();
  44360. }
  44361. resized();
  44362. }
  44363. }
  44364. END_JUCE_NAMESPACE
  44365. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44366. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44367. BEGIN_JUCE_NAMESPACE
  44368. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44369. Toolbar* const toolbar_)
  44370. : factory (factory_),
  44371. toolbar (toolbar_)
  44372. {
  44373. Component* const itemHolder = new Component();
  44374. Array <int> allIds;
  44375. factory_.getAllToolbarItemIds (allIds);
  44376. for (int i = 0; i < allIds.size(); ++i)
  44377. {
  44378. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44379. jassert (tc != 0);
  44380. if (tc != 0)
  44381. {
  44382. itemHolder->addAndMakeVisible (tc);
  44383. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44384. }
  44385. }
  44386. viewport = new Viewport();
  44387. viewport->setViewedComponent (itemHolder);
  44388. addAndMakeVisible (viewport);
  44389. }
  44390. ToolbarItemPalette::~ToolbarItemPalette()
  44391. {
  44392. viewport->getViewedComponent()->deleteAllChildren();
  44393. deleteAllChildren();
  44394. }
  44395. void ToolbarItemPalette::resized()
  44396. {
  44397. viewport->setBoundsInset (BorderSize (1));
  44398. Component* const itemHolder = viewport->getViewedComponent();
  44399. const int indent = 8;
  44400. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44401. const int height = toolbar->getThickness();
  44402. int x = indent;
  44403. int y = indent;
  44404. int maxX = 0;
  44405. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44406. {
  44407. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44408. if (tc != 0)
  44409. {
  44410. tc->setStyle (toolbar->getStyle());
  44411. int preferredSize = 1, minSize = 1, maxSize = 1;
  44412. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44413. {
  44414. if (x + preferredSize > preferredWidth && x > indent)
  44415. {
  44416. x = indent;
  44417. y += height;
  44418. }
  44419. tc->setBounds (x, y, preferredSize, height);
  44420. x += preferredSize + 8;
  44421. maxX = jmax (maxX, x);
  44422. }
  44423. }
  44424. }
  44425. itemHolder->setSize (maxX, y + height + 8);
  44426. }
  44427. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44428. {
  44429. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44430. jassert (tc != 0);
  44431. if (tc != 0)
  44432. {
  44433. tc->setBounds (comp->getBounds());
  44434. tc->setStyle (toolbar->getStyle());
  44435. tc->setEditingMode (comp->getEditingMode());
  44436. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44437. }
  44438. }
  44439. END_JUCE_NAMESPACE
  44440. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44441. /*** Start of inlined file: juce_TreeView.cpp ***/
  44442. BEGIN_JUCE_NAMESPACE
  44443. class TreeViewContentComponent : public Component,
  44444. public TooltipClient
  44445. {
  44446. public:
  44447. TreeViewContentComponent (TreeView& owner_)
  44448. : owner (owner_),
  44449. buttonUnderMouse (0),
  44450. isDragging (false)
  44451. {
  44452. }
  44453. ~TreeViewContentComponent()
  44454. {
  44455. deleteAllChildren();
  44456. }
  44457. void mouseDown (const MouseEvent& e)
  44458. {
  44459. updateButtonUnderMouse (e);
  44460. isDragging = false;
  44461. needSelectionOnMouseUp = false;
  44462. Rectangle<int> pos;
  44463. TreeViewItem* const item = findItemAt (e.y, pos);
  44464. if (item == 0)
  44465. return;
  44466. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44467. // as selection clicks)
  44468. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44469. {
  44470. if (e.x >= pos.getX() - owner.getIndentSize())
  44471. item->setOpen (! item->isOpen());
  44472. // (clicks to the left of an open/close button are ignored)
  44473. }
  44474. else
  44475. {
  44476. // mouse-down inside the body of the item..
  44477. if (! owner.isMultiSelectEnabled())
  44478. item->setSelected (true, true);
  44479. else if (item->isSelected())
  44480. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44481. else
  44482. selectBasedOnModifiers (item, e.mods);
  44483. if (e.x >= pos.getX())
  44484. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44485. }
  44486. }
  44487. void mouseUp (const MouseEvent& e)
  44488. {
  44489. updateButtonUnderMouse (e);
  44490. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44491. {
  44492. Rectangle<int> pos;
  44493. TreeViewItem* const item = findItemAt (e.y, pos);
  44494. if (item != 0)
  44495. selectBasedOnModifiers (item, e.mods);
  44496. }
  44497. }
  44498. void mouseDoubleClick (const MouseEvent& e)
  44499. {
  44500. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44501. {
  44502. Rectangle<int> pos;
  44503. TreeViewItem* const item = findItemAt (e.y, pos);
  44504. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44505. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44506. }
  44507. }
  44508. void mouseDrag (const MouseEvent& e)
  44509. {
  44510. if (isEnabled()
  44511. && ! (isDragging || e.mouseWasClicked()
  44512. || e.getDistanceFromDragStart() < 5
  44513. || e.mods.isPopupMenu()))
  44514. {
  44515. isDragging = true;
  44516. Rectangle<int> pos;
  44517. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44518. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44519. {
  44520. const String dragDescription (item->getDragSourceDescription());
  44521. if (dragDescription.isNotEmpty())
  44522. {
  44523. DragAndDropContainer* const dragContainer
  44524. = DragAndDropContainer::findParentDragContainerFor (this);
  44525. if (dragContainer != 0)
  44526. {
  44527. pos.setSize (pos.getWidth(), item->itemHeight);
  44528. Image dragImage (Component::createComponentSnapshot (pos, true));
  44529. dragImage.multiplyAllAlphas (0.6f);
  44530. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44531. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44532. }
  44533. else
  44534. {
  44535. // to be able to do a drag-and-drop operation, the treeview needs to
  44536. // be inside a component which is also a DragAndDropContainer.
  44537. jassertfalse;
  44538. }
  44539. }
  44540. }
  44541. }
  44542. }
  44543. void mouseMove (const MouseEvent& e)
  44544. {
  44545. updateButtonUnderMouse (e);
  44546. }
  44547. void mouseExit (const MouseEvent& e)
  44548. {
  44549. updateButtonUnderMouse (e);
  44550. }
  44551. void paint (Graphics& g)
  44552. {
  44553. if (owner.rootItem != 0)
  44554. {
  44555. owner.handleAsyncUpdate();
  44556. if (! owner.rootItemVisible)
  44557. g.setOrigin (0, -owner.rootItem->itemHeight);
  44558. owner.rootItem->paintRecursively (g, getWidth());
  44559. }
  44560. }
  44561. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44562. {
  44563. if (owner.rootItem != 0)
  44564. {
  44565. owner.handleAsyncUpdate();
  44566. if (! owner.rootItemVisible)
  44567. y += owner.rootItem->itemHeight;
  44568. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44569. if (ti != 0)
  44570. itemPosition = ti->getItemPosition (false);
  44571. return ti;
  44572. }
  44573. return 0;
  44574. }
  44575. void updateComponents()
  44576. {
  44577. const int visibleTop = -getY();
  44578. const int visibleBottom = visibleTop + getParentHeight();
  44579. BigInteger itemsToKeep;
  44580. {
  44581. TreeViewItem* item = owner.rootItem;
  44582. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44583. while (item != 0 && y < visibleBottom)
  44584. {
  44585. y += item->itemHeight;
  44586. if (y >= visibleTop)
  44587. {
  44588. const int index = rowComponentIds.indexOf (item->uid);
  44589. if (index < 0)
  44590. {
  44591. Component* const comp = item->createItemComponent();
  44592. if (comp != 0)
  44593. {
  44594. addAndMakeVisible (comp);
  44595. itemsToKeep.setBit (rowComponentItems.size());
  44596. rowComponentItems.add (item);
  44597. rowComponentIds.add (item->uid);
  44598. rowComponents.add (comp);
  44599. }
  44600. }
  44601. else
  44602. {
  44603. itemsToKeep.setBit (index);
  44604. }
  44605. }
  44606. item = item->getNextVisibleItem (true);
  44607. }
  44608. }
  44609. for (int i = rowComponentItems.size(); --i >= 0;)
  44610. {
  44611. Component* const comp = rowComponents.getUnchecked(i);
  44612. bool keep = false;
  44613. if (isParentOf (comp))
  44614. {
  44615. if (itemsToKeep[i])
  44616. {
  44617. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44618. Rectangle<int> pos (item->getItemPosition (false));
  44619. pos.setSize (pos.getWidth(), item->itemHeight);
  44620. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44621. {
  44622. keep = true;
  44623. comp->setBounds (pos);
  44624. }
  44625. }
  44626. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44627. {
  44628. keep = true;
  44629. comp->setSize (0, 0);
  44630. }
  44631. }
  44632. if (! keep)
  44633. {
  44634. delete comp;
  44635. rowComponents.remove (i);
  44636. rowComponentIds.remove (i);
  44637. rowComponentItems.remove (i);
  44638. }
  44639. }
  44640. }
  44641. void updateButtonUnderMouse (const MouseEvent& e)
  44642. {
  44643. TreeViewItem* newItem = 0;
  44644. if (owner.openCloseButtonsVisible)
  44645. {
  44646. Rectangle<int> pos;
  44647. TreeViewItem* item = findItemAt (e.y, pos);
  44648. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44649. {
  44650. newItem = item;
  44651. if (! newItem->mightContainSubItems())
  44652. newItem = 0;
  44653. }
  44654. }
  44655. if (buttonUnderMouse != newItem)
  44656. {
  44657. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44658. {
  44659. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44660. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44661. }
  44662. buttonUnderMouse = newItem;
  44663. if (buttonUnderMouse != 0)
  44664. {
  44665. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44666. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44667. }
  44668. }
  44669. }
  44670. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44671. {
  44672. return item == buttonUnderMouse;
  44673. }
  44674. void resized()
  44675. {
  44676. owner.itemsChanged();
  44677. }
  44678. const String getTooltip()
  44679. {
  44680. Rectangle<int> pos;
  44681. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44682. if (item != 0)
  44683. return item->getTooltip();
  44684. return owner.getTooltip();
  44685. }
  44686. juce_UseDebuggingNewOperator
  44687. private:
  44688. TreeView& owner;
  44689. Array <TreeViewItem*> rowComponentItems;
  44690. Array <int> rowComponentIds;
  44691. Array <Component*> rowComponents;
  44692. TreeViewItem* buttonUnderMouse;
  44693. bool isDragging, needSelectionOnMouseUp;
  44694. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44695. {
  44696. TreeViewItem* firstSelected = 0;
  44697. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44698. {
  44699. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44700. jassert (lastSelected != 0);
  44701. int rowStart = firstSelected->getRowNumberInTree();
  44702. int rowEnd = lastSelected->getRowNumberInTree();
  44703. if (rowStart > rowEnd)
  44704. swapVariables (rowStart, rowEnd);
  44705. int ourRow = item->getRowNumberInTree();
  44706. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44707. if (ourRow > otherEnd)
  44708. swapVariables (ourRow, otherEnd);
  44709. for (int i = ourRow; i <= otherEnd; ++i)
  44710. owner.getItemOnRow (i)->setSelected (true, false);
  44711. }
  44712. else
  44713. {
  44714. const bool cmd = modifiers.isCommandDown();
  44715. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44716. }
  44717. }
  44718. bool containsItem (TreeViewItem* const item) const
  44719. {
  44720. for (int i = rowComponentItems.size(); --i >= 0;)
  44721. if (rowComponentItems.getUnchecked(i) == item)
  44722. return true;
  44723. return false;
  44724. }
  44725. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44726. {
  44727. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44728. {
  44729. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44730. if (source->isDragging())
  44731. {
  44732. Component* const underMouse = source->getComponentUnderMouse();
  44733. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44734. return true;
  44735. }
  44736. }
  44737. return false;
  44738. }
  44739. TreeViewContentComponent (const TreeViewContentComponent&);
  44740. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44741. };
  44742. class TreeView::TreeViewport : public Viewport
  44743. {
  44744. public:
  44745. TreeViewport() throw() : lastX (-1) {}
  44746. ~TreeViewport() throw() {}
  44747. void updateComponents (const bool triggerResize = false)
  44748. {
  44749. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44750. if (tvc != 0)
  44751. {
  44752. if (triggerResize)
  44753. tvc->resized();
  44754. else
  44755. tvc->updateComponents();
  44756. }
  44757. repaint();
  44758. }
  44759. void visibleAreaChanged (int x, int, int, int)
  44760. {
  44761. const bool hasScrolledSideways = (x != lastX);
  44762. lastX = x;
  44763. updateComponents (hasScrolledSideways);
  44764. }
  44765. juce_UseDebuggingNewOperator
  44766. private:
  44767. int lastX;
  44768. TreeViewport (const TreeViewport&);
  44769. TreeViewport& operator= (const TreeViewport&);
  44770. };
  44771. TreeView::TreeView (const String& componentName)
  44772. : Component (componentName),
  44773. rootItem (0),
  44774. indentSize (24),
  44775. defaultOpenness (false),
  44776. needsRecalculating (true),
  44777. rootItemVisible (true),
  44778. multiSelectEnabled (false),
  44779. openCloseButtonsVisible (true)
  44780. {
  44781. addAndMakeVisible (viewport = new TreeViewport());
  44782. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44783. viewport->setWantsKeyboardFocus (false);
  44784. setWantsKeyboardFocus (true);
  44785. }
  44786. TreeView::~TreeView()
  44787. {
  44788. if (rootItem != 0)
  44789. rootItem->setOwnerView (0);
  44790. }
  44791. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44792. {
  44793. if (rootItem != newRootItem)
  44794. {
  44795. if (newRootItem != 0)
  44796. {
  44797. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44798. if (newRootItem->ownerView != 0)
  44799. newRootItem->ownerView->setRootItem (0);
  44800. }
  44801. if (rootItem != 0)
  44802. rootItem->setOwnerView (0);
  44803. rootItem = newRootItem;
  44804. if (newRootItem != 0)
  44805. newRootItem->setOwnerView (this);
  44806. needsRecalculating = true;
  44807. handleAsyncUpdate();
  44808. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44809. {
  44810. rootItem->setOpen (false); // force a re-open
  44811. rootItem->setOpen (true);
  44812. }
  44813. }
  44814. }
  44815. void TreeView::deleteRootItem()
  44816. {
  44817. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44818. setRootItem (0);
  44819. }
  44820. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44821. {
  44822. rootItemVisible = shouldBeVisible;
  44823. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44824. {
  44825. rootItem->setOpen (false); // force a re-open
  44826. rootItem->setOpen (true);
  44827. }
  44828. itemsChanged();
  44829. }
  44830. void TreeView::colourChanged()
  44831. {
  44832. setOpaque (findColour (backgroundColourId).isOpaque());
  44833. repaint();
  44834. }
  44835. void TreeView::setIndentSize (const int newIndentSize)
  44836. {
  44837. if (indentSize != newIndentSize)
  44838. {
  44839. indentSize = newIndentSize;
  44840. resized();
  44841. }
  44842. }
  44843. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44844. {
  44845. if (defaultOpenness != isOpenByDefault)
  44846. {
  44847. defaultOpenness = isOpenByDefault;
  44848. itemsChanged();
  44849. }
  44850. }
  44851. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44852. {
  44853. multiSelectEnabled = canMultiSelect;
  44854. }
  44855. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44856. {
  44857. if (openCloseButtonsVisible != shouldBeVisible)
  44858. {
  44859. openCloseButtonsVisible = shouldBeVisible;
  44860. itemsChanged();
  44861. }
  44862. }
  44863. Viewport* TreeView::getViewport() const throw()
  44864. {
  44865. return viewport;
  44866. }
  44867. void TreeView::clearSelectedItems()
  44868. {
  44869. if (rootItem != 0)
  44870. rootItem->deselectAllRecursively();
  44871. }
  44872. int TreeView::getNumSelectedItems() const throw()
  44873. {
  44874. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44875. }
  44876. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44877. {
  44878. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44879. }
  44880. int TreeView::getNumRowsInTree() const
  44881. {
  44882. if (rootItem != 0)
  44883. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44884. return 0;
  44885. }
  44886. TreeViewItem* TreeView::getItemOnRow (int index) const
  44887. {
  44888. if (! rootItemVisible)
  44889. ++index;
  44890. if (rootItem != 0 && index >= 0)
  44891. return rootItem->getItemOnRow (index);
  44892. return 0;
  44893. }
  44894. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44895. {
  44896. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44897. Rectangle<int> pos;
  44898. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44899. }
  44900. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44901. {
  44902. if (rootItem == 0)
  44903. return 0;
  44904. return rootItem->findItemFromIdentifierString (identifierString);
  44905. }
  44906. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44907. {
  44908. XmlElement* e = 0;
  44909. if (rootItem != 0)
  44910. {
  44911. e = rootItem->getOpennessState();
  44912. if (e != 0 && alsoIncludeScrollPosition)
  44913. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44914. }
  44915. return e;
  44916. }
  44917. void TreeView::restoreOpennessState (const XmlElement& newState)
  44918. {
  44919. if (rootItem != 0)
  44920. {
  44921. rootItem->restoreOpennessState (newState);
  44922. if (newState.hasAttribute ("scrollPos"))
  44923. viewport->setViewPosition (viewport->getViewPositionX(),
  44924. newState.getIntAttribute ("scrollPos"));
  44925. }
  44926. }
  44927. void TreeView::paint (Graphics& g)
  44928. {
  44929. g.fillAll (findColour (backgroundColourId));
  44930. }
  44931. void TreeView::resized()
  44932. {
  44933. viewport->setBounds (getLocalBounds());
  44934. itemsChanged();
  44935. handleAsyncUpdate();
  44936. }
  44937. void TreeView::enablementChanged()
  44938. {
  44939. repaint();
  44940. }
  44941. void TreeView::moveSelectedRow (int delta)
  44942. {
  44943. if (delta == 0)
  44944. return;
  44945. int rowSelected = 0;
  44946. TreeViewItem* const firstSelected = getSelectedItem (0);
  44947. if (firstSelected != 0)
  44948. rowSelected = firstSelected->getRowNumberInTree();
  44949. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44950. for (;;)
  44951. {
  44952. TreeViewItem* item = getItemOnRow (rowSelected);
  44953. if (item != 0)
  44954. {
  44955. if (! item->canBeSelected())
  44956. {
  44957. // if the row we want to highlight doesn't allow it, try skipping
  44958. // to the next item..
  44959. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44960. rowSelected + (delta < 0 ? -1 : 1));
  44961. if (rowSelected != nextRowToTry)
  44962. {
  44963. rowSelected = nextRowToTry;
  44964. continue;
  44965. }
  44966. else
  44967. {
  44968. break;
  44969. }
  44970. }
  44971. item->setSelected (true, true);
  44972. scrollToKeepItemVisible (item);
  44973. }
  44974. break;
  44975. }
  44976. }
  44977. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44978. {
  44979. if (item != 0 && item->ownerView == this)
  44980. {
  44981. handleAsyncUpdate();
  44982. item = item->getDeepestOpenParentItem();
  44983. int y = item->y;
  44984. int viewTop = viewport->getViewPositionY();
  44985. if (y < viewTop)
  44986. {
  44987. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44988. }
  44989. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44990. {
  44991. viewport->setViewPosition (viewport->getViewPositionX(),
  44992. (y + item->itemHeight) - viewport->getViewHeight());
  44993. }
  44994. }
  44995. }
  44996. bool TreeView::keyPressed (const KeyPress& key)
  44997. {
  44998. if (key.isKeyCode (KeyPress::upKey))
  44999. {
  45000. moveSelectedRow (-1);
  45001. }
  45002. else if (key.isKeyCode (KeyPress::downKey))
  45003. {
  45004. moveSelectedRow (1);
  45005. }
  45006. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45007. {
  45008. if (rootItem != 0)
  45009. {
  45010. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45011. if (key.isKeyCode (KeyPress::pageUpKey))
  45012. rowsOnScreen = -rowsOnScreen;
  45013. moveSelectedRow (rowsOnScreen);
  45014. }
  45015. }
  45016. else if (key.isKeyCode (KeyPress::homeKey))
  45017. {
  45018. moveSelectedRow (-0x3fffffff);
  45019. }
  45020. else if (key.isKeyCode (KeyPress::endKey))
  45021. {
  45022. moveSelectedRow (0x3fffffff);
  45023. }
  45024. else if (key.isKeyCode (KeyPress::returnKey))
  45025. {
  45026. TreeViewItem* const firstSelected = getSelectedItem (0);
  45027. if (firstSelected != 0)
  45028. firstSelected->setOpen (! firstSelected->isOpen());
  45029. }
  45030. else if (key.isKeyCode (KeyPress::leftKey))
  45031. {
  45032. TreeViewItem* const firstSelected = getSelectedItem (0);
  45033. if (firstSelected != 0)
  45034. {
  45035. if (firstSelected->isOpen())
  45036. {
  45037. firstSelected->setOpen (false);
  45038. }
  45039. else
  45040. {
  45041. TreeViewItem* parent = firstSelected->parentItem;
  45042. if ((! rootItemVisible) && parent == rootItem)
  45043. parent = 0;
  45044. if (parent != 0)
  45045. {
  45046. parent->setSelected (true, true);
  45047. scrollToKeepItemVisible (parent);
  45048. }
  45049. }
  45050. }
  45051. }
  45052. else if (key.isKeyCode (KeyPress::rightKey))
  45053. {
  45054. TreeViewItem* const firstSelected = getSelectedItem (0);
  45055. if (firstSelected != 0)
  45056. {
  45057. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45058. moveSelectedRow (1);
  45059. else
  45060. firstSelected->setOpen (true);
  45061. }
  45062. }
  45063. else
  45064. {
  45065. return false;
  45066. }
  45067. return true;
  45068. }
  45069. void TreeView::itemsChanged() throw()
  45070. {
  45071. needsRecalculating = true;
  45072. repaint();
  45073. triggerAsyncUpdate();
  45074. }
  45075. void TreeView::handleAsyncUpdate()
  45076. {
  45077. if (needsRecalculating)
  45078. {
  45079. needsRecalculating = false;
  45080. const ScopedLock sl (nodeAlterationLock);
  45081. if (rootItem != 0)
  45082. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45083. viewport->updateComponents();
  45084. if (rootItem != 0)
  45085. {
  45086. viewport->getViewedComponent()
  45087. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45088. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45089. }
  45090. else
  45091. {
  45092. viewport->getViewedComponent()->setSize (0, 0);
  45093. }
  45094. }
  45095. }
  45096. class TreeView::InsertPointHighlight : public Component
  45097. {
  45098. public:
  45099. InsertPointHighlight()
  45100. : lastItem (0)
  45101. {
  45102. setSize (100, 12);
  45103. setAlwaysOnTop (true);
  45104. setInterceptsMouseClicks (false, false);
  45105. }
  45106. ~InsertPointHighlight() {}
  45107. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45108. {
  45109. lastItem = item;
  45110. lastIndex = insertIndex;
  45111. const int offset = getHeight() / 2;
  45112. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45113. }
  45114. void paint (Graphics& g)
  45115. {
  45116. Path p;
  45117. const float h = (float) getHeight();
  45118. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45119. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45120. p.lineTo ((float) getWidth(), h / 2.0f);
  45121. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45122. g.strokePath (p, PathStrokeType (2.0f));
  45123. }
  45124. TreeViewItem* lastItem;
  45125. int lastIndex;
  45126. private:
  45127. InsertPointHighlight (const InsertPointHighlight&);
  45128. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45129. };
  45130. class TreeView::TargetGroupHighlight : public Component
  45131. {
  45132. public:
  45133. TargetGroupHighlight()
  45134. {
  45135. setAlwaysOnTop (true);
  45136. setInterceptsMouseClicks (false, false);
  45137. }
  45138. ~TargetGroupHighlight() {}
  45139. void setTargetPosition (TreeViewItem* const item) throw()
  45140. {
  45141. Rectangle<int> r (item->getItemPosition (true));
  45142. r.setHeight (item->getItemHeight());
  45143. setBounds (r);
  45144. }
  45145. void paint (Graphics& g)
  45146. {
  45147. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45148. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45149. }
  45150. private:
  45151. TargetGroupHighlight (const TargetGroupHighlight&);
  45152. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45153. };
  45154. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45155. {
  45156. beginDragAutoRepeat (100);
  45157. if (dragInsertPointHighlight == 0)
  45158. {
  45159. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45160. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45161. }
  45162. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45163. dragTargetGroupHighlight->setTargetPosition (item);
  45164. }
  45165. void TreeView::hideDragHighlight() throw()
  45166. {
  45167. dragInsertPointHighlight = 0;
  45168. dragTargetGroupHighlight = 0;
  45169. }
  45170. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45171. const StringArray& files, const String& sourceDescription,
  45172. Component* sourceComponent) const throw()
  45173. {
  45174. insertIndex = 0;
  45175. TreeViewItem* item = getItemAt (y);
  45176. if (item == 0)
  45177. return 0;
  45178. Rectangle<int> itemPos (item->getItemPosition (true));
  45179. insertIndex = item->getIndexInParent();
  45180. const int oldY = y;
  45181. y = itemPos.getY();
  45182. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45183. {
  45184. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45185. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45186. {
  45187. // Check if we're trying to drag into an empty group item..
  45188. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45189. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45190. {
  45191. insertIndex = 0;
  45192. x = itemPos.getX() + getIndentSize();
  45193. y = itemPos.getBottom();
  45194. return item;
  45195. }
  45196. }
  45197. }
  45198. if (oldY > itemPos.getCentreY())
  45199. {
  45200. y += item->getItemHeight();
  45201. while (item->isLastOfSiblings() && item->parentItem != 0
  45202. && item->parentItem->parentItem != 0)
  45203. {
  45204. if (x > itemPos.getX())
  45205. break;
  45206. item = item->parentItem;
  45207. itemPos = item->getItemPosition (true);
  45208. insertIndex = item->getIndexInParent();
  45209. }
  45210. ++insertIndex;
  45211. }
  45212. x = itemPos.getX();
  45213. return item->parentItem;
  45214. }
  45215. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45216. {
  45217. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45218. int insertIndex;
  45219. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45220. if (item != 0)
  45221. {
  45222. if (scrolled || dragInsertPointHighlight == 0
  45223. || dragInsertPointHighlight->lastItem != item
  45224. || dragInsertPointHighlight->lastIndex != insertIndex)
  45225. {
  45226. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45227. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45228. showDragHighlight (item, insertIndex, x, y);
  45229. else
  45230. hideDragHighlight();
  45231. }
  45232. }
  45233. else
  45234. {
  45235. hideDragHighlight();
  45236. }
  45237. }
  45238. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45239. {
  45240. hideDragHighlight();
  45241. int insertIndex;
  45242. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45243. if (item != 0)
  45244. {
  45245. if (files.size() > 0)
  45246. {
  45247. if (item->isInterestedInFileDrag (files))
  45248. item->filesDropped (files, insertIndex);
  45249. }
  45250. else
  45251. {
  45252. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45253. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45254. }
  45255. }
  45256. }
  45257. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45258. {
  45259. return true;
  45260. }
  45261. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45262. {
  45263. fileDragMove (files, x, y);
  45264. }
  45265. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45266. {
  45267. handleDrag (files, String::empty, 0, x, y);
  45268. }
  45269. void TreeView::fileDragExit (const StringArray&)
  45270. {
  45271. hideDragHighlight();
  45272. }
  45273. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45274. {
  45275. handleDrop (files, String::empty, 0, x, y);
  45276. }
  45277. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45278. {
  45279. return true;
  45280. }
  45281. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45282. {
  45283. itemDragMove (sourceDescription, sourceComponent, x, y);
  45284. }
  45285. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45286. {
  45287. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45288. }
  45289. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45290. {
  45291. hideDragHighlight();
  45292. }
  45293. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45294. {
  45295. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45296. }
  45297. enum TreeViewOpenness
  45298. {
  45299. opennessDefault = 0,
  45300. opennessClosed = 1,
  45301. opennessOpen = 2
  45302. };
  45303. TreeViewItem::TreeViewItem()
  45304. : ownerView (0),
  45305. parentItem (0),
  45306. y (0),
  45307. itemHeight (0),
  45308. totalHeight (0),
  45309. selected (false),
  45310. redrawNeeded (true),
  45311. drawLinesInside (true),
  45312. drawsInLeftMargin (false),
  45313. openness (opennessDefault)
  45314. {
  45315. static int nextUID = 0;
  45316. uid = nextUID++;
  45317. }
  45318. TreeViewItem::~TreeViewItem()
  45319. {
  45320. }
  45321. const String TreeViewItem::getUniqueName() const
  45322. {
  45323. return String::empty;
  45324. }
  45325. void TreeViewItem::itemOpennessChanged (bool)
  45326. {
  45327. }
  45328. int TreeViewItem::getNumSubItems() const throw()
  45329. {
  45330. return subItems.size();
  45331. }
  45332. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45333. {
  45334. return subItems [index];
  45335. }
  45336. void TreeViewItem::clearSubItems()
  45337. {
  45338. if (subItems.size() > 0)
  45339. {
  45340. if (ownerView != 0)
  45341. {
  45342. const ScopedLock sl (ownerView->nodeAlterationLock);
  45343. subItems.clear();
  45344. treeHasChanged();
  45345. }
  45346. else
  45347. {
  45348. subItems.clear();
  45349. }
  45350. }
  45351. }
  45352. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45353. {
  45354. if (newItem != 0)
  45355. {
  45356. newItem->parentItem = this;
  45357. newItem->setOwnerView (ownerView);
  45358. newItem->y = 0;
  45359. newItem->itemHeight = newItem->getItemHeight();
  45360. newItem->totalHeight = 0;
  45361. newItem->itemWidth = newItem->getItemWidth();
  45362. newItem->totalWidth = 0;
  45363. if (ownerView != 0)
  45364. {
  45365. const ScopedLock sl (ownerView->nodeAlterationLock);
  45366. subItems.insert (insertPosition, newItem);
  45367. treeHasChanged();
  45368. if (newItem->isOpen())
  45369. newItem->itemOpennessChanged (true);
  45370. }
  45371. else
  45372. {
  45373. subItems.insert (insertPosition, newItem);
  45374. if (newItem->isOpen())
  45375. newItem->itemOpennessChanged (true);
  45376. }
  45377. }
  45378. }
  45379. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45380. {
  45381. if (ownerView != 0)
  45382. {
  45383. const ScopedLock sl (ownerView->nodeAlterationLock);
  45384. if (((unsigned int) index) < (unsigned int) subItems.size())
  45385. {
  45386. subItems.remove (index, deleteItem);
  45387. treeHasChanged();
  45388. }
  45389. }
  45390. else
  45391. {
  45392. subItems.remove (index, deleteItem);
  45393. }
  45394. }
  45395. bool TreeViewItem::isOpen() const throw()
  45396. {
  45397. if (openness == opennessDefault)
  45398. return ownerView != 0 && ownerView->defaultOpenness;
  45399. else
  45400. return openness == opennessOpen;
  45401. }
  45402. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45403. {
  45404. if (isOpen() != shouldBeOpen)
  45405. {
  45406. openness = shouldBeOpen ? opennessOpen
  45407. : opennessClosed;
  45408. treeHasChanged();
  45409. itemOpennessChanged (isOpen());
  45410. }
  45411. }
  45412. bool TreeViewItem::isSelected() const throw()
  45413. {
  45414. return selected;
  45415. }
  45416. void TreeViewItem::deselectAllRecursively()
  45417. {
  45418. setSelected (false, false);
  45419. for (int i = 0; i < subItems.size(); ++i)
  45420. subItems.getUnchecked(i)->deselectAllRecursively();
  45421. }
  45422. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45423. const bool deselectOtherItemsFirst)
  45424. {
  45425. if (shouldBeSelected && ! canBeSelected())
  45426. return;
  45427. if (deselectOtherItemsFirst)
  45428. getTopLevelItem()->deselectAllRecursively();
  45429. if (shouldBeSelected != selected)
  45430. {
  45431. selected = shouldBeSelected;
  45432. if (ownerView != 0)
  45433. ownerView->repaint();
  45434. itemSelectionChanged (shouldBeSelected);
  45435. }
  45436. }
  45437. void TreeViewItem::paintItem (Graphics&, int, int)
  45438. {
  45439. }
  45440. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45441. {
  45442. ownerView->getLookAndFeel()
  45443. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45444. }
  45445. void TreeViewItem::itemClicked (const MouseEvent&)
  45446. {
  45447. }
  45448. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45449. {
  45450. if (mightContainSubItems())
  45451. setOpen (! isOpen());
  45452. }
  45453. void TreeViewItem::itemSelectionChanged (bool)
  45454. {
  45455. }
  45456. const String TreeViewItem::getTooltip()
  45457. {
  45458. return String::empty;
  45459. }
  45460. const String TreeViewItem::getDragSourceDescription()
  45461. {
  45462. return String::empty;
  45463. }
  45464. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45465. {
  45466. return false;
  45467. }
  45468. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45469. {
  45470. }
  45471. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45472. {
  45473. return false;
  45474. }
  45475. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45476. {
  45477. }
  45478. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45479. {
  45480. const int indentX = getIndentX();
  45481. int width = itemWidth;
  45482. if (ownerView != 0 && width < 0)
  45483. width = ownerView->viewport->getViewWidth() - indentX;
  45484. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45485. if (relativeToTreeViewTopLeft)
  45486. r -= ownerView->viewport->getViewPosition();
  45487. return r;
  45488. }
  45489. void TreeViewItem::treeHasChanged() const throw()
  45490. {
  45491. if (ownerView != 0)
  45492. ownerView->itemsChanged();
  45493. }
  45494. void TreeViewItem::repaintItem() const
  45495. {
  45496. if (ownerView != 0 && areAllParentsOpen())
  45497. {
  45498. Rectangle<int> r (getItemPosition (true));
  45499. r.setLeft (0);
  45500. ownerView->viewport->repaint (r);
  45501. }
  45502. }
  45503. bool TreeViewItem::areAllParentsOpen() const throw()
  45504. {
  45505. return parentItem == 0
  45506. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45507. }
  45508. void TreeViewItem::updatePositions (int newY)
  45509. {
  45510. y = newY;
  45511. itemHeight = getItemHeight();
  45512. totalHeight = itemHeight;
  45513. itemWidth = getItemWidth();
  45514. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45515. if (isOpen())
  45516. {
  45517. newY += totalHeight;
  45518. for (int i = 0; i < subItems.size(); ++i)
  45519. {
  45520. TreeViewItem* const ti = subItems.getUnchecked(i);
  45521. ti->updatePositions (newY);
  45522. newY += ti->totalHeight;
  45523. totalHeight += ti->totalHeight;
  45524. totalWidth = jmax (totalWidth, ti->totalWidth);
  45525. }
  45526. }
  45527. }
  45528. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45529. {
  45530. TreeViewItem* result = this;
  45531. TreeViewItem* item = this;
  45532. while (item->parentItem != 0)
  45533. {
  45534. item = item->parentItem;
  45535. if (! item->isOpen())
  45536. result = item;
  45537. }
  45538. return result;
  45539. }
  45540. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45541. {
  45542. ownerView = newOwner;
  45543. for (int i = subItems.size(); --i >= 0;)
  45544. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45545. }
  45546. int TreeViewItem::getIndentX() const throw()
  45547. {
  45548. const int indentWidth = ownerView->getIndentSize();
  45549. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45550. if (! ownerView->openCloseButtonsVisible)
  45551. x -= indentWidth;
  45552. TreeViewItem* p = parentItem;
  45553. while (p != 0)
  45554. {
  45555. x += indentWidth;
  45556. p = p->parentItem;
  45557. }
  45558. return x;
  45559. }
  45560. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45561. {
  45562. drawsInLeftMargin = canDrawInLeftMargin;
  45563. }
  45564. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45565. {
  45566. jassert (ownerView != 0);
  45567. if (ownerView == 0)
  45568. return;
  45569. const int indent = getIndentX();
  45570. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45571. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45572. const float halfH = itemHeight * 0.5f;
  45573. int depth = 0;
  45574. TreeViewItem* p = parentItem;
  45575. while (p != 0)
  45576. {
  45577. ++depth;
  45578. p = p->parentItem;
  45579. }
  45580. if (! ownerView->rootItemVisible)
  45581. --depth;
  45582. const int indentWidth = ownerView->getIndentSize();
  45583. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45584. {
  45585. float x = (depth + 0.5f) * indentWidth;
  45586. if (depth >= 0)
  45587. {
  45588. if (parentItem != 0 && parentItem->drawLinesInside)
  45589. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45590. if ((parentItem != 0 && parentItem->drawLinesInside)
  45591. || (parentItem == 0 && drawLinesInside))
  45592. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45593. }
  45594. p = parentItem;
  45595. int d = depth;
  45596. while (p != 0 && --d >= 0)
  45597. {
  45598. x -= (float) indentWidth;
  45599. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45600. && ! p->isLastOfSiblings())
  45601. {
  45602. g.drawLine (x, 0, x, (float) itemHeight);
  45603. }
  45604. p = p->parentItem;
  45605. }
  45606. if (mightContainSubItems())
  45607. {
  45608. g.saveState();
  45609. g.setOrigin (depth * indentWidth, 0);
  45610. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45611. paintOpenCloseButton (g, indentWidth, itemHeight,
  45612. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45613. ->isMouseOverButton (this));
  45614. g.restoreState();
  45615. }
  45616. }
  45617. {
  45618. g.saveState();
  45619. g.setOrigin (indent, 0);
  45620. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45621. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45622. paintItem (g, itemW, itemHeight);
  45623. g.restoreState();
  45624. }
  45625. if (isOpen())
  45626. {
  45627. const Rectangle<int> clip (g.getClipBounds());
  45628. for (int i = 0; i < subItems.size(); ++i)
  45629. {
  45630. TreeViewItem* const ti = subItems.getUnchecked(i);
  45631. const int relY = ti->y - y;
  45632. if (relY >= clip.getBottom())
  45633. break;
  45634. if (relY + ti->totalHeight >= clip.getY())
  45635. {
  45636. g.saveState();
  45637. g.setOrigin (0, relY);
  45638. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45639. ti->paintRecursively (g, width);
  45640. g.restoreState();
  45641. }
  45642. }
  45643. }
  45644. }
  45645. bool TreeViewItem::isLastOfSiblings() const throw()
  45646. {
  45647. return parentItem == 0
  45648. || parentItem->subItems.getLast() == this;
  45649. }
  45650. int TreeViewItem::getIndexInParent() const throw()
  45651. {
  45652. if (parentItem == 0)
  45653. return 0;
  45654. return parentItem->subItems.indexOf (this);
  45655. }
  45656. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45657. {
  45658. return (parentItem == 0) ? this
  45659. : parentItem->getTopLevelItem();
  45660. }
  45661. int TreeViewItem::getNumRows() const throw()
  45662. {
  45663. int num = 1;
  45664. if (isOpen())
  45665. {
  45666. for (int i = subItems.size(); --i >= 0;)
  45667. num += subItems.getUnchecked(i)->getNumRows();
  45668. }
  45669. return num;
  45670. }
  45671. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45672. {
  45673. if (index == 0)
  45674. return this;
  45675. if (index > 0 && isOpen())
  45676. {
  45677. --index;
  45678. for (int i = 0; i < subItems.size(); ++i)
  45679. {
  45680. TreeViewItem* const item = subItems.getUnchecked(i);
  45681. if (index == 0)
  45682. return item;
  45683. const int numRows = item->getNumRows();
  45684. if (numRows > index)
  45685. return item->getItemOnRow (index);
  45686. index -= numRows;
  45687. }
  45688. }
  45689. return 0;
  45690. }
  45691. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45692. {
  45693. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45694. {
  45695. const int h = itemHeight;
  45696. if (targetY < h)
  45697. return this;
  45698. if (isOpen())
  45699. {
  45700. targetY -= h;
  45701. for (int i = 0; i < subItems.size(); ++i)
  45702. {
  45703. TreeViewItem* const ti = subItems.getUnchecked(i);
  45704. if (targetY < ti->totalHeight)
  45705. return ti->findItemRecursively (targetY);
  45706. targetY -= ti->totalHeight;
  45707. }
  45708. }
  45709. }
  45710. return 0;
  45711. }
  45712. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45713. {
  45714. int total = 0;
  45715. if (isSelected())
  45716. ++total;
  45717. for (int i = subItems.size(); --i >= 0;)
  45718. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45719. return total;
  45720. }
  45721. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45722. {
  45723. if (isSelected())
  45724. {
  45725. if (index == 0)
  45726. return this;
  45727. --index;
  45728. }
  45729. if (index >= 0)
  45730. {
  45731. for (int i = 0; i < subItems.size(); ++i)
  45732. {
  45733. TreeViewItem* const item = subItems.getUnchecked(i);
  45734. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45735. if (found != 0)
  45736. return found;
  45737. index -= item->countSelectedItemsRecursively();
  45738. }
  45739. }
  45740. return 0;
  45741. }
  45742. int TreeViewItem::getRowNumberInTree() const throw()
  45743. {
  45744. if (parentItem != 0 && ownerView != 0)
  45745. {
  45746. int n = 1 + parentItem->getRowNumberInTree();
  45747. int ourIndex = parentItem->subItems.indexOf (this);
  45748. jassert (ourIndex >= 0);
  45749. while (--ourIndex >= 0)
  45750. n += parentItem->subItems [ourIndex]->getNumRows();
  45751. if (parentItem->parentItem == 0
  45752. && ! ownerView->rootItemVisible)
  45753. --n;
  45754. return n;
  45755. }
  45756. else
  45757. {
  45758. return 0;
  45759. }
  45760. }
  45761. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45762. {
  45763. drawLinesInside = drawLines;
  45764. }
  45765. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45766. {
  45767. if (recurse && isOpen() && subItems.size() > 0)
  45768. return subItems [0];
  45769. if (parentItem != 0)
  45770. {
  45771. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45772. if (nextIndex >= parentItem->subItems.size())
  45773. return parentItem->getNextVisibleItem (false);
  45774. return parentItem->subItems [nextIndex];
  45775. }
  45776. return 0;
  45777. }
  45778. const String TreeViewItem::getItemIdentifierString() const
  45779. {
  45780. String s;
  45781. if (parentItem != 0)
  45782. s = parentItem->getItemIdentifierString();
  45783. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45784. }
  45785. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45786. {
  45787. const String thisId (getUniqueName());
  45788. if (thisId == identifierString)
  45789. return this;
  45790. if (identifierString.startsWith (thisId + "/"))
  45791. {
  45792. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45793. bool wasOpen = isOpen();
  45794. setOpen (true);
  45795. for (int i = subItems.size(); --i >= 0;)
  45796. {
  45797. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45798. if (item != 0)
  45799. return item;
  45800. }
  45801. setOpen (wasOpen);
  45802. }
  45803. return 0;
  45804. }
  45805. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45806. {
  45807. if (e.hasTagName ("CLOSED"))
  45808. {
  45809. setOpen (false);
  45810. }
  45811. else if (e.hasTagName ("OPEN"))
  45812. {
  45813. setOpen (true);
  45814. forEachXmlChildElement (e, n)
  45815. {
  45816. const String id (n->getStringAttribute ("id"));
  45817. for (int i = 0; i < subItems.size(); ++i)
  45818. {
  45819. TreeViewItem* const ti = subItems.getUnchecked(i);
  45820. if (ti->getUniqueName() == id)
  45821. {
  45822. ti->restoreOpennessState (*n);
  45823. break;
  45824. }
  45825. }
  45826. }
  45827. }
  45828. }
  45829. XmlElement* TreeViewItem::getOpennessState() const throw()
  45830. {
  45831. const String name (getUniqueName());
  45832. if (name.isNotEmpty())
  45833. {
  45834. XmlElement* e;
  45835. if (isOpen())
  45836. {
  45837. e = new XmlElement ("OPEN");
  45838. for (int i = 0; i < subItems.size(); ++i)
  45839. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45840. }
  45841. else
  45842. {
  45843. e = new XmlElement ("CLOSED");
  45844. }
  45845. e->setAttribute ("id", name);
  45846. return e;
  45847. }
  45848. else
  45849. {
  45850. // trying to save the openness for an element that has no name - this won't
  45851. // work because it needs the names to identify what to open.
  45852. jassertfalse;
  45853. }
  45854. return 0;
  45855. }
  45856. END_JUCE_NAMESPACE
  45857. /*** End of inlined file: juce_TreeView.cpp ***/
  45858. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45859. BEGIN_JUCE_NAMESPACE
  45860. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45861. : fileList (listToShow)
  45862. {
  45863. }
  45864. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45865. {
  45866. }
  45867. FileBrowserListener::~FileBrowserListener()
  45868. {
  45869. }
  45870. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45871. {
  45872. listeners.add (listener);
  45873. }
  45874. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45875. {
  45876. listeners.remove (listener);
  45877. }
  45878. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45879. {
  45880. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45881. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45882. }
  45883. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45884. {
  45885. if (fileList.getDirectory().exists())
  45886. {
  45887. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45888. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45889. }
  45890. }
  45891. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45892. {
  45893. if (fileList.getDirectory().exists())
  45894. {
  45895. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45896. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45897. }
  45898. }
  45899. END_JUCE_NAMESPACE
  45900. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45901. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45902. BEGIN_JUCE_NAMESPACE
  45903. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45904. TimeSliceThread& thread_)
  45905. : fileFilter (fileFilter_),
  45906. thread (thread_),
  45907. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45908. fileFindHandle (0),
  45909. shouldStop (true)
  45910. {
  45911. }
  45912. DirectoryContentsList::~DirectoryContentsList()
  45913. {
  45914. clear();
  45915. }
  45916. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45917. {
  45918. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45919. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45920. }
  45921. bool DirectoryContentsList::ignoresHiddenFiles() const
  45922. {
  45923. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45924. }
  45925. const File& DirectoryContentsList::getDirectory() const
  45926. {
  45927. return root;
  45928. }
  45929. void DirectoryContentsList::setDirectory (const File& directory,
  45930. const bool includeDirectories,
  45931. const bool includeFiles)
  45932. {
  45933. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45934. if (directory != root)
  45935. {
  45936. clear();
  45937. root = directory;
  45938. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45939. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45940. }
  45941. int newFlags = fileTypeFlags;
  45942. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45943. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45944. setTypeFlags (newFlags);
  45945. }
  45946. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45947. {
  45948. if (fileTypeFlags != newFlags)
  45949. {
  45950. fileTypeFlags = newFlags;
  45951. refresh();
  45952. }
  45953. }
  45954. void DirectoryContentsList::clear()
  45955. {
  45956. shouldStop = true;
  45957. thread.removeTimeSliceClient (this);
  45958. fileFindHandle = 0;
  45959. if (files.size() > 0)
  45960. {
  45961. files.clear();
  45962. changed();
  45963. }
  45964. }
  45965. void DirectoryContentsList::refresh()
  45966. {
  45967. clear();
  45968. if (root.isDirectory())
  45969. {
  45970. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45971. shouldStop = false;
  45972. thread.addTimeSliceClient (this);
  45973. }
  45974. }
  45975. int DirectoryContentsList::getNumFiles() const
  45976. {
  45977. return files.size();
  45978. }
  45979. bool DirectoryContentsList::getFileInfo (const int index,
  45980. FileInfo& result) const
  45981. {
  45982. const ScopedLock sl (fileListLock);
  45983. const FileInfo* const info = files [index];
  45984. if (info != 0)
  45985. {
  45986. result = *info;
  45987. return true;
  45988. }
  45989. return false;
  45990. }
  45991. const File DirectoryContentsList::getFile (const int index) const
  45992. {
  45993. const ScopedLock sl (fileListLock);
  45994. const FileInfo* const info = files [index];
  45995. if (info != 0)
  45996. return root.getChildFile (info->filename);
  45997. return File::nonexistent;
  45998. }
  45999. bool DirectoryContentsList::isStillLoading() const
  46000. {
  46001. return fileFindHandle != 0;
  46002. }
  46003. void DirectoryContentsList::changed()
  46004. {
  46005. sendChangeMessage (this);
  46006. }
  46007. bool DirectoryContentsList::useTimeSlice()
  46008. {
  46009. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46010. bool hasChanged = false;
  46011. for (int i = 100; --i >= 0;)
  46012. {
  46013. if (! checkNextFile (hasChanged))
  46014. {
  46015. if (hasChanged)
  46016. changed();
  46017. return false;
  46018. }
  46019. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46020. break;
  46021. }
  46022. if (hasChanged)
  46023. changed();
  46024. return true;
  46025. }
  46026. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46027. {
  46028. if (fileFindHandle != 0)
  46029. {
  46030. bool fileFoundIsDir, isHidden, isReadOnly;
  46031. int64 fileSize;
  46032. Time modTime, creationTime;
  46033. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46034. &modTime, &creationTime, &isReadOnly))
  46035. {
  46036. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46037. fileSize, modTime, creationTime, isReadOnly))
  46038. {
  46039. hasChanged = true;
  46040. }
  46041. return true;
  46042. }
  46043. else
  46044. {
  46045. fileFindHandle = 0;
  46046. }
  46047. }
  46048. return false;
  46049. }
  46050. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46051. const DirectoryContentsList::FileInfo* const second)
  46052. {
  46053. #if JUCE_WINDOWS
  46054. if (first->isDirectory != second->isDirectory)
  46055. return first->isDirectory ? -1 : 1;
  46056. #endif
  46057. return first->filename.compareIgnoreCase (second->filename);
  46058. }
  46059. bool DirectoryContentsList::addFile (const File& file,
  46060. const bool isDir,
  46061. const int64 fileSize,
  46062. const Time& modTime,
  46063. const Time& creationTime,
  46064. const bool isReadOnly)
  46065. {
  46066. if (fileFilter == 0
  46067. || ((! isDir) && fileFilter->isFileSuitable (file))
  46068. || (isDir && fileFilter->isDirectorySuitable (file)))
  46069. {
  46070. ScopedPointer <FileInfo> info (new FileInfo());
  46071. info->filename = file.getFileName();
  46072. info->fileSize = fileSize;
  46073. info->modificationTime = modTime;
  46074. info->creationTime = creationTime;
  46075. info->isDirectory = isDir;
  46076. info->isReadOnly = isReadOnly;
  46077. const ScopedLock sl (fileListLock);
  46078. for (int i = files.size(); --i >= 0;)
  46079. if (files.getUnchecked(i)->filename == info->filename)
  46080. return false;
  46081. files.addSorted (*this, info.release());
  46082. return true;
  46083. }
  46084. return false;
  46085. }
  46086. END_JUCE_NAMESPACE
  46087. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46088. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46089. BEGIN_JUCE_NAMESPACE
  46090. FileBrowserComponent::FileBrowserComponent (int flags_,
  46091. const File& initialFileOrDirectory,
  46092. const FileFilter* fileFilter_,
  46093. FilePreviewComponent* previewComp_)
  46094. : FileFilter (String::empty),
  46095. fileFilter (fileFilter_),
  46096. flags (flags_),
  46097. previewComp (previewComp_),
  46098. thread ("Juce FileBrowser")
  46099. {
  46100. // You need to specify one or other of the open/save flags..
  46101. jassert ((flags & (saveMode | openMode)) != 0);
  46102. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46103. // You need to specify at least one of these flags..
  46104. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46105. String filename;
  46106. if (initialFileOrDirectory == File::nonexistent)
  46107. {
  46108. currentRoot = File::getCurrentWorkingDirectory();
  46109. }
  46110. else if (initialFileOrDirectory.isDirectory())
  46111. {
  46112. currentRoot = initialFileOrDirectory;
  46113. }
  46114. else
  46115. {
  46116. chosenFiles.add (initialFileOrDirectory);
  46117. currentRoot = initialFileOrDirectory.getParentDirectory();
  46118. filename = initialFileOrDirectory.getFileName();
  46119. }
  46120. fileList = new DirectoryContentsList (this, thread);
  46121. if ((flags & useTreeView) != 0)
  46122. {
  46123. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46124. if ((flags & canSelectMultipleItems) != 0)
  46125. tree->setMultiSelectEnabled (true);
  46126. addAndMakeVisible (tree);
  46127. fileListComponent = tree;
  46128. }
  46129. else
  46130. {
  46131. FileListComponent* const list = new FileListComponent (*fileList);
  46132. list->setOutlineThickness (1);
  46133. if ((flags & canSelectMultipleItems) != 0)
  46134. list->setMultipleSelectionEnabled (true);
  46135. addAndMakeVisible (list);
  46136. fileListComponent = list;
  46137. }
  46138. fileListComponent->addListener (this);
  46139. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46140. currentPathBox->setEditableText (true);
  46141. StringArray rootNames, rootPaths;
  46142. const BigInteger separators (getRoots (rootNames, rootPaths));
  46143. for (int i = 0; i < rootNames.size(); ++i)
  46144. {
  46145. if (separators [i])
  46146. currentPathBox->addSeparator();
  46147. currentPathBox->addItem (rootNames[i], i + 1);
  46148. }
  46149. currentPathBox->addSeparator();
  46150. currentPathBox->addListener (this);
  46151. addAndMakeVisible (filenameBox = new TextEditor());
  46152. filenameBox->setMultiLine (false);
  46153. filenameBox->setSelectAllWhenFocused (true);
  46154. filenameBox->setText (filename, false);
  46155. filenameBox->addListener (this);
  46156. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46157. Label* label = new Label ("f", TRANS("file:"));
  46158. addAndMakeVisible (label);
  46159. label->attachToComponent (filenameBox, true);
  46160. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46161. goUpButton->addButtonListener (this);
  46162. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46163. if (previewComp != 0)
  46164. addAndMakeVisible (previewComp);
  46165. setRoot (currentRoot);
  46166. thread.startThread (4);
  46167. }
  46168. FileBrowserComponent::~FileBrowserComponent()
  46169. {
  46170. if (previewComp != 0)
  46171. removeChildComponent (previewComp);
  46172. deleteAllChildren();
  46173. fileList = 0;
  46174. thread.stopThread (10000);
  46175. }
  46176. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46177. {
  46178. listeners.add (newListener);
  46179. }
  46180. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46181. {
  46182. listeners.remove (listener);
  46183. }
  46184. bool FileBrowserComponent::isSaveMode() const throw()
  46185. {
  46186. return (flags & saveMode) != 0;
  46187. }
  46188. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46189. {
  46190. if (chosenFiles.size() == 0 && currentFileIsValid())
  46191. return 1;
  46192. return chosenFiles.size();
  46193. }
  46194. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46195. {
  46196. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46197. return currentRoot;
  46198. if (! filenameBox->isReadOnly())
  46199. return currentRoot.getChildFile (filenameBox->getText());
  46200. return chosenFiles[index];
  46201. }
  46202. bool FileBrowserComponent::currentFileIsValid() const
  46203. {
  46204. if (isSaveMode())
  46205. return ! getSelectedFile (0).isDirectory();
  46206. else
  46207. return getSelectedFile (0).exists();
  46208. }
  46209. const File FileBrowserComponent::getHighlightedFile() const throw()
  46210. {
  46211. return fileListComponent->getSelectedFile (0);
  46212. }
  46213. void FileBrowserComponent::deselectAllFiles()
  46214. {
  46215. fileListComponent->deselectAllFiles();
  46216. }
  46217. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46218. {
  46219. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46220. : false;
  46221. }
  46222. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46223. {
  46224. return true;
  46225. }
  46226. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46227. {
  46228. if (f.isDirectory())
  46229. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46230. return (flags & canSelectFiles) != 0 && f.exists()
  46231. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46232. }
  46233. const File FileBrowserComponent::getRoot() const
  46234. {
  46235. return currentRoot;
  46236. }
  46237. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46238. {
  46239. if (currentRoot != newRootDirectory)
  46240. {
  46241. fileListComponent->scrollToTop();
  46242. String path (newRootDirectory.getFullPathName());
  46243. if (path.isEmpty())
  46244. path = File::separatorString;
  46245. StringArray rootNames, rootPaths;
  46246. getRoots (rootNames, rootPaths);
  46247. if (! rootPaths.contains (path, true))
  46248. {
  46249. bool alreadyListed = false;
  46250. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46251. {
  46252. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46253. {
  46254. alreadyListed = true;
  46255. break;
  46256. }
  46257. }
  46258. if (! alreadyListed)
  46259. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46260. }
  46261. }
  46262. currentRoot = newRootDirectory;
  46263. fileList->setDirectory (currentRoot, true, true);
  46264. String currentRootName (currentRoot.getFullPathName());
  46265. if (currentRootName.isEmpty())
  46266. currentRootName = File::separatorString;
  46267. currentPathBox->setText (currentRootName, true);
  46268. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46269. && currentRoot.getParentDirectory() != currentRoot);
  46270. }
  46271. void FileBrowserComponent::goUp()
  46272. {
  46273. setRoot (getRoot().getParentDirectory());
  46274. }
  46275. void FileBrowserComponent::refresh()
  46276. {
  46277. fileList->refresh();
  46278. }
  46279. const String FileBrowserComponent::getActionVerb() const
  46280. {
  46281. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46282. }
  46283. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46284. {
  46285. return previewComp;
  46286. }
  46287. void FileBrowserComponent::resized()
  46288. {
  46289. getLookAndFeel()
  46290. .layoutFileBrowserComponent (*this, fileListComponent,
  46291. previewComp, currentPathBox,
  46292. filenameBox, goUpButton);
  46293. }
  46294. void FileBrowserComponent::sendListenerChangeMessage()
  46295. {
  46296. Component::BailOutChecker checker (this);
  46297. if (previewComp != 0)
  46298. previewComp->selectedFileChanged (getSelectedFile (0));
  46299. // You shouldn't delete the browser when the file gets changed!
  46300. jassert (! checker.shouldBailOut());
  46301. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46302. }
  46303. void FileBrowserComponent::selectionChanged()
  46304. {
  46305. StringArray newFilenames;
  46306. bool resetChosenFiles = true;
  46307. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46308. {
  46309. const File f (fileListComponent->getSelectedFile (i));
  46310. if (isFileOrDirSuitable (f))
  46311. {
  46312. if (resetChosenFiles)
  46313. {
  46314. chosenFiles.clear();
  46315. resetChosenFiles = false;
  46316. }
  46317. chosenFiles.add (f);
  46318. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46319. }
  46320. }
  46321. if (newFilenames.size() > 0)
  46322. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46323. sendListenerChangeMessage();
  46324. }
  46325. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46326. {
  46327. Component::BailOutChecker checker (this);
  46328. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46329. }
  46330. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46331. {
  46332. if (f.isDirectory())
  46333. {
  46334. setRoot (f);
  46335. if ((flags & canSelectDirectories) != 0)
  46336. filenameBox->setText (String::empty);
  46337. }
  46338. else
  46339. {
  46340. Component::BailOutChecker checker (this);
  46341. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46342. }
  46343. }
  46344. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46345. {
  46346. (void) key;
  46347. #if JUCE_LINUX || JUCE_WINDOWS
  46348. if (key.getModifiers().isCommandDown()
  46349. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46350. {
  46351. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46352. fileList->refresh();
  46353. return true;
  46354. }
  46355. #endif
  46356. return false;
  46357. }
  46358. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46359. {
  46360. sendListenerChangeMessage();
  46361. }
  46362. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46363. {
  46364. if (filenameBox->getText().containsChar (File::separator))
  46365. {
  46366. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46367. if (f.isDirectory())
  46368. {
  46369. setRoot (f);
  46370. chosenFiles.clear();
  46371. filenameBox->setText (String::empty);
  46372. }
  46373. else
  46374. {
  46375. setRoot (f.getParentDirectory());
  46376. chosenFiles.clear();
  46377. chosenFiles.add (f);
  46378. filenameBox->setText (f.getFileName());
  46379. }
  46380. }
  46381. else
  46382. {
  46383. fileDoubleClicked (getSelectedFile (0));
  46384. }
  46385. }
  46386. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46387. {
  46388. }
  46389. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46390. {
  46391. if (! isSaveMode())
  46392. selectionChanged();
  46393. }
  46394. void FileBrowserComponent::buttonClicked (Button*)
  46395. {
  46396. goUp();
  46397. }
  46398. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46399. {
  46400. const String newText (currentPathBox->getText().trim().unquoted());
  46401. if (newText.isNotEmpty())
  46402. {
  46403. const int index = currentPathBox->getSelectedId() - 1;
  46404. StringArray rootNames, rootPaths;
  46405. getRoots (rootNames, rootPaths);
  46406. if (rootPaths [index].isNotEmpty())
  46407. {
  46408. setRoot (File (rootPaths [index]));
  46409. }
  46410. else
  46411. {
  46412. File f (newText);
  46413. for (;;)
  46414. {
  46415. if (f.isDirectory())
  46416. {
  46417. setRoot (f);
  46418. break;
  46419. }
  46420. if (f.getParentDirectory() == f)
  46421. break;
  46422. f = f.getParentDirectory();
  46423. }
  46424. }
  46425. }
  46426. }
  46427. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46428. {
  46429. BigInteger separators;
  46430. #if JUCE_WINDOWS
  46431. Array<File> roots;
  46432. File::findFileSystemRoots (roots);
  46433. rootPaths.clear();
  46434. for (int i = 0; i < roots.size(); ++i)
  46435. {
  46436. const File& drive = roots.getReference(i);
  46437. String name (drive.getFullPathName());
  46438. rootPaths.add (name);
  46439. if (drive.isOnHardDisk())
  46440. {
  46441. String volume (drive.getVolumeLabel());
  46442. if (volume.isEmpty())
  46443. volume = TRANS("Hard Drive");
  46444. name << " [" << drive.getVolumeLabel() << ']';
  46445. }
  46446. else if (drive.isOnCDRomDrive())
  46447. {
  46448. name << TRANS(" [CD/DVD drive]");
  46449. }
  46450. rootNames.add (name);
  46451. }
  46452. separators.setBit (rootPaths.size());
  46453. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46454. rootNames.add ("Documents");
  46455. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46456. rootNames.add ("Desktop");
  46457. #endif
  46458. #if JUCE_MAC
  46459. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46460. rootNames.add ("Home folder");
  46461. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46462. rootNames.add ("Documents");
  46463. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46464. rootNames.add ("Desktop");
  46465. separators.setBit (rootPaths.size());
  46466. Array <File> volumes;
  46467. File vol ("/Volumes");
  46468. vol.findChildFiles (volumes, File::findDirectories, false);
  46469. for (int i = 0; i < volumes.size(); ++i)
  46470. {
  46471. const File& volume = volumes.getReference(i);
  46472. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46473. {
  46474. rootPaths.add (volume.getFullPathName());
  46475. rootNames.add (volume.getFileName());
  46476. }
  46477. }
  46478. #endif
  46479. #if JUCE_LINUX
  46480. rootPaths.add ("/");
  46481. rootNames.add ("/");
  46482. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46483. rootNames.add ("Home folder");
  46484. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46485. rootNames.add ("Desktop");
  46486. #endif
  46487. return separators;
  46488. }
  46489. END_JUCE_NAMESPACE
  46490. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46491. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46492. BEGIN_JUCE_NAMESPACE
  46493. FileChooser::FileChooser (const String& chooserBoxTitle,
  46494. const File& currentFileOrDirectory,
  46495. const String& fileFilters,
  46496. const bool useNativeDialogBox_)
  46497. : title (chooserBoxTitle),
  46498. filters (fileFilters),
  46499. startingFile (currentFileOrDirectory),
  46500. useNativeDialogBox (useNativeDialogBox_)
  46501. {
  46502. #if JUCE_LINUX
  46503. useNativeDialogBox = false;
  46504. #endif
  46505. if (! fileFilters.containsNonWhitespaceChars())
  46506. filters = "*";
  46507. }
  46508. FileChooser::~FileChooser()
  46509. {
  46510. }
  46511. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46512. {
  46513. return showDialog (false, true, false, false, false, previewComponent);
  46514. }
  46515. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46516. {
  46517. return showDialog (false, true, false, false, true, previewComponent);
  46518. }
  46519. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46520. {
  46521. return showDialog (true, true, false, false, true, previewComponent);
  46522. }
  46523. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46524. {
  46525. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46526. }
  46527. bool FileChooser::browseForDirectory()
  46528. {
  46529. return showDialog (true, false, false, false, false, 0);
  46530. }
  46531. const File FileChooser::getResult() const
  46532. {
  46533. // if you've used a multiple-file select, you should use the getResults() method
  46534. // to retrieve all the files that were chosen.
  46535. jassert (results.size() <= 1);
  46536. return results.getFirst();
  46537. }
  46538. const Array<File>& FileChooser::getResults() const
  46539. {
  46540. return results;
  46541. }
  46542. bool FileChooser::showDialog (const bool selectsDirectories,
  46543. const bool selectsFiles,
  46544. const bool isSave,
  46545. const bool warnAboutOverwritingExistingFiles,
  46546. const bool selectMultipleFiles,
  46547. FilePreviewComponent* const previewComponent)
  46548. {
  46549. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46550. results.clear();
  46551. // the preview component needs to be the right size before you pass it in here..
  46552. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46553. && previewComponent->getHeight() > 10));
  46554. #if JUCE_WINDOWS
  46555. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46556. #elif JUCE_MAC
  46557. if (useNativeDialogBox && (previewComponent == 0))
  46558. #else
  46559. if (false)
  46560. #endif
  46561. {
  46562. showPlatformDialog (results, title, startingFile, filters,
  46563. selectsDirectories, selectsFiles, isSave,
  46564. warnAboutOverwritingExistingFiles,
  46565. selectMultipleFiles,
  46566. previewComponent);
  46567. }
  46568. else
  46569. {
  46570. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46571. selectsDirectories ? "*" : String::empty,
  46572. String::empty);
  46573. int flags = isSave ? FileBrowserComponent::saveMode
  46574. : FileBrowserComponent::openMode;
  46575. if (selectsFiles)
  46576. flags |= FileBrowserComponent::canSelectFiles;
  46577. if (selectsDirectories)
  46578. {
  46579. flags |= FileBrowserComponent::canSelectDirectories;
  46580. if (! isSave)
  46581. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46582. }
  46583. if (selectMultipleFiles)
  46584. flags |= FileBrowserComponent::canSelectMultipleItems;
  46585. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46586. FileChooserDialogBox box (title, String::empty,
  46587. browserComponent,
  46588. warnAboutOverwritingExistingFiles,
  46589. browserComponent.findColour (AlertWindow::backgroundColourId));
  46590. if (box.show())
  46591. {
  46592. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46593. results.add (browserComponent.getSelectedFile (i));
  46594. }
  46595. }
  46596. if (previouslyFocused != 0)
  46597. previouslyFocused->grabKeyboardFocus();
  46598. return results.size() > 0;
  46599. }
  46600. FilePreviewComponent::FilePreviewComponent()
  46601. {
  46602. }
  46603. FilePreviewComponent::~FilePreviewComponent()
  46604. {
  46605. }
  46606. END_JUCE_NAMESPACE
  46607. /*** End of inlined file: juce_FileChooser.cpp ***/
  46608. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46609. BEGIN_JUCE_NAMESPACE
  46610. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46611. const String& instructions,
  46612. FileBrowserComponent& chooserComponent,
  46613. const bool warnAboutOverwritingExistingFiles_,
  46614. const Colour& backgroundColour)
  46615. : ResizableWindow (name, backgroundColour, true),
  46616. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46617. {
  46618. content = new ContentComponent();
  46619. content->setName (name);
  46620. content->instructions = instructions;
  46621. content->chooserComponent = &chooserComponent;
  46622. content->addAndMakeVisible (&chooserComponent);
  46623. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46624. content->addAndMakeVisible (content->okButton);
  46625. content->okButton->addButtonListener (this);
  46626. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46627. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46628. content->cancelButton = new TextButton (TRANS("Cancel"));
  46629. content->addAndMakeVisible (content->cancelButton);
  46630. content->cancelButton->addButtonListener (this);
  46631. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46632. setContentComponent (content);
  46633. setResizable (true, true);
  46634. setResizeLimits (300, 300, 1200, 1000);
  46635. content->chooserComponent->addListener (this);
  46636. }
  46637. FileChooserDialogBox::~FileChooserDialogBox()
  46638. {
  46639. content->chooserComponent->removeListener (this);
  46640. }
  46641. bool FileChooserDialogBox::show (int w, int h)
  46642. {
  46643. return showAt (-1, -1, w, h);
  46644. }
  46645. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46646. {
  46647. if (w <= 0)
  46648. {
  46649. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46650. if (previewComp != 0)
  46651. w = 400 + previewComp->getWidth();
  46652. else
  46653. w = 600;
  46654. }
  46655. if (h <= 0)
  46656. h = 500;
  46657. if (x < 0 || y < 0)
  46658. centreWithSize (w, h);
  46659. else
  46660. setBounds (x, y, w, h);
  46661. const bool ok = (runModalLoop() != 0);
  46662. setVisible (false);
  46663. return ok;
  46664. }
  46665. void FileChooserDialogBox::buttonClicked (Button* button)
  46666. {
  46667. if (button == content->okButton)
  46668. {
  46669. if (warnAboutOverwritingExistingFiles
  46670. && content->chooserComponent->isSaveMode()
  46671. && content->chooserComponent->getSelectedFile(0).exists())
  46672. {
  46673. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46674. TRANS("File already exists"),
  46675. TRANS("There's already a file called:")
  46676. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46677. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46678. TRANS("overwrite"),
  46679. TRANS("cancel")))
  46680. {
  46681. return;
  46682. }
  46683. }
  46684. exitModalState (1);
  46685. }
  46686. else if (button == content->cancelButton)
  46687. closeButtonPressed();
  46688. }
  46689. void FileChooserDialogBox::closeButtonPressed()
  46690. {
  46691. setVisible (false);
  46692. }
  46693. void FileChooserDialogBox::selectionChanged()
  46694. {
  46695. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46696. }
  46697. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46698. {
  46699. }
  46700. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46701. {
  46702. selectionChanged();
  46703. content->okButton->triggerClick();
  46704. }
  46705. FileChooserDialogBox::ContentComponent::ContentComponent()
  46706. {
  46707. setInterceptsMouseClicks (false, true);
  46708. }
  46709. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46710. {
  46711. delete okButton;
  46712. delete cancelButton;
  46713. }
  46714. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46715. {
  46716. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46717. text.draw (g);
  46718. }
  46719. void FileChooserDialogBox::ContentComponent::resized()
  46720. {
  46721. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46722. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46723. const int y = roundToInt (bb.getBottom()) + 10;
  46724. const int buttonHeight = 26;
  46725. const int buttonY = getHeight() - buttonHeight - 8;
  46726. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46727. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46728. proportionOfWidth (0.2f), buttonHeight);
  46729. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46730. proportionOfWidth (0.2f), buttonHeight);
  46731. }
  46732. END_JUCE_NAMESPACE
  46733. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46734. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46735. BEGIN_JUCE_NAMESPACE
  46736. FileFilter::FileFilter (const String& filterDescription)
  46737. : description (filterDescription)
  46738. {
  46739. }
  46740. FileFilter::~FileFilter()
  46741. {
  46742. }
  46743. const String& FileFilter::getDescription() const throw()
  46744. {
  46745. return description;
  46746. }
  46747. END_JUCE_NAMESPACE
  46748. /*** End of inlined file: juce_FileFilter.cpp ***/
  46749. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46750. BEGIN_JUCE_NAMESPACE
  46751. const Image juce_createIconForFile (const File& file);
  46752. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46753. : ListBox (String::empty, 0),
  46754. DirectoryContentsDisplayComponent (listToShow)
  46755. {
  46756. setModel (this);
  46757. fileList.addChangeListener (this);
  46758. }
  46759. FileListComponent::~FileListComponent()
  46760. {
  46761. fileList.removeChangeListener (this);
  46762. }
  46763. int FileListComponent::getNumSelectedFiles() const
  46764. {
  46765. return getNumSelectedRows();
  46766. }
  46767. const File FileListComponent::getSelectedFile (int index) const
  46768. {
  46769. return fileList.getFile (getSelectedRow (index));
  46770. }
  46771. void FileListComponent::deselectAllFiles()
  46772. {
  46773. deselectAllRows();
  46774. }
  46775. void FileListComponent::scrollToTop()
  46776. {
  46777. getVerticalScrollBar()->setCurrentRangeStart (0);
  46778. }
  46779. void FileListComponent::changeListenerCallback (void*)
  46780. {
  46781. updateContent();
  46782. if (lastDirectory != fileList.getDirectory())
  46783. {
  46784. lastDirectory = fileList.getDirectory();
  46785. deselectAllRows();
  46786. }
  46787. }
  46788. class FileListItemComponent : public Component,
  46789. public TimeSliceClient,
  46790. public AsyncUpdater
  46791. {
  46792. public:
  46793. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46794. : owner (owner_), thread (thread_),
  46795. highlighted (false), index (0), icon (0)
  46796. {
  46797. }
  46798. ~FileListItemComponent()
  46799. {
  46800. thread.removeTimeSliceClient (this);
  46801. clearIcon();
  46802. }
  46803. void paint (Graphics& g)
  46804. {
  46805. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46806. file.getFileName(),
  46807. &icon,
  46808. fileSize, modTime,
  46809. isDirectory, highlighted,
  46810. index);
  46811. }
  46812. void mouseDown (const MouseEvent& e)
  46813. {
  46814. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46815. owner.sendMouseClickMessage (file, e);
  46816. }
  46817. void mouseDoubleClick (const MouseEvent&)
  46818. {
  46819. owner.sendDoubleClickMessage (file);
  46820. }
  46821. void update (const File& root,
  46822. const DirectoryContentsList::FileInfo* const fileInfo,
  46823. const int index_,
  46824. const bool highlighted_)
  46825. {
  46826. thread.removeTimeSliceClient (this);
  46827. if (highlighted_ != highlighted
  46828. || index_ != index)
  46829. {
  46830. index = index_;
  46831. highlighted = highlighted_;
  46832. repaint();
  46833. }
  46834. File newFile;
  46835. String newFileSize;
  46836. String newModTime;
  46837. if (fileInfo != 0)
  46838. {
  46839. newFile = root.getChildFile (fileInfo->filename);
  46840. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46841. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46842. }
  46843. if (newFile != file
  46844. || fileSize != newFileSize
  46845. || modTime != newModTime)
  46846. {
  46847. file = newFile;
  46848. fileSize = newFileSize;
  46849. modTime = newModTime;
  46850. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46851. repaint();
  46852. clearIcon();
  46853. }
  46854. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46855. {
  46856. updateIcon (true);
  46857. if (! icon.isValid())
  46858. thread.addTimeSliceClient (this);
  46859. }
  46860. }
  46861. bool useTimeSlice()
  46862. {
  46863. updateIcon (false);
  46864. return false;
  46865. }
  46866. void handleAsyncUpdate()
  46867. {
  46868. repaint();
  46869. }
  46870. juce_UseDebuggingNewOperator
  46871. private:
  46872. FileListComponent& owner;
  46873. TimeSliceThread& thread;
  46874. bool highlighted;
  46875. int index;
  46876. File file;
  46877. String fileSize;
  46878. String modTime;
  46879. Image icon;
  46880. bool isDirectory;
  46881. void clearIcon()
  46882. {
  46883. icon = Image::null;
  46884. }
  46885. void updateIcon (const bool onlyUpdateIfCached)
  46886. {
  46887. if (icon.isNull())
  46888. {
  46889. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46890. Image im (ImageCache::getFromHashCode (hashCode));
  46891. if (im.isNull() && ! onlyUpdateIfCached)
  46892. {
  46893. im = juce_createIconForFile (file);
  46894. if (im.isValid())
  46895. ImageCache::addImageToCache (im, hashCode);
  46896. }
  46897. if (im.isValid())
  46898. {
  46899. icon = im;
  46900. triggerAsyncUpdate();
  46901. }
  46902. }
  46903. }
  46904. };
  46905. int FileListComponent::getNumRows()
  46906. {
  46907. return fileList.getNumFiles();
  46908. }
  46909. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46910. {
  46911. }
  46912. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46913. {
  46914. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46915. if (comp == 0)
  46916. {
  46917. delete existingComponentToUpdate;
  46918. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46919. }
  46920. DirectoryContentsList::FileInfo fileInfo;
  46921. if (fileList.getFileInfo (row, fileInfo))
  46922. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46923. else
  46924. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46925. return comp;
  46926. }
  46927. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46928. {
  46929. sendSelectionChangeMessage();
  46930. }
  46931. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46932. {
  46933. }
  46934. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46935. {
  46936. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46937. }
  46938. END_JUCE_NAMESPACE
  46939. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46940. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46941. BEGIN_JUCE_NAMESPACE
  46942. FilenameComponent::FilenameComponent (const String& name,
  46943. const File& currentFile,
  46944. const bool canEditFilename,
  46945. const bool isDirectory,
  46946. const bool isForSaving,
  46947. const String& fileBrowserWildcard,
  46948. const String& enforcedSuffix_,
  46949. const String& textWhenNothingSelected)
  46950. : Component (name),
  46951. maxRecentFiles (30),
  46952. isDir (isDirectory),
  46953. isSaving (isForSaving),
  46954. isFileDragOver (false),
  46955. wildcard (fileBrowserWildcard),
  46956. enforcedSuffix (enforcedSuffix_)
  46957. {
  46958. addAndMakeVisible (&filenameBox);
  46959. filenameBox.setEditableText (canEditFilename);
  46960. filenameBox.addListener (this);
  46961. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46962. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46963. setBrowseButtonText ("...");
  46964. setCurrentFile (currentFile, true);
  46965. }
  46966. FilenameComponent::~FilenameComponent()
  46967. {
  46968. }
  46969. void FilenameComponent::paintOverChildren (Graphics& g)
  46970. {
  46971. if (isFileDragOver)
  46972. {
  46973. g.setColour (Colours::red.withAlpha (0.2f));
  46974. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46975. }
  46976. }
  46977. void FilenameComponent::resized()
  46978. {
  46979. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46980. }
  46981. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46982. {
  46983. browseButtonText = newBrowseButtonText;
  46984. lookAndFeelChanged();
  46985. }
  46986. void FilenameComponent::lookAndFeelChanged()
  46987. {
  46988. browseButton = 0;
  46989. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46990. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46991. resized();
  46992. browseButton->addButtonListener (this);
  46993. }
  46994. void FilenameComponent::setTooltip (const String& newTooltip)
  46995. {
  46996. SettableTooltipClient::setTooltip (newTooltip);
  46997. filenameBox.setTooltip (newTooltip);
  46998. }
  46999. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47000. {
  47001. defaultBrowseFile = newDefaultDirectory;
  47002. }
  47003. void FilenameComponent::buttonClicked (Button*)
  47004. {
  47005. FileChooser fc (TRANS("Choose a new file"),
  47006. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47007. : getCurrentFile(),
  47008. wildcard);
  47009. if (isDir ? fc.browseForDirectory()
  47010. : (isSaving ? fc.browseForFileToSave (false)
  47011. : fc.browseForFileToOpen()))
  47012. {
  47013. setCurrentFile (fc.getResult(), true);
  47014. }
  47015. }
  47016. void FilenameComponent::comboBoxChanged (ComboBox*)
  47017. {
  47018. setCurrentFile (getCurrentFile(), true);
  47019. }
  47020. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47021. {
  47022. return true;
  47023. }
  47024. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47025. {
  47026. isFileDragOver = false;
  47027. repaint();
  47028. const File f (filenames[0]);
  47029. if (f.exists() && (f.isDirectory() == isDir))
  47030. setCurrentFile (f, true);
  47031. }
  47032. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47033. {
  47034. isFileDragOver = true;
  47035. repaint();
  47036. }
  47037. void FilenameComponent::fileDragExit (const StringArray&)
  47038. {
  47039. isFileDragOver = false;
  47040. repaint();
  47041. }
  47042. const File FilenameComponent::getCurrentFile() const
  47043. {
  47044. File f (filenameBox.getText());
  47045. if (enforcedSuffix.isNotEmpty())
  47046. f = f.withFileExtension (enforcedSuffix);
  47047. return f;
  47048. }
  47049. void FilenameComponent::setCurrentFile (File newFile,
  47050. const bool addToRecentlyUsedList,
  47051. const bool sendChangeNotification)
  47052. {
  47053. if (enforcedSuffix.isNotEmpty())
  47054. newFile = newFile.withFileExtension (enforcedSuffix);
  47055. if (newFile.getFullPathName() != lastFilename)
  47056. {
  47057. lastFilename = newFile.getFullPathName();
  47058. if (addToRecentlyUsedList)
  47059. addRecentlyUsedFile (newFile);
  47060. filenameBox.setText (lastFilename, true);
  47061. if (sendChangeNotification)
  47062. triggerAsyncUpdate();
  47063. }
  47064. }
  47065. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47066. {
  47067. filenameBox.setEditableText (shouldBeEditable);
  47068. }
  47069. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47070. {
  47071. StringArray names;
  47072. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47073. names.add (filenameBox.getItemText (i));
  47074. return names;
  47075. }
  47076. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47077. {
  47078. if (filenames != getRecentlyUsedFilenames())
  47079. {
  47080. filenameBox.clear();
  47081. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47082. filenameBox.addItem (filenames[i], i + 1);
  47083. }
  47084. }
  47085. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47086. {
  47087. maxRecentFiles = jmax (1, newMaximum);
  47088. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47089. }
  47090. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47091. {
  47092. StringArray files (getRecentlyUsedFilenames());
  47093. if (file.getFullPathName().isNotEmpty())
  47094. {
  47095. files.removeString (file.getFullPathName(), true);
  47096. files.insert (0, file.getFullPathName());
  47097. setRecentlyUsedFilenames (files);
  47098. }
  47099. }
  47100. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47101. {
  47102. listeners.add (listener);
  47103. }
  47104. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47105. {
  47106. listeners.remove (listener);
  47107. }
  47108. void FilenameComponent::handleAsyncUpdate()
  47109. {
  47110. Component::BailOutChecker checker (this);
  47111. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47112. }
  47113. END_JUCE_NAMESPACE
  47114. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47115. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47116. BEGIN_JUCE_NAMESPACE
  47117. FileSearchPathListComponent::FileSearchPathListComponent()
  47118. {
  47119. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47120. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47121. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47122. listBox->setOutlineThickness (1);
  47123. addAndMakeVisible (addButton = new TextButton ("+"));
  47124. addButton->addButtonListener (this);
  47125. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47126. addAndMakeVisible (removeButton = new TextButton ("-"));
  47127. removeButton->addButtonListener (this);
  47128. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47129. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47130. changeButton->addButtonListener (this);
  47131. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47132. upButton->addButtonListener (this);
  47133. {
  47134. Path arrowPath;
  47135. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47136. DrawablePath arrowImage;
  47137. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47138. arrowImage.setPath (arrowPath);
  47139. upButton->setImages (&arrowImage);
  47140. }
  47141. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47142. downButton->addButtonListener (this);
  47143. {
  47144. Path arrowPath;
  47145. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47146. DrawablePath arrowImage;
  47147. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47148. arrowImage.setPath (arrowPath);
  47149. downButton->setImages (&arrowImage);
  47150. }
  47151. updateButtons();
  47152. }
  47153. FileSearchPathListComponent::~FileSearchPathListComponent()
  47154. {
  47155. deleteAllChildren();
  47156. }
  47157. void FileSearchPathListComponent::updateButtons()
  47158. {
  47159. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47160. removeButton->setEnabled (anythingSelected);
  47161. changeButton->setEnabled (anythingSelected);
  47162. upButton->setEnabled (anythingSelected);
  47163. downButton->setEnabled (anythingSelected);
  47164. }
  47165. void FileSearchPathListComponent::changed()
  47166. {
  47167. listBox->updateContent();
  47168. listBox->repaint();
  47169. updateButtons();
  47170. }
  47171. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47172. {
  47173. if (newPath.toString() != path.toString())
  47174. {
  47175. path = newPath;
  47176. changed();
  47177. }
  47178. }
  47179. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47180. {
  47181. defaultBrowseTarget = newDefaultDirectory;
  47182. }
  47183. int FileSearchPathListComponent::getNumRows()
  47184. {
  47185. return path.getNumPaths();
  47186. }
  47187. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47188. {
  47189. if (rowIsSelected)
  47190. g.fillAll (findColour (TextEditor::highlightColourId));
  47191. g.setColour (findColour (ListBox::textColourId));
  47192. Font f (height * 0.7f);
  47193. f.setHorizontalScale (0.9f);
  47194. g.setFont (f);
  47195. g.drawText (path [rowNumber].getFullPathName(),
  47196. 4, 0, width - 6, height,
  47197. Justification::centredLeft, true);
  47198. }
  47199. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47200. {
  47201. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47202. {
  47203. path.remove (row);
  47204. changed();
  47205. }
  47206. }
  47207. void FileSearchPathListComponent::returnKeyPressed (int row)
  47208. {
  47209. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47210. if (chooser.browseForDirectory())
  47211. {
  47212. path.remove (row);
  47213. path.add (chooser.getResult(), row);
  47214. changed();
  47215. }
  47216. }
  47217. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47218. {
  47219. returnKeyPressed (row);
  47220. }
  47221. void FileSearchPathListComponent::selectedRowsChanged (int)
  47222. {
  47223. updateButtons();
  47224. }
  47225. void FileSearchPathListComponent::paint (Graphics& g)
  47226. {
  47227. g.fillAll (findColour (backgroundColourId));
  47228. }
  47229. void FileSearchPathListComponent::resized()
  47230. {
  47231. const int buttonH = 22;
  47232. const int buttonY = getHeight() - buttonH - 4;
  47233. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47234. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47235. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47236. changeButton->changeWidthToFitText (buttonH);
  47237. downButton->setSize (buttonH * 2, buttonH);
  47238. upButton->setSize (buttonH * 2, buttonH);
  47239. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47240. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47241. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47242. }
  47243. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47244. {
  47245. return true;
  47246. }
  47247. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47248. {
  47249. for (int i = filenames.size(); --i >= 0;)
  47250. {
  47251. const File f (filenames[i]);
  47252. if (f.isDirectory())
  47253. {
  47254. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47255. path.add (f, row);
  47256. changed();
  47257. }
  47258. }
  47259. }
  47260. void FileSearchPathListComponent::buttonClicked (Button* button)
  47261. {
  47262. const int currentRow = listBox->getSelectedRow();
  47263. if (button == removeButton)
  47264. {
  47265. deleteKeyPressed (currentRow);
  47266. }
  47267. else if (button == addButton)
  47268. {
  47269. File start (defaultBrowseTarget);
  47270. if (start == File::nonexistent)
  47271. start = path [0];
  47272. if (start == File::nonexistent)
  47273. start = File::getCurrentWorkingDirectory();
  47274. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47275. if (chooser.browseForDirectory())
  47276. {
  47277. path.add (chooser.getResult(), currentRow);
  47278. }
  47279. }
  47280. else if (button == changeButton)
  47281. {
  47282. returnKeyPressed (currentRow);
  47283. }
  47284. else if (button == upButton)
  47285. {
  47286. if (currentRow > 0 && currentRow < path.getNumPaths())
  47287. {
  47288. const File f (path[currentRow]);
  47289. path.remove (currentRow);
  47290. path.add (f, currentRow - 1);
  47291. listBox->selectRow (currentRow - 1);
  47292. }
  47293. }
  47294. else if (button == downButton)
  47295. {
  47296. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47297. {
  47298. const File f (path[currentRow]);
  47299. path.remove (currentRow);
  47300. path.add (f, currentRow + 1);
  47301. listBox->selectRow (currentRow + 1);
  47302. }
  47303. }
  47304. changed();
  47305. }
  47306. END_JUCE_NAMESPACE
  47307. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47308. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47309. BEGIN_JUCE_NAMESPACE
  47310. const Image juce_createIconForFile (const File& file);
  47311. class FileListTreeItem : public TreeViewItem,
  47312. public TimeSliceClient,
  47313. public AsyncUpdater,
  47314. public ChangeListener
  47315. {
  47316. public:
  47317. FileListTreeItem (FileTreeComponent& owner_,
  47318. DirectoryContentsList* const parentContentsList_,
  47319. const int indexInContentsList_,
  47320. const File& file_,
  47321. TimeSliceThread& thread_)
  47322. : file (file_),
  47323. owner (owner_),
  47324. parentContentsList (parentContentsList_),
  47325. indexInContentsList (indexInContentsList_),
  47326. subContentsList (0),
  47327. canDeleteSubContentsList (false),
  47328. thread (thread_),
  47329. icon (0)
  47330. {
  47331. DirectoryContentsList::FileInfo fileInfo;
  47332. if (parentContentsList_ != 0
  47333. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47334. {
  47335. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47336. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47337. isDirectory = fileInfo.isDirectory;
  47338. }
  47339. else
  47340. {
  47341. isDirectory = true;
  47342. }
  47343. }
  47344. ~FileListTreeItem()
  47345. {
  47346. thread.removeTimeSliceClient (this);
  47347. clearSubItems();
  47348. if (canDeleteSubContentsList)
  47349. delete subContentsList;
  47350. }
  47351. bool mightContainSubItems() { return isDirectory; }
  47352. const String getUniqueName() const { return file.getFullPathName(); }
  47353. int getItemHeight() const { return 22; }
  47354. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47355. void itemOpennessChanged (bool isNowOpen)
  47356. {
  47357. if (isNowOpen)
  47358. {
  47359. clearSubItems();
  47360. isDirectory = file.isDirectory();
  47361. if (isDirectory)
  47362. {
  47363. if (subContentsList == 0)
  47364. {
  47365. jassert (parentContentsList != 0);
  47366. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47367. l->setDirectory (file, true, true);
  47368. setSubContentsList (l);
  47369. canDeleteSubContentsList = true;
  47370. }
  47371. changeListenerCallback (0);
  47372. }
  47373. }
  47374. }
  47375. void setSubContentsList (DirectoryContentsList* newList)
  47376. {
  47377. jassert (subContentsList == 0);
  47378. subContentsList = newList;
  47379. newList->addChangeListener (this);
  47380. }
  47381. void changeListenerCallback (void*)
  47382. {
  47383. clearSubItems();
  47384. if (isOpen() && subContentsList != 0)
  47385. {
  47386. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47387. {
  47388. FileListTreeItem* const item
  47389. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47390. addSubItem (item);
  47391. }
  47392. }
  47393. }
  47394. void paintItem (Graphics& g, int width, int height)
  47395. {
  47396. if (file != File::nonexistent)
  47397. {
  47398. updateIcon (true);
  47399. if (icon.isNull())
  47400. thread.addTimeSliceClient (this);
  47401. }
  47402. owner.getLookAndFeel()
  47403. .drawFileBrowserRow (g, width, height,
  47404. file.getFileName(),
  47405. &icon, fileSize, modTime,
  47406. isDirectory, isSelected(),
  47407. indexInContentsList);
  47408. }
  47409. void itemClicked (const MouseEvent& e)
  47410. {
  47411. owner.sendMouseClickMessage (file, e);
  47412. }
  47413. void itemDoubleClicked (const MouseEvent& e)
  47414. {
  47415. TreeViewItem::itemDoubleClicked (e);
  47416. owner.sendDoubleClickMessage (file);
  47417. }
  47418. void itemSelectionChanged (bool)
  47419. {
  47420. owner.sendSelectionChangeMessage();
  47421. }
  47422. bool useTimeSlice()
  47423. {
  47424. updateIcon (false);
  47425. thread.removeTimeSliceClient (this);
  47426. return false;
  47427. }
  47428. void handleAsyncUpdate()
  47429. {
  47430. owner.repaint();
  47431. }
  47432. const File file;
  47433. juce_UseDebuggingNewOperator
  47434. private:
  47435. FileTreeComponent& owner;
  47436. DirectoryContentsList* parentContentsList;
  47437. int indexInContentsList;
  47438. DirectoryContentsList* subContentsList;
  47439. bool isDirectory, canDeleteSubContentsList;
  47440. TimeSliceThread& thread;
  47441. Image icon;
  47442. String fileSize;
  47443. String modTime;
  47444. void updateIcon (const bool onlyUpdateIfCached)
  47445. {
  47446. if (icon.isNull())
  47447. {
  47448. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47449. Image im (ImageCache::getFromHashCode (hashCode));
  47450. if (im.isNull() && ! onlyUpdateIfCached)
  47451. {
  47452. im = juce_createIconForFile (file);
  47453. if (im.isValid())
  47454. ImageCache::addImageToCache (im, hashCode);
  47455. }
  47456. if (im.isValid())
  47457. {
  47458. icon = im;
  47459. triggerAsyncUpdate();
  47460. }
  47461. }
  47462. }
  47463. };
  47464. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47465. : DirectoryContentsDisplayComponent (listToShow)
  47466. {
  47467. FileListTreeItem* const root
  47468. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47469. listToShow.getTimeSliceThread());
  47470. root->setSubContentsList (&listToShow);
  47471. setRootItemVisible (false);
  47472. setRootItem (root);
  47473. }
  47474. FileTreeComponent::~FileTreeComponent()
  47475. {
  47476. deleteRootItem();
  47477. }
  47478. const File FileTreeComponent::getSelectedFile (const int index) const
  47479. {
  47480. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47481. return item != 0 ? item->file
  47482. : File::nonexistent;
  47483. }
  47484. void FileTreeComponent::deselectAllFiles()
  47485. {
  47486. clearSelectedItems();
  47487. }
  47488. void FileTreeComponent::scrollToTop()
  47489. {
  47490. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47491. }
  47492. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47493. {
  47494. dragAndDropDescription = description;
  47495. }
  47496. END_JUCE_NAMESPACE
  47497. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47498. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47499. BEGIN_JUCE_NAMESPACE
  47500. ImagePreviewComponent::ImagePreviewComponent()
  47501. {
  47502. }
  47503. ImagePreviewComponent::~ImagePreviewComponent()
  47504. {
  47505. }
  47506. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47507. {
  47508. const int availableW = proportionOfWidth (0.97f);
  47509. const int availableH = getHeight() - 13 * 4;
  47510. const double scale = jmin (1.0,
  47511. availableW / (double) w,
  47512. availableH / (double) h);
  47513. w = roundToInt (scale * w);
  47514. h = roundToInt (scale * h);
  47515. }
  47516. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47517. {
  47518. if (fileToLoad != file)
  47519. {
  47520. fileToLoad = file;
  47521. startTimer (100);
  47522. }
  47523. }
  47524. void ImagePreviewComponent::timerCallback()
  47525. {
  47526. stopTimer();
  47527. currentThumbnail = Image::null;
  47528. currentDetails = String::empty;
  47529. repaint();
  47530. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47531. if (in != 0)
  47532. {
  47533. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47534. if (format != 0)
  47535. {
  47536. currentThumbnail = format->decodeImage (*in);
  47537. if (currentThumbnail.isValid())
  47538. {
  47539. int w = currentThumbnail.getWidth();
  47540. int h = currentThumbnail.getHeight();
  47541. currentDetails
  47542. << fileToLoad.getFileName() << "\n"
  47543. << format->getFormatName() << "\n"
  47544. << w << " x " << h << " pixels\n"
  47545. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47546. getThumbSize (w, h);
  47547. currentThumbnail = currentThumbnail.rescaled (w, h);
  47548. }
  47549. }
  47550. }
  47551. }
  47552. void ImagePreviewComponent::paint (Graphics& g)
  47553. {
  47554. if (currentThumbnail.isValid())
  47555. {
  47556. g.setFont (13.0f);
  47557. int w = currentThumbnail.getWidth();
  47558. int h = currentThumbnail.getHeight();
  47559. getThumbSize (w, h);
  47560. const int numLines = 4;
  47561. const int totalH = 13 * numLines + h + 4;
  47562. const int y = (getHeight() - totalH) / 2;
  47563. g.drawImageWithin (currentThumbnail,
  47564. (getWidth() - w) / 2, y, w, h,
  47565. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47566. false);
  47567. g.drawFittedText (currentDetails,
  47568. 0, y + h + 4, getWidth(), 100,
  47569. Justification::centredTop, numLines);
  47570. }
  47571. }
  47572. END_JUCE_NAMESPACE
  47573. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47574. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47575. BEGIN_JUCE_NAMESPACE
  47576. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47577. const String& directoryWildcardPatterns,
  47578. const String& description_)
  47579. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47580. : (description_ + " (" + fileWildcardPatterns + ")"))
  47581. {
  47582. parse (fileWildcardPatterns, fileWildcards);
  47583. parse (directoryWildcardPatterns, directoryWildcards);
  47584. }
  47585. WildcardFileFilter::~WildcardFileFilter()
  47586. {
  47587. }
  47588. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47589. {
  47590. return match (file, fileWildcards);
  47591. }
  47592. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47593. {
  47594. return match (file, directoryWildcards);
  47595. }
  47596. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47597. {
  47598. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47599. result.trim();
  47600. result.removeEmptyStrings();
  47601. // special case for *.*, because people use it to mean "any file", but it
  47602. // would actually ignore files with no extension.
  47603. for (int i = result.size(); --i >= 0;)
  47604. if (result[i] == "*.*")
  47605. result.set (i, "*");
  47606. }
  47607. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47608. {
  47609. const String filename (file.getFileName());
  47610. for (int i = wildcards.size(); --i >= 0;)
  47611. if (filename.matchesWildcard (wildcards[i], true))
  47612. return true;
  47613. return false;
  47614. }
  47615. END_JUCE_NAMESPACE
  47616. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47617. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47618. BEGIN_JUCE_NAMESPACE
  47619. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47620. {
  47621. }
  47622. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47623. {
  47624. }
  47625. namespace KeyboardFocusHelpers
  47626. {
  47627. // This will sort a set of components, so that they are ordered in terms of
  47628. // left-to-right and then top-to-bottom.
  47629. class ScreenPositionComparator
  47630. {
  47631. public:
  47632. ScreenPositionComparator() {}
  47633. static int compareElements (const Component* const first, const Component* const second)
  47634. {
  47635. int explicitOrder1 = first->getExplicitFocusOrder();
  47636. if (explicitOrder1 <= 0)
  47637. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47638. int explicitOrder2 = second->getExplicitFocusOrder();
  47639. if (explicitOrder2 <= 0)
  47640. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47641. if (explicitOrder1 != explicitOrder2)
  47642. return explicitOrder1 - explicitOrder2;
  47643. const int diff = first->getY() - second->getY();
  47644. return (diff == 0) ? first->getX() - second->getX()
  47645. : diff;
  47646. }
  47647. };
  47648. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47649. {
  47650. if (parent->getNumChildComponents() > 0)
  47651. {
  47652. Array <Component*> localComps;
  47653. ScreenPositionComparator comparator;
  47654. int i;
  47655. for (i = parent->getNumChildComponents(); --i >= 0;)
  47656. {
  47657. Component* const c = parent->getChildComponent (i);
  47658. if (c->isVisible() && c->isEnabled())
  47659. localComps.addSorted (comparator, c);
  47660. }
  47661. for (i = 0; i < localComps.size(); ++i)
  47662. {
  47663. Component* const c = localComps.getUnchecked (i);
  47664. if (c->getWantsKeyboardFocus())
  47665. comps.add (c);
  47666. if (! c->isFocusContainer())
  47667. findAllFocusableComponents (c, comps);
  47668. }
  47669. }
  47670. }
  47671. }
  47672. static Component* getIncrementedComponent (Component* const current, const int delta)
  47673. {
  47674. Component* focusContainer = current->getParentComponent();
  47675. if (focusContainer != 0)
  47676. {
  47677. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47678. focusContainer = focusContainer->getParentComponent();
  47679. if (focusContainer != 0)
  47680. {
  47681. Array <Component*> comps;
  47682. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47683. if (comps.size() > 0)
  47684. {
  47685. const int index = comps.indexOf (current);
  47686. return comps [(index + comps.size() + delta) % comps.size()];
  47687. }
  47688. }
  47689. }
  47690. return 0;
  47691. }
  47692. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47693. {
  47694. return getIncrementedComponent (current, 1);
  47695. }
  47696. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47697. {
  47698. return getIncrementedComponent (current, -1);
  47699. }
  47700. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47701. {
  47702. Array <Component*> comps;
  47703. if (parentComponent != 0)
  47704. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47705. return comps.getFirst();
  47706. }
  47707. END_JUCE_NAMESPACE
  47708. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47709. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47710. BEGIN_JUCE_NAMESPACE
  47711. bool KeyListener::keyStateChanged (const bool, Component*)
  47712. {
  47713. return false;
  47714. }
  47715. END_JUCE_NAMESPACE
  47716. /*** End of inlined file: juce_KeyListener.cpp ***/
  47717. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47718. BEGIN_JUCE_NAMESPACE
  47719. // N.B. these two includes are put here deliberately to avoid problems with
  47720. // old GCCs failing on long include paths
  47721. const int maxKeys = 3;
  47722. class KeyMappingChangeButton : public Button
  47723. {
  47724. public:
  47725. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47726. const CommandID commandID_,
  47727. const String& keyName,
  47728. const int keyNum_)
  47729. : Button (keyName),
  47730. owner (owner_),
  47731. commandID (commandID_),
  47732. keyNum (keyNum_)
  47733. {
  47734. setWantsKeyboardFocus (false);
  47735. setTriggeredOnMouseDown (keyNum >= 0);
  47736. if (keyNum_ < 0)
  47737. setTooltip (TRANS("adds a new key-mapping"));
  47738. else
  47739. setTooltip (TRANS("click to change this key-mapping"));
  47740. }
  47741. ~KeyMappingChangeButton()
  47742. {
  47743. }
  47744. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47745. {
  47746. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47747. keyNum >= 0 ? getName() : String::empty);
  47748. }
  47749. void clicked()
  47750. {
  47751. if (keyNum >= 0)
  47752. {
  47753. // existing key clicked..
  47754. PopupMenu m;
  47755. m.addItem (1, TRANS("change this key-mapping"));
  47756. m.addSeparator();
  47757. m.addItem (2, TRANS("remove this key-mapping"));
  47758. const int res = m.show();
  47759. if (res == 1)
  47760. {
  47761. owner->assignNewKey (commandID, keyNum);
  47762. }
  47763. else if (res == 2)
  47764. {
  47765. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47766. }
  47767. }
  47768. else
  47769. {
  47770. // + button pressed..
  47771. owner->assignNewKey (commandID, -1);
  47772. }
  47773. }
  47774. void fitToContent (const int h) throw()
  47775. {
  47776. if (keyNum < 0)
  47777. {
  47778. setSize (h, h);
  47779. }
  47780. else
  47781. {
  47782. Font f (h * 0.6f);
  47783. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47784. }
  47785. }
  47786. juce_UseDebuggingNewOperator
  47787. private:
  47788. KeyMappingEditorComponent* const owner;
  47789. const CommandID commandID;
  47790. const int keyNum;
  47791. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47792. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47793. };
  47794. class KeyMappingItemComponent : public Component
  47795. {
  47796. public:
  47797. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47798. const CommandID commandID_)
  47799. : owner (owner_),
  47800. commandID (commandID_)
  47801. {
  47802. setInterceptsMouseClicks (false, true);
  47803. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47804. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47805. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47806. {
  47807. KeyMappingChangeButton* const kb
  47808. = new KeyMappingChangeButton (owner_, commandID,
  47809. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47810. kb->setEnabled (! isReadOnly);
  47811. addAndMakeVisible (kb);
  47812. }
  47813. KeyMappingChangeButton* const kb
  47814. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47815. addChildComponent (kb);
  47816. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47817. }
  47818. ~KeyMappingItemComponent()
  47819. {
  47820. deleteAllChildren();
  47821. }
  47822. void paint (Graphics& g)
  47823. {
  47824. g.setFont (getHeight() * 0.7f);
  47825. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47826. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47827. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47828. Justification::centredLeft, true);
  47829. }
  47830. void resized()
  47831. {
  47832. int x = getWidth() - 4;
  47833. for (int i = getNumChildComponents(); --i >= 0;)
  47834. {
  47835. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47836. kb->fitToContent (getHeight() - 2);
  47837. kb->setTopRightPosition (x, 1);
  47838. x -= kb->getWidth() + 5;
  47839. }
  47840. }
  47841. juce_UseDebuggingNewOperator
  47842. private:
  47843. KeyMappingEditorComponent* const owner;
  47844. const CommandID commandID;
  47845. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47846. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47847. };
  47848. class KeyMappingTreeViewItem : public TreeViewItem
  47849. {
  47850. public:
  47851. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47852. const CommandID commandID_)
  47853. : owner (owner_),
  47854. commandID (commandID_)
  47855. {
  47856. }
  47857. ~KeyMappingTreeViewItem()
  47858. {
  47859. }
  47860. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47861. bool mightContainSubItems() { return false; }
  47862. int getItemHeight() const { return 20; }
  47863. Component* createItemComponent()
  47864. {
  47865. return new KeyMappingItemComponent (owner, commandID);
  47866. }
  47867. juce_UseDebuggingNewOperator
  47868. private:
  47869. KeyMappingEditorComponent* const owner;
  47870. const CommandID commandID;
  47871. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47872. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47873. };
  47874. class KeyCategoryTreeViewItem : public TreeViewItem
  47875. {
  47876. public:
  47877. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47878. const String& name)
  47879. : owner (owner_),
  47880. categoryName (name)
  47881. {
  47882. }
  47883. ~KeyCategoryTreeViewItem()
  47884. {
  47885. }
  47886. const String getUniqueName() const { return categoryName + "_cat"; }
  47887. bool mightContainSubItems() { return true; }
  47888. int getItemHeight() const { return 28; }
  47889. void paintItem (Graphics& g, int width, int height)
  47890. {
  47891. g.setFont (height * 0.6f, Font::bold);
  47892. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47893. g.drawText (categoryName,
  47894. 2, 0, width - 2, height,
  47895. Justification::centredLeft, true);
  47896. }
  47897. void itemOpennessChanged (bool isNowOpen)
  47898. {
  47899. if (isNowOpen)
  47900. {
  47901. if (getNumSubItems() == 0)
  47902. {
  47903. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47904. for (int i = 0; i < commands.size(); ++i)
  47905. {
  47906. if (owner->shouldCommandBeIncluded (commands[i]))
  47907. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47908. }
  47909. }
  47910. }
  47911. else
  47912. {
  47913. clearSubItems();
  47914. }
  47915. }
  47916. juce_UseDebuggingNewOperator
  47917. private:
  47918. KeyMappingEditorComponent* owner;
  47919. String categoryName;
  47920. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47921. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47922. };
  47923. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47924. const bool showResetToDefaultButton)
  47925. : mappings (mappingManager)
  47926. {
  47927. jassert (mappingManager != 0); // can't be null!
  47928. mappingManager->addChangeListener (this);
  47929. setLinesDrawnForSubItems (false);
  47930. resetButton = 0;
  47931. if (showResetToDefaultButton)
  47932. {
  47933. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47934. resetButton->addButtonListener (this);
  47935. }
  47936. addAndMakeVisible (tree = new TreeView());
  47937. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47938. tree->setRootItemVisible (false);
  47939. tree->setDefaultOpenness (true);
  47940. tree->setRootItem (this);
  47941. }
  47942. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47943. {
  47944. mappings->removeChangeListener (this);
  47945. deleteAllChildren();
  47946. }
  47947. bool KeyMappingEditorComponent::mightContainSubItems()
  47948. {
  47949. return true;
  47950. }
  47951. const String KeyMappingEditorComponent::getUniqueName() const
  47952. {
  47953. return "keys";
  47954. }
  47955. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47956. const Colour& textColour)
  47957. {
  47958. setColour (backgroundColourId, mainBackground);
  47959. setColour (textColourId, textColour);
  47960. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47961. }
  47962. void KeyMappingEditorComponent::parentHierarchyChanged()
  47963. {
  47964. changeListenerCallback (0);
  47965. }
  47966. void KeyMappingEditorComponent::resized()
  47967. {
  47968. int h = getHeight();
  47969. if (resetButton != 0)
  47970. {
  47971. const int buttonHeight = 20;
  47972. h -= buttonHeight + 8;
  47973. int x = getWidth() - 8;
  47974. resetButton->changeWidthToFitText (buttonHeight);
  47975. resetButton->setTopRightPosition (x, h + 6);
  47976. }
  47977. tree->setBounds (0, 0, getWidth(), h);
  47978. }
  47979. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47980. {
  47981. if (button == resetButton)
  47982. {
  47983. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47984. TRANS("Reset to defaults"),
  47985. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47986. TRANS("Reset")))
  47987. {
  47988. mappings->resetToDefaultMappings();
  47989. }
  47990. }
  47991. }
  47992. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47993. {
  47994. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47995. clearSubItems();
  47996. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47997. for (int i = 0; i < categories.size(); ++i)
  47998. {
  47999. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48000. int count = 0;
  48001. for (int j = 0; j < commands.size(); ++j)
  48002. if (shouldCommandBeIncluded (commands[j]))
  48003. ++count;
  48004. if (count > 0)
  48005. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48006. }
  48007. if (oldOpenness != 0)
  48008. tree->restoreOpennessState (*oldOpenness);
  48009. }
  48010. class KeyEntryWindow : public AlertWindow
  48011. {
  48012. public:
  48013. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48014. : AlertWindow (TRANS("New key-mapping"),
  48015. TRANS("Please press a key combination now..."),
  48016. AlertWindow::NoIcon),
  48017. owner (owner_)
  48018. {
  48019. addButton (TRANS("ok"), 1);
  48020. addButton (TRANS("cancel"), 0);
  48021. // (avoid return + escape keys getting processed by the buttons..)
  48022. for (int i = getNumChildComponents(); --i >= 0;)
  48023. getChildComponent (i)->setWantsKeyboardFocus (false);
  48024. setWantsKeyboardFocus (true);
  48025. grabKeyboardFocus();
  48026. }
  48027. ~KeyEntryWindow()
  48028. {
  48029. }
  48030. bool keyPressed (const KeyPress& key)
  48031. {
  48032. lastPress = key;
  48033. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48034. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48035. if (previousCommand != 0)
  48036. {
  48037. message << "\n\n"
  48038. << TRANS("(Currently assigned to \"")
  48039. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48040. << "\")";
  48041. }
  48042. setMessage (message);
  48043. return true;
  48044. }
  48045. bool keyStateChanged (bool)
  48046. {
  48047. return true;
  48048. }
  48049. KeyPress lastPress;
  48050. juce_UseDebuggingNewOperator
  48051. private:
  48052. KeyMappingEditorComponent* owner;
  48053. KeyEntryWindow (const KeyEntryWindow&);
  48054. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48055. };
  48056. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48057. {
  48058. KeyEntryWindow entryWindow (this);
  48059. if (entryWindow.runModalLoop() != 0)
  48060. {
  48061. entryWindow.setVisible (false);
  48062. if (entryWindow.lastPress.isValid())
  48063. {
  48064. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48065. if (previousCommand != 0)
  48066. {
  48067. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48068. TRANS("Change key-mapping"),
  48069. TRANS("This key is already assigned to the command \"")
  48070. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48071. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48072. TRANS("re-assign"),
  48073. TRANS("cancel")))
  48074. {
  48075. return;
  48076. }
  48077. }
  48078. mappings->removeKeyPress (entryWindow.lastPress);
  48079. if (index >= 0)
  48080. mappings->removeKeyPress (commandID, index);
  48081. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48082. }
  48083. }
  48084. }
  48085. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48086. {
  48087. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48088. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48089. }
  48090. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48091. {
  48092. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48093. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48094. }
  48095. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48096. {
  48097. return key.getTextDescription();
  48098. }
  48099. END_JUCE_NAMESPACE
  48100. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48101. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48102. BEGIN_JUCE_NAMESPACE
  48103. KeyPress::KeyPress() throw()
  48104. : keyCode (0),
  48105. mods (0),
  48106. textCharacter (0)
  48107. {
  48108. }
  48109. KeyPress::KeyPress (const int keyCode_,
  48110. const ModifierKeys& mods_,
  48111. const juce_wchar textCharacter_) throw()
  48112. : keyCode (keyCode_),
  48113. mods (mods_),
  48114. textCharacter (textCharacter_)
  48115. {
  48116. }
  48117. KeyPress::KeyPress (const int keyCode_) throw()
  48118. : keyCode (keyCode_),
  48119. textCharacter (0)
  48120. {
  48121. }
  48122. KeyPress::KeyPress (const KeyPress& other) throw()
  48123. : keyCode (other.keyCode),
  48124. mods (other.mods),
  48125. textCharacter (other.textCharacter)
  48126. {
  48127. }
  48128. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48129. {
  48130. keyCode = other.keyCode;
  48131. mods = other.mods;
  48132. textCharacter = other.textCharacter;
  48133. return *this;
  48134. }
  48135. bool KeyPress::operator== (const KeyPress& other) const throw()
  48136. {
  48137. return mods.getRawFlags() == other.mods.getRawFlags()
  48138. && (textCharacter == other.textCharacter
  48139. || textCharacter == 0
  48140. || other.textCharacter == 0)
  48141. && (keyCode == other.keyCode
  48142. || (keyCode < 256
  48143. && other.keyCode < 256
  48144. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48145. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48146. }
  48147. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48148. {
  48149. return ! operator== (other);
  48150. }
  48151. bool KeyPress::isCurrentlyDown() const
  48152. {
  48153. return isKeyCurrentlyDown (keyCode)
  48154. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48155. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48156. }
  48157. namespace KeyPressHelpers
  48158. {
  48159. struct KeyNameAndCode
  48160. {
  48161. const char* name;
  48162. int code;
  48163. };
  48164. static const KeyNameAndCode translations[] =
  48165. {
  48166. { "spacebar", KeyPress::spaceKey },
  48167. { "return", KeyPress::returnKey },
  48168. { "escape", KeyPress::escapeKey },
  48169. { "backspace", KeyPress::backspaceKey },
  48170. { "cursor left", KeyPress::leftKey },
  48171. { "cursor right", KeyPress::rightKey },
  48172. { "cursor up", KeyPress::upKey },
  48173. { "cursor down", KeyPress::downKey },
  48174. { "page up", KeyPress::pageUpKey },
  48175. { "page down", KeyPress::pageDownKey },
  48176. { "home", KeyPress::homeKey },
  48177. { "end", KeyPress::endKey },
  48178. { "delete", KeyPress::deleteKey },
  48179. { "insert", KeyPress::insertKey },
  48180. { "tab", KeyPress::tabKey },
  48181. { "play", KeyPress::playKey },
  48182. { "stop", KeyPress::stopKey },
  48183. { "fast forward", KeyPress::fastForwardKey },
  48184. { "rewind", KeyPress::rewindKey }
  48185. };
  48186. static const String numberPadPrefix() { return "numpad "; }
  48187. }
  48188. const KeyPress KeyPress::createFromDescription (const String& desc)
  48189. {
  48190. int modifiers = 0;
  48191. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48192. || desc.containsWholeWordIgnoreCase ("control")
  48193. || desc.containsWholeWordIgnoreCase ("ctl"))
  48194. modifiers |= ModifierKeys::ctrlModifier;
  48195. if (desc.containsWholeWordIgnoreCase ("shift")
  48196. || desc.containsWholeWordIgnoreCase ("shft"))
  48197. modifiers |= ModifierKeys::shiftModifier;
  48198. if (desc.containsWholeWordIgnoreCase ("alt")
  48199. || desc.containsWholeWordIgnoreCase ("option"))
  48200. modifiers |= ModifierKeys::altModifier;
  48201. if (desc.containsWholeWordIgnoreCase ("command")
  48202. || desc.containsWholeWordIgnoreCase ("cmd"))
  48203. modifiers |= ModifierKeys::commandModifier;
  48204. int key = 0;
  48205. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48206. {
  48207. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48208. {
  48209. key = KeyPressHelpers::translations[i].code;
  48210. break;
  48211. }
  48212. }
  48213. if (key == 0)
  48214. {
  48215. // see if it's a numpad key..
  48216. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48217. {
  48218. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48219. if (lastChar >= '0' && lastChar <= '9')
  48220. key = numberPad0 + lastChar - '0';
  48221. else if (lastChar == '+')
  48222. key = numberPadAdd;
  48223. else if (lastChar == '-')
  48224. key = numberPadSubtract;
  48225. else if (lastChar == '*')
  48226. key = numberPadMultiply;
  48227. else if (lastChar == '/')
  48228. key = numberPadDivide;
  48229. else if (lastChar == '.')
  48230. key = numberPadDecimalPoint;
  48231. else if (lastChar == '=')
  48232. key = numberPadEquals;
  48233. else if (desc.endsWith ("separator"))
  48234. key = numberPadSeparator;
  48235. else if (desc.endsWith ("delete"))
  48236. key = numberPadDelete;
  48237. }
  48238. if (key == 0)
  48239. {
  48240. // see if it's a function key..
  48241. for (int i = 1; i <= 12; ++i)
  48242. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48243. key = F1Key + i - 1;
  48244. if (key == 0)
  48245. {
  48246. // give up and use the hex code..
  48247. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48248. .toLowerCase()
  48249. .retainCharacters ("0123456789abcdef")
  48250. .getHexValue32();
  48251. if (hexCode > 0)
  48252. key = hexCode;
  48253. else
  48254. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48255. }
  48256. }
  48257. }
  48258. return KeyPress (key, ModifierKeys (modifiers), 0);
  48259. }
  48260. const String KeyPress::getTextDescription() const
  48261. {
  48262. String desc;
  48263. if (keyCode > 0)
  48264. {
  48265. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48266. // want to store it as being a slash, not shift+whatever.
  48267. if (textCharacter == '/')
  48268. return "/";
  48269. if (mods.isCtrlDown())
  48270. desc << "ctrl + ";
  48271. if (mods.isShiftDown())
  48272. desc << "shift + ";
  48273. #if JUCE_MAC
  48274. // only do this on the mac, because on Windows ctrl and command are the same,
  48275. // and this would get confusing
  48276. if (mods.isCommandDown())
  48277. desc << "command + ";
  48278. if (mods.isAltDown())
  48279. desc << "option + ";
  48280. #else
  48281. if (mods.isAltDown())
  48282. desc << "alt + ";
  48283. #endif
  48284. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48285. if (keyCode == KeyPressHelpers::translations[i].code)
  48286. return desc + KeyPressHelpers::translations[i].name;
  48287. if (keyCode >= F1Key && keyCode <= F16Key)
  48288. desc << 'F' << (1 + keyCode - F1Key);
  48289. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48290. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48291. else if (keyCode >= 33 && keyCode < 176)
  48292. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48293. else if (keyCode == numberPadAdd)
  48294. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48295. else if (keyCode == numberPadSubtract)
  48296. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48297. else if (keyCode == numberPadMultiply)
  48298. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48299. else if (keyCode == numberPadDivide)
  48300. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48301. else if (keyCode == numberPadSeparator)
  48302. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48303. else if (keyCode == numberPadDecimalPoint)
  48304. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48305. else if (keyCode == numberPadDelete)
  48306. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48307. else
  48308. desc << '#' << String::toHexString (keyCode);
  48309. }
  48310. return desc;
  48311. }
  48312. END_JUCE_NAMESPACE
  48313. /*** End of inlined file: juce_KeyPress.cpp ***/
  48314. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48315. BEGIN_JUCE_NAMESPACE
  48316. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48317. : commandManager (commandManager_)
  48318. {
  48319. // A manager is needed to get the descriptions of commands, and will be called when
  48320. // a command is invoked. So you can't leave this null..
  48321. jassert (commandManager_ != 0);
  48322. Desktop::getInstance().addFocusChangeListener (this);
  48323. }
  48324. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48325. : commandManager (other.commandManager)
  48326. {
  48327. Desktop::getInstance().addFocusChangeListener (this);
  48328. }
  48329. KeyPressMappingSet::~KeyPressMappingSet()
  48330. {
  48331. Desktop::getInstance().removeFocusChangeListener (this);
  48332. }
  48333. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48334. {
  48335. for (int i = 0; i < mappings.size(); ++i)
  48336. if (mappings.getUnchecked(i)->commandID == commandID)
  48337. return mappings.getUnchecked (i)->keypresses;
  48338. return Array <KeyPress> ();
  48339. }
  48340. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48341. const KeyPress& newKeyPress,
  48342. int insertIndex)
  48343. {
  48344. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48345. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48346. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48347. && ! newKeyPress.getModifiers().isShiftDown()));
  48348. if (findCommandForKeyPress (newKeyPress) != commandID)
  48349. {
  48350. removeKeyPress (newKeyPress);
  48351. if (newKeyPress.isValid())
  48352. {
  48353. for (int i = mappings.size(); --i >= 0;)
  48354. {
  48355. if (mappings.getUnchecked(i)->commandID == commandID)
  48356. {
  48357. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48358. sendChangeMessage (this);
  48359. return;
  48360. }
  48361. }
  48362. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48363. if (ci != 0)
  48364. {
  48365. CommandMapping* const cm = new CommandMapping();
  48366. cm->commandID = commandID;
  48367. cm->keypresses.add (newKeyPress);
  48368. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48369. mappings.add (cm);
  48370. sendChangeMessage (this);
  48371. }
  48372. }
  48373. }
  48374. }
  48375. void KeyPressMappingSet::resetToDefaultMappings()
  48376. {
  48377. mappings.clear();
  48378. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48379. {
  48380. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48381. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48382. {
  48383. addKeyPress (ci->commandID,
  48384. ci->defaultKeypresses.getReference (j));
  48385. }
  48386. }
  48387. sendChangeMessage (this);
  48388. }
  48389. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48390. {
  48391. clearAllKeyPresses (commandID);
  48392. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48393. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48394. {
  48395. addKeyPress (ci->commandID,
  48396. ci->defaultKeypresses.getReference (j));
  48397. }
  48398. }
  48399. void KeyPressMappingSet::clearAllKeyPresses()
  48400. {
  48401. if (mappings.size() > 0)
  48402. {
  48403. sendChangeMessage (this);
  48404. mappings.clear();
  48405. }
  48406. }
  48407. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48408. {
  48409. for (int i = mappings.size(); --i >= 0;)
  48410. {
  48411. if (mappings.getUnchecked(i)->commandID == commandID)
  48412. {
  48413. mappings.remove (i);
  48414. sendChangeMessage (this);
  48415. }
  48416. }
  48417. }
  48418. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48419. {
  48420. if (keypress.isValid())
  48421. {
  48422. for (int i = mappings.size(); --i >= 0;)
  48423. {
  48424. CommandMapping* const cm = mappings.getUnchecked(i);
  48425. for (int j = cm->keypresses.size(); --j >= 0;)
  48426. {
  48427. if (keypress == cm->keypresses [j])
  48428. {
  48429. cm->keypresses.remove (j);
  48430. sendChangeMessage (this);
  48431. }
  48432. }
  48433. }
  48434. }
  48435. }
  48436. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48437. {
  48438. for (int i = mappings.size(); --i >= 0;)
  48439. {
  48440. if (mappings.getUnchecked(i)->commandID == commandID)
  48441. {
  48442. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48443. sendChangeMessage (this);
  48444. break;
  48445. }
  48446. }
  48447. }
  48448. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48449. {
  48450. for (int i = 0; i < mappings.size(); ++i)
  48451. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48452. return mappings.getUnchecked(i)->commandID;
  48453. return 0;
  48454. }
  48455. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48456. {
  48457. for (int i = mappings.size(); --i >= 0;)
  48458. if (mappings.getUnchecked(i)->commandID == commandID)
  48459. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48460. return false;
  48461. }
  48462. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48463. const KeyPress& key,
  48464. const bool isKeyDown,
  48465. const int millisecsSinceKeyPressed,
  48466. Component* const originatingComponent) const
  48467. {
  48468. ApplicationCommandTarget::InvocationInfo info (commandID);
  48469. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48470. info.isKeyDown = isKeyDown;
  48471. info.keyPress = key;
  48472. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48473. info.originatingComponent = originatingComponent;
  48474. commandManager->invoke (info, false);
  48475. }
  48476. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48477. {
  48478. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48479. {
  48480. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48481. {
  48482. // if the XML was created as a set of differences from the default mappings,
  48483. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48484. resetToDefaultMappings();
  48485. }
  48486. else
  48487. {
  48488. // if the XML was created calling createXml (false), then we need to clear all
  48489. // the keys and treat the xml as describing the entire set of mappings.
  48490. clearAllKeyPresses();
  48491. }
  48492. forEachXmlChildElement (xmlVersion, map)
  48493. {
  48494. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48495. if (commandId != 0)
  48496. {
  48497. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48498. if (map->hasTagName ("MAPPING"))
  48499. {
  48500. addKeyPress (commandId, key);
  48501. }
  48502. else if (map->hasTagName ("UNMAPPING"))
  48503. {
  48504. if (containsMapping (commandId, key))
  48505. removeKeyPress (key);
  48506. }
  48507. }
  48508. }
  48509. return true;
  48510. }
  48511. return false;
  48512. }
  48513. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48514. {
  48515. ScopedPointer <KeyPressMappingSet> defaultSet;
  48516. if (saveDifferencesFromDefaultSet)
  48517. {
  48518. defaultSet = new KeyPressMappingSet (commandManager);
  48519. defaultSet->resetToDefaultMappings();
  48520. }
  48521. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48522. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48523. int i;
  48524. for (i = 0; i < mappings.size(); ++i)
  48525. {
  48526. const CommandMapping* const cm = mappings.getUnchecked(i);
  48527. for (int j = 0; j < cm->keypresses.size(); ++j)
  48528. {
  48529. if (defaultSet == 0
  48530. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48531. {
  48532. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48533. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48534. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48535. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48536. }
  48537. }
  48538. }
  48539. if (defaultSet != 0)
  48540. {
  48541. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48542. {
  48543. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48544. for (int j = 0; j < cm->keypresses.size(); ++j)
  48545. {
  48546. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48547. {
  48548. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48549. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48550. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48551. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48552. }
  48553. }
  48554. }
  48555. }
  48556. return doc;
  48557. }
  48558. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48559. Component* originatingComponent)
  48560. {
  48561. bool used = false;
  48562. const CommandID commandID = findCommandForKeyPress (key);
  48563. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48564. if (ci != 0
  48565. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48566. {
  48567. ApplicationCommandInfo info (0);
  48568. if (commandManager->getTargetForCommand (commandID, info) != 0
  48569. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48570. {
  48571. invokeCommand (commandID, key, true, 0, originatingComponent);
  48572. used = true;
  48573. }
  48574. else
  48575. {
  48576. if (originatingComponent != 0)
  48577. originatingComponent->getLookAndFeel().playAlertSound();
  48578. }
  48579. }
  48580. return used;
  48581. }
  48582. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48583. {
  48584. bool used = false;
  48585. const uint32 now = Time::getMillisecondCounter();
  48586. for (int i = mappings.size(); --i >= 0;)
  48587. {
  48588. CommandMapping* const cm = mappings.getUnchecked(i);
  48589. if (cm->wantsKeyUpDownCallbacks)
  48590. {
  48591. for (int j = cm->keypresses.size(); --j >= 0;)
  48592. {
  48593. const KeyPress key (cm->keypresses.getReference (j));
  48594. const bool isDown = key.isCurrentlyDown();
  48595. int keyPressEntryIndex = 0;
  48596. bool wasDown = false;
  48597. for (int k = keysDown.size(); --k >= 0;)
  48598. {
  48599. if (key == keysDown.getUnchecked(k)->key)
  48600. {
  48601. keyPressEntryIndex = k;
  48602. wasDown = true;
  48603. used = true;
  48604. break;
  48605. }
  48606. }
  48607. if (isDown != wasDown)
  48608. {
  48609. int millisecs = 0;
  48610. if (isDown)
  48611. {
  48612. KeyPressTime* const k = new KeyPressTime();
  48613. k->key = key;
  48614. k->timeWhenPressed = now;
  48615. keysDown.add (k);
  48616. }
  48617. else
  48618. {
  48619. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48620. if (now > pressTime)
  48621. millisecs = now - pressTime;
  48622. keysDown.remove (keyPressEntryIndex);
  48623. }
  48624. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48625. used = true;
  48626. }
  48627. }
  48628. }
  48629. }
  48630. return used;
  48631. }
  48632. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48633. {
  48634. if (focusedComponent != 0)
  48635. focusedComponent->keyStateChanged (false);
  48636. }
  48637. END_JUCE_NAMESPACE
  48638. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48639. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48640. BEGIN_JUCE_NAMESPACE
  48641. ModifierKeys::ModifierKeys (const int flags_) throw()
  48642. : flags (flags_)
  48643. {
  48644. }
  48645. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48646. : flags (other.flags)
  48647. {
  48648. }
  48649. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48650. {
  48651. flags = other.flags;
  48652. return *this;
  48653. }
  48654. ModifierKeys ModifierKeys::currentModifiers;
  48655. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48656. {
  48657. return currentModifiers;
  48658. }
  48659. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48660. {
  48661. int num = 0;
  48662. if (isLeftButtonDown()) ++num;
  48663. if (isRightButtonDown()) ++num;
  48664. if (isMiddleButtonDown()) ++num;
  48665. return num;
  48666. }
  48667. END_JUCE_NAMESPACE
  48668. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48669. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48670. BEGIN_JUCE_NAMESPACE
  48671. class ComponentAnimator::AnimationTask
  48672. {
  48673. public:
  48674. AnimationTask (Component* const comp)
  48675. : component (comp)
  48676. {
  48677. }
  48678. Component::SafePointer<Component> component;
  48679. Rectangle<int> destination;
  48680. int msElapsed, msTotal;
  48681. double startSpeed, midSpeed, endSpeed, lastProgress;
  48682. double left, top, right, bottom;
  48683. bool useTimeslice (const int elapsed)
  48684. {
  48685. if (component == 0)
  48686. return false;
  48687. msElapsed += elapsed;
  48688. double newProgress = msElapsed / (double) msTotal;
  48689. if (newProgress >= 0 && newProgress < 1.0)
  48690. {
  48691. newProgress = timeToDistance (newProgress);
  48692. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48693. jassert (newProgress >= lastProgress);
  48694. lastProgress = newProgress;
  48695. left += (destination.getX() - left) * delta;
  48696. top += (destination.getY() - top) * delta;
  48697. right += (destination.getRight() - right) * delta;
  48698. bottom += (destination.getBottom() - bottom) * delta;
  48699. if (delta < 1.0)
  48700. {
  48701. const Rectangle<int> newBounds (roundToInt (left),
  48702. roundToInt (top),
  48703. roundToInt (right - left),
  48704. roundToInt (bottom - top));
  48705. if (newBounds != destination)
  48706. {
  48707. component->setBounds (newBounds);
  48708. return true;
  48709. }
  48710. }
  48711. }
  48712. component->setBounds (destination);
  48713. return false;
  48714. }
  48715. void moveToFinalDestination()
  48716. {
  48717. if (component != 0)
  48718. component->setBounds (destination);
  48719. }
  48720. private:
  48721. inline double timeToDistance (const double time) const
  48722. {
  48723. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48724. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48725. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48726. }
  48727. };
  48728. ComponentAnimator::ComponentAnimator()
  48729. : lastTime (0)
  48730. {
  48731. }
  48732. ComponentAnimator::~ComponentAnimator()
  48733. {
  48734. cancelAllAnimations (false);
  48735. jassert (tasks.size() == 0);
  48736. }
  48737. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48738. {
  48739. for (int i = tasks.size(); --i >= 0;)
  48740. if (component == tasks.getUnchecked(i)->component.getComponent())
  48741. return tasks.getUnchecked(i);
  48742. return 0;
  48743. }
  48744. void ComponentAnimator::animateComponent (Component* const component,
  48745. const Rectangle<int>& finalPosition,
  48746. const int millisecondsToSpendMoving,
  48747. const double startSpeed,
  48748. const double endSpeed)
  48749. {
  48750. if (component != 0)
  48751. {
  48752. AnimationTask* at = findTaskFor (component);
  48753. if (at == 0)
  48754. {
  48755. at = new AnimationTask (component);
  48756. tasks.add (at);
  48757. sendChangeMessage (this);
  48758. }
  48759. at->msElapsed = 0;
  48760. at->lastProgress = 0;
  48761. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48762. at->destination = finalPosition;
  48763. // the speeds must be 0 or greater!
  48764. jassert (startSpeed >= 0 && endSpeed >= 0)
  48765. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48766. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48767. at->midSpeed = invTotalDistance;
  48768. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48769. at->left = component->getX();
  48770. at->top = component->getY();
  48771. at->right = component->getRight();
  48772. at->bottom = component->getBottom();
  48773. if (! isTimerRunning())
  48774. {
  48775. lastTime = Time::getMillisecondCounter();
  48776. startTimer (1000 / 50);
  48777. }
  48778. }
  48779. }
  48780. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48781. {
  48782. for (int i = tasks.size(); --i >= 0;)
  48783. {
  48784. AnimationTask* const at = tasks.getUnchecked(i);
  48785. if (moveComponentsToTheirFinalPositions)
  48786. at->moveToFinalDestination();
  48787. delete at;
  48788. tasks.remove (i);
  48789. sendChangeMessage (this);
  48790. }
  48791. }
  48792. void ComponentAnimator::cancelAnimation (Component* const component,
  48793. const bool moveComponentToItsFinalPosition)
  48794. {
  48795. AnimationTask* const at = findTaskFor (component);
  48796. if (at != 0)
  48797. {
  48798. if (moveComponentToItsFinalPosition)
  48799. at->moveToFinalDestination();
  48800. tasks.removeValue (at);
  48801. delete at;
  48802. sendChangeMessage (this);
  48803. }
  48804. }
  48805. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48806. {
  48807. AnimationTask* const at = findTaskFor (component);
  48808. if (at != 0)
  48809. return at->destination;
  48810. else if (component != 0)
  48811. return component->getBounds();
  48812. return Rectangle<int>();
  48813. }
  48814. bool ComponentAnimator::isAnimating (Component* component) const
  48815. {
  48816. return findTaskFor (component) != 0;
  48817. }
  48818. void ComponentAnimator::timerCallback()
  48819. {
  48820. const uint32 timeNow = Time::getMillisecondCounter();
  48821. if (lastTime == 0 || lastTime == timeNow)
  48822. lastTime = timeNow;
  48823. const int elapsed = timeNow - lastTime;
  48824. for (int i = tasks.size(); --i >= 0;)
  48825. {
  48826. AnimationTask* const at = tasks.getUnchecked(i);
  48827. if (! at->useTimeslice (elapsed))
  48828. {
  48829. tasks.remove (i);
  48830. delete at;
  48831. sendChangeMessage (this);
  48832. }
  48833. }
  48834. lastTime = timeNow;
  48835. if (tasks.size() == 0)
  48836. stopTimer();
  48837. }
  48838. END_JUCE_NAMESPACE
  48839. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48840. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48841. BEGIN_JUCE_NAMESPACE
  48842. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48843. : minW (0),
  48844. maxW (0x3fffffff),
  48845. minH (0),
  48846. maxH (0x3fffffff),
  48847. minOffTop (0),
  48848. minOffLeft (0),
  48849. minOffBottom (0),
  48850. minOffRight (0),
  48851. aspectRatio (0.0)
  48852. {
  48853. }
  48854. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48855. {
  48856. }
  48857. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48858. {
  48859. minW = minimumWidth;
  48860. }
  48861. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48862. {
  48863. maxW = maximumWidth;
  48864. }
  48865. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48866. {
  48867. minH = minimumHeight;
  48868. }
  48869. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48870. {
  48871. maxH = maximumHeight;
  48872. }
  48873. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48874. {
  48875. jassert (maxW >= minimumWidth);
  48876. jassert (maxH >= minimumHeight);
  48877. jassert (minimumWidth > 0 && minimumHeight > 0);
  48878. minW = minimumWidth;
  48879. minH = minimumHeight;
  48880. if (minW > maxW)
  48881. maxW = minW;
  48882. if (minH > maxH)
  48883. maxH = minH;
  48884. }
  48885. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48886. {
  48887. jassert (maximumWidth >= minW);
  48888. jassert (maximumHeight >= minH);
  48889. jassert (maximumWidth > 0 && maximumHeight > 0);
  48890. maxW = jmax (minW, maximumWidth);
  48891. maxH = jmax (minH, maximumHeight);
  48892. }
  48893. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48894. const int minimumHeight,
  48895. const int maximumWidth,
  48896. const int maximumHeight) throw()
  48897. {
  48898. jassert (maximumWidth >= minimumWidth);
  48899. jassert (maximumHeight >= minimumHeight);
  48900. jassert (maximumWidth > 0 && maximumHeight > 0);
  48901. jassert (minimumWidth > 0 && minimumHeight > 0);
  48902. minW = jmax (0, minimumWidth);
  48903. minH = jmax (0, minimumHeight);
  48904. maxW = jmax (minW, maximumWidth);
  48905. maxH = jmax (minH, maximumHeight);
  48906. }
  48907. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48908. const int minimumWhenOffTheLeft,
  48909. const int minimumWhenOffTheBottom,
  48910. const int minimumWhenOffTheRight) throw()
  48911. {
  48912. minOffTop = minimumWhenOffTheTop;
  48913. minOffLeft = minimumWhenOffTheLeft;
  48914. minOffBottom = minimumWhenOffTheBottom;
  48915. minOffRight = minimumWhenOffTheRight;
  48916. }
  48917. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48918. {
  48919. aspectRatio = jmax (0.0, widthOverHeight);
  48920. }
  48921. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48922. {
  48923. return aspectRatio;
  48924. }
  48925. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48926. const Rectangle<int>& targetBounds,
  48927. const bool isStretchingTop,
  48928. const bool isStretchingLeft,
  48929. const bool isStretchingBottom,
  48930. const bool isStretchingRight)
  48931. {
  48932. jassert (component != 0);
  48933. Rectangle<int> limits, bounds (targetBounds);
  48934. BorderSize border;
  48935. Component* const parent = component->getParentComponent();
  48936. if (parent == 0)
  48937. {
  48938. ComponentPeer* peer = component->getPeer();
  48939. if (peer != 0)
  48940. border = peer->getFrameSize();
  48941. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48942. }
  48943. else
  48944. {
  48945. limits.setSize (parent->getWidth(), parent->getHeight());
  48946. }
  48947. border.addTo (bounds);
  48948. checkBounds (bounds,
  48949. border.addedTo (component->getBounds()), limits,
  48950. isStretchingTop, isStretchingLeft,
  48951. isStretchingBottom, isStretchingRight);
  48952. border.subtractFrom (bounds);
  48953. applyBoundsToComponent (component, bounds);
  48954. }
  48955. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48956. {
  48957. setBoundsForComponent (component, component->getBounds(),
  48958. false, false, false, false);
  48959. }
  48960. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48961. const Rectangle<int>& bounds)
  48962. {
  48963. component->setBounds (bounds);
  48964. }
  48965. void ComponentBoundsConstrainer::resizeStart()
  48966. {
  48967. }
  48968. void ComponentBoundsConstrainer::resizeEnd()
  48969. {
  48970. }
  48971. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48972. const Rectangle<int>& old,
  48973. const Rectangle<int>& limits,
  48974. const bool isStretchingTop,
  48975. const bool isStretchingLeft,
  48976. const bool isStretchingBottom,
  48977. const bool isStretchingRight)
  48978. {
  48979. int x = bounds.getX();
  48980. int y = bounds.getY();
  48981. int w = bounds.getWidth();
  48982. int h = bounds.getHeight();
  48983. // constrain the size if it's being stretched..
  48984. if (isStretchingLeft)
  48985. {
  48986. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48987. w = old.getRight() - x;
  48988. }
  48989. if (isStretchingRight)
  48990. {
  48991. w = jlimit (minW, maxW, w);
  48992. }
  48993. if (isStretchingTop)
  48994. {
  48995. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48996. h = old.getBottom() - y;
  48997. }
  48998. if (isStretchingBottom)
  48999. {
  49000. h = jlimit (minH, maxH, h);
  49001. }
  49002. // constrain the aspect ratio if one has been specified..
  49003. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49004. {
  49005. bool adjustWidth;
  49006. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49007. {
  49008. adjustWidth = true;
  49009. }
  49010. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49011. {
  49012. adjustWidth = false;
  49013. }
  49014. else
  49015. {
  49016. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49017. const double newRatio = std::abs (w / (double) h);
  49018. adjustWidth = (oldRatio > newRatio);
  49019. }
  49020. if (adjustWidth)
  49021. {
  49022. w = roundToInt (h * aspectRatio);
  49023. if (w > maxW || w < minW)
  49024. {
  49025. w = jlimit (minW, maxW, w);
  49026. h = roundToInt (w / aspectRatio);
  49027. }
  49028. }
  49029. else
  49030. {
  49031. h = roundToInt (w / aspectRatio);
  49032. if (h > maxH || h < minH)
  49033. {
  49034. h = jlimit (minH, maxH, h);
  49035. w = roundToInt (h * aspectRatio);
  49036. }
  49037. }
  49038. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49039. {
  49040. x = old.getX() + (old.getWidth() - w) / 2;
  49041. }
  49042. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49043. {
  49044. y = old.getY() + (old.getHeight() - h) / 2;
  49045. }
  49046. else
  49047. {
  49048. if (isStretchingLeft)
  49049. x = old.getRight() - w;
  49050. if (isStretchingTop)
  49051. y = old.getBottom() - h;
  49052. }
  49053. }
  49054. // ...and constrain the position if limits have been set for that.
  49055. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49056. {
  49057. if (minOffTop > 0)
  49058. {
  49059. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49060. if (y < limit)
  49061. {
  49062. if (isStretchingTop)
  49063. h -= (limit - y);
  49064. y = limit;
  49065. }
  49066. }
  49067. if (minOffLeft > 0)
  49068. {
  49069. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49070. if (x < limit)
  49071. {
  49072. if (isStretchingLeft)
  49073. w -= (limit - x);
  49074. x = limit;
  49075. }
  49076. }
  49077. if (minOffBottom > 0)
  49078. {
  49079. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49080. if (y > limit)
  49081. {
  49082. if (isStretchingBottom)
  49083. h += (limit - y);
  49084. else
  49085. y = limit;
  49086. }
  49087. }
  49088. if (minOffRight > 0)
  49089. {
  49090. const int limit = limits.getRight() - jmin (minOffRight, w);
  49091. if (x > limit)
  49092. {
  49093. if (isStretchingRight)
  49094. w += (limit - x);
  49095. else
  49096. x = limit;
  49097. }
  49098. }
  49099. }
  49100. jassert (w >= 0 && h >= 0);
  49101. bounds = Rectangle<int> (x, y, w, h);
  49102. }
  49103. END_JUCE_NAMESPACE
  49104. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49105. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49106. BEGIN_JUCE_NAMESPACE
  49107. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49108. : component (component_),
  49109. lastPeer (0),
  49110. reentrant (false)
  49111. {
  49112. jassert (component != 0); // can't use this with a null pointer..
  49113. component->addComponentListener (this);
  49114. registerWithParentComps();
  49115. }
  49116. ComponentMovementWatcher::~ComponentMovementWatcher()
  49117. {
  49118. component->removeComponentListener (this);
  49119. unregister();
  49120. }
  49121. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49122. {
  49123. // agh! don't delete the target component without deleting this object first!
  49124. jassert (component != 0);
  49125. if (! reentrant)
  49126. {
  49127. reentrant = true;
  49128. ComponentPeer* const peer = component->getPeer();
  49129. if (peer != lastPeer)
  49130. {
  49131. componentPeerChanged();
  49132. if (component == 0)
  49133. return;
  49134. lastPeer = peer;
  49135. }
  49136. unregister();
  49137. registerWithParentComps();
  49138. reentrant = false;
  49139. componentMovedOrResized (*component, true, true);
  49140. }
  49141. }
  49142. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49143. {
  49144. // agh! don't delete the target component without deleting this object first!
  49145. jassert (component != 0);
  49146. if (wasMoved)
  49147. {
  49148. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49149. wasMoved = lastBounds.getPosition() != pos;
  49150. lastBounds.setPosition (pos);
  49151. }
  49152. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49153. lastBounds.setSize (component->getWidth(), component->getHeight());
  49154. if (wasMoved || wasResized)
  49155. componentMovedOrResized (wasMoved, wasResized);
  49156. }
  49157. void ComponentMovementWatcher::registerWithParentComps()
  49158. {
  49159. Component* p = component->getParentComponent();
  49160. while (p != 0)
  49161. {
  49162. p->addComponentListener (this);
  49163. registeredParentComps.add (p);
  49164. p = p->getParentComponent();
  49165. }
  49166. }
  49167. void ComponentMovementWatcher::unregister()
  49168. {
  49169. for (int i = registeredParentComps.size(); --i >= 0;)
  49170. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49171. registeredParentComps.clear();
  49172. }
  49173. END_JUCE_NAMESPACE
  49174. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49175. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49176. BEGIN_JUCE_NAMESPACE
  49177. GroupComponent::GroupComponent (const String& componentName,
  49178. const String& labelText)
  49179. : Component (componentName),
  49180. text (labelText),
  49181. justification (Justification::left)
  49182. {
  49183. setInterceptsMouseClicks (false, true);
  49184. }
  49185. GroupComponent::~GroupComponent()
  49186. {
  49187. }
  49188. void GroupComponent::setText (const String& newText)
  49189. {
  49190. if (text != newText)
  49191. {
  49192. text = newText;
  49193. repaint();
  49194. }
  49195. }
  49196. const String GroupComponent::getText() const
  49197. {
  49198. return text;
  49199. }
  49200. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49201. {
  49202. if (justification != newJustification)
  49203. {
  49204. justification = newJustification;
  49205. repaint();
  49206. }
  49207. }
  49208. void GroupComponent::paint (Graphics& g)
  49209. {
  49210. getLookAndFeel()
  49211. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49212. text, justification,
  49213. *this);
  49214. }
  49215. void GroupComponent::enablementChanged()
  49216. {
  49217. repaint();
  49218. }
  49219. void GroupComponent::colourChanged()
  49220. {
  49221. repaint();
  49222. }
  49223. END_JUCE_NAMESPACE
  49224. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49225. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49226. BEGIN_JUCE_NAMESPACE
  49227. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49228. : DocumentWindow (String::empty, backgroundColour,
  49229. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49230. {
  49231. }
  49232. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49233. {
  49234. }
  49235. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49236. {
  49237. MultiDocumentPanel* const owner = getOwner();
  49238. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49239. if (owner != 0)
  49240. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49241. }
  49242. void MultiDocumentPanelWindow::closeButtonPressed()
  49243. {
  49244. MultiDocumentPanel* const owner = getOwner();
  49245. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49246. if (owner != 0)
  49247. owner->closeDocument (getContentComponent(), true);
  49248. }
  49249. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49250. {
  49251. DocumentWindow::activeWindowStatusChanged();
  49252. updateOrder();
  49253. }
  49254. void MultiDocumentPanelWindow::broughtToFront()
  49255. {
  49256. DocumentWindow::broughtToFront();
  49257. updateOrder();
  49258. }
  49259. void MultiDocumentPanelWindow::updateOrder()
  49260. {
  49261. MultiDocumentPanel* const owner = getOwner();
  49262. if (owner != 0)
  49263. owner->updateOrder();
  49264. }
  49265. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49266. {
  49267. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49268. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49269. }
  49270. class MDITabbedComponentInternal : public TabbedComponent
  49271. {
  49272. public:
  49273. MDITabbedComponentInternal()
  49274. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49275. {
  49276. }
  49277. ~MDITabbedComponentInternal()
  49278. {
  49279. }
  49280. void currentTabChanged (int, const String&)
  49281. {
  49282. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49283. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49284. if (owner != 0)
  49285. owner->updateOrder();
  49286. }
  49287. };
  49288. MultiDocumentPanel::MultiDocumentPanel()
  49289. : mode (MaximisedWindowsWithTabs),
  49290. tabComponent (0),
  49291. backgroundColour (Colours::lightblue),
  49292. maximumNumDocuments (0),
  49293. numDocsBeforeTabsUsed (0)
  49294. {
  49295. setOpaque (true);
  49296. }
  49297. MultiDocumentPanel::~MultiDocumentPanel()
  49298. {
  49299. closeAllDocuments (false);
  49300. }
  49301. static bool shouldDeleteComp (Component* const c)
  49302. {
  49303. return c->getProperties() ["mdiDocumentDelete_"];
  49304. }
  49305. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49306. {
  49307. while (components.size() > 0)
  49308. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49309. return false;
  49310. return true;
  49311. }
  49312. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49313. {
  49314. return new MultiDocumentPanelWindow (backgroundColour);
  49315. }
  49316. void MultiDocumentPanel::addWindow (Component* component)
  49317. {
  49318. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49319. dw->setResizable (true, false);
  49320. dw->setContentComponent (component, false, true);
  49321. dw->setName (component->getName());
  49322. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49323. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49324. int x = 4;
  49325. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49326. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49327. x += 16;
  49328. dw->setTopLeftPosition (x, x);
  49329. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49330. if (pos.toString().isNotEmpty())
  49331. dw->restoreWindowStateFromString (pos.toString());
  49332. addAndMakeVisible (dw);
  49333. dw->toFront (true);
  49334. }
  49335. bool MultiDocumentPanel::addDocument (Component* const component,
  49336. const Colour& docColour,
  49337. const bool deleteWhenRemoved)
  49338. {
  49339. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49340. // with a frame-within-a-frame! Just pass in the bare content component.
  49341. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49342. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49343. return false;
  49344. components.add (component);
  49345. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49346. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49347. component->addComponentListener (this);
  49348. if (mode == FloatingWindows)
  49349. {
  49350. if (isFullscreenWhenOneDocument())
  49351. {
  49352. if (components.size() == 1)
  49353. {
  49354. addAndMakeVisible (component);
  49355. }
  49356. else
  49357. {
  49358. if (components.size() == 2)
  49359. addWindow (components.getFirst());
  49360. addWindow (component);
  49361. }
  49362. }
  49363. else
  49364. {
  49365. addWindow (component);
  49366. }
  49367. }
  49368. else
  49369. {
  49370. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49371. {
  49372. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49373. Array <Component*> temp (components);
  49374. for (int i = 0; i < temp.size(); ++i)
  49375. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49376. resized();
  49377. }
  49378. else
  49379. {
  49380. if (tabComponent != 0)
  49381. tabComponent->addTab (component->getName(), docColour, component, false);
  49382. else
  49383. addAndMakeVisible (component);
  49384. }
  49385. setActiveDocument (component);
  49386. }
  49387. resized();
  49388. activeDocumentChanged();
  49389. return true;
  49390. }
  49391. bool MultiDocumentPanel::closeDocument (Component* component,
  49392. const bool checkItsOkToCloseFirst)
  49393. {
  49394. if (components.contains (component))
  49395. {
  49396. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49397. return false;
  49398. component->removeComponentListener (this);
  49399. const bool shouldDelete = shouldDeleteComp (component);
  49400. component->getProperties().remove ("mdiDocumentDelete_");
  49401. component->getProperties().remove ("mdiDocumentBkg_");
  49402. if (mode == FloatingWindows)
  49403. {
  49404. for (int i = getNumChildComponents(); --i >= 0;)
  49405. {
  49406. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49407. if (dw != 0 && dw->getContentComponent() == component)
  49408. {
  49409. dw->setContentComponent (0, false);
  49410. delete dw;
  49411. break;
  49412. }
  49413. }
  49414. if (shouldDelete)
  49415. delete component;
  49416. components.removeValue (component);
  49417. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49418. {
  49419. for (int i = getNumChildComponents(); --i >= 0;)
  49420. {
  49421. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49422. if (dw != 0)
  49423. {
  49424. dw->setContentComponent (0, false);
  49425. delete dw;
  49426. }
  49427. }
  49428. addAndMakeVisible (components.getFirst());
  49429. }
  49430. }
  49431. else
  49432. {
  49433. jassert (components.indexOf (component) >= 0);
  49434. if (tabComponent != 0)
  49435. {
  49436. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49437. if (tabComponent->getTabContentComponent (i) == component)
  49438. tabComponent->removeTab (i);
  49439. }
  49440. else
  49441. {
  49442. removeChildComponent (component);
  49443. }
  49444. if (shouldDelete)
  49445. delete component;
  49446. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49447. deleteAndZero (tabComponent);
  49448. components.removeValue (component);
  49449. if (components.size() > 0 && tabComponent == 0)
  49450. addAndMakeVisible (components.getFirst());
  49451. }
  49452. resized();
  49453. activeDocumentChanged();
  49454. }
  49455. else
  49456. {
  49457. jassertfalse;
  49458. }
  49459. return true;
  49460. }
  49461. int MultiDocumentPanel::getNumDocuments() const throw()
  49462. {
  49463. return components.size();
  49464. }
  49465. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49466. {
  49467. return components [index];
  49468. }
  49469. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49470. {
  49471. if (mode == FloatingWindows)
  49472. {
  49473. for (int i = getNumChildComponents(); --i >= 0;)
  49474. {
  49475. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49476. if (dw != 0 && dw->isActiveWindow())
  49477. return dw->getContentComponent();
  49478. }
  49479. }
  49480. return components.getLast();
  49481. }
  49482. void MultiDocumentPanel::setActiveDocument (Component* component)
  49483. {
  49484. if (mode == FloatingWindows)
  49485. {
  49486. component = getContainerComp (component);
  49487. if (component != 0)
  49488. component->toFront (true);
  49489. }
  49490. else if (tabComponent != 0)
  49491. {
  49492. jassert (components.indexOf (component) >= 0);
  49493. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49494. {
  49495. if (tabComponent->getTabContentComponent (i) == component)
  49496. {
  49497. tabComponent->setCurrentTabIndex (i);
  49498. break;
  49499. }
  49500. }
  49501. }
  49502. else
  49503. {
  49504. component->grabKeyboardFocus();
  49505. }
  49506. }
  49507. void MultiDocumentPanel::activeDocumentChanged()
  49508. {
  49509. }
  49510. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49511. {
  49512. maximumNumDocuments = newNumber;
  49513. }
  49514. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49515. {
  49516. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49517. }
  49518. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49519. {
  49520. return numDocsBeforeTabsUsed != 0;
  49521. }
  49522. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49523. {
  49524. if (mode != newLayoutMode)
  49525. {
  49526. mode = newLayoutMode;
  49527. if (mode == FloatingWindows)
  49528. {
  49529. deleteAndZero (tabComponent);
  49530. }
  49531. else
  49532. {
  49533. for (int i = getNumChildComponents(); --i >= 0;)
  49534. {
  49535. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49536. if (dw != 0)
  49537. {
  49538. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49539. dw->setContentComponent (0, false);
  49540. delete dw;
  49541. }
  49542. }
  49543. }
  49544. resized();
  49545. const Array <Component*> tempComps (components);
  49546. components.clear();
  49547. for (int i = 0; i < tempComps.size(); ++i)
  49548. {
  49549. Component* const c = tempComps.getUnchecked(i);
  49550. addDocument (c,
  49551. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49552. shouldDeleteComp (c));
  49553. }
  49554. }
  49555. }
  49556. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49557. {
  49558. if (backgroundColour != newBackgroundColour)
  49559. {
  49560. backgroundColour = newBackgroundColour;
  49561. setOpaque (newBackgroundColour.isOpaque());
  49562. repaint();
  49563. }
  49564. }
  49565. void MultiDocumentPanel::paint (Graphics& g)
  49566. {
  49567. g.fillAll (backgroundColour);
  49568. }
  49569. void MultiDocumentPanel::resized()
  49570. {
  49571. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49572. {
  49573. for (int i = getNumChildComponents(); --i >= 0;)
  49574. getChildComponent (i)->setBounds (getLocalBounds());
  49575. }
  49576. setWantsKeyboardFocus (components.size() == 0);
  49577. }
  49578. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49579. {
  49580. if (mode == FloatingWindows)
  49581. {
  49582. for (int i = 0; i < getNumChildComponents(); ++i)
  49583. {
  49584. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49585. if (dw != 0 && dw->getContentComponent() == c)
  49586. {
  49587. c = dw;
  49588. break;
  49589. }
  49590. }
  49591. }
  49592. return c;
  49593. }
  49594. void MultiDocumentPanel::componentNameChanged (Component&)
  49595. {
  49596. if (mode == FloatingWindows)
  49597. {
  49598. for (int i = 0; i < getNumChildComponents(); ++i)
  49599. {
  49600. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49601. if (dw != 0)
  49602. dw->setName (dw->getContentComponent()->getName());
  49603. }
  49604. }
  49605. else if (tabComponent != 0)
  49606. {
  49607. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49608. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49609. }
  49610. }
  49611. void MultiDocumentPanel::updateOrder()
  49612. {
  49613. const Array <Component*> oldList (components);
  49614. if (mode == FloatingWindows)
  49615. {
  49616. components.clear();
  49617. for (int i = 0; i < getNumChildComponents(); ++i)
  49618. {
  49619. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49620. if (dw != 0)
  49621. components.add (dw->getContentComponent());
  49622. }
  49623. }
  49624. else
  49625. {
  49626. if (tabComponent != 0)
  49627. {
  49628. Component* const current = tabComponent->getCurrentContentComponent();
  49629. if (current != 0)
  49630. {
  49631. components.removeValue (current);
  49632. components.add (current);
  49633. }
  49634. }
  49635. }
  49636. if (components != oldList)
  49637. activeDocumentChanged();
  49638. }
  49639. END_JUCE_NAMESPACE
  49640. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49641. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49642. BEGIN_JUCE_NAMESPACE
  49643. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49644. : zone (zoneFlags)
  49645. {
  49646. }
  49647. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49648. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49649. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49650. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49651. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49652. const BorderSize& border,
  49653. const Point<int>& position)
  49654. {
  49655. int z = 0;
  49656. if (totalSize.contains (position)
  49657. && ! border.subtractedFrom (totalSize).contains (position))
  49658. {
  49659. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49660. if (position.getX() < jmax (border.getLeft(), minW))
  49661. z |= left;
  49662. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49663. z |= right;
  49664. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49665. if (position.getY() < jmax (border.getTop(), minH))
  49666. z |= top;
  49667. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49668. z |= bottom;
  49669. }
  49670. return Zone (z);
  49671. }
  49672. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49673. {
  49674. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49675. switch (zone)
  49676. {
  49677. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49678. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49679. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49680. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49681. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49682. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49683. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49684. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49685. default: break;
  49686. }
  49687. return mc;
  49688. }
  49689. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49690. {
  49691. if (isDraggingWholeObject())
  49692. return b + offset;
  49693. if (isDraggingLeftEdge())
  49694. b.setLeft (b.getX() + offset.getX());
  49695. if (isDraggingRightEdge())
  49696. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49697. if (isDraggingTopEdge())
  49698. b.setTop (b.getY() + offset.getY());
  49699. if (isDraggingBottomEdge())
  49700. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49701. return b;
  49702. }
  49703. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49704. {
  49705. if (isDraggingWholeObject())
  49706. return b + offset;
  49707. if (isDraggingLeftEdge())
  49708. b.setLeft (b.getX() + offset.getX());
  49709. if (isDraggingRightEdge())
  49710. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49711. if (isDraggingTopEdge())
  49712. b.setTop (b.getY() + offset.getY());
  49713. if (isDraggingBottomEdge())
  49714. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49715. return b;
  49716. }
  49717. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49718. ComponentBoundsConstrainer* const constrainer_)
  49719. : component (componentToResize),
  49720. constrainer (constrainer_),
  49721. borderSize (5),
  49722. mouseZone (0)
  49723. {
  49724. }
  49725. ResizableBorderComponent::~ResizableBorderComponent()
  49726. {
  49727. }
  49728. void ResizableBorderComponent::paint (Graphics& g)
  49729. {
  49730. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49731. }
  49732. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49733. {
  49734. updateMouseZone (e);
  49735. }
  49736. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49737. {
  49738. updateMouseZone (e);
  49739. }
  49740. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49741. {
  49742. if (component == 0)
  49743. {
  49744. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49745. return;
  49746. }
  49747. updateMouseZone (e);
  49748. originalBounds = component->getBounds();
  49749. if (constrainer != 0)
  49750. constrainer->resizeStart();
  49751. }
  49752. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49753. {
  49754. if (component == 0)
  49755. {
  49756. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49757. return;
  49758. }
  49759. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49760. if (constrainer != 0)
  49761. constrainer->setBoundsForComponent (component, bounds,
  49762. mouseZone.isDraggingTopEdge(),
  49763. mouseZone.isDraggingLeftEdge(),
  49764. mouseZone.isDraggingBottomEdge(),
  49765. mouseZone.isDraggingRightEdge());
  49766. else
  49767. component->setBounds (bounds);
  49768. }
  49769. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49770. {
  49771. if (constrainer != 0)
  49772. constrainer->resizeEnd();
  49773. }
  49774. bool ResizableBorderComponent::hitTest (int x, int y)
  49775. {
  49776. return x < borderSize.getLeft()
  49777. || x >= getWidth() - borderSize.getRight()
  49778. || y < borderSize.getTop()
  49779. || y >= getHeight() - borderSize.getBottom();
  49780. }
  49781. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49782. {
  49783. if (borderSize != newBorderSize)
  49784. {
  49785. borderSize = newBorderSize;
  49786. repaint();
  49787. }
  49788. }
  49789. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49790. {
  49791. return borderSize;
  49792. }
  49793. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49794. {
  49795. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49796. if (mouseZone != newZone)
  49797. {
  49798. mouseZone = newZone;
  49799. setMouseCursor (newZone.getMouseCursor());
  49800. }
  49801. }
  49802. END_JUCE_NAMESPACE
  49803. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49804. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49805. BEGIN_JUCE_NAMESPACE
  49806. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49807. ComponentBoundsConstrainer* const constrainer_)
  49808. : component (componentToResize),
  49809. constrainer (constrainer_)
  49810. {
  49811. setRepaintsOnMouseActivity (true);
  49812. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49813. }
  49814. ResizableCornerComponent::~ResizableCornerComponent()
  49815. {
  49816. }
  49817. void ResizableCornerComponent::paint (Graphics& g)
  49818. {
  49819. getLookAndFeel()
  49820. .drawCornerResizer (g, getWidth(), getHeight(),
  49821. isMouseOverOrDragging(),
  49822. isMouseButtonDown());
  49823. }
  49824. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49825. {
  49826. if (component == 0)
  49827. {
  49828. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49829. return;
  49830. }
  49831. originalBounds = component->getBounds();
  49832. if (constrainer != 0)
  49833. constrainer->resizeStart();
  49834. }
  49835. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49836. {
  49837. if (component == 0)
  49838. {
  49839. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49840. return;
  49841. }
  49842. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49843. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49844. if (constrainer != 0)
  49845. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49846. else
  49847. component->setBounds (r);
  49848. }
  49849. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49850. {
  49851. if (constrainer != 0)
  49852. constrainer->resizeStart();
  49853. }
  49854. bool ResizableCornerComponent::hitTest (int x, int y)
  49855. {
  49856. if (getWidth() <= 0)
  49857. return false;
  49858. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49859. return y >= yAtX - getHeight() / 4;
  49860. }
  49861. END_JUCE_NAMESPACE
  49862. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49863. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49864. BEGIN_JUCE_NAMESPACE
  49865. class ScrollBar::ScrollbarButton : public Button
  49866. {
  49867. public:
  49868. int direction;
  49869. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49870. : Button (String::empty),
  49871. direction (direction_),
  49872. owner (owner_)
  49873. {
  49874. setWantsKeyboardFocus (false);
  49875. }
  49876. ~ScrollbarButton()
  49877. {
  49878. }
  49879. void paintButton (Graphics& g, bool over, bool down)
  49880. {
  49881. getLookAndFeel()
  49882. .drawScrollbarButton (g, owner,
  49883. getWidth(), getHeight(),
  49884. direction,
  49885. owner.isVertical(),
  49886. over, down);
  49887. }
  49888. void clicked()
  49889. {
  49890. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49891. }
  49892. juce_UseDebuggingNewOperator
  49893. private:
  49894. ScrollBar& owner;
  49895. ScrollbarButton (const ScrollbarButton&);
  49896. ScrollbarButton& operator= (const ScrollbarButton&);
  49897. };
  49898. ScrollBar::ScrollBar (const bool vertical_,
  49899. const bool buttonsAreVisible)
  49900. : totalRange (0.0, 1.0),
  49901. visibleRange (0.0, 0.1),
  49902. singleStepSize (0.1),
  49903. thumbAreaStart (0),
  49904. thumbAreaSize (0),
  49905. thumbStart (0),
  49906. thumbSize (0),
  49907. initialDelayInMillisecs (100),
  49908. repeatDelayInMillisecs (50),
  49909. minimumDelayInMillisecs (10),
  49910. vertical (vertical_),
  49911. isDraggingThumb (false),
  49912. autohides (true)
  49913. {
  49914. setButtonVisibility (buttonsAreVisible);
  49915. setRepaintsOnMouseActivity (true);
  49916. setFocusContainer (true);
  49917. }
  49918. ScrollBar::~ScrollBar()
  49919. {
  49920. upButton = 0;
  49921. downButton = 0;
  49922. }
  49923. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49924. {
  49925. if (totalRange != newRangeLimit)
  49926. {
  49927. totalRange = newRangeLimit;
  49928. setCurrentRange (visibleRange);
  49929. updateThumbPosition();
  49930. }
  49931. }
  49932. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49933. {
  49934. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49935. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49936. }
  49937. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49938. {
  49939. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49940. if (visibleRange != constrainedRange)
  49941. {
  49942. visibleRange = constrainedRange;
  49943. updateThumbPosition();
  49944. triggerAsyncUpdate();
  49945. }
  49946. }
  49947. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49948. {
  49949. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49950. }
  49951. void ScrollBar::setCurrentRangeStart (const double newStart)
  49952. {
  49953. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49954. }
  49955. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49956. {
  49957. singleStepSize = newSingleStepSize;
  49958. }
  49959. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49960. {
  49961. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49962. }
  49963. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49964. {
  49965. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49966. }
  49967. void ScrollBar::scrollToTop()
  49968. {
  49969. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49970. }
  49971. void ScrollBar::scrollToBottom()
  49972. {
  49973. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49974. }
  49975. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49976. const int repeatDelayInMillisecs_,
  49977. const int minimumDelayInMillisecs_)
  49978. {
  49979. initialDelayInMillisecs = initialDelayInMillisecs_;
  49980. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49981. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49982. if (upButton != 0)
  49983. {
  49984. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49985. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49986. }
  49987. }
  49988. void ScrollBar::addListener (Listener* const listener)
  49989. {
  49990. listeners.add (listener);
  49991. }
  49992. void ScrollBar::removeListener (Listener* const listener)
  49993. {
  49994. listeners.remove (listener);
  49995. }
  49996. void ScrollBar::handleAsyncUpdate()
  49997. {
  49998. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49999. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50000. }
  50001. void ScrollBar::updateThumbPosition()
  50002. {
  50003. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50004. : thumbAreaSize);
  50005. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50006. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50007. if (newThumbSize > thumbAreaSize)
  50008. newThumbSize = thumbAreaSize;
  50009. int newThumbStart = thumbAreaStart;
  50010. if (totalRange.getLength() > visibleRange.getLength())
  50011. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50012. / (totalRange.getLength() - visibleRange.getLength()));
  50013. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50014. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50015. {
  50016. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50017. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50018. if (vertical)
  50019. repaint (0, repaintStart, getWidth(), repaintSize);
  50020. else
  50021. repaint (repaintStart, 0, repaintSize, getHeight());
  50022. thumbStart = newThumbStart;
  50023. thumbSize = newThumbSize;
  50024. }
  50025. }
  50026. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50027. {
  50028. if (vertical != shouldBeVertical)
  50029. {
  50030. vertical = shouldBeVertical;
  50031. if (upButton != 0)
  50032. {
  50033. upButton->direction = vertical ? 0 : 3;
  50034. downButton->direction = vertical ? 2 : 1;
  50035. }
  50036. updateThumbPosition();
  50037. }
  50038. }
  50039. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50040. {
  50041. upButton = 0;
  50042. downButton = 0;
  50043. if (buttonsAreVisible)
  50044. {
  50045. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50046. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50047. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50048. }
  50049. updateThumbPosition();
  50050. }
  50051. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50052. {
  50053. autohides = shouldHideWhenFullRange;
  50054. updateThumbPosition();
  50055. }
  50056. bool ScrollBar::autoHides() const throw()
  50057. {
  50058. return autohides;
  50059. }
  50060. void ScrollBar::paint (Graphics& g)
  50061. {
  50062. if (thumbAreaSize > 0)
  50063. {
  50064. LookAndFeel& lf = getLookAndFeel();
  50065. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50066. ? thumbSize : 0;
  50067. if (vertical)
  50068. {
  50069. lf.drawScrollbar (g, *this,
  50070. 0, thumbAreaStart,
  50071. getWidth(), thumbAreaSize,
  50072. vertical,
  50073. thumbStart, thumb,
  50074. isMouseOver(), isMouseButtonDown());
  50075. }
  50076. else
  50077. {
  50078. lf.drawScrollbar (g, *this,
  50079. thumbAreaStart, 0,
  50080. thumbAreaSize, getHeight(),
  50081. vertical,
  50082. thumbStart, thumb,
  50083. isMouseOver(), isMouseButtonDown());
  50084. }
  50085. }
  50086. }
  50087. void ScrollBar::lookAndFeelChanged()
  50088. {
  50089. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50090. }
  50091. void ScrollBar::resized()
  50092. {
  50093. const int length = ((vertical) ? getHeight() : getWidth());
  50094. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50095. : 0;
  50096. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50097. {
  50098. thumbAreaStart = length >> 1;
  50099. thumbAreaSize = 0;
  50100. }
  50101. else
  50102. {
  50103. thumbAreaStart = buttonSize;
  50104. thumbAreaSize = length - (buttonSize << 1);
  50105. }
  50106. if (upButton != 0)
  50107. {
  50108. if (vertical)
  50109. {
  50110. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50111. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50112. }
  50113. else
  50114. {
  50115. upButton->setBounds (0, 0, buttonSize, getHeight());
  50116. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50117. }
  50118. }
  50119. updateThumbPosition();
  50120. }
  50121. void ScrollBar::mouseDown (const MouseEvent& e)
  50122. {
  50123. isDraggingThumb = false;
  50124. lastMousePos = vertical ? e.y : e.x;
  50125. dragStartMousePos = lastMousePos;
  50126. dragStartRange = visibleRange.getStart();
  50127. if (dragStartMousePos < thumbStart)
  50128. {
  50129. moveScrollbarInPages (-1);
  50130. startTimer (400);
  50131. }
  50132. else if (dragStartMousePos >= thumbStart + thumbSize)
  50133. {
  50134. moveScrollbarInPages (1);
  50135. startTimer (400);
  50136. }
  50137. else
  50138. {
  50139. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50140. && (thumbAreaSize > thumbSize);
  50141. }
  50142. }
  50143. void ScrollBar::mouseDrag (const MouseEvent& e)
  50144. {
  50145. if (isDraggingThumb)
  50146. {
  50147. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50148. setCurrentRangeStart (dragStartRange
  50149. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50150. / (thumbAreaSize - thumbSize));
  50151. }
  50152. else
  50153. {
  50154. lastMousePos = (vertical) ? e.y : e.x;
  50155. }
  50156. }
  50157. void ScrollBar::mouseUp (const MouseEvent&)
  50158. {
  50159. isDraggingThumb = false;
  50160. stopTimer();
  50161. repaint();
  50162. }
  50163. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50164. float wheelIncrementX,
  50165. float wheelIncrementY)
  50166. {
  50167. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50168. if (increment < 0)
  50169. increment = jmin (increment * 10.0f, -1.0f);
  50170. else if (increment > 0)
  50171. increment = jmax (increment * 10.0f, 1.0f);
  50172. setCurrentRange (visibleRange - singleStepSize * increment);
  50173. }
  50174. void ScrollBar::timerCallback()
  50175. {
  50176. if (isMouseButtonDown())
  50177. {
  50178. startTimer (40);
  50179. if (lastMousePos < thumbStart)
  50180. setCurrentRange (visibleRange - visibleRange.getLength());
  50181. else if (lastMousePos > thumbStart + thumbSize)
  50182. setCurrentRangeStart (visibleRange.getEnd());
  50183. }
  50184. else
  50185. {
  50186. stopTimer();
  50187. }
  50188. }
  50189. bool ScrollBar::keyPressed (const KeyPress& key)
  50190. {
  50191. if (! isVisible())
  50192. return false;
  50193. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50194. moveScrollbarInSteps (-1);
  50195. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50196. moveScrollbarInSteps (1);
  50197. else if (key.isKeyCode (KeyPress::pageUpKey))
  50198. moveScrollbarInPages (-1);
  50199. else if (key.isKeyCode (KeyPress::pageDownKey))
  50200. moveScrollbarInPages (1);
  50201. else if (key.isKeyCode (KeyPress::homeKey))
  50202. scrollToTop();
  50203. else if (key.isKeyCode (KeyPress::endKey))
  50204. scrollToBottom();
  50205. else
  50206. return false;
  50207. return true;
  50208. }
  50209. END_JUCE_NAMESPACE
  50210. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50211. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50212. BEGIN_JUCE_NAMESPACE
  50213. StretchableLayoutManager::StretchableLayoutManager()
  50214. : totalSize (0)
  50215. {
  50216. }
  50217. StretchableLayoutManager::~StretchableLayoutManager()
  50218. {
  50219. }
  50220. void StretchableLayoutManager::clearAllItems()
  50221. {
  50222. items.clear();
  50223. totalSize = 0;
  50224. }
  50225. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50226. const double minimumSize,
  50227. const double maximumSize,
  50228. const double preferredSize)
  50229. {
  50230. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50231. if (layout == 0)
  50232. {
  50233. layout = new ItemLayoutProperties();
  50234. layout->itemIndex = itemIndex;
  50235. int i;
  50236. for (i = 0; i < items.size(); ++i)
  50237. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50238. break;
  50239. items.insert (i, layout);
  50240. }
  50241. layout->minSize = minimumSize;
  50242. layout->maxSize = maximumSize;
  50243. layout->preferredSize = preferredSize;
  50244. layout->currentSize = 0;
  50245. }
  50246. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50247. double& minimumSize,
  50248. double& maximumSize,
  50249. double& preferredSize) const
  50250. {
  50251. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50252. if (layout != 0)
  50253. {
  50254. minimumSize = layout->minSize;
  50255. maximumSize = layout->maxSize;
  50256. preferredSize = layout->preferredSize;
  50257. return true;
  50258. }
  50259. return false;
  50260. }
  50261. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50262. {
  50263. totalSize = newTotalSize;
  50264. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50265. }
  50266. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50267. {
  50268. int pos = 0;
  50269. for (int i = 0; i < itemIndex; ++i)
  50270. {
  50271. const ItemLayoutProperties* const layout = getInfoFor (i);
  50272. if (layout != 0)
  50273. pos += layout->currentSize;
  50274. }
  50275. return pos;
  50276. }
  50277. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50278. {
  50279. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50280. if (layout != 0)
  50281. return layout->currentSize;
  50282. return 0;
  50283. }
  50284. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50285. {
  50286. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50287. if (layout != 0)
  50288. return -layout->currentSize / (double) totalSize;
  50289. return 0;
  50290. }
  50291. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50292. int newPosition)
  50293. {
  50294. for (int i = items.size(); --i >= 0;)
  50295. {
  50296. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50297. if (layout->itemIndex == itemIndex)
  50298. {
  50299. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50300. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50301. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50302. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50303. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50304. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50305. endPos += layout->currentSize;
  50306. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50307. updatePrefSizesToMatchCurrentPositions();
  50308. break;
  50309. }
  50310. }
  50311. }
  50312. void StretchableLayoutManager::layOutComponents (Component** const components,
  50313. int numComponents,
  50314. int x, int y, int w, int h,
  50315. const bool vertically,
  50316. const bool resizeOtherDimension)
  50317. {
  50318. setTotalSize (vertically ? h : w);
  50319. int pos = vertically ? y : x;
  50320. for (int i = 0; i < numComponents; ++i)
  50321. {
  50322. const ItemLayoutProperties* const layout = getInfoFor (i);
  50323. if (layout != 0)
  50324. {
  50325. Component* const c = components[i];
  50326. if (c != 0)
  50327. {
  50328. if (i == numComponents - 1)
  50329. {
  50330. // if it's the last item, crop it to exactly fit the available space..
  50331. if (resizeOtherDimension)
  50332. {
  50333. if (vertically)
  50334. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50335. else
  50336. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50337. }
  50338. else
  50339. {
  50340. if (vertically)
  50341. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50342. else
  50343. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50344. }
  50345. }
  50346. else
  50347. {
  50348. if (resizeOtherDimension)
  50349. {
  50350. if (vertically)
  50351. c->setBounds (x, pos, w, layout->currentSize);
  50352. else
  50353. c->setBounds (pos, y, layout->currentSize, h);
  50354. }
  50355. else
  50356. {
  50357. if (vertically)
  50358. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50359. else
  50360. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50361. }
  50362. }
  50363. }
  50364. pos += layout->currentSize;
  50365. }
  50366. }
  50367. }
  50368. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50369. {
  50370. for (int i = items.size(); --i >= 0;)
  50371. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50372. return items.getUnchecked(i);
  50373. return 0;
  50374. }
  50375. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50376. const int endIndex,
  50377. const int availableSpace,
  50378. int startPos)
  50379. {
  50380. // calculate the total sizes
  50381. int i;
  50382. double totalIdealSize = 0.0;
  50383. int totalMinimums = 0;
  50384. for (i = startIndex; i < endIndex; ++i)
  50385. {
  50386. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50387. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50388. totalMinimums += layout->currentSize;
  50389. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50390. }
  50391. if (totalIdealSize <= 0)
  50392. totalIdealSize = 1.0;
  50393. // now calc the best sizes..
  50394. int extraSpace = availableSpace - totalMinimums;
  50395. while (extraSpace > 0)
  50396. {
  50397. int numWantingMoreSpace = 0;
  50398. int numHavingTakenExtraSpace = 0;
  50399. // first figure out how many comps want a slice of the extra space..
  50400. for (i = startIndex; i < endIndex; ++i)
  50401. {
  50402. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50403. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50404. const int bestSize = jlimit (layout->currentSize,
  50405. jmax (layout->currentSize,
  50406. sizeToRealSize (layout->maxSize, totalSize)),
  50407. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50408. if (bestSize > layout->currentSize)
  50409. ++numWantingMoreSpace;
  50410. }
  50411. // ..share out the extra space..
  50412. for (i = startIndex; i < endIndex; ++i)
  50413. {
  50414. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50415. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50416. int bestSize = jlimit (layout->currentSize,
  50417. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50418. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50419. const int extraWanted = bestSize - layout->currentSize;
  50420. if (extraWanted > 0)
  50421. {
  50422. const int extraAllowed = jmin (extraWanted,
  50423. extraSpace / jmax (1, numWantingMoreSpace));
  50424. if (extraAllowed > 0)
  50425. {
  50426. ++numHavingTakenExtraSpace;
  50427. --numWantingMoreSpace;
  50428. layout->currentSize += extraAllowed;
  50429. extraSpace -= extraAllowed;
  50430. }
  50431. }
  50432. }
  50433. if (numHavingTakenExtraSpace <= 0)
  50434. break;
  50435. }
  50436. // ..and calculate the end position
  50437. for (i = startIndex; i < endIndex; ++i)
  50438. {
  50439. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50440. startPos += layout->currentSize;
  50441. }
  50442. return startPos;
  50443. }
  50444. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50445. const int endIndex) const
  50446. {
  50447. int totalMinimums = 0;
  50448. for (int i = startIndex; i < endIndex; ++i)
  50449. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50450. return totalMinimums;
  50451. }
  50452. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50453. {
  50454. int totalMaximums = 0;
  50455. for (int i = startIndex; i < endIndex; ++i)
  50456. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50457. return totalMaximums;
  50458. }
  50459. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50460. {
  50461. for (int i = 0; i < items.size(); ++i)
  50462. {
  50463. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50464. layout->preferredSize
  50465. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50466. : getItemCurrentAbsoluteSize (i);
  50467. }
  50468. }
  50469. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50470. {
  50471. if (size < 0)
  50472. size *= -totalSpace;
  50473. return roundToInt (size);
  50474. }
  50475. END_JUCE_NAMESPACE
  50476. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50477. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50478. BEGIN_JUCE_NAMESPACE
  50479. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50480. const int itemIndex_,
  50481. const bool isVertical_)
  50482. : layout (layout_),
  50483. itemIndex (itemIndex_),
  50484. isVertical (isVertical_)
  50485. {
  50486. setRepaintsOnMouseActivity (true);
  50487. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50488. : MouseCursor::UpDownResizeCursor));
  50489. }
  50490. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50491. {
  50492. }
  50493. void StretchableLayoutResizerBar::paint (Graphics& g)
  50494. {
  50495. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50496. getWidth(), getHeight(),
  50497. isVertical,
  50498. isMouseOver(),
  50499. isMouseButtonDown());
  50500. }
  50501. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50502. {
  50503. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50504. }
  50505. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50506. {
  50507. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50508. : e.getDistanceFromDragStartY());
  50509. layout->setItemPosition (itemIndex, desiredPos);
  50510. hasBeenMoved();
  50511. }
  50512. void StretchableLayoutResizerBar::hasBeenMoved()
  50513. {
  50514. if (getParentComponent() != 0)
  50515. getParentComponent()->resized();
  50516. }
  50517. END_JUCE_NAMESPACE
  50518. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50519. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50520. BEGIN_JUCE_NAMESPACE
  50521. StretchableObjectResizer::StretchableObjectResizer()
  50522. {
  50523. }
  50524. StretchableObjectResizer::~StretchableObjectResizer()
  50525. {
  50526. }
  50527. void StretchableObjectResizer::addItem (const double size,
  50528. const double minSize, const double maxSize,
  50529. const int order)
  50530. {
  50531. // the order must be >= 0 but less than the maximum integer value.
  50532. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50533. Item* const item = new Item();
  50534. item->size = size;
  50535. item->minSize = minSize;
  50536. item->maxSize = maxSize;
  50537. item->order = order;
  50538. items.add (item);
  50539. }
  50540. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50541. {
  50542. const Item* const it = items [index];
  50543. return it != 0 ? it->size : 0;
  50544. }
  50545. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50546. {
  50547. int order = 0;
  50548. for (;;)
  50549. {
  50550. double currentSize = 0;
  50551. double minSize = 0;
  50552. double maxSize = 0;
  50553. int nextHighestOrder = std::numeric_limits<int>::max();
  50554. for (int i = 0; i < items.size(); ++i)
  50555. {
  50556. const Item* const it = items.getUnchecked(i);
  50557. currentSize += it->size;
  50558. if (it->order <= order)
  50559. {
  50560. minSize += it->minSize;
  50561. maxSize += it->maxSize;
  50562. }
  50563. else
  50564. {
  50565. minSize += it->size;
  50566. maxSize += it->size;
  50567. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50568. }
  50569. }
  50570. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50571. if (thisIterationTarget >= currentSize)
  50572. {
  50573. const double availableExtraSpace = maxSize - currentSize;
  50574. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50575. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50576. for (int i = 0; i < items.size(); ++i)
  50577. {
  50578. Item* const it = items.getUnchecked(i);
  50579. if (it->order <= order)
  50580. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50581. }
  50582. }
  50583. else
  50584. {
  50585. const double amountOfSlack = currentSize - minSize;
  50586. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50587. const double scale = targetAmountOfSlack / amountOfSlack;
  50588. for (int i = 0; i < items.size(); ++i)
  50589. {
  50590. Item* const it = items.getUnchecked(i);
  50591. if (it->order <= order)
  50592. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50593. }
  50594. }
  50595. if (nextHighestOrder < std::numeric_limits<int>::max())
  50596. order = nextHighestOrder;
  50597. else
  50598. break;
  50599. }
  50600. }
  50601. END_JUCE_NAMESPACE
  50602. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50603. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50604. BEGIN_JUCE_NAMESPACE
  50605. TabBarButton::TabBarButton (const String& name,
  50606. TabbedButtonBar* const owner_,
  50607. const int index)
  50608. : Button (name),
  50609. owner (owner_),
  50610. tabIndex (index),
  50611. overlapPixels (0)
  50612. {
  50613. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50614. setComponentEffect (&shadow);
  50615. setWantsKeyboardFocus (false);
  50616. }
  50617. TabBarButton::~TabBarButton()
  50618. {
  50619. }
  50620. void TabBarButton::paintButton (Graphics& g,
  50621. bool isMouseOverButton,
  50622. bool isButtonDown)
  50623. {
  50624. int x, y, w, h;
  50625. getActiveArea (x, y, w, h);
  50626. g.setOrigin (x, y);
  50627. getLookAndFeel()
  50628. .drawTabButton (g, w, h,
  50629. owner->getTabBackgroundColour (tabIndex),
  50630. tabIndex, getButtonText(), *this,
  50631. owner->getOrientation(),
  50632. isMouseOverButton, isButtonDown,
  50633. getToggleState());
  50634. }
  50635. void TabBarButton::clicked (const ModifierKeys& mods)
  50636. {
  50637. if (mods.isPopupMenu())
  50638. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50639. else
  50640. owner->setCurrentTabIndex (tabIndex);
  50641. }
  50642. bool TabBarButton::hitTest (int mx, int my)
  50643. {
  50644. int x, y, w, h;
  50645. getActiveArea (x, y, w, h);
  50646. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50647. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50648. {
  50649. if (((unsigned int) mx) < (unsigned int) getWidth()
  50650. && my >= y + overlapPixels
  50651. && my < y + h - overlapPixels)
  50652. return true;
  50653. }
  50654. else
  50655. {
  50656. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50657. && ((unsigned int) my) < (unsigned int) getHeight())
  50658. return true;
  50659. }
  50660. Path p;
  50661. getLookAndFeel()
  50662. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50663. owner->getOrientation(),
  50664. false, false, getToggleState());
  50665. return p.contains ((float) (mx - x),
  50666. (float) (my - y));
  50667. }
  50668. int TabBarButton::getBestTabLength (const int depth)
  50669. {
  50670. return jlimit (depth * 2,
  50671. depth * 7,
  50672. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50673. }
  50674. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50675. {
  50676. x = 0;
  50677. y = 0;
  50678. int r = getWidth();
  50679. int b = getHeight();
  50680. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50681. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50682. r -= spaceAroundImage;
  50683. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50684. x += spaceAroundImage;
  50685. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50686. y += spaceAroundImage;
  50687. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50688. b -= spaceAroundImage;
  50689. w = r - x;
  50690. h = b - y;
  50691. }
  50692. class TabAreaBehindFrontButtonComponent : public Component
  50693. {
  50694. public:
  50695. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50696. : owner (owner_)
  50697. {
  50698. setInterceptsMouseClicks (false, false);
  50699. }
  50700. ~TabAreaBehindFrontButtonComponent()
  50701. {
  50702. }
  50703. void paint (Graphics& g)
  50704. {
  50705. getLookAndFeel()
  50706. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50707. *owner, owner->getOrientation());
  50708. }
  50709. void enablementChanged()
  50710. {
  50711. repaint();
  50712. }
  50713. private:
  50714. TabbedButtonBar* const owner;
  50715. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50716. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50717. };
  50718. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50719. : orientation (orientation_),
  50720. currentTabIndex (-1)
  50721. {
  50722. setInterceptsMouseClicks (false, true);
  50723. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50724. setFocusContainer (true);
  50725. }
  50726. TabbedButtonBar::~TabbedButtonBar()
  50727. {
  50728. extraTabsButton = 0;
  50729. deleteAllChildren();
  50730. }
  50731. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50732. {
  50733. orientation = newOrientation;
  50734. for (int i = getNumChildComponents(); --i >= 0;)
  50735. getChildComponent (i)->resized();
  50736. resized();
  50737. }
  50738. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50739. {
  50740. return new TabBarButton (name, this, index);
  50741. }
  50742. void TabbedButtonBar::clearTabs()
  50743. {
  50744. tabs.clear();
  50745. tabColours.clear();
  50746. currentTabIndex = -1;
  50747. extraTabsButton = 0;
  50748. removeChildComponent (behindFrontTab);
  50749. deleteAllChildren();
  50750. addChildComponent (behindFrontTab);
  50751. setCurrentTabIndex (-1);
  50752. }
  50753. void TabbedButtonBar::addTab (const String& tabName,
  50754. const Colour& tabBackgroundColour,
  50755. int insertIndex)
  50756. {
  50757. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50758. if (tabName.isNotEmpty())
  50759. {
  50760. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50761. insertIndex = tabs.size();
  50762. for (int i = tabs.size(); --i >= insertIndex;)
  50763. {
  50764. TabBarButton* const tb = getTabButton (i);
  50765. if (tb != 0)
  50766. tb->tabIndex++;
  50767. }
  50768. tabs.insert (insertIndex, tabName);
  50769. tabColours.insert (insertIndex, tabBackgroundColour);
  50770. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50771. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50772. addAndMakeVisible (tb, insertIndex);
  50773. resized();
  50774. if (currentTabIndex < 0)
  50775. setCurrentTabIndex (0);
  50776. }
  50777. }
  50778. void TabbedButtonBar::setTabName (const int tabIndex,
  50779. const String& newName)
  50780. {
  50781. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50782. && tabs[tabIndex] != newName)
  50783. {
  50784. tabs.set (tabIndex, newName);
  50785. TabBarButton* const tb = getTabButton (tabIndex);
  50786. if (tb != 0)
  50787. tb->setButtonText (newName);
  50788. resized();
  50789. }
  50790. }
  50791. void TabbedButtonBar::removeTab (const int tabIndex)
  50792. {
  50793. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50794. {
  50795. const int oldTabIndex = currentTabIndex;
  50796. if (currentTabIndex == tabIndex)
  50797. currentTabIndex = -1;
  50798. tabs.remove (tabIndex);
  50799. tabColours.remove (tabIndex);
  50800. delete getTabButton (tabIndex);
  50801. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50802. {
  50803. TabBarButton* const tb = getTabButton (i);
  50804. if (tb != 0)
  50805. tb->tabIndex--;
  50806. }
  50807. resized();
  50808. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50809. }
  50810. }
  50811. void TabbedButtonBar::moveTab (const int currentIndex,
  50812. const int newIndex)
  50813. {
  50814. tabs.move (currentIndex, newIndex);
  50815. tabColours.move (currentIndex, newIndex);
  50816. resized();
  50817. }
  50818. int TabbedButtonBar::getNumTabs() const
  50819. {
  50820. return tabs.size();
  50821. }
  50822. const StringArray TabbedButtonBar::getTabNames() const
  50823. {
  50824. return tabs;
  50825. }
  50826. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50827. {
  50828. if (currentTabIndex != newIndex)
  50829. {
  50830. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50831. newIndex = -1;
  50832. currentTabIndex = newIndex;
  50833. for (int i = 0; i < getNumChildComponents(); ++i)
  50834. {
  50835. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50836. if (tb != 0)
  50837. tb->setToggleState (tb->tabIndex == newIndex, false);
  50838. }
  50839. resized();
  50840. if (sendChangeMessage_)
  50841. sendChangeMessage (this);
  50842. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50843. }
  50844. }
  50845. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50846. {
  50847. for (int i = getNumChildComponents(); --i >= 0;)
  50848. {
  50849. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50850. if (tb != 0 && tb->tabIndex == index)
  50851. return tb;
  50852. }
  50853. return 0;
  50854. }
  50855. void TabbedButtonBar::lookAndFeelChanged()
  50856. {
  50857. extraTabsButton = 0;
  50858. resized();
  50859. }
  50860. void TabbedButtonBar::resized()
  50861. {
  50862. const double minimumScale = 0.7;
  50863. int depth = getWidth();
  50864. int length = getHeight();
  50865. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50866. swapVariables (depth, length);
  50867. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50868. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50869. int i, totalLength = overlap;
  50870. int numVisibleButtons = tabs.size();
  50871. for (i = 0; i < getNumChildComponents(); ++i)
  50872. {
  50873. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50874. if (tb != 0)
  50875. {
  50876. totalLength += tb->getBestTabLength (depth) - overlap;
  50877. tb->overlapPixels = overlap / 2;
  50878. }
  50879. }
  50880. double scale = 1.0;
  50881. if (totalLength > length)
  50882. scale = jmax (minimumScale, length / (double) totalLength);
  50883. const bool isTooBig = totalLength * scale > length;
  50884. int tabsButtonPos = 0;
  50885. if (isTooBig)
  50886. {
  50887. if (extraTabsButton == 0)
  50888. {
  50889. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50890. extraTabsButton->addButtonListener (this);
  50891. extraTabsButton->setAlwaysOnTop (true);
  50892. extraTabsButton->setTriggeredOnMouseDown (true);
  50893. }
  50894. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50895. extraTabsButton->setSize (buttonSize, buttonSize);
  50896. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50897. {
  50898. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50899. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50900. }
  50901. else
  50902. {
  50903. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50904. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50905. }
  50906. totalLength = 0;
  50907. for (i = 0; i < tabs.size(); ++i)
  50908. {
  50909. TabBarButton* const tb = getTabButton (i);
  50910. if (tb != 0)
  50911. {
  50912. const int newLength = totalLength + tb->getBestTabLength (depth);
  50913. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50914. {
  50915. totalLength += overlap;
  50916. break;
  50917. }
  50918. numVisibleButtons = i + 1;
  50919. totalLength = newLength - overlap;
  50920. }
  50921. }
  50922. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50923. }
  50924. else
  50925. {
  50926. extraTabsButton = 0;
  50927. }
  50928. int pos = 0;
  50929. TabBarButton* frontTab = 0;
  50930. for (i = 0; i < tabs.size(); ++i)
  50931. {
  50932. TabBarButton* const tb = getTabButton (i);
  50933. if (tb != 0)
  50934. {
  50935. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50936. if (i < numVisibleButtons)
  50937. {
  50938. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50939. tb->setBounds (pos, 0, bestLength, getHeight());
  50940. else
  50941. tb->setBounds (0, pos, getWidth(), bestLength);
  50942. tb->toBack();
  50943. if (tb->tabIndex == currentTabIndex)
  50944. frontTab = tb;
  50945. tb->setVisible (true);
  50946. }
  50947. else
  50948. {
  50949. tb->setVisible (false);
  50950. }
  50951. pos += bestLength - overlap;
  50952. }
  50953. }
  50954. behindFrontTab->setBounds (getLocalBounds());
  50955. if (frontTab != 0)
  50956. {
  50957. frontTab->toFront (false);
  50958. behindFrontTab->toBehind (frontTab);
  50959. }
  50960. }
  50961. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50962. {
  50963. return tabColours [tabIndex];
  50964. }
  50965. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50966. {
  50967. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50968. && tabColours [tabIndex] != newColour)
  50969. {
  50970. tabColours.set (tabIndex, newColour);
  50971. repaint();
  50972. }
  50973. }
  50974. void TabbedButtonBar::buttonClicked (Button* button)
  50975. {
  50976. if (button == extraTabsButton)
  50977. {
  50978. PopupMenu m;
  50979. for (int i = 0; i < tabs.size(); ++i)
  50980. {
  50981. TabBarButton* const tb = getTabButton (i);
  50982. if (tb != 0 && ! tb->isVisible())
  50983. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50984. }
  50985. const int res = m.showAt (extraTabsButton);
  50986. if (res != 0)
  50987. setCurrentTabIndex (res - 1);
  50988. }
  50989. }
  50990. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50991. {
  50992. }
  50993. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50994. {
  50995. }
  50996. END_JUCE_NAMESPACE
  50997. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50998. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50999. BEGIN_JUCE_NAMESPACE
  51000. class TabCompButtonBar : public TabbedButtonBar
  51001. {
  51002. public:
  51003. TabCompButtonBar (TabbedComponent* const owner_,
  51004. const TabbedButtonBar::Orientation orientation_)
  51005. : TabbedButtonBar (orientation_),
  51006. owner (owner_)
  51007. {
  51008. }
  51009. ~TabCompButtonBar()
  51010. {
  51011. }
  51012. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51013. {
  51014. owner->changeCallback (newCurrentTabIndex, newTabName);
  51015. }
  51016. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51017. {
  51018. owner->popupMenuClickOnTab (tabIndex, tabName);
  51019. }
  51020. const Colour getTabBackgroundColour (const int tabIndex)
  51021. {
  51022. return owner->tabs->getTabBackgroundColour (tabIndex);
  51023. }
  51024. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51025. {
  51026. return owner->createTabButton (tabName, tabIndex);
  51027. }
  51028. juce_UseDebuggingNewOperator
  51029. private:
  51030. TabbedComponent* const owner;
  51031. TabCompButtonBar (const TabCompButtonBar&);
  51032. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51033. };
  51034. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51035. : panelComponent (0),
  51036. tabDepth (30),
  51037. outlineThickness (1),
  51038. edgeIndent (0)
  51039. {
  51040. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51041. }
  51042. TabbedComponent::~TabbedComponent()
  51043. {
  51044. clearTabs();
  51045. delete tabs;
  51046. }
  51047. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51048. {
  51049. tabs->setOrientation (orientation);
  51050. resized();
  51051. }
  51052. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51053. {
  51054. return tabs->getOrientation();
  51055. }
  51056. void TabbedComponent::setTabBarDepth (const int newDepth)
  51057. {
  51058. if (tabDepth != newDepth)
  51059. {
  51060. tabDepth = newDepth;
  51061. resized();
  51062. }
  51063. }
  51064. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51065. {
  51066. return new TabBarButton (tabName, tabs, tabIndex);
  51067. }
  51068. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51069. void TabbedComponent::clearTabs()
  51070. {
  51071. if (panelComponent != 0)
  51072. {
  51073. panelComponent->setVisible (false);
  51074. removeChildComponent (panelComponent);
  51075. panelComponent = 0;
  51076. }
  51077. tabs->clearTabs();
  51078. for (int i = contentComponents.size(); --i >= 0;)
  51079. {
  51080. Component* const c = contentComponents.getUnchecked(i);
  51081. // be careful not to delete these components until they've been removed from the tab component
  51082. jassert (c == 0 || c->isValidComponent());
  51083. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51084. delete c;
  51085. }
  51086. contentComponents.clear();
  51087. }
  51088. void TabbedComponent::addTab (const String& tabName,
  51089. const Colour& tabBackgroundColour,
  51090. Component* const contentComponent,
  51091. const bool deleteComponentWhenNotNeeded,
  51092. const int insertIndex)
  51093. {
  51094. contentComponents.insert (insertIndex, contentComponent);
  51095. if (contentComponent != 0)
  51096. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51097. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51098. }
  51099. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51100. {
  51101. tabs->setTabName (tabIndex, newName);
  51102. }
  51103. void TabbedComponent::removeTab (const int tabIndex)
  51104. {
  51105. Component* const c = contentComponents [tabIndex];
  51106. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51107. {
  51108. if (c == panelComponent)
  51109. panelComponent = 0;
  51110. delete c;
  51111. }
  51112. contentComponents.remove (tabIndex);
  51113. tabs->removeTab (tabIndex);
  51114. }
  51115. int TabbedComponent::getNumTabs() const
  51116. {
  51117. return tabs->getNumTabs();
  51118. }
  51119. const StringArray TabbedComponent::getTabNames() const
  51120. {
  51121. return tabs->getTabNames();
  51122. }
  51123. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51124. {
  51125. return contentComponents [tabIndex];
  51126. }
  51127. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51128. {
  51129. return tabs->getTabBackgroundColour (tabIndex);
  51130. }
  51131. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51132. {
  51133. tabs->setTabBackgroundColour (tabIndex, newColour);
  51134. if (getCurrentTabIndex() == tabIndex)
  51135. repaint();
  51136. }
  51137. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51138. {
  51139. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51140. }
  51141. int TabbedComponent::getCurrentTabIndex() const
  51142. {
  51143. return tabs->getCurrentTabIndex();
  51144. }
  51145. const String& TabbedComponent::getCurrentTabName() const
  51146. {
  51147. return tabs->getCurrentTabName();
  51148. }
  51149. void TabbedComponent::setOutline (int thickness)
  51150. {
  51151. outlineThickness = thickness;
  51152. repaint();
  51153. }
  51154. void TabbedComponent::setIndent (const int indentThickness)
  51155. {
  51156. edgeIndent = indentThickness;
  51157. }
  51158. void TabbedComponent::paint (Graphics& g)
  51159. {
  51160. g.fillAll (findColour (backgroundColourId));
  51161. const TabbedButtonBar::Orientation o = getOrientation();
  51162. int x = 0;
  51163. int y = 0;
  51164. int r = getWidth();
  51165. int b = getHeight();
  51166. if (o == TabbedButtonBar::TabsAtTop)
  51167. y += tabDepth;
  51168. else if (o == TabbedButtonBar::TabsAtBottom)
  51169. b -= tabDepth;
  51170. else if (o == TabbedButtonBar::TabsAtLeft)
  51171. x += tabDepth;
  51172. else if (o == TabbedButtonBar::TabsAtRight)
  51173. r -= tabDepth;
  51174. g.reduceClipRegion (x, y, r - x, b - y);
  51175. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51176. if (outlineThickness > 0)
  51177. {
  51178. if (o == TabbedButtonBar::TabsAtTop)
  51179. --y;
  51180. else if (o == TabbedButtonBar::TabsAtBottom)
  51181. ++b;
  51182. else if (o == TabbedButtonBar::TabsAtLeft)
  51183. --x;
  51184. else if (o == TabbedButtonBar::TabsAtRight)
  51185. ++r;
  51186. g.setColour (findColour (outlineColourId));
  51187. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51188. }
  51189. }
  51190. void TabbedComponent::resized()
  51191. {
  51192. const TabbedButtonBar::Orientation o = getOrientation();
  51193. const int indent = edgeIndent + outlineThickness;
  51194. BorderSize indents (indent);
  51195. if (o == TabbedButtonBar::TabsAtTop)
  51196. {
  51197. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51198. indents.setTop (tabDepth + edgeIndent);
  51199. }
  51200. else if (o == TabbedButtonBar::TabsAtBottom)
  51201. {
  51202. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51203. indents.setBottom (tabDepth + edgeIndent);
  51204. }
  51205. else if (o == TabbedButtonBar::TabsAtLeft)
  51206. {
  51207. tabs->setBounds (0, 0, tabDepth, getHeight());
  51208. indents.setLeft (tabDepth + edgeIndent);
  51209. }
  51210. else if (o == TabbedButtonBar::TabsAtRight)
  51211. {
  51212. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51213. indents.setRight (tabDepth + edgeIndent);
  51214. }
  51215. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51216. for (int i = contentComponents.size(); --i >= 0;)
  51217. if (contentComponents.getUnchecked (i) != 0)
  51218. contentComponents.getUnchecked (i)->setBounds (bounds);
  51219. }
  51220. void TabbedComponent::lookAndFeelChanged()
  51221. {
  51222. for (int i = contentComponents.size(); --i >= 0;)
  51223. if (contentComponents.getUnchecked (i) != 0)
  51224. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51225. }
  51226. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51227. const String& newTabName)
  51228. {
  51229. if (panelComponent != 0)
  51230. {
  51231. panelComponent->setVisible (false);
  51232. removeChildComponent (panelComponent);
  51233. panelComponent = 0;
  51234. }
  51235. if (getCurrentTabIndex() >= 0)
  51236. {
  51237. panelComponent = contentComponents [getCurrentTabIndex()];
  51238. if (panelComponent != 0)
  51239. {
  51240. // do these ops as two stages instead of addAndMakeVisible() so that the
  51241. // component has always got a parent when it gets the visibilityChanged() callback
  51242. addChildComponent (panelComponent);
  51243. panelComponent->setVisible (true);
  51244. panelComponent->toFront (true);
  51245. }
  51246. repaint();
  51247. }
  51248. resized();
  51249. currentTabChanged (newCurrentTabIndex, newTabName);
  51250. }
  51251. void TabbedComponent::currentTabChanged (const int, const String&)
  51252. {
  51253. }
  51254. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51255. {
  51256. }
  51257. END_JUCE_NAMESPACE
  51258. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51259. /*** Start of inlined file: juce_Viewport.cpp ***/
  51260. BEGIN_JUCE_NAMESPACE
  51261. Viewport::Viewport (const String& componentName)
  51262. : Component (componentName),
  51263. scrollBarThickness (0),
  51264. singleStepX (16),
  51265. singleStepY (16),
  51266. showHScrollbar (true),
  51267. showVScrollbar (true),
  51268. verticalScrollBar (true),
  51269. horizontalScrollBar (false)
  51270. {
  51271. // content holder is used to clip the contents so they don't overlap the scrollbars
  51272. addAndMakeVisible (&contentHolder);
  51273. contentHolder.setInterceptsMouseClicks (false, true);
  51274. addChildComponent (&verticalScrollBar);
  51275. addChildComponent (&horizontalScrollBar);
  51276. verticalScrollBar.addListener (this);
  51277. horizontalScrollBar.addListener (this);
  51278. setInterceptsMouseClicks (false, true);
  51279. setWantsKeyboardFocus (true);
  51280. }
  51281. Viewport::~Viewport()
  51282. {
  51283. contentHolder.deleteAllChildren();
  51284. }
  51285. void Viewport::visibleAreaChanged (int, int, int, int)
  51286. {
  51287. }
  51288. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51289. {
  51290. if (contentComp.getComponent() != newViewedComponent)
  51291. {
  51292. {
  51293. ScopedPointer<Component> oldCompDeleter (contentComp);
  51294. contentComp = 0;
  51295. }
  51296. contentComp = newViewedComponent;
  51297. if (contentComp != 0)
  51298. {
  51299. contentComp->setTopLeftPosition (0, 0);
  51300. contentHolder.addAndMakeVisible (contentComp);
  51301. contentComp->addComponentListener (this);
  51302. }
  51303. updateVisibleArea();
  51304. }
  51305. }
  51306. int Viewport::getMaximumVisibleWidth() const
  51307. {
  51308. return contentHolder.getWidth();
  51309. }
  51310. int Viewport::getMaximumVisibleHeight() const
  51311. {
  51312. return contentHolder.getHeight();
  51313. }
  51314. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51315. {
  51316. if (contentComp != 0)
  51317. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51318. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51319. }
  51320. void Viewport::setViewPosition (const Point<int>& newPosition)
  51321. {
  51322. setViewPosition (newPosition.getX(), newPosition.getY());
  51323. }
  51324. void Viewport::setViewPositionProportionately (const double x, const double y)
  51325. {
  51326. if (contentComp != 0)
  51327. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51328. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51329. }
  51330. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51331. {
  51332. if (contentComp != 0)
  51333. {
  51334. int dx = 0, dy = 0;
  51335. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51336. {
  51337. if (mouseX < activeBorderThickness)
  51338. dx = activeBorderThickness - mouseX;
  51339. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51340. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51341. if (dx < 0)
  51342. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51343. else
  51344. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51345. }
  51346. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51347. {
  51348. if (mouseY < activeBorderThickness)
  51349. dy = activeBorderThickness - mouseY;
  51350. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51351. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51352. if (dy < 0)
  51353. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51354. else
  51355. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51356. }
  51357. if (dx != 0 || dy != 0)
  51358. {
  51359. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51360. contentComp->getY() + dy);
  51361. return true;
  51362. }
  51363. }
  51364. return false;
  51365. }
  51366. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51367. {
  51368. updateVisibleArea();
  51369. }
  51370. void Viewport::resized()
  51371. {
  51372. updateVisibleArea();
  51373. }
  51374. void Viewport::updateVisibleArea()
  51375. {
  51376. const int scrollbarWidth = getScrollBarThickness();
  51377. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51378. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51379. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51380. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51381. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51382. Rectangle<int> contentArea (getLocalBounds());
  51383. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51384. {
  51385. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51386. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51387. if (vBarVisible)
  51388. contentArea.setWidth (getWidth() - scrollbarWidth);
  51389. if (hBarVisible)
  51390. contentArea.setHeight (getHeight() - scrollbarWidth);
  51391. if (! contentArea.contains (contentComp->getBounds()))
  51392. {
  51393. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51394. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51395. }
  51396. }
  51397. if (vBarVisible)
  51398. contentArea.setWidth (getWidth() - scrollbarWidth);
  51399. if (hBarVisible)
  51400. contentArea.setHeight (getHeight() - scrollbarWidth);
  51401. contentHolder.setBounds (contentArea);
  51402. Rectangle<int> contentBounds;
  51403. if (contentComp != 0)
  51404. contentBounds = contentComp->getBounds();
  51405. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51406. if (hBarVisible)
  51407. {
  51408. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51409. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51410. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51411. horizontalScrollBar.setSingleStepSize (singleStepX);
  51412. horizontalScrollBar.cancelPendingUpdate();
  51413. }
  51414. if (vBarVisible)
  51415. {
  51416. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51417. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51418. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51419. verticalScrollBar.setSingleStepSize (singleStepY);
  51420. verticalScrollBar.cancelPendingUpdate();
  51421. }
  51422. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51423. horizontalScrollBar.setVisible (hBarVisible);
  51424. verticalScrollBar.setVisible (vBarVisible);
  51425. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51426. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51427. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51428. if (lastVisibleArea != visibleArea)
  51429. {
  51430. lastVisibleArea = visibleArea;
  51431. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51432. }
  51433. horizontalScrollBar.handleUpdateNowIfNeeded();
  51434. verticalScrollBar.handleUpdateNowIfNeeded();
  51435. }
  51436. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51437. {
  51438. if (singleStepX != stepX || singleStepY != stepY)
  51439. {
  51440. singleStepX = stepX;
  51441. singleStepY = stepY;
  51442. updateVisibleArea();
  51443. }
  51444. }
  51445. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51446. const bool showHorizontalScrollbarIfNeeded)
  51447. {
  51448. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51449. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51450. {
  51451. showVScrollbar = showVerticalScrollbarIfNeeded;
  51452. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51453. updateVisibleArea();
  51454. }
  51455. }
  51456. void Viewport::setScrollBarThickness (const int thickness)
  51457. {
  51458. if (scrollBarThickness != thickness)
  51459. {
  51460. scrollBarThickness = thickness;
  51461. updateVisibleArea();
  51462. }
  51463. }
  51464. int Viewport::getScrollBarThickness() const
  51465. {
  51466. return scrollBarThickness > 0 ? scrollBarThickness
  51467. : getLookAndFeel().getDefaultScrollbarWidth();
  51468. }
  51469. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51470. {
  51471. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51472. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51473. }
  51474. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51475. {
  51476. const int newRangeStartInt = roundToInt (newRangeStart);
  51477. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51478. {
  51479. setViewPosition (newRangeStartInt, getViewPositionY());
  51480. }
  51481. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51482. {
  51483. setViewPosition (getViewPositionX(), newRangeStartInt);
  51484. }
  51485. }
  51486. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51487. {
  51488. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51489. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51490. }
  51491. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51492. {
  51493. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51494. {
  51495. const bool hasVertBar = verticalScrollBar.isVisible();
  51496. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51497. if (hasHorzBar || hasVertBar)
  51498. {
  51499. if (wheelIncrementX != 0)
  51500. {
  51501. wheelIncrementX *= 14.0f * singleStepX;
  51502. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51503. : jmax (wheelIncrementX, 1.0f);
  51504. }
  51505. if (wheelIncrementY != 0)
  51506. {
  51507. wheelIncrementY *= 14.0f * singleStepY;
  51508. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51509. : jmax (wheelIncrementY, 1.0f);
  51510. }
  51511. Point<int> pos (getViewPosition());
  51512. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51513. {
  51514. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51515. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51516. }
  51517. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51518. {
  51519. if (wheelIncrementX == 0 && ! hasVertBar)
  51520. wheelIncrementX = wheelIncrementY;
  51521. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51522. }
  51523. else if (hasVertBar && wheelIncrementY != 0)
  51524. {
  51525. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51526. }
  51527. if (pos != getViewPosition())
  51528. {
  51529. setViewPosition (pos);
  51530. return true;
  51531. }
  51532. }
  51533. }
  51534. return false;
  51535. }
  51536. bool Viewport::keyPressed (const KeyPress& key)
  51537. {
  51538. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51539. || key.isKeyCode (KeyPress::downKey)
  51540. || key.isKeyCode (KeyPress::pageUpKey)
  51541. || key.isKeyCode (KeyPress::pageDownKey)
  51542. || key.isKeyCode (KeyPress::homeKey)
  51543. || key.isKeyCode (KeyPress::endKey);
  51544. if (verticalScrollBar.isVisible() && isUpDownKey)
  51545. return verticalScrollBar.keyPressed (key);
  51546. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51547. || key.isKeyCode (KeyPress::rightKey);
  51548. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51549. return horizontalScrollBar.keyPressed (key);
  51550. return false;
  51551. }
  51552. END_JUCE_NAMESPACE
  51553. /*** End of inlined file: juce_Viewport.cpp ***/
  51554. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51555. BEGIN_JUCE_NAMESPACE
  51556. static const Colour createBaseColour (const Colour& buttonColour,
  51557. const bool hasKeyboardFocus,
  51558. const bool isMouseOverButton,
  51559. const bool isButtonDown) throw()
  51560. {
  51561. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51562. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51563. if (isButtonDown)
  51564. return baseColour.contrasting (0.2f);
  51565. else if (isMouseOverButton)
  51566. return baseColour.contrasting (0.1f);
  51567. return baseColour;
  51568. }
  51569. LookAndFeel::LookAndFeel()
  51570. {
  51571. /* if this fails it means you're trying to create a LookAndFeel object before
  51572. the static Colours have been initialised. That ain't gonna work. It probably
  51573. means that you're using a static LookAndFeel object and that your compiler has
  51574. decided to intialise it before the Colours class.
  51575. */
  51576. jassert (Colours::white == Colour (0xffffffff));
  51577. // set up the standard set of colours..
  51578. const int textButtonColour = 0xffbbbbff;
  51579. const int textHighlightColour = 0x401111ee;
  51580. const int standardOutlineColour = 0xb2808080;
  51581. static const int standardColours[] =
  51582. {
  51583. TextButton::buttonColourId, textButtonColour,
  51584. TextButton::buttonOnColourId, 0xff4444ff,
  51585. TextButton::textColourOnId, 0xff000000,
  51586. TextButton::textColourOffId, 0xff000000,
  51587. ComboBox::buttonColourId, 0xffbbbbff,
  51588. ComboBox::outlineColourId, standardOutlineColour,
  51589. ToggleButton::textColourId, 0xff000000,
  51590. TextEditor::backgroundColourId, 0xffffffff,
  51591. TextEditor::textColourId, 0xff000000,
  51592. TextEditor::highlightColourId, textHighlightColour,
  51593. TextEditor::highlightedTextColourId, 0xff000000,
  51594. TextEditor::caretColourId, 0xff000000,
  51595. TextEditor::outlineColourId, 0x00000000,
  51596. TextEditor::focusedOutlineColourId, textButtonColour,
  51597. TextEditor::shadowColourId, 0x38000000,
  51598. Label::backgroundColourId, 0x00000000,
  51599. Label::textColourId, 0xff000000,
  51600. Label::outlineColourId, 0x00000000,
  51601. ScrollBar::backgroundColourId, 0x00000000,
  51602. ScrollBar::thumbColourId, 0xffffffff,
  51603. ScrollBar::trackColourId, 0xffffffff,
  51604. TreeView::linesColourId, 0x4c000000,
  51605. TreeView::backgroundColourId, 0x00000000,
  51606. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51607. PopupMenu::backgroundColourId, 0xffffffff,
  51608. PopupMenu::textColourId, 0xff000000,
  51609. PopupMenu::headerTextColourId, 0xff000000,
  51610. PopupMenu::highlightedTextColourId, 0xffffffff,
  51611. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51612. ComboBox::textColourId, 0xff000000,
  51613. ComboBox::backgroundColourId, 0xffffffff,
  51614. ComboBox::arrowColourId, 0x99000000,
  51615. ListBox::backgroundColourId, 0xffffffff,
  51616. ListBox::outlineColourId, standardOutlineColour,
  51617. ListBox::textColourId, 0xff000000,
  51618. Slider::backgroundColourId, 0x00000000,
  51619. Slider::thumbColourId, textButtonColour,
  51620. Slider::trackColourId, 0x7fffffff,
  51621. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51622. Slider::rotarySliderOutlineColourId, 0x66000000,
  51623. Slider::textBoxTextColourId, 0xff000000,
  51624. Slider::textBoxBackgroundColourId, 0xffffffff,
  51625. Slider::textBoxHighlightColourId, textHighlightColour,
  51626. Slider::textBoxOutlineColourId, standardOutlineColour,
  51627. ResizableWindow::backgroundColourId, 0xff777777,
  51628. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51629. AlertWindow::backgroundColourId, 0xffededed,
  51630. AlertWindow::textColourId, 0xff000000,
  51631. AlertWindow::outlineColourId, 0xff666666,
  51632. ProgressBar::backgroundColourId, 0xffeeeeee,
  51633. ProgressBar::foregroundColourId, 0xffaaaaee,
  51634. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51635. TooltipWindow::textColourId, 0xff000000,
  51636. TooltipWindow::outlineColourId, 0x4c000000,
  51637. TabbedComponent::backgroundColourId, 0x00000000,
  51638. TabbedComponent::outlineColourId, 0xff777777,
  51639. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51640. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51641. Toolbar::backgroundColourId, 0xfff6f8f9,
  51642. Toolbar::separatorColourId, 0x4c000000,
  51643. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51644. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51645. Toolbar::labelTextColourId, 0xff000000,
  51646. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51647. HyperlinkButton::textColourId, 0xcc1111ee,
  51648. GroupComponent::outlineColourId, 0x66000000,
  51649. GroupComponent::textColourId, 0xff000000,
  51650. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51651. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51652. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51653. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51654. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51655. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51656. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51657. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51658. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51659. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51660. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51661. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51662. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51663. CodeEditorComponent::caretColourId, 0xff000000,
  51664. CodeEditorComponent::highlightColourId, textHighlightColour,
  51665. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51666. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51667. ColourSelector::labelTextColourId, 0xff000000,
  51668. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51669. KeyMappingEditorComponent::textColourId, 0xff000000,
  51670. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51671. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51672. };
  51673. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51674. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51675. static String defaultSansName, defaultSerifName, defaultFixedName;
  51676. if (defaultSansName.isEmpty())
  51677. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51678. defaultSans = defaultSansName;
  51679. defaultSerif = defaultSerifName;
  51680. defaultFixed = defaultFixedName;
  51681. }
  51682. LookAndFeel::~LookAndFeel()
  51683. {
  51684. }
  51685. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51686. {
  51687. const int index = colourIds.indexOf (colourId);
  51688. if (index >= 0)
  51689. return colours [index];
  51690. jassertfalse;
  51691. return Colours::black;
  51692. }
  51693. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51694. {
  51695. const int index = colourIds.indexOf (colourId);
  51696. if (index >= 0)
  51697. {
  51698. colours.set (index, colour);
  51699. }
  51700. else
  51701. {
  51702. colourIds.add (colourId);
  51703. colours.add (colour);
  51704. }
  51705. }
  51706. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51707. {
  51708. return colourIds.contains (colourId);
  51709. }
  51710. static LookAndFeel* defaultLF = 0;
  51711. static LookAndFeel* currentDefaultLF = 0;
  51712. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51713. {
  51714. // if this happens, your app hasn't initialised itself properly.. if you're
  51715. // trying to hack your own main() function, have a look at
  51716. // JUCEApplication::initialiseForGUI()
  51717. jassert (currentDefaultLF != 0);
  51718. return *currentDefaultLF;
  51719. }
  51720. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51721. {
  51722. if (newDefaultLookAndFeel == 0)
  51723. {
  51724. if (defaultLF == 0)
  51725. defaultLF = new LookAndFeel();
  51726. newDefaultLookAndFeel = defaultLF;
  51727. }
  51728. currentDefaultLF = newDefaultLookAndFeel;
  51729. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51730. {
  51731. Component* const c = Desktop::getInstance().getComponent (i);
  51732. if (c != 0)
  51733. c->sendLookAndFeelChange();
  51734. }
  51735. }
  51736. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51737. {
  51738. if (currentDefaultLF == defaultLF)
  51739. currentDefaultLF = 0;
  51740. deleteAndZero (defaultLF);
  51741. }
  51742. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51743. {
  51744. String faceName (font.getTypefaceName());
  51745. if (faceName == Font::getDefaultSansSerifFontName())
  51746. faceName = defaultSans;
  51747. else if (faceName == Font::getDefaultSerifFontName())
  51748. faceName = defaultSerif;
  51749. else if (faceName == Font::getDefaultMonospacedFontName())
  51750. faceName = defaultFixed;
  51751. Font f (font);
  51752. f.setTypefaceName (faceName);
  51753. return Typeface::createSystemTypefaceFor (f);
  51754. }
  51755. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51756. {
  51757. defaultSans = newName;
  51758. }
  51759. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51760. {
  51761. return component.getMouseCursor();
  51762. }
  51763. void LookAndFeel::drawButtonBackground (Graphics& g,
  51764. Button& button,
  51765. const Colour& backgroundColour,
  51766. bool isMouseOverButton,
  51767. bool isButtonDown)
  51768. {
  51769. const int width = button.getWidth();
  51770. const int height = button.getHeight();
  51771. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51772. const float halfThickness = outlineThickness * 0.5f;
  51773. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51774. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51775. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51776. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51777. const Colour baseColour (createBaseColour (backgroundColour,
  51778. button.hasKeyboardFocus (true),
  51779. isMouseOverButton, isButtonDown)
  51780. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51781. drawGlassLozenge (g,
  51782. indentL,
  51783. indentT,
  51784. width - indentL - indentR,
  51785. height - indentT - indentB,
  51786. baseColour, outlineThickness, -1.0f,
  51787. button.isConnectedOnLeft(),
  51788. button.isConnectedOnRight(),
  51789. button.isConnectedOnTop(),
  51790. button.isConnectedOnBottom());
  51791. }
  51792. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51793. {
  51794. return button.getFont();
  51795. }
  51796. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51797. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51798. {
  51799. Font font (getFontForTextButton (button));
  51800. g.setFont (font);
  51801. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51802. : TextButton::textColourOffId)
  51803. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51804. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51805. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51806. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51807. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51808. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51809. g.drawFittedText (button.getButtonText(),
  51810. leftIndent,
  51811. yIndent,
  51812. button.getWidth() - leftIndent - rightIndent,
  51813. button.getHeight() - yIndent * 2,
  51814. Justification::centred, 2);
  51815. }
  51816. void LookAndFeel::drawTickBox (Graphics& g,
  51817. Component& component,
  51818. float x, float y, float w, float h,
  51819. const bool ticked,
  51820. const bool isEnabled,
  51821. const bool isMouseOverButton,
  51822. const bool isButtonDown)
  51823. {
  51824. const float boxSize = w * 0.7f;
  51825. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51826. createBaseColour (component.findColour (TextButton::buttonColourId)
  51827. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51828. true,
  51829. isMouseOverButton,
  51830. isButtonDown),
  51831. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51832. if (ticked)
  51833. {
  51834. Path tick;
  51835. tick.startNewSubPath (1.5f, 3.0f);
  51836. tick.lineTo (3.0f, 6.0f);
  51837. tick.lineTo (6.0f, 0.0f);
  51838. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51839. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51840. .translated (x, y));
  51841. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51842. }
  51843. }
  51844. void LookAndFeel::drawToggleButton (Graphics& g,
  51845. ToggleButton& button,
  51846. bool isMouseOverButton,
  51847. bool isButtonDown)
  51848. {
  51849. if (button.hasKeyboardFocus (true))
  51850. {
  51851. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51852. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51853. }
  51854. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51855. const float tickWidth = fontSize * 1.1f;
  51856. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51857. tickWidth, tickWidth,
  51858. button.getToggleState(),
  51859. button.isEnabled(),
  51860. isMouseOverButton,
  51861. isButtonDown);
  51862. g.setColour (button.findColour (ToggleButton::textColourId));
  51863. g.setFont (fontSize);
  51864. if (! button.isEnabled())
  51865. g.setOpacity (0.5f);
  51866. const int textX = (int) tickWidth + 5;
  51867. g.drawFittedText (button.getButtonText(),
  51868. textX, 0,
  51869. button.getWidth() - textX - 2, button.getHeight(),
  51870. Justification::centredLeft, 10);
  51871. }
  51872. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51873. {
  51874. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51875. const int tickWidth = jmin (24, button.getHeight());
  51876. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51877. button.getHeight());
  51878. }
  51879. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51880. const String& message,
  51881. const String& button1,
  51882. const String& button2,
  51883. const String& button3,
  51884. AlertWindow::AlertIconType iconType,
  51885. int numButtons,
  51886. Component* associatedComponent)
  51887. {
  51888. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51889. if (numButtons == 1)
  51890. {
  51891. aw->addButton (button1, 0,
  51892. KeyPress (KeyPress::escapeKey, 0, 0),
  51893. KeyPress (KeyPress::returnKey, 0, 0));
  51894. }
  51895. else
  51896. {
  51897. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51898. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51899. if (button1ShortCut == button2ShortCut)
  51900. button2ShortCut = KeyPress();
  51901. if (numButtons == 2)
  51902. {
  51903. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51904. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51905. }
  51906. else if (numButtons == 3)
  51907. {
  51908. aw->addButton (button1, 1, button1ShortCut);
  51909. aw->addButton (button2, 2, button2ShortCut);
  51910. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51911. }
  51912. }
  51913. return aw;
  51914. }
  51915. void LookAndFeel::drawAlertBox (Graphics& g,
  51916. AlertWindow& alert,
  51917. const Rectangle<int>& textArea,
  51918. TextLayout& textLayout)
  51919. {
  51920. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51921. int iconSpaceUsed = 0;
  51922. Justification alignment (Justification::horizontallyCentred);
  51923. const int iconWidth = 80;
  51924. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51925. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51926. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51927. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51928. iconSize, iconSize);
  51929. if (alert.getAlertType() != AlertWindow::NoIcon)
  51930. {
  51931. Path icon;
  51932. uint32 colour;
  51933. char character;
  51934. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51935. {
  51936. colour = 0x55ff5555;
  51937. character = '!';
  51938. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51939. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51940. (float) iconRect.getX(), (float) iconRect.getBottom());
  51941. icon = icon.createPathWithRoundedCorners (5.0f);
  51942. }
  51943. else
  51944. {
  51945. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51946. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51947. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51948. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51949. }
  51950. GlyphArrangement ga;
  51951. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51952. String::charToString (character),
  51953. (float) iconRect.getX(), (float) iconRect.getY(),
  51954. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51955. Justification::centred, false);
  51956. ga.createPath (icon);
  51957. icon.setUsingNonZeroWinding (false);
  51958. g.setColour (Colour (colour));
  51959. g.fillPath (icon);
  51960. iconSpaceUsed = iconWidth;
  51961. alignment = Justification::left;
  51962. }
  51963. g.setColour (alert.findColour (AlertWindow::textColourId));
  51964. textLayout.drawWithin (g,
  51965. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51966. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51967. alignment.getFlags() | Justification::top);
  51968. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51969. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51970. }
  51971. int LookAndFeel::getAlertBoxWindowFlags()
  51972. {
  51973. return ComponentPeer::windowAppearsOnTaskbar
  51974. | ComponentPeer::windowHasDropShadow;
  51975. }
  51976. int LookAndFeel::getAlertWindowButtonHeight()
  51977. {
  51978. return 28;
  51979. }
  51980. const Font LookAndFeel::getAlertWindowFont()
  51981. {
  51982. return Font (12.0f);
  51983. }
  51984. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51985. int width, int height,
  51986. double progress, const String& textToShow)
  51987. {
  51988. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51989. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51990. g.fillAll (background);
  51991. if (progress >= 0.0f && progress < 1.0f)
  51992. {
  51993. drawGlassLozenge (g, 1.0f, 1.0f,
  51994. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51995. (float) (height - 2),
  51996. foreground,
  51997. 0.5f, 0.0f,
  51998. true, true, true, true);
  51999. }
  52000. else
  52001. {
  52002. // spinning bar..
  52003. g.setColour (foreground);
  52004. const int stripeWidth = height * 2;
  52005. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52006. Path p;
  52007. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52008. p.addQuadrilateral (x, 0.0f,
  52009. x + stripeWidth * 0.5f, 0.0f,
  52010. x, (float) height,
  52011. x - stripeWidth * 0.5f, (float) height);
  52012. Image im (Image::ARGB, width, height, true);
  52013. {
  52014. Graphics g2 (im);
  52015. drawGlassLozenge (g2, 1.0f, 1.0f,
  52016. (float) (width - 2),
  52017. (float) (height - 2),
  52018. foreground,
  52019. 0.5f, 0.0f,
  52020. true, true, true, true);
  52021. }
  52022. g.setTiledImageFill (im, 0, 0, 0.85f);
  52023. g.fillPath (p);
  52024. }
  52025. if (textToShow.isNotEmpty())
  52026. {
  52027. g.setColour (Colour::contrasting (background, foreground));
  52028. g.setFont (height * 0.6f);
  52029. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52030. }
  52031. }
  52032. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52033. {
  52034. const float radius = jmin (w, h) * 0.4f;
  52035. const float thickness = radius * 0.15f;
  52036. Path p;
  52037. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52038. radius * 0.6f, thickness,
  52039. thickness * 0.5f);
  52040. const float cx = x + w * 0.5f;
  52041. const float cy = y + h * 0.5f;
  52042. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52043. for (int i = 0; i < 12; ++i)
  52044. {
  52045. const int n = (i + 12 - animationIndex) % 12;
  52046. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52047. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52048. .translated (cx, cy));
  52049. }
  52050. }
  52051. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52052. ScrollBar& scrollbar,
  52053. int width, int height,
  52054. int buttonDirection,
  52055. bool /*isScrollbarVertical*/,
  52056. bool /*isMouseOverButton*/,
  52057. bool isButtonDown)
  52058. {
  52059. Path p;
  52060. if (buttonDirection == 0)
  52061. p.addTriangle (width * 0.5f, height * 0.2f,
  52062. width * 0.1f, height * 0.7f,
  52063. width * 0.9f, height * 0.7f);
  52064. else if (buttonDirection == 1)
  52065. p.addTriangle (width * 0.8f, height * 0.5f,
  52066. width * 0.3f, height * 0.1f,
  52067. width * 0.3f, height * 0.9f);
  52068. else if (buttonDirection == 2)
  52069. p.addTriangle (width * 0.5f, height * 0.8f,
  52070. width * 0.1f, height * 0.3f,
  52071. width * 0.9f, height * 0.3f);
  52072. else if (buttonDirection == 3)
  52073. p.addTriangle (width * 0.2f, height * 0.5f,
  52074. width * 0.7f, height * 0.1f,
  52075. width * 0.7f, height * 0.9f);
  52076. if (isButtonDown)
  52077. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52078. else
  52079. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52080. g.fillPath (p);
  52081. g.setColour (Colour (0x80000000));
  52082. g.strokePath (p, PathStrokeType (0.5f));
  52083. }
  52084. void LookAndFeel::drawScrollbar (Graphics& g,
  52085. ScrollBar& scrollbar,
  52086. int x, int y,
  52087. int width, int height,
  52088. bool isScrollbarVertical,
  52089. int thumbStartPosition,
  52090. int thumbSize,
  52091. bool /*isMouseOver*/,
  52092. bool /*isMouseDown*/)
  52093. {
  52094. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52095. Path slotPath, thumbPath;
  52096. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52097. const float slotIndentx2 = slotIndent * 2.0f;
  52098. const float thumbIndent = slotIndent + 1.0f;
  52099. const float thumbIndentx2 = thumbIndent * 2.0f;
  52100. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52101. if (isScrollbarVertical)
  52102. {
  52103. slotPath.addRoundedRectangle (x + slotIndent,
  52104. y + slotIndent,
  52105. width - slotIndentx2,
  52106. height - slotIndentx2,
  52107. (width - slotIndentx2) * 0.5f);
  52108. if (thumbSize > 0)
  52109. thumbPath.addRoundedRectangle (x + thumbIndent,
  52110. thumbStartPosition + thumbIndent,
  52111. width - thumbIndentx2,
  52112. thumbSize - thumbIndentx2,
  52113. (width - thumbIndentx2) * 0.5f);
  52114. gx1 = (float) x;
  52115. gx2 = x + width * 0.7f;
  52116. }
  52117. else
  52118. {
  52119. slotPath.addRoundedRectangle (x + slotIndent,
  52120. y + slotIndent,
  52121. width - slotIndentx2,
  52122. height - slotIndentx2,
  52123. (height - slotIndentx2) * 0.5f);
  52124. if (thumbSize > 0)
  52125. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52126. y + thumbIndent,
  52127. thumbSize - thumbIndentx2,
  52128. height - thumbIndentx2,
  52129. (height - thumbIndentx2) * 0.5f);
  52130. gy1 = (float) y;
  52131. gy2 = y + height * 0.7f;
  52132. }
  52133. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52134. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52135. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52136. g.fillPath (slotPath);
  52137. if (isScrollbarVertical)
  52138. {
  52139. gx1 = x + width * 0.6f;
  52140. gx2 = (float) x + width;
  52141. }
  52142. else
  52143. {
  52144. gy1 = y + height * 0.6f;
  52145. gy2 = (float) y + height;
  52146. }
  52147. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52148. Colour (0x19000000), gx2, gy2, false));
  52149. g.fillPath (slotPath);
  52150. g.setColour (thumbColour);
  52151. g.fillPath (thumbPath);
  52152. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52153. Colours::transparentBlack, gx2, gy2, false));
  52154. g.saveState();
  52155. if (isScrollbarVertical)
  52156. g.reduceClipRegion (x + width / 2, y, width, height);
  52157. else
  52158. g.reduceClipRegion (x, y + height / 2, width, height);
  52159. g.fillPath (thumbPath);
  52160. g.restoreState();
  52161. g.setColour (Colour (0x4c000000));
  52162. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52163. }
  52164. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52165. {
  52166. return 0;
  52167. }
  52168. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52169. {
  52170. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52171. }
  52172. int LookAndFeel::getDefaultScrollbarWidth()
  52173. {
  52174. return 18;
  52175. }
  52176. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52177. {
  52178. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52179. : scrollbar.getHeight());
  52180. }
  52181. const Path LookAndFeel::getTickShape (const float height)
  52182. {
  52183. static const unsigned char tickShapeData[] =
  52184. {
  52185. 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,
  52186. 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,
  52187. 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,
  52188. 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,
  52189. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52190. };
  52191. Path p;
  52192. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52193. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52194. return p;
  52195. }
  52196. const Path LookAndFeel::getCrossShape (const float height)
  52197. {
  52198. static const unsigned char crossShapeData[] =
  52199. {
  52200. 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,
  52201. 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,
  52202. 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,
  52203. 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,
  52204. 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,
  52205. 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,
  52206. 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
  52207. };
  52208. Path p;
  52209. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52210. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52211. return p;
  52212. }
  52213. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52214. {
  52215. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52216. x += (w - boxSize) >> 1;
  52217. y += (h - boxSize) >> 1;
  52218. w = boxSize;
  52219. h = boxSize;
  52220. g.setColour (Colour (0xe5ffffff));
  52221. g.fillRect (x, y, w, h);
  52222. g.setColour (Colour (0x80000000));
  52223. g.drawRect (x, y, w, h);
  52224. const float size = boxSize / 2 + 1.0f;
  52225. const float centre = (float) (boxSize / 2);
  52226. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52227. if (isPlus)
  52228. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52229. }
  52230. void LookAndFeel::drawBubble (Graphics& g,
  52231. float tipX, float tipY,
  52232. float boxX, float boxY,
  52233. float boxW, float boxH)
  52234. {
  52235. int side = 0;
  52236. if (tipX < boxX)
  52237. side = 1;
  52238. else if (tipX > boxX + boxW)
  52239. side = 3;
  52240. else if (tipY > boxY + boxH)
  52241. side = 2;
  52242. const float indent = 2.0f;
  52243. Path p;
  52244. p.addBubble (boxX + indent,
  52245. boxY + indent,
  52246. boxW - indent * 2.0f,
  52247. boxH - indent * 2.0f,
  52248. 5.0f,
  52249. tipX, tipY,
  52250. side,
  52251. 0.5f,
  52252. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52253. //xxx need to take comp as param for colour
  52254. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52255. g.fillPath (p);
  52256. //xxx as above
  52257. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52258. g.strokePath (p, PathStrokeType (1.33f));
  52259. }
  52260. const Font LookAndFeel::getPopupMenuFont()
  52261. {
  52262. return Font (17.0f);
  52263. }
  52264. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52265. const bool isSeparator,
  52266. int standardMenuItemHeight,
  52267. int& idealWidth,
  52268. int& idealHeight)
  52269. {
  52270. if (isSeparator)
  52271. {
  52272. idealWidth = 50;
  52273. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52274. }
  52275. else
  52276. {
  52277. Font font (getPopupMenuFont());
  52278. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52279. font.setHeight (standardMenuItemHeight / 1.3f);
  52280. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52281. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52282. }
  52283. }
  52284. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52285. {
  52286. const Colour background (findColour (PopupMenu::backgroundColourId));
  52287. g.fillAll (background);
  52288. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52289. for (int i = 0; i < height; i += 3)
  52290. g.fillRect (0, i, width, 1);
  52291. #if ! JUCE_MAC
  52292. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52293. g.drawRect (0, 0, width, height);
  52294. #endif
  52295. }
  52296. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52297. int width, int height,
  52298. bool isScrollUpArrow)
  52299. {
  52300. const Colour background (findColour (PopupMenu::backgroundColourId));
  52301. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52302. background.withAlpha (0.0f),
  52303. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52304. false));
  52305. g.fillRect (1, 1, width - 2, height - 2);
  52306. const float hw = width * 0.5f;
  52307. const float arrowW = height * 0.3f;
  52308. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52309. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52310. Path p;
  52311. p.addTriangle (hw - arrowW, y1,
  52312. hw + arrowW, y1,
  52313. hw, y2);
  52314. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52315. g.fillPath (p);
  52316. }
  52317. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52318. int width, int height,
  52319. const bool isSeparator,
  52320. const bool isActive,
  52321. const bool isHighlighted,
  52322. const bool isTicked,
  52323. const bool hasSubMenu,
  52324. const String& text,
  52325. const String& shortcutKeyText,
  52326. Image* image,
  52327. const Colour* const textColourToUse)
  52328. {
  52329. const float halfH = height * 0.5f;
  52330. if (isSeparator)
  52331. {
  52332. const float separatorIndent = 5.5f;
  52333. g.setColour (Colour (0x33000000));
  52334. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52335. g.setColour (Colour (0x66ffffff));
  52336. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52337. }
  52338. else
  52339. {
  52340. Colour textColour (findColour (PopupMenu::textColourId));
  52341. if (textColourToUse != 0)
  52342. textColour = *textColourToUse;
  52343. if (isHighlighted)
  52344. {
  52345. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52346. g.fillRect (1, 1, width - 2, height - 2);
  52347. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52348. }
  52349. else
  52350. {
  52351. g.setColour (textColour);
  52352. }
  52353. if (! isActive)
  52354. g.setOpacity (0.3f);
  52355. Font font (getPopupMenuFont());
  52356. if (font.getHeight() > height / 1.3f)
  52357. font.setHeight (height / 1.3f);
  52358. g.setFont (font);
  52359. const int leftBorder = (height * 5) / 4;
  52360. const int rightBorder = 4;
  52361. if (image != 0)
  52362. {
  52363. g.drawImageWithin (*image,
  52364. 2, 1, leftBorder - 4, height - 2,
  52365. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52366. }
  52367. else if (isTicked)
  52368. {
  52369. const Path tick (getTickShape (1.0f));
  52370. const float th = font.getAscent();
  52371. const float ty = halfH - th * 0.5f;
  52372. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52373. th, true));
  52374. }
  52375. g.drawFittedText (text,
  52376. leftBorder, 0,
  52377. width - (leftBorder + rightBorder), height,
  52378. Justification::centredLeft, 1);
  52379. if (shortcutKeyText.isNotEmpty())
  52380. {
  52381. Font f2 (font);
  52382. f2.setHeight (f2.getHeight() * 0.75f);
  52383. f2.setHorizontalScale (0.95f);
  52384. g.setFont (f2);
  52385. g.drawText (shortcutKeyText,
  52386. leftBorder,
  52387. 0,
  52388. width - (leftBorder + rightBorder + 4),
  52389. height,
  52390. Justification::centredRight,
  52391. true);
  52392. }
  52393. if (hasSubMenu)
  52394. {
  52395. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52396. const float x = width - height * 0.6f;
  52397. Path p;
  52398. p.addTriangle (x, halfH - arrowH * 0.5f,
  52399. x, halfH + arrowH * 0.5f,
  52400. x + arrowH * 0.6f, halfH);
  52401. g.fillPath (p);
  52402. }
  52403. }
  52404. }
  52405. int LookAndFeel::getMenuWindowFlags()
  52406. {
  52407. return ComponentPeer::windowHasDropShadow;
  52408. }
  52409. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52410. bool, MenuBarComponent& menuBar)
  52411. {
  52412. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52413. if (menuBar.isEnabled())
  52414. {
  52415. drawShinyButtonShape (g,
  52416. -4.0f, 0.0f,
  52417. width + 8.0f, (float) height,
  52418. 0.0f,
  52419. baseColour,
  52420. 0.4f,
  52421. true, true, true, true);
  52422. }
  52423. else
  52424. {
  52425. g.fillAll (baseColour);
  52426. }
  52427. }
  52428. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52429. {
  52430. return Font (menuBar.getHeight() * 0.7f);
  52431. }
  52432. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52433. {
  52434. return getMenuBarFont (menuBar, itemIndex, itemText)
  52435. .getStringWidth (itemText) + menuBar.getHeight();
  52436. }
  52437. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52438. int width, int height,
  52439. int itemIndex,
  52440. const String& itemText,
  52441. bool isMouseOverItem,
  52442. bool isMenuOpen,
  52443. bool /*isMouseOverBar*/,
  52444. MenuBarComponent& menuBar)
  52445. {
  52446. if (! menuBar.isEnabled())
  52447. {
  52448. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52449. .withMultipliedAlpha (0.5f));
  52450. }
  52451. else if (isMenuOpen || isMouseOverItem)
  52452. {
  52453. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52454. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52455. }
  52456. else
  52457. {
  52458. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52459. }
  52460. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52461. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52462. }
  52463. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52464. TextEditor& textEditor)
  52465. {
  52466. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52467. }
  52468. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52469. {
  52470. if (textEditor.isEnabled())
  52471. {
  52472. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52473. {
  52474. const int border = 2;
  52475. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52476. g.drawRect (0, 0, width, height, border);
  52477. g.setOpacity (1.0f);
  52478. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52479. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52480. }
  52481. else
  52482. {
  52483. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52484. g.drawRect (0, 0, width, height);
  52485. g.setOpacity (1.0f);
  52486. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52487. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52488. }
  52489. }
  52490. }
  52491. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52492. const bool isButtonDown,
  52493. int buttonX, int buttonY,
  52494. int buttonW, int buttonH,
  52495. ComboBox& box)
  52496. {
  52497. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52498. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52499. {
  52500. g.setColour (box.findColour (TextButton::buttonColourId));
  52501. g.drawRect (0, 0, width, height, 2);
  52502. }
  52503. else
  52504. {
  52505. g.setColour (box.findColour (ComboBox::outlineColourId));
  52506. g.drawRect (0, 0, width, height);
  52507. }
  52508. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52509. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52510. box.hasKeyboardFocus (true),
  52511. false, isButtonDown)
  52512. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52513. drawGlassLozenge (g,
  52514. buttonX + outlineThickness, buttonY + outlineThickness,
  52515. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52516. baseColour, outlineThickness, -1.0f,
  52517. true, true, true, true);
  52518. if (box.isEnabled())
  52519. {
  52520. const float arrowX = 0.3f;
  52521. const float arrowH = 0.2f;
  52522. Path p;
  52523. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52524. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52525. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52526. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52527. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52528. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52529. g.setColour (box.findColour (ComboBox::arrowColourId));
  52530. g.fillPath (p);
  52531. }
  52532. }
  52533. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52534. {
  52535. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52536. }
  52537. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52538. {
  52539. return new Label (String::empty, String::empty);
  52540. }
  52541. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52542. {
  52543. label.setBounds (1, 1,
  52544. box.getWidth() + 3 - box.getHeight(),
  52545. box.getHeight() - 2);
  52546. label.setFont (getComboBoxFont (box));
  52547. }
  52548. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52549. {
  52550. g.fillAll (label.findColour (Label::backgroundColourId));
  52551. if (! label.isBeingEdited())
  52552. {
  52553. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52554. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52555. g.setFont (label.getFont());
  52556. g.drawFittedText (label.getText(),
  52557. label.getHorizontalBorderSize(),
  52558. label.getVerticalBorderSize(),
  52559. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52560. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52561. label.getJustificationType(),
  52562. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52563. label.getMinimumHorizontalScale());
  52564. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52565. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52566. }
  52567. else if (label.isEnabled())
  52568. {
  52569. g.setColour (label.findColour (Label::outlineColourId));
  52570. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52571. }
  52572. }
  52573. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52574. int x, int y,
  52575. int width, int height,
  52576. float /*sliderPos*/,
  52577. float /*minSliderPos*/,
  52578. float /*maxSliderPos*/,
  52579. const Slider::SliderStyle /*style*/,
  52580. Slider& slider)
  52581. {
  52582. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52583. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52584. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52585. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52586. Path indent;
  52587. if (slider.isHorizontal())
  52588. {
  52589. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52590. const float ih = sliderRadius;
  52591. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52592. gradCol2, 0.0f, iy + ih, false));
  52593. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52594. width + sliderRadius, ih,
  52595. 5.0f);
  52596. g.fillPath (indent);
  52597. }
  52598. else
  52599. {
  52600. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52601. const float iw = sliderRadius;
  52602. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52603. gradCol2, ix + iw, 0.0f, false));
  52604. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52605. iw, height + sliderRadius,
  52606. 5.0f);
  52607. g.fillPath (indent);
  52608. }
  52609. g.setColour (Colour (0x4c000000));
  52610. g.strokePath (indent, PathStrokeType (0.5f));
  52611. }
  52612. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52613. int x, int y,
  52614. int width, int height,
  52615. float sliderPos,
  52616. float minSliderPos,
  52617. float maxSliderPos,
  52618. const Slider::SliderStyle style,
  52619. Slider& slider)
  52620. {
  52621. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52622. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52623. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52624. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52625. slider.isMouseButtonDown() && slider.isEnabled()));
  52626. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52627. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52628. {
  52629. float kx, ky;
  52630. if (style == Slider::LinearVertical)
  52631. {
  52632. kx = x + width * 0.5f;
  52633. ky = sliderPos;
  52634. }
  52635. else
  52636. {
  52637. kx = sliderPos;
  52638. ky = y + height * 0.5f;
  52639. }
  52640. drawGlassSphere (g,
  52641. kx - sliderRadius,
  52642. ky - sliderRadius,
  52643. sliderRadius * 2.0f,
  52644. knobColour, outlineThickness);
  52645. }
  52646. else
  52647. {
  52648. if (style == Slider::ThreeValueVertical)
  52649. {
  52650. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52651. sliderPos - sliderRadius,
  52652. sliderRadius * 2.0f,
  52653. knobColour, outlineThickness);
  52654. }
  52655. else if (style == Slider::ThreeValueHorizontal)
  52656. {
  52657. drawGlassSphere (g,sliderPos - sliderRadius,
  52658. y + height * 0.5f - sliderRadius,
  52659. sliderRadius * 2.0f,
  52660. knobColour, outlineThickness);
  52661. }
  52662. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52663. {
  52664. const float sr = jmin (sliderRadius, width * 0.4f);
  52665. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52666. minSliderPos - sliderRadius,
  52667. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52668. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52669. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52670. }
  52671. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52672. {
  52673. const float sr = jmin (sliderRadius, height * 0.4f);
  52674. drawGlassPointer (g, minSliderPos - sr,
  52675. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52676. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52677. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52678. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52679. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52680. }
  52681. }
  52682. }
  52683. void LookAndFeel::drawLinearSlider (Graphics& g,
  52684. int x, int y,
  52685. int width, int height,
  52686. float sliderPos,
  52687. float minSliderPos,
  52688. float maxSliderPos,
  52689. const Slider::SliderStyle style,
  52690. Slider& slider)
  52691. {
  52692. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52693. if (style == Slider::LinearBar)
  52694. {
  52695. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52696. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52697. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52698. false,
  52699. isMouseOver,
  52700. isMouseOver || slider.isMouseButtonDown()));
  52701. drawShinyButtonShape (g,
  52702. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52703. baseColour,
  52704. slider.isEnabled() ? 0.9f : 0.3f,
  52705. true, true, true, true);
  52706. }
  52707. else
  52708. {
  52709. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52710. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52711. }
  52712. }
  52713. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52714. {
  52715. return jmin (7,
  52716. slider.getHeight() / 2,
  52717. slider.getWidth() / 2) + 2;
  52718. }
  52719. void LookAndFeel::drawRotarySlider (Graphics& g,
  52720. int x, int y,
  52721. int width, int height,
  52722. float sliderPos,
  52723. const float rotaryStartAngle,
  52724. const float rotaryEndAngle,
  52725. Slider& slider)
  52726. {
  52727. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52728. const float centreX = x + width * 0.5f;
  52729. const float centreY = y + height * 0.5f;
  52730. const float rx = centreX - radius;
  52731. const float ry = centreY - radius;
  52732. const float rw = radius * 2.0f;
  52733. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52734. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52735. if (radius > 12.0f)
  52736. {
  52737. if (slider.isEnabled())
  52738. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52739. else
  52740. g.setColour (Colour (0x80808080));
  52741. const float thickness = 0.7f;
  52742. {
  52743. Path filledArc;
  52744. filledArc.addPieSegment (rx, ry, rw, rw,
  52745. rotaryStartAngle,
  52746. angle,
  52747. thickness);
  52748. g.fillPath (filledArc);
  52749. }
  52750. if (thickness > 0)
  52751. {
  52752. const float innerRadius = radius * 0.2f;
  52753. Path p;
  52754. p.addTriangle (-innerRadius, 0.0f,
  52755. 0.0f, -radius * thickness * 1.1f,
  52756. innerRadius, 0.0f);
  52757. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52758. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52759. }
  52760. if (slider.isEnabled())
  52761. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52762. else
  52763. g.setColour (Colour (0x80808080));
  52764. Path outlineArc;
  52765. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52766. outlineArc.closeSubPath();
  52767. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52768. }
  52769. else
  52770. {
  52771. if (slider.isEnabled())
  52772. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52773. else
  52774. g.setColour (Colour (0x80808080));
  52775. Path p;
  52776. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52777. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52778. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52779. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52780. }
  52781. }
  52782. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52783. {
  52784. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52785. }
  52786. class SliderLabelComp : public Label
  52787. {
  52788. public:
  52789. SliderLabelComp() : Label (String::empty, String::empty) {}
  52790. ~SliderLabelComp() {}
  52791. void mouseWheelMove (const MouseEvent&, float, float) {}
  52792. };
  52793. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52794. {
  52795. Label* const l = new SliderLabelComp();
  52796. l->setJustificationType (Justification::centred);
  52797. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52798. l->setColour (Label::backgroundColourId,
  52799. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52800. : slider.findColour (Slider::textBoxBackgroundColourId));
  52801. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52802. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52803. l->setColour (TextEditor::backgroundColourId,
  52804. slider.findColour (Slider::textBoxBackgroundColourId)
  52805. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52806. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52807. return l;
  52808. }
  52809. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52810. {
  52811. return 0;
  52812. }
  52813. static const TextLayout layoutTooltipText (const String& text) throw()
  52814. {
  52815. const float tooltipFontSize = 12.0f;
  52816. const int maxToolTipWidth = 400;
  52817. const Font f (tooltipFontSize, Font::bold);
  52818. TextLayout tl (text, f);
  52819. tl.layout (maxToolTipWidth, Justification::left, true);
  52820. return tl;
  52821. }
  52822. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52823. {
  52824. const TextLayout tl (layoutTooltipText (tipText));
  52825. width = tl.getWidth() + 14;
  52826. height = tl.getHeight() + 6;
  52827. }
  52828. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52829. {
  52830. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52831. const Colour textCol (findColour (TooltipWindow::textColourId));
  52832. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52833. g.setColour (findColour (TooltipWindow::outlineColourId));
  52834. g.drawRect (0, 0, width, height, 1);
  52835. #endif
  52836. const TextLayout tl (layoutTooltipText (text));
  52837. g.setColour (findColour (TooltipWindow::textColourId));
  52838. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52839. }
  52840. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52841. {
  52842. return new TextButton (text, TRANS("click to browse for a different file"));
  52843. }
  52844. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52845. ComboBox* filenameBox,
  52846. Button* browseButton)
  52847. {
  52848. browseButton->setSize (80, filenameComp.getHeight());
  52849. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52850. if (tb != 0)
  52851. tb->changeWidthToFitText();
  52852. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52853. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52854. }
  52855. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52856. int imageX, int imageY, int imageW, int imageH,
  52857. const Colour& overlayColour,
  52858. float imageOpacity,
  52859. ImageButton& button)
  52860. {
  52861. if (! button.isEnabled())
  52862. imageOpacity *= 0.3f;
  52863. if (! overlayColour.isOpaque())
  52864. {
  52865. g.setOpacity (imageOpacity);
  52866. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52867. 0, 0, image->getWidth(), image->getHeight(), false);
  52868. }
  52869. if (! overlayColour.isTransparent())
  52870. {
  52871. g.setColour (overlayColour);
  52872. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52873. 0, 0, image->getWidth(), image->getHeight(), true);
  52874. }
  52875. }
  52876. void LookAndFeel::drawCornerResizer (Graphics& g,
  52877. int w, int h,
  52878. bool /*isMouseOver*/,
  52879. bool /*isMouseDragging*/)
  52880. {
  52881. const float lineThickness = jmin (w, h) * 0.075f;
  52882. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52883. {
  52884. g.setColour (Colours::lightgrey);
  52885. g.drawLine (w * i,
  52886. h + 1.0f,
  52887. w + 1.0f,
  52888. h * i,
  52889. lineThickness);
  52890. g.setColour (Colours::darkgrey);
  52891. g.drawLine (w * i + lineThickness,
  52892. h + 1.0f,
  52893. w + 1.0f,
  52894. h * i + lineThickness,
  52895. lineThickness);
  52896. }
  52897. }
  52898. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52899. const BorderSize& /*borders*/)
  52900. {
  52901. }
  52902. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52903. const BorderSize& /*border*/, ResizableWindow& window)
  52904. {
  52905. g.fillAll (window.getBackgroundColour());
  52906. }
  52907. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52908. const BorderSize& border, ResizableWindow&)
  52909. {
  52910. g.setColour (Colour (0x80000000));
  52911. g.drawRect (0, 0, w, h);
  52912. g.setColour (Colour (0x19000000));
  52913. g.drawRect (border.getLeft() - 1,
  52914. border.getTop() - 1,
  52915. w + 2 - border.getLeftAndRight(),
  52916. h + 2 - border.getTopAndBottom());
  52917. }
  52918. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52919. Graphics& g, int w, int h,
  52920. int titleSpaceX, int titleSpaceW,
  52921. const Image* icon,
  52922. bool drawTitleTextOnLeft)
  52923. {
  52924. const bool isActive = window.isActiveWindow();
  52925. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52926. 0.0f, 0.0f,
  52927. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52928. 0.0f, (float) h, false));
  52929. g.fillAll();
  52930. Font font (h * 0.65f, Font::bold);
  52931. g.setFont (font);
  52932. int textW = font.getStringWidth (window.getName());
  52933. int iconW = 0;
  52934. int iconH = 0;
  52935. if (icon != 0)
  52936. {
  52937. iconH = (int) font.getHeight();
  52938. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52939. }
  52940. textW = jmin (titleSpaceW, textW + iconW);
  52941. int textX = drawTitleTextOnLeft ? titleSpaceX
  52942. : jmax (titleSpaceX, (w - textW) / 2);
  52943. if (textX + textW > titleSpaceX + titleSpaceW)
  52944. textX = titleSpaceX + titleSpaceW - textW;
  52945. if (icon != 0)
  52946. {
  52947. g.setOpacity (isActive ? 1.0f : 0.6f);
  52948. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52949. RectanglePlacement::centred, false);
  52950. textX += iconW;
  52951. textW -= iconW;
  52952. }
  52953. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52954. g.setColour (findColour (DocumentWindow::textColourId));
  52955. else
  52956. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52957. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52958. }
  52959. class GlassWindowButton : public Button
  52960. {
  52961. public:
  52962. GlassWindowButton (const String& name, const Colour& col,
  52963. const Path& normalShape_,
  52964. const Path& toggledShape_) throw()
  52965. : Button (name),
  52966. colour (col),
  52967. normalShape (normalShape_),
  52968. toggledShape (toggledShape_)
  52969. {
  52970. }
  52971. ~GlassWindowButton()
  52972. {
  52973. }
  52974. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52975. {
  52976. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52977. if (! isEnabled())
  52978. alpha *= 0.5f;
  52979. float x = 0, y = 0, diam;
  52980. if (getWidth() < getHeight())
  52981. {
  52982. diam = (float) getWidth();
  52983. y = (getHeight() - getWidth()) * 0.5f;
  52984. }
  52985. else
  52986. {
  52987. diam = (float) getHeight();
  52988. y = (getWidth() - getHeight()) * 0.5f;
  52989. }
  52990. x += diam * 0.05f;
  52991. y += diam * 0.05f;
  52992. diam *= 0.9f;
  52993. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52994. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52995. g.fillEllipse (x, y, diam, diam);
  52996. x += 2.0f;
  52997. y += 2.0f;
  52998. diam -= 4.0f;
  52999. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53000. Path& p = getToggleState() ? toggledShape : normalShape;
  53001. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53002. diam * 0.4f, diam * 0.4f, true));
  53003. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53004. g.fillPath (p, t);
  53005. }
  53006. juce_UseDebuggingNewOperator
  53007. private:
  53008. Colour colour;
  53009. Path normalShape, toggledShape;
  53010. GlassWindowButton (const GlassWindowButton&);
  53011. GlassWindowButton& operator= (const GlassWindowButton&);
  53012. };
  53013. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53014. {
  53015. Path shape;
  53016. const float crossThickness = 0.25f;
  53017. if (buttonType == DocumentWindow::closeButton)
  53018. {
  53019. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53020. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53021. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53022. }
  53023. else if (buttonType == DocumentWindow::minimiseButton)
  53024. {
  53025. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53026. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53027. }
  53028. else if (buttonType == DocumentWindow::maximiseButton)
  53029. {
  53030. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53031. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53032. Path fullscreenShape;
  53033. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53034. fullscreenShape.lineTo (0.0f, 100.0f);
  53035. fullscreenShape.lineTo (0.0f, 0.0f);
  53036. fullscreenShape.lineTo (100.0f, 0.0f);
  53037. fullscreenShape.lineTo (100.0f, 45.0f);
  53038. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53039. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53040. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53041. }
  53042. jassertfalse;
  53043. return 0;
  53044. }
  53045. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53046. int titleBarX,
  53047. int titleBarY,
  53048. int titleBarW,
  53049. int titleBarH,
  53050. Button* minimiseButton,
  53051. Button* maximiseButton,
  53052. Button* closeButton,
  53053. bool positionTitleBarButtonsOnLeft)
  53054. {
  53055. const int buttonW = titleBarH - titleBarH / 8;
  53056. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53057. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53058. if (closeButton != 0)
  53059. {
  53060. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53061. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53062. }
  53063. if (positionTitleBarButtonsOnLeft)
  53064. swapVariables (minimiseButton, maximiseButton);
  53065. if (maximiseButton != 0)
  53066. {
  53067. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53068. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53069. }
  53070. if (minimiseButton != 0)
  53071. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53072. }
  53073. int LookAndFeel::getDefaultMenuBarHeight()
  53074. {
  53075. return 24;
  53076. }
  53077. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53078. {
  53079. return new DropShadower (0.4f, 1, 5, 10);
  53080. }
  53081. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53082. int w, int h,
  53083. bool /*isVerticalBar*/,
  53084. bool isMouseOver,
  53085. bool isMouseDragging)
  53086. {
  53087. float alpha = 0.5f;
  53088. if (isMouseOver || isMouseDragging)
  53089. {
  53090. g.fillAll (Colour (0x190000ff));
  53091. alpha = 1.0f;
  53092. }
  53093. const float cx = w * 0.5f;
  53094. const float cy = h * 0.5f;
  53095. const float cr = jmin (w, h) * 0.4f;
  53096. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53097. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53098. true));
  53099. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53100. }
  53101. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53102. const String& text,
  53103. const Justification& position,
  53104. GroupComponent& group)
  53105. {
  53106. const float textH = 15.0f;
  53107. const float indent = 3.0f;
  53108. const float textEdgeGap = 4.0f;
  53109. float cs = 5.0f;
  53110. Font f (textH);
  53111. Path p;
  53112. float x = indent;
  53113. float y = f.getAscent() - 3.0f;
  53114. float w = jmax (0.0f, width - x * 2.0f);
  53115. float h = jmax (0.0f, height - y - indent);
  53116. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53117. const float cs2 = 2.0f * cs;
  53118. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53119. float textX = cs + textEdgeGap;
  53120. if (position.testFlags (Justification::horizontallyCentred))
  53121. textX = cs + (w - cs2 - textW) * 0.5f;
  53122. else if (position.testFlags (Justification::right))
  53123. textX = w - cs - textW - textEdgeGap;
  53124. p.startNewSubPath (x + textX + textW, y);
  53125. p.lineTo (x + w - cs, y);
  53126. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53127. p.lineTo (x + w, y + h - cs);
  53128. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53129. p.lineTo (x + cs, y + h);
  53130. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53131. p.lineTo (x, y + cs);
  53132. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53133. p.lineTo (x + textX, y);
  53134. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53135. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53136. .withMultipliedAlpha (alpha));
  53137. g.strokePath (p, PathStrokeType (2.0f));
  53138. g.setColour (group.findColour (GroupComponent::textColourId)
  53139. .withMultipliedAlpha (alpha));
  53140. g.setFont (f);
  53141. g.drawText (text,
  53142. roundToInt (x + textX), 0,
  53143. roundToInt (textW),
  53144. roundToInt (textH),
  53145. Justification::centred, true);
  53146. }
  53147. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53148. {
  53149. return 1 + tabDepth / 3;
  53150. }
  53151. int LookAndFeel::getTabButtonSpaceAroundImage()
  53152. {
  53153. return 4;
  53154. }
  53155. void LookAndFeel::createTabButtonShape (Path& p,
  53156. int width, int height,
  53157. int /*tabIndex*/,
  53158. const String& /*text*/,
  53159. Button& /*button*/,
  53160. TabbedButtonBar::Orientation orientation,
  53161. const bool /*isMouseOver*/,
  53162. const bool /*isMouseDown*/,
  53163. const bool /*isFrontTab*/)
  53164. {
  53165. const float w = (float) width;
  53166. const float h = (float) height;
  53167. float length = w;
  53168. float depth = h;
  53169. if (orientation == TabbedButtonBar::TabsAtLeft
  53170. || orientation == TabbedButtonBar::TabsAtRight)
  53171. {
  53172. swapVariables (length, depth);
  53173. }
  53174. const float indent = (float) getTabButtonOverlap ((int) depth);
  53175. const float overhang = 4.0f;
  53176. if (orientation == TabbedButtonBar::TabsAtLeft)
  53177. {
  53178. p.startNewSubPath (w, 0.0f);
  53179. p.lineTo (0.0f, indent);
  53180. p.lineTo (0.0f, h - indent);
  53181. p.lineTo (w, h);
  53182. p.lineTo (w + overhang, h + overhang);
  53183. p.lineTo (w + overhang, -overhang);
  53184. }
  53185. else if (orientation == TabbedButtonBar::TabsAtRight)
  53186. {
  53187. p.startNewSubPath (0.0f, 0.0f);
  53188. p.lineTo (w, indent);
  53189. p.lineTo (w, h - indent);
  53190. p.lineTo (0.0f, h);
  53191. p.lineTo (-overhang, h + overhang);
  53192. p.lineTo (-overhang, -overhang);
  53193. }
  53194. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53195. {
  53196. p.startNewSubPath (0.0f, 0.0f);
  53197. p.lineTo (indent, h);
  53198. p.lineTo (w - indent, h);
  53199. p.lineTo (w, 0.0f);
  53200. p.lineTo (w + overhang, -overhang);
  53201. p.lineTo (-overhang, -overhang);
  53202. }
  53203. else
  53204. {
  53205. p.startNewSubPath (0.0f, h);
  53206. p.lineTo (indent, 0.0f);
  53207. p.lineTo (w - indent, 0.0f);
  53208. p.lineTo (w, h);
  53209. p.lineTo (w + overhang, h + overhang);
  53210. p.lineTo (-overhang, h + overhang);
  53211. }
  53212. p.closeSubPath();
  53213. p = p.createPathWithRoundedCorners (3.0f);
  53214. }
  53215. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53216. const Path& path,
  53217. const Colour& preferredColour,
  53218. int /*tabIndex*/,
  53219. const String& /*text*/,
  53220. Button& button,
  53221. TabbedButtonBar::Orientation /*orientation*/,
  53222. const bool /*isMouseOver*/,
  53223. const bool /*isMouseDown*/,
  53224. const bool isFrontTab)
  53225. {
  53226. g.setColour (isFrontTab ? preferredColour
  53227. : preferredColour.withMultipliedAlpha (0.9f));
  53228. g.fillPath (path);
  53229. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53230. : TabbedButtonBar::tabOutlineColourId, false)
  53231. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53232. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53233. }
  53234. void LookAndFeel::drawTabButtonText (Graphics& g,
  53235. int x, int y, int w, int h,
  53236. const Colour& preferredBackgroundColour,
  53237. int /*tabIndex*/,
  53238. const String& text,
  53239. Button& button,
  53240. TabbedButtonBar::Orientation orientation,
  53241. const bool isMouseOver,
  53242. const bool isMouseDown,
  53243. const bool isFrontTab)
  53244. {
  53245. int length = w;
  53246. int depth = h;
  53247. if (orientation == TabbedButtonBar::TabsAtLeft
  53248. || orientation == TabbedButtonBar::TabsAtRight)
  53249. {
  53250. swapVariables (length, depth);
  53251. }
  53252. Font font (depth * 0.6f);
  53253. font.setUnderline (button.hasKeyboardFocus (false));
  53254. GlyphArrangement textLayout;
  53255. textLayout.addFittedText (font, text.trim(),
  53256. 0.0f, 0.0f, (float) length, (float) depth,
  53257. Justification::centred,
  53258. jmax (1, depth / 12));
  53259. AffineTransform transform;
  53260. if (orientation == TabbedButtonBar::TabsAtLeft)
  53261. {
  53262. transform = transform.rotated (float_Pi * -0.5f)
  53263. .translated ((float) x, (float) (y + h));
  53264. }
  53265. else if (orientation == TabbedButtonBar::TabsAtRight)
  53266. {
  53267. transform = transform.rotated (float_Pi * 0.5f)
  53268. .translated ((float) (x + w), (float) y);
  53269. }
  53270. else
  53271. {
  53272. transform = transform.translated ((float) x, (float) y);
  53273. }
  53274. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53275. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53276. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53277. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53278. else
  53279. g.setColour (preferredBackgroundColour.contrasting());
  53280. if (! (isMouseOver || isMouseDown))
  53281. g.setOpacity (0.8f);
  53282. if (! button.isEnabled())
  53283. g.setOpacity (0.3f);
  53284. textLayout.draw (g, transform);
  53285. }
  53286. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53287. const String& text,
  53288. int tabDepth,
  53289. Button&)
  53290. {
  53291. Font f (tabDepth * 0.6f);
  53292. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53293. }
  53294. void LookAndFeel::drawTabButton (Graphics& g,
  53295. int w, int h,
  53296. const Colour& preferredColour,
  53297. int tabIndex,
  53298. const String& text,
  53299. Button& button,
  53300. TabbedButtonBar::Orientation orientation,
  53301. const bool isMouseOver,
  53302. const bool isMouseDown,
  53303. const bool isFrontTab)
  53304. {
  53305. int length = w;
  53306. int depth = h;
  53307. if (orientation == TabbedButtonBar::TabsAtLeft
  53308. || orientation == TabbedButtonBar::TabsAtRight)
  53309. {
  53310. swapVariables (length, depth);
  53311. }
  53312. Path tabShape;
  53313. createTabButtonShape (tabShape, w, h,
  53314. tabIndex, text, button, orientation,
  53315. isMouseOver, isMouseDown, isFrontTab);
  53316. fillTabButtonShape (g, tabShape, preferredColour,
  53317. tabIndex, text, button, orientation,
  53318. isMouseOver, isMouseDown, isFrontTab);
  53319. const int indent = getTabButtonOverlap (depth);
  53320. int x = 0, y = 0;
  53321. if (orientation == TabbedButtonBar::TabsAtLeft
  53322. || orientation == TabbedButtonBar::TabsAtRight)
  53323. {
  53324. y += indent;
  53325. h -= indent * 2;
  53326. }
  53327. else
  53328. {
  53329. x += indent;
  53330. w -= indent * 2;
  53331. }
  53332. drawTabButtonText (g, x, y, w, h, preferredColour,
  53333. tabIndex, text, button, orientation,
  53334. isMouseOver, isMouseDown, isFrontTab);
  53335. }
  53336. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53337. int w, int h,
  53338. TabbedButtonBar& tabBar,
  53339. TabbedButtonBar::Orientation orientation)
  53340. {
  53341. const float shadowSize = 0.2f;
  53342. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53343. Rectangle<int> shadowRect;
  53344. if (orientation == TabbedButtonBar::TabsAtLeft)
  53345. {
  53346. x1 = (float) w;
  53347. x2 = w * (1.0f - shadowSize);
  53348. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53349. }
  53350. else if (orientation == TabbedButtonBar::TabsAtRight)
  53351. {
  53352. x2 = w * shadowSize;
  53353. shadowRect.setBounds (0, 0, (int) x2, h);
  53354. }
  53355. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53356. {
  53357. y2 = h * shadowSize;
  53358. shadowRect.setBounds (0, 0, w, (int) y2);
  53359. }
  53360. else
  53361. {
  53362. y1 = (float) h;
  53363. y2 = h * (1.0f - shadowSize);
  53364. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53365. }
  53366. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53367. Colours::transparentBlack, x2, y2, false));
  53368. shadowRect.expand (2, 2);
  53369. g.fillRect (shadowRect);
  53370. g.setColour (Colour (0x80000000));
  53371. if (orientation == TabbedButtonBar::TabsAtLeft)
  53372. {
  53373. g.fillRect (w - 1, 0, 1, h);
  53374. }
  53375. else if (orientation == TabbedButtonBar::TabsAtRight)
  53376. {
  53377. g.fillRect (0, 0, 1, h);
  53378. }
  53379. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53380. {
  53381. g.fillRect (0, 0, w, 1);
  53382. }
  53383. else
  53384. {
  53385. g.fillRect (0, h - 1, w, 1);
  53386. }
  53387. }
  53388. Button* LookAndFeel::createTabBarExtrasButton()
  53389. {
  53390. const float thickness = 7.0f;
  53391. const float indent = 22.0f;
  53392. Path p;
  53393. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53394. DrawablePath ellipse;
  53395. ellipse.setPath (p);
  53396. ellipse.setFill (Colour (0x99ffffff));
  53397. p.clear();
  53398. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53399. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53400. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53401. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53402. p.setUsingNonZeroWinding (false);
  53403. DrawablePath dp;
  53404. dp.setPath (p);
  53405. dp.setFill (Colour (0x59000000));
  53406. DrawableComposite normalImage;
  53407. normalImage.insertDrawable (ellipse);
  53408. normalImage.insertDrawable (dp);
  53409. dp.setFill (Colour (0xcc000000));
  53410. DrawableComposite overImage;
  53411. overImage.insertDrawable (ellipse);
  53412. overImage.insertDrawable (dp);
  53413. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53414. db->setImages (&normalImage, &overImage, 0);
  53415. return db;
  53416. }
  53417. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53418. {
  53419. g.fillAll (Colours::white);
  53420. const int w = header.getWidth();
  53421. const int h = header.getHeight();
  53422. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53423. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53424. false));
  53425. g.fillRect (0, h / 2, w, h);
  53426. g.setColour (Colour (0x33000000));
  53427. g.fillRect (0, h - 1, w, 1);
  53428. for (int i = header.getNumColumns (true); --i >= 0;)
  53429. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53430. }
  53431. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53432. int width, int height,
  53433. bool isMouseOver, bool isMouseDown,
  53434. int columnFlags)
  53435. {
  53436. if (isMouseDown)
  53437. g.fillAll (Colour (0x8899aadd));
  53438. else if (isMouseOver)
  53439. g.fillAll (Colour (0x5599aadd));
  53440. int rightOfText = width - 4;
  53441. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53442. {
  53443. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53444. const float bottom = height - top;
  53445. const float w = height * 0.5f;
  53446. const float x = rightOfText - (w * 1.25f);
  53447. rightOfText = (int) x;
  53448. Path sortArrow;
  53449. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53450. g.setColour (Colour (0x99000000));
  53451. g.fillPath (sortArrow);
  53452. }
  53453. g.setColour (Colours::black);
  53454. g.setFont (height * 0.5f, Font::bold);
  53455. const int textX = 4;
  53456. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53457. }
  53458. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53459. {
  53460. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53461. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53462. background.darker (0.1f),
  53463. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53464. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53465. false));
  53466. g.fillAll();
  53467. }
  53468. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53469. {
  53470. return createTabBarExtrasButton();
  53471. }
  53472. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53473. bool isMouseOver, bool isMouseDown,
  53474. ToolbarItemComponent& component)
  53475. {
  53476. if (isMouseDown)
  53477. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53478. else if (isMouseOver)
  53479. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53480. }
  53481. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53482. const String& text, ToolbarItemComponent& component)
  53483. {
  53484. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53485. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53486. const float fontHeight = jmin (14.0f, height * 0.85f);
  53487. g.setFont (fontHeight);
  53488. g.drawFittedText (text,
  53489. x, y, width, height,
  53490. Justification::centred,
  53491. jmax (1, height / (int) fontHeight));
  53492. }
  53493. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53494. bool isOpen, int width, int height)
  53495. {
  53496. const int buttonSize = (height * 3) / 4;
  53497. const int buttonIndent = (height - buttonSize) / 2;
  53498. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53499. const int textX = buttonIndent * 2 + buttonSize + 2;
  53500. g.setColour (Colours::black);
  53501. g.setFont (height * 0.7f, Font::bold);
  53502. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53503. }
  53504. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53505. PropertyComponent&)
  53506. {
  53507. g.setColour (Colour (0x66ffffff));
  53508. g.fillRect (0, 0, width, height - 1);
  53509. }
  53510. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53511. PropertyComponent& component)
  53512. {
  53513. g.setColour (Colours::black);
  53514. if (! component.isEnabled())
  53515. g.setOpacity (0.6f);
  53516. g.setFont (jmin (height, 24) * 0.65f);
  53517. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53518. g.drawFittedText (component.getName(),
  53519. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53520. Justification::centredLeft, 2);
  53521. }
  53522. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53523. {
  53524. return Rectangle<int> (component.getWidth() / 3, 1,
  53525. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53526. }
  53527. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53528. {
  53529. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53530. {
  53531. Graphics g2 (content);
  53532. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53533. g2.fillPath (path);
  53534. g2.setColour (Colours::white.withAlpha (0.8f));
  53535. g2.strokePath (path, PathStrokeType (2.0f));
  53536. }
  53537. DropShadowEffect shadow;
  53538. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53539. shadow.applyEffect (content, g);
  53540. }
  53541. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53542. const String& instructions,
  53543. GlyphArrangement& text,
  53544. int width)
  53545. {
  53546. text.clear();
  53547. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53548. 8.0f, 22.0f, width - 16.0f,
  53549. Justification::centred);
  53550. text.addJustifiedText (Font (14.0f), instructions,
  53551. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53552. Justification::centred);
  53553. }
  53554. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53555. const String& filename, Image* icon,
  53556. const String& fileSizeDescription,
  53557. const String& fileTimeDescription,
  53558. const bool isDirectory,
  53559. const bool isItemSelected,
  53560. const int /*itemIndex*/)
  53561. {
  53562. if (isItemSelected)
  53563. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53564. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53565. g.setFont (height * 0.7f);
  53566. Image im;
  53567. if (icon != 0)
  53568. im = *icon;
  53569. if (im.isNull())
  53570. im = isDirectory ? getDefaultFolderImage()
  53571. : getDefaultDocumentFileImage();
  53572. const int x = 32;
  53573. if (im.isValid())
  53574. {
  53575. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53576. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53577. false);
  53578. }
  53579. if (width > 450 && ! isDirectory)
  53580. {
  53581. const int sizeX = roundToInt (width * 0.7f);
  53582. const int dateX = roundToInt (width * 0.8f);
  53583. g.drawFittedText (filename,
  53584. x, 0, sizeX - x, height,
  53585. Justification::centredLeft, 1);
  53586. g.setFont (height * 0.5f);
  53587. g.setColour (Colours::darkgrey);
  53588. if (! isDirectory)
  53589. {
  53590. g.drawFittedText (fileSizeDescription,
  53591. sizeX, 0, dateX - sizeX - 8, height,
  53592. Justification::centredRight, 1);
  53593. g.drawFittedText (fileTimeDescription,
  53594. dateX, 0, width - 8 - dateX, height,
  53595. Justification::centredRight, 1);
  53596. }
  53597. }
  53598. else
  53599. {
  53600. g.drawFittedText (filename,
  53601. x, 0, width - x, height,
  53602. Justification::centredLeft, 1);
  53603. }
  53604. }
  53605. Button* LookAndFeel::createFileBrowserGoUpButton()
  53606. {
  53607. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53608. Path arrowPath;
  53609. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53610. DrawablePath arrowImage;
  53611. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53612. arrowImage.setPath (arrowPath);
  53613. goUpButton->setImages (&arrowImage);
  53614. return goUpButton;
  53615. }
  53616. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53617. DirectoryContentsDisplayComponent* fileListComponent,
  53618. FilePreviewComponent* previewComp,
  53619. ComboBox* currentPathBox,
  53620. TextEditor* filenameBox,
  53621. Button* goUpButton)
  53622. {
  53623. const int x = 8;
  53624. int w = browserComp.getWidth() - x - x;
  53625. if (previewComp != 0)
  53626. {
  53627. const int previewWidth = w / 3;
  53628. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53629. w -= previewWidth + 4;
  53630. }
  53631. int y = 4;
  53632. const int controlsHeight = 22;
  53633. const int bottomSectionHeight = controlsHeight + 8;
  53634. const int upButtonWidth = 50;
  53635. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53636. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53637. y += controlsHeight + 4;
  53638. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53639. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53640. y = listAsComp->getBottom() + 4;
  53641. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53642. }
  53643. const Image LookAndFeel::getDefaultFolderImage()
  53644. {
  53645. 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,
  53646. 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,
  53647. 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,
  53648. 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,
  53649. 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,
  53650. 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,
  53651. 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,
  53652. 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,
  53653. 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,
  53654. 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,
  53655. 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,
  53656. 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,
  53657. 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,
  53658. 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,
  53659. 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,
  53660. 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,
  53661. 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,
  53662. 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,
  53663. 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,
  53664. 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,
  53665. 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,
  53666. 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,
  53667. 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,
  53668. 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,
  53669. 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,
  53670. 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,
  53671. 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,
  53672. 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,
  53673. 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,
  53674. 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,
  53675. 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,
  53676. 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,
  53677. 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,
  53678. 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,
  53679. 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,
  53680. 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,
  53681. 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,
  53682. 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,
  53683. 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,
  53684. 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,
  53685. 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,
  53686. 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,
  53687. 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,
  53688. 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};
  53689. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53690. }
  53691. const Image LookAndFeel::getDefaultDocumentFileImage()
  53692. {
  53693. 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,
  53694. 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,
  53695. 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,
  53696. 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,
  53697. 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,
  53698. 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,
  53699. 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,
  53700. 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,
  53701. 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,
  53702. 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,
  53703. 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,
  53704. 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,
  53705. 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,
  53706. 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,
  53707. 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,
  53708. 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,
  53709. 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,
  53710. 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,
  53711. 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,
  53712. 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,
  53713. 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,
  53714. 174,66,96,130,0,0};
  53715. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53716. }
  53717. void LookAndFeel::playAlertSound()
  53718. {
  53719. PlatformUtilities::beep();
  53720. }
  53721. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53722. {
  53723. g.setColour (Colours::white.withAlpha (0.7f));
  53724. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53725. g.setColour (Colours::black.withAlpha (0.2f));
  53726. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53727. const int totalBlocks = 7;
  53728. const int numBlocks = roundToInt (totalBlocks * level);
  53729. const float w = (width - 6.0f) / (float) totalBlocks;
  53730. for (int i = 0; i < totalBlocks; ++i)
  53731. {
  53732. if (i >= numBlocks)
  53733. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53734. else
  53735. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53736. : Colours::red);
  53737. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53738. }
  53739. }
  53740. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53741. {
  53742. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53743. if (keyDescription.isNotEmpty())
  53744. {
  53745. if (button.isEnabled())
  53746. {
  53747. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53748. g.fillAll (textColour.withAlpha (alpha));
  53749. g.setOpacity (0.3f);
  53750. g.drawBevel (0, 0, width, height, 2);
  53751. }
  53752. g.setColour (textColour);
  53753. g.setFont (height * 0.6f);
  53754. g.drawFittedText (keyDescription,
  53755. 3, 0, width - 6, height,
  53756. Justification::centred, 1);
  53757. }
  53758. else
  53759. {
  53760. const float thickness = 7.0f;
  53761. const float indent = 22.0f;
  53762. Path p;
  53763. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53764. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53765. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53766. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53767. p.setUsingNonZeroWinding (false);
  53768. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53769. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53770. }
  53771. if (button.hasKeyboardFocus (false))
  53772. {
  53773. g.setColour (textColour.withAlpha (0.4f));
  53774. g.drawRect (0, 0, width, height);
  53775. }
  53776. }
  53777. static void createRoundedPath (Path& p,
  53778. const float x, const float y,
  53779. const float w, const float h,
  53780. const float cs,
  53781. const bool curveTopLeft, const bool curveTopRight,
  53782. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53783. {
  53784. const float cs2 = 2.0f * cs;
  53785. if (curveTopLeft)
  53786. {
  53787. p.startNewSubPath (x, y + cs);
  53788. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53789. }
  53790. else
  53791. {
  53792. p.startNewSubPath (x, y);
  53793. }
  53794. if (curveTopRight)
  53795. {
  53796. p.lineTo (x + w - cs, y);
  53797. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53798. }
  53799. else
  53800. {
  53801. p.lineTo (x + w, y);
  53802. }
  53803. if (curveBottomRight)
  53804. {
  53805. p.lineTo (x + w, y + h - cs);
  53806. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53807. }
  53808. else
  53809. {
  53810. p.lineTo (x + w, y + h);
  53811. }
  53812. if (curveBottomLeft)
  53813. {
  53814. p.lineTo (x + cs, y + h);
  53815. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53816. }
  53817. else
  53818. {
  53819. p.lineTo (x, y + h);
  53820. }
  53821. p.closeSubPath();
  53822. }
  53823. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53824. float x, float y, float w, float h,
  53825. float maxCornerSize,
  53826. const Colour& baseColour,
  53827. const float strokeWidth,
  53828. const bool flatOnLeft,
  53829. const bool flatOnRight,
  53830. const bool flatOnTop,
  53831. const bool flatOnBottom) throw()
  53832. {
  53833. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53834. return;
  53835. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53836. Path outline;
  53837. createRoundedPath (outline, x, y, w, h, cs,
  53838. ! (flatOnLeft || flatOnTop),
  53839. ! (flatOnRight || flatOnTop),
  53840. ! (flatOnLeft || flatOnBottom),
  53841. ! (flatOnRight || flatOnBottom));
  53842. ColourGradient cg (baseColour, 0.0f, y,
  53843. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53844. false);
  53845. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53846. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53847. g.setGradientFill (cg);
  53848. g.fillPath (outline);
  53849. g.setColour (Colour (0x80000000));
  53850. g.strokePath (outline, PathStrokeType (strokeWidth));
  53851. }
  53852. void LookAndFeel::drawGlassSphere (Graphics& g,
  53853. const float x, const float y,
  53854. const float diameter,
  53855. const Colour& colour,
  53856. const float outlineThickness) throw()
  53857. {
  53858. if (diameter <= outlineThickness)
  53859. return;
  53860. Path p;
  53861. p.addEllipse (x, y, diameter, diameter);
  53862. {
  53863. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53864. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53865. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53866. g.setGradientFill (cg);
  53867. g.fillPath (p);
  53868. }
  53869. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53870. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53871. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53872. ColourGradient cg (Colours::transparentBlack,
  53873. x + diameter * 0.5f, y + diameter * 0.5f,
  53874. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53875. x, y + diameter * 0.5f, true);
  53876. cg.addColour (0.7, Colours::transparentBlack);
  53877. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53878. g.setGradientFill (cg);
  53879. g.fillPath (p);
  53880. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53881. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53882. }
  53883. void LookAndFeel::drawGlassPointer (Graphics& g,
  53884. const float x, const float y,
  53885. const float diameter,
  53886. const Colour& colour, const float outlineThickness,
  53887. const int direction) throw()
  53888. {
  53889. if (diameter <= outlineThickness)
  53890. return;
  53891. Path p;
  53892. p.startNewSubPath (x + diameter * 0.5f, y);
  53893. p.lineTo (x + diameter, y + diameter * 0.6f);
  53894. p.lineTo (x + diameter, y + diameter);
  53895. p.lineTo (x, y + diameter);
  53896. p.lineTo (x, y + diameter * 0.6f);
  53897. p.closeSubPath();
  53898. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53899. {
  53900. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53901. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53902. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53903. g.setGradientFill (cg);
  53904. g.fillPath (p);
  53905. }
  53906. ColourGradient cg (Colours::transparentBlack,
  53907. x + diameter * 0.5f, y + diameter * 0.5f,
  53908. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53909. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53910. cg.addColour (0.5, Colours::transparentBlack);
  53911. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53912. g.setGradientFill (cg);
  53913. g.fillPath (p);
  53914. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53915. g.strokePath (p, PathStrokeType (outlineThickness));
  53916. }
  53917. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53918. const float x, const float y,
  53919. const float width, const float height,
  53920. const Colour& colour,
  53921. const float outlineThickness,
  53922. const float cornerSize,
  53923. const bool flatOnLeft,
  53924. const bool flatOnRight,
  53925. const bool flatOnTop,
  53926. const bool flatOnBottom) throw()
  53927. {
  53928. if (width <= outlineThickness || height <= outlineThickness)
  53929. return;
  53930. const int intX = (int) x;
  53931. const int intY = (int) y;
  53932. const int intW = (int) width;
  53933. const int intH = (int) height;
  53934. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53935. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53936. const int intEdge = (int) edgeBlurRadius;
  53937. Path outline;
  53938. createRoundedPath (outline, x, y, width, height, cs,
  53939. ! (flatOnLeft || flatOnTop),
  53940. ! (flatOnRight || flatOnTop),
  53941. ! (flatOnLeft || flatOnBottom),
  53942. ! (flatOnRight || flatOnBottom));
  53943. {
  53944. ColourGradient cg (colour.darker (0.2f), 0, y,
  53945. colour.darker (0.2f), 0, y + height, false);
  53946. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53947. cg.addColour (0.4, colour);
  53948. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53949. g.setGradientFill (cg);
  53950. g.fillPath (outline);
  53951. }
  53952. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53953. colour.darker (0.2f), x, y + height * 0.5f, true);
  53954. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53955. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53956. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53957. {
  53958. g.saveState();
  53959. g.setGradientFill (cg);
  53960. g.reduceClipRegion (intX, intY, intEdge, intH);
  53961. g.fillPath (outline);
  53962. g.restoreState();
  53963. }
  53964. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53965. {
  53966. cg.point1.setX (x + width - edgeBlurRadius);
  53967. cg.point2.setX (x + width);
  53968. g.saveState();
  53969. g.setGradientFill (cg);
  53970. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53971. g.fillPath (outline);
  53972. g.restoreState();
  53973. }
  53974. {
  53975. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53976. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53977. Path highlight;
  53978. createRoundedPath (highlight,
  53979. x + leftIndent,
  53980. y + cs * 0.1f,
  53981. width - (leftIndent + rightIndent),
  53982. height * 0.4f, cs * 0.4f,
  53983. ! (flatOnLeft || flatOnTop),
  53984. ! (flatOnRight || flatOnTop),
  53985. ! (flatOnLeft || flatOnBottom),
  53986. ! (flatOnRight || flatOnBottom));
  53987. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53988. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53989. g.fillPath (highlight);
  53990. }
  53991. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53992. g.strokePath (outline, PathStrokeType (outlineThickness));
  53993. }
  53994. END_JUCE_NAMESPACE
  53995. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53996. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53997. BEGIN_JUCE_NAMESPACE
  53998. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53999. {
  54000. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54001. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54002. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54003. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54004. setColour (Slider::thumbColourId, Colours::white);
  54005. setColour (Slider::trackColourId, Colour (0x7f000000));
  54006. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54007. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54008. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54009. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54010. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54011. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54012. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54013. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54014. }
  54015. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54016. {
  54017. }
  54018. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54019. Button& button,
  54020. const Colour& backgroundColour,
  54021. bool isMouseOverButton,
  54022. bool isButtonDown)
  54023. {
  54024. const int width = button.getWidth();
  54025. const int height = button.getHeight();
  54026. const float indent = 2.0f;
  54027. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54028. roundToInt (height * 0.4f));
  54029. Path p;
  54030. p.addRoundedRectangle (indent, indent,
  54031. width - indent * 2.0f,
  54032. height - indent * 2.0f,
  54033. (float) cornerSize);
  54034. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54035. if (isMouseOverButton)
  54036. {
  54037. if (isButtonDown)
  54038. bc = bc.brighter();
  54039. else if (bc.getBrightness() > 0.5f)
  54040. bc = bc.darker (0.1f);
  54041. else
  54042. bc = bc.brighter (0.1f);
  54043. }
  54044. g.setColour (bc);
  54045. g.fillPath (p);
  54046. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54047. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54048. }
  54049. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54050. Component& /*component*/,
  54051. float x, float y, float w, float h,
  54052. const bool ticked,
  54053. const bool isEnabled,
  54054. const bool /*isMouseOverButton*/,
  54055. const bool isButtonDown)
  54056. {
  54057. Path box;
  54058. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54059. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54060. : Colours::lightgrey.withAlpha (0.1f));
  54061. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54062. g.fillPath (box, trans);
  54063. g.setColour (Colours::black.withAlpha (0.6f));
  54064. g.strokePath (box, PathStrokeType (0.9f), trans);
  54065. if (ticked)
  54066. {
  54067. Path tick;
  54068. tick.startNewSubPath (1.5f, 3.0f);
  54069. tick.lineTo (3.0f, 6.0f);
  54070. tick.lineTo (6.0f, 0.0f);
  54071. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54072. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54073. }
  54074. }
  54075. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54076. ToggleButton& button,
  54077. bool isMouseOverButton,
  54078. bool isButtonDown)
  54079. {
  54080. if (button.hasKeyboardFocus (true))
  54081. {
  54082. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54083. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54084. }
  54085. const int tickWidth = jmin (20, button.getHeight() - 4);
  54086. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54087. (float) tickWidth, (float) tickWidth,
  54088. button.getToggleState(),
  54089. button.isEnabled(),
  54090. isMouseOverButton,
  54091. isButtonDown);
  54092. g.setColour (button.findColour (ToggleButton::textColourId));
  54093. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54094. if (! button.isEnabled())
  54095. g.setOpacity (0.5f);
  54096. const int textX = tickWidth + 5;
  54097. g.drawFittedText (button.getButtonText(),
  54098. textX, 4,
  54099. button.getWidth() - textX - 2, button.getHeight() - 8,
  54100. Justification::centredLeft, 10);
  54101. }
  54102. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54103. int width, int height,
  54104. double progress, const String& textToShow)
  54105. {
  54106. if (progress < 0 || progress >= 1.0)
  54107. {
  54108. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54109. }
  54110. else
  54111. {
  54112. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54113. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54114. g.fillAll (background);
  54115. g.setColour (foreground);
  54116. g.fillRect (1, 1,
  54117. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54118. height - 2);
  54119. if (textToShow.isNotEmpty())
  54120. {
  54121. g.setColour (Colour::contrasting (background, foreground));
  54122. g.setFont (height * 0.6f);
  54123. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54124. }
  54125. }
  54126. }
  54127. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54128. ScrollBar& bar,
  54129. int width, int height,
  54130. int buttonDirection,
  54131. bool isScrollbarVertical,
  54132. bool isMouseOverButton,
  54133. bool isButtonDown)
  54134. {
  54135. if (isScrollbarVertical)
  54136. width -= 2;
  54137. else
  54138. height -= 2;
  54139. Path p;
  54140. if (buttonDirection == 0)
  54141. p.addTriangle (width * 0.5f, height * 0.2f,
  54142. width * 0.1f, height * 0.7f,
  54143. width * 0.9f, height * 0.7f);
  54144. else if (buttonDirection == 1)
  54145. p.addTriangle (width * 0.8f, height * 0.5f,
  54146. width * 0.3f, height * 0.1f,
  54147. width * 0.3f, height * 0.9f);
  54148. else if (buttonDirection == 2)
  54149. p.addTriangle (width * 0.5f, height * 0.8f,
  54150. width * 0.1f, height * 0.3f,
  54151. width * 0.9f, height * 0.3f);
  54152. else if (buttonDirection == 3)
  54153. p.addTriangle (width * 0.2f, height * 0.5f,
  54154. width * 0.7f, height * 0.1f,
  54155. width * 0.7f, height * 0.9f);
  54156. if (isButtonDown)
  54157. g.setColour (Colours::white);
  54158. else if (isMouseOverButton)
  54159. g.setColour (Colours::white.withAlpha (0.7f));
  54160. else
  54161. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54162. g.fillPath (p);
  54163. g.setColour (Colours::black.withAlpha (0.5f));
  54164. g.strokePath (p, PathStrokeType (0.5f));
  54165. }
  54166. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54167. ScrollBar& bar,
  54168. int x, int y,
  54169. int width, int height,
  54170. bool isScrollbarVertical,
  54171. int thumbStartPosition,
  54172. int thumbSize,
  54173. bool isMouseOver,
  54174. bool isMouseDown)
  54175. {
  54176. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54177. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54178. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54179. if (thumbSize > 0.0f)
  54180. {
  54181. Rectangle<int> thumb;
  54182. if (isScrollbarVertical)
  54183. {
  54184. width -= 2;
  54185. g.fillRect (x + roundToInt (width * 0.35f), y,
  54186. roundToInt (width * 0.3f), height);
  54187. thumb.setBounds (x + 1, thumbStartPosition,
  54188. width - 2, thumbSize);
  54189. }
  54190. else
  54191. {
  54192. height -= 2;
  54193. g.fillRect (x, y + roundToInt (height * 0.35f),
  54194. width, roundToInt (height * 0.3f));
  54195. thumb.setBounds (thumbStartPosition, y + 1,
  54196. thumbSize, height - 2);
  54197. }
  54198. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54199. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54200. g.fillRect (thumb);
  54201. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54202. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54203. if (thumbSize > 16)
  54204. {
  54205. for (int i = 3; --i >= 0;)
  54206. {
  54207. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54208. g.setColour (Colours::black.withAlpha (0.15f));
  54209. if (isScrollbarVertical)
  54210. {
  54211. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54212. g.setColour (Colours::white.withAlpha (0.15f));
  54213. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54214. }
  54215. else
  54216. {
  54217. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54218. g.setColour (Colours::white.withAlpha (0.15f));
  54219. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54220. }
  54221. }
  54222. }
  54223. }
  54224. }
  54225. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54226. {
  54227. return &scrollbarShadow;
  54228. }
  54229. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54230. {
  54231. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54232. g.setColour (Colours::black.withAlpha (0.6f));
  54233. g.drawRect (0, 0, width, height);
  54234. }
  54235. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54236. bool, MenuBarComponent& menuBar)
  54237. {
  54238. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54239. }
  54240. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54241. {
  54242. if (textEditor.isEnabled())
  54243. {
  54244. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54245. g.drawRect (0, 0, width, height);
  54246. }
  54247. }
  54248. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54249. const bool isButtonDown,
  54250. int buttonX, int buttonY,
  54251. int buttonW, int buttonH,
  54252. ComboBox& box)
  54253. {
  54254. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54255. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54256. : ComboBox::backgroundColourId));
  54257. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54258. g.setColour (box.findColour (ComboBox::outlineColourId));
  54259. g.drawRect (0, 0, width, height);
  54260. const float arrowX = 0.2f;
  54261. const float arrowH = 0.3f;
  54262. if (box.isEnabled())
  54263. {
  54264. Path p;
  54265. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54266. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54267. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54268. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54269. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54270. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54271. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54272. : ComboBox::buttonColourId));
  54273. g.fillPath (p);
  54274. }
  54275. }
  54276. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54277. {
  54278. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54279. f.setHorizontalScale (0.9f);
  54280. return f;
  54281. }
  54282. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54283. {
  54284. Path p;
  54285. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54286. g.setColour (fill);
  54287. g.fillPath (p);
  54288. g.setColour (outline);
  54289. g.strokePath (p, PathStrokeType (0.3f));
  54290. }
  54291. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54292. int x, int y,
  54293. int w, int h,
  54294. float sliderPos,
  54295. float minSliderPos,
  54296. float maxSliderPos,
  54297. const Slider::SliderStyle style,
  54298. Slider& slider)
  54299. {
  54300. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54301. if (style == Slider::LinearBar)
  54302. {
  54303. g.setColour (slider.findColour (Slider::thumbColourId));
  54304. g.fillRect (x, y, (int) sliderPos - x, h);
  54305. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54306. g.drawRect (x, y, (int) sliderPos - x, h);
  54307. }
  54308. else
  54309. {
  54310. g.setColour (slider.findColour (Slider::trackColourId)
  54311. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54312. if (slider.isHorizontal())
  54313. {
  54314. g.fillRect (x, y + roundToInt (h * 0.6f),
  54315. w, roundToInt (h * 0.2f));
  54316. }
  54317. else
  54318. {
  54319. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54320. jmin (4, roundToInt (w * 0.2f)), h);
  54321. }
  54322. float alpha = 0.35f;
  54323. if (slider.isEnabled())
  54324. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54325. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54326. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54327. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54328. {
  54329. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54330. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54331. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54332. fill, outline);
  54333. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54334. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54335. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54336. fill, outline);
  54337. }
  54338. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54339. {
  54340. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54341. minSliderPos - 7.0f, y + h * 0.9f ,
  54342. minSliderPos, y + h * 0.9f,
  54343. fill, outline);
  54344. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54345. maxSliderPos, y + h * 0.9f,
  54346. maxSliderPos + 7.0f, y + h * 0.9f,
  54347. fill, outline);
  54348. }
  54349. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54350. {
  54351. drawTriangle (g, sliderPos, y + h * 0.9f,
  54352. sliderPos - 7.0f, y + h * 0.2f,
  54353. sliderPos + 7.0f, y + h * 0.2f,
  54354. fill, outline);
  54355. }
  54356. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54357. {
  54358. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54359. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54360. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54361. fill, outline);
  54362. }
  54363. }
  54364. }
  54365. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54366. {
  54367. if (isIncrement)
  54368. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54369. else
  54370. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54371. }
  54372. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54373. {
  54374. return &scrollbarShadow;
  54375. }
  54376. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54377. {
  54378. return 8;
  54379. }
  54380. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54381. int w, int h,
  54382. bool isMouseOver,
  54383. bool isMouseDragging)
  54384. {
  54385. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54386. : Colours::darkgrey);
  54387. const float lineThickness = jmin (w, h) * 0.1f;
  54388. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54389. {
  54390. g.drawLine (w * i,
  54391. h + 1.0f,
  54392. w + 1.0f,
  54393. h * i,
  54394. lineThickness);
  54395. }
  54396. }
  54397. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54398. {
  54399. Path shape;
  54400. if (buttonType == DocumentWindow::closeButton)
  54401. {
  54402. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54403. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54404. ShapeButton* const b = new ShapeButton ("close",
  54405. Colour (0x7fff3333),
  54406. Colour (0xd7ff3333),
  54407. Colour (0xf7ff3333));
  54408. b->setShape (shape, true, true, true);
  54409. return b;
  54410. }
  54411. else if (buttonType == DocumentWindow::minimiseButton)
  54412. {
  54413. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54414. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54415. DrawablePath dp;
  54416. dp.setPath (shape);
  54417. dp.setFill (Colours::black.withAlpha (0.3f));
  54418. b->setImages (&dp);
  54419. return b;
  54420. }
  54421. else if (buttonType == DocumentWindow::maximiseButton)
  54422. {
  54423. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54424. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54425. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54426. DrawablePath dp;
  54427. dp.setPath (shape);
  54428. dp.setFill (Colours::black.withAlpha (0.3f));
  54429. b->setImages (&dp);
  54430. return b;
  54431. }
  54432. jassertfalse;
  54433. return 0;
  54434. }
  54435. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54436. int titleBarX,
  54437. int titleBarY,
  54438. int titleBarW,
  54439. int titleBarH,
  54440. Button* minimiseButton,
  54441. Button* maximiseButton,
  54442. Button* closeButton,
  54443. bool positionTitleBarButtonsOnLeft)
  54444. {
  54445. titleBarY += titleBarH / 8;
  54446. titleBarH -= titleBarH / 4;
  54447. const int buttonW = titleBarH;
  54448. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54449. : titleBarX + titleBarW - buttonW - 4;
  54450. if (closeButton != 0)
  54451. {
  54452. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54453. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54454. : -(buttonW + buttonW / 5);
  54455. }
  54456. if (positionTitleBarButtonsOnLeft)
  54457. swapVariables (minimiseButton, maximiseButton);
  54458. if (maximiseButton != 0)
  54459. {
  54460. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54461. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54462. }
  54463. if (minimiseButton != 0)
  54464. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54465. }
  54466. END_JUCE_NAMESPACE
  54467. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54468. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54469. BEGIN_JUCE_NAMESPACE
  54470. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54471. : model (0),
  54472. itemUnderMouse (-1),
  54473. currentPopupIndex (-1),
  54474. topLevelIndexClicked (0),
  54475. lastMouseX (0),
  54476. lastMouseY (0)
  54477. {
  54478. setRepaintsOnMouseActivity (true);
  54479. setWantsKeyboardFocus (false);
  54480. setMouseClickGrabsKeyboardFocus (false);
  54481. setModel (model_);
  54482. }
  54483. MenuBarComponent::~MenuBarComponent()
  54484. {
  54485. setModel (0);
  54486. Desktop::getInstance().removeGlobalMouseListener (this);
  54487. }
  54488. MenuBarModel* MenuBarComponent::getModel() const throw()
  54489. {
  54490. return model;
  54491. }
  54492. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54493. {
  54494. if (model != newModel)
  54495. {
  54496. if (model != 0)
  54497. model->removeListener (this);
  54498. model = newModel;
  54499. if (model != 0)
  54500. model->addListener (this);
  54501. repaint();
  54502. menuBarItemsChanged (0);
  54503. }
  54504. }
  54505. void MenuBarComponent::paint (Graphics& g)
  54506. {
  54507. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54508. getLookAndFeel().drawMenuBarBackground (g,
  54509. getWidth(),
  54510. getHeight(),
  54511. isMouseOverBar,
  54512. *this);
  54513. if (model != 0)
  54514. {
  54515. for (int i = 0; i < menuNames.size(); ++i)
  54516. {
  54517. g.saveState();
  54518. g.setOrigin (xPositions [i], 0);
  54519. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54520. getLookAndFeel().drawMenuBarItem (g,
  54521. xPositions[i + 1] - xPositions[i],
  54522. getHeight(),
  54523. i,
  54524. menuNames[i],
  54525. i == itemUnderMouse,
  54526. i == currentPopupIndex,
  54527. isMouseOverBar,
  54528. *this);
  54529. g.restoreState();
  54530. }
  54531. }
  54532. }
  54533. void MenuBarComponent::resized()
  54534. {
  54535. xPositions.clear();
  54536. int x = 2;
  54537. xPositions.add (x);
  54538. for (int i = 0; i < menuNames.size(); ++i)
  54539. {
  54540. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54541. xPositions.add (x);
  54542. }
  54543. }
  54544. int MenuBarComponent::getItemAt (const int x, const int y)
  54545. {
  54546. for (int i = 0; i < xPositions.size(); ++i)
  54547. if (x >= xPositions[i] && x < xPositions[i + 1])
  54548. return reallyContains (x, y, true) ? i : -1;
  54549. return -1;
  54550. }
  54551. void MenuBarComponent::repaintMenuItem (int index)
  54552. {
  54553. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54554. {
  54555. const int x1 = xPositions [index];
  54556. const int x2 = xPositions [index + 1];
  54557. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54558. }
  54559. }
  54560. void MenuBarComponent::setItemUnderMouse (const int index)
  54561. {
  54562. if (itemUnderMouse != index)
  54563. {
  54564. repaintMenuItem (itemUnderMouse);
  54565. itemUnderMouse = index;
  54566. repaintMenuItem (itemUnderMouse);
  54567. }
  54568. }
  54569. void MenuBarComponent::setOpenItem (int index)
  54570. {
  54571. if (currentPopupIndex != index)
  54572. {
  54573. repaintMenuItem (currentPopupIndex);
  54574. currentPopupIndex = index;
  54575. repaintMenuItem (currentPopupIndex);
  54576. if (index >= 0)
  54577. Desktop::getInstance().addGlobalMouseListener (this);
  54578. else
  54579. Desktop::getInstance().removeGlobalMouseListener (this);
  54580. }
  54581. }
  54582. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54583. {
  54584. setItemUnderMouse (getItemAt (x, y));
  54585. }
  54586. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  54587. {
  54588. public:
  54589. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  54590. : bar (bar_), topLevelIndex (topLevelIndex_)
  54591. {
  54592. }
  54593. ~AsyncCallback() {}
  54594. void modalStateFinished (int returnValue)
  54595. {
  54596. if (bar != 0)
  54597. bar->menuDismissed (topLevelIndex, returnValue);
  54598. }
  54599. private:
  54600. Component::SafePointer<MenuBarComponent> bar;
  54601. const int topLevelIndex;
  54602. AsyncCallback (const AsyncCallback&);
  54603. AsyncCallback& operator= (const AsyncCallback&);
  54604. };
  54605. void MenuBarComponent::showMenu (int index)
  54606. {
  54607. if (index != currentPopupIndex)
  54608. {
  54609. PopupMenu::dismissAllActiveMenus();
  54610. menuBarItemsChanged (0);
  54611. setOpenItem (index);
  54612. setItemUnderMouse (index);
  54613. if (index >= 0)
  54614. {
  54615. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54616. menuNames [itemUnderMouse]));
  54617. if (m.lookAndFeel == 0)
  54618. m.setLookAndFeel (&getLookAndFeel());
  54619. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  54620. m.showMenu (itemPos + getScreenPosition(),
  54621. 0, itemPos.getWidth(), 0, 0, true, this,
  54622. new AsyncCallback (this, index));
  54623. }
  54624. }
  54625. }
  54626. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  54627. {
  54628. topLevelIndexClicked = topLevelIndex;
  54629. postCommandMessage (itemId);
  54630. }
  54631. void MenuBarComponent::handleCommandMessage (int commandId)
  54632. {
  54633. const Point<int> mousePos (getMouseXYRelative());
  54634. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54635. if (! isCurrentlyBlockedByAnotherModalComponent())
  54636. setOpenItem (-1);
  54637. if (commandId != 0 && model != 0)
  54638. model->menuItemSelected (commandId, topLevelIndexClicked);
  54639. }
  54640. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54641. {
  54642. if (e.eventComponent == this)
  54643. updateItemUnderMouse (e.x, e.y);
  54644. }
  54645. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54646. {
  54647. if (e.eventComponent == this)
  54648. updateItemUnderMouse (e.x, e.y);
  54649. }
  54650. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54651. {
  54652. if (currentPopupIndex < 0)
  54653. {
  54654. const MouseEvent e2 (e.getEventRelativeTo (this));
  54655. updateItemUnderMouse (e2.x, e2.y);
  54656. currentPopupIndex = -2;
  54657. showMenu (itemUnderMouse);
  54658. }
  54659. }
  54660. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54661. {
  54662. const MouseEvent e2 (e.getEventRelativeTo (this));
  54663. const int item = getItemAt (e2.x, e2.y);
  54664. if (item >= 0)
  54665. showMenu (item);
  54666. }
  54667. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54668. {
  54669. const MouseEvent e2 (e.getEventRelativeTo (this));
  54670. updateItemUnderMouse (e2.x, e2.y);
  54671. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  54672. {
  54673. setOpenItem (-1);
  54674. PopupMenu::dismissAllActiveMenus();
  54675. }
  54676. }
  54677. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54678. {
  54679. const MouseEvent e2 (e.getEventRelativeTo (this));
  54680. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54681. {
  54682. if (currentPopupIndex >= 0)
  54683. {
  54684. const int item = getItemAt (e2.x, e2.y);
  54685. if (item >= 0)
  54686. showMenu (item);
  54687. }
  54688. else
  54689. {
  54690. updateItemUnderMouse (e2.x, e2.y);
  54691. }
  54692. lastMouseX = e2.x;
  54693. lastMouseY = e2.y;
  54694. }
  54695. }
  54696. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54697. {
  54698. bool used = false;
  54699. const int numMenus = menuNames.size();
  54700. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54701. if (key.isKeyCode (KeyPress::leftKey))
  54702. {
  54703. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54704. used = true;
  54705. }
  54706. else if (key.isKeyCode (KeyPress::rightKey))
  54707. {
  54708. showMenu ((currentIndex + 1) % numMenus);
  54709. used = true;
  54710. }
  54711. return used;
  54712. }
  54713. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54714. {
  54715. StringArray newNames;
  54716. if (model != 0)
  54717. newNames = model->getMenuBarNames();
  54718. if (newNames != menuNames)
  54719. {
  54720. menuNames = newNames;
  54721. repaint();
  54722. resized();
  54723. }
  54724. }
  54725. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54726. const ApplicationCommandTarget::InvocationInfo& info)
  54727. {
  54728. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54729. return;
  54730. for (int i = 0; i < menuNames.size(); ++i)
  54731. {
  54732. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54733. if (menu.containsCommandItem (info.commandID))
  54734. {
  54735. setItemUnderMouse (i);
  54736. startTimer (200);
  54737. break;
  54738. }
  54739. }
  54740. }
  54741. void MenuBarComponent::timerCallback()
  54742. {
  54743. stopTimer();
  54744. const Point<int> mousePos (getMouseXYRelative());
  54745. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54746. }
  54747. END_JUCE_NAMESPACE
  54748. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54749. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54750. BEGIN_JUCE_NAMESPACE
  54751. MenuBarModel::MenuBarModel() throw()
  54752. : manager (0)
  54753. {
  54754. }
  54755. MenuBarModel::~MenuBarModel()
  54756. {
  54757. setApplicationCommandManagerToWatch (0);
  54758. }
  54759. void MenuBarModel::menuItemsChanged()
  54760. {
  54761. triggerAsyncUpdate();
  54762. }
  54763. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54764. {
  54765. if (manager != newManager)
  54766. {
  54767. if (manager != 0)
  54768. manager->removeListener (this);
  54769. manager = newManager;
  54770. if (manager != 0)
  54771. manager->addListener (this);
  54772. }
  54773. }
  54774. void MenuBarModel::addListener (Listener* const newListener) throw()
  54775. {
  54776. listeners.add (newListener);
  54777. }
  54778. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  54779. {
  54780. // Trying to remove a listener that isn't on the list!
  54781. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54782. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54783. jassert (listeners.contains (listenerToRemove));
  54784. listeners.remove (listenerToRemove);
  54785. }
  54786. void MenuBarModel::handleAsyncUpdate()
  54787. {
  54788. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  54789. }
  54790. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54791. {
  54792. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  54793. }
  54794. void MenuBarModel::applicationCommandListChanged()
  54795. {
  54796. menuItemsChanged();
  54797. }
  54798. END_JUCE_NAMESPACE
  54799. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54800. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54801. BEGIN_JUCE_NAMESPACE
  54802. class PopupMenu::Item
  54803. {
  54804. public:
  54805. Item()
  54806. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54807. usesColour (false), customComp (0), commandManager (0)
  54808. {
  54809. }
  54810. Item (const int itemId_,
  54811. const String& text_,
  54812. const bool active_,
  54813. const bool isTicked_,
  54814. const Image& im,
  54815. const Colour& textColour_,
  54816. const bool usesColour_,
  54817. PopupMenuCustomComponent* const customComp_,
  54818. const PopupMenu* const subMenu_,
  54819. ApplicationCommandManager* const commandManager_)
  54820. : itemId (itemId_), text (text_), textColour (textColour_),
  54821. active (active_), isSeparator (false), isTicked (isTicked_),
  54822. usesColour (usesColour_), image (im), customComp (customComp_),
  54823. commandManager (commandManager_)
  54824. {
  54825. if (subMenu_ != 0)
  54826. subMenu = new PopupMenu (*subMenu_);
  54827. if (commandManager_ != 0 && itemId_ != 0)
  54828. {
  54829. String shortcutKey;
  54830. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54831. ->getKeyPressesAssignedToCommand (itemId_));
  54832. for (int i = 0; i < keyPresses.size(); ++i)
  54833. {
  54834. const String key (keyPresses.getReference(i).getTextDescription());
  54835. if (shortcutKey.isNotEmpty())
  54836. shortcutKey << ", ";
  54837. if (key.length() == 1)
  54838. shortcutKey << "shortcut: '" << key << '\'';
  54839. else
  54840. shortcutKey << key;
  54841. }
  54842. shortcutKey = shortcutKey.trim();
  54843. if (shortcutKey.isNotEmpty())
  54844. text << "<end>" << shortcutKey;
  54845. }
  54846. }
  54847. Item (const Item& other)
  54848. : itemId (other.itemId),
  54849. text (other.text),
  54850. textColour (other.textColour),
  54851. active (other.active),
  54852. isSeparator (other.isSeparator),
  54853. isTicked (other.isTicked),
  54854. usesColour (other.usesColour),
  54855. image (other.image),
  54856. customComp (other.customComp),
  54857. commandManager (other.commandManager)
  54858. {
  54859. if (other.subMenu != 0)
  54860. subMenu = new PopupMenu (*(other.subMenu));
  54861. }
  54862. ~Item()
  54863. {
  54864. customComp = 0;
  54865. }
  54866. bool canBeTriggered() const throw()
  54867. {
  54868. return active && ! (isSeparator || (subMenu != 0));
  54869. }
  54870. bool hasActiveSubMenu() const throw()
  54871. {
  54872. return active && (subMenu != 0);
  54873. }
  54874. const int itemId;
  54875. String text;
  54876. const Colour textColour;
  54877. const bool active, isSeparator, isTicked, usesColour;
  54878. Image image;
  54879. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54880. ScopedPointer <PopupMenu> subMenu;
  54881. ApplicationCommandManager* const commandManager;
  54882. juce_UseDebuggingNewOperator
  54883. private:
  54884. Item& operator= (const Item&);
  54885. };
  54886. class PopupMenu::ItemComponent : public Component
  54887. {
  54888. public:
  54889. ItemComponent (const PopupMenu::Item& itemInfo_)
  54890. : itemInfo (itemInfo_),
  54891. isHighlighted (false)
  54892. {
  54893. if (itemInfo.customComp != 0)
  54894. addAndMakeVisible (itemInfo.customComp);
  54895. }
  54896. ~ItemComponent()
  54897. {
  54898. if (itemInfo.customComp != 0)
  54899. removeChildComponent (itemInfo.customComp);
  54900. }
  54901. void getIdealSize (int& idealWidth,
  54902. int& idealHeight,
  54903. const int standardItemHeight)
  54904. {
  54905. if (itemInfo.customComp != 0)
  54906. {
  54907. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54908. }
  54909. else
  54910. {
  54911. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54912. itemInfo.isSeparator,
  54913. standardItemHeight,
  54914. idealWidth,
  54915. idealHeight);
  54916. }
  54917. }
  54918. void paint (Graphics& g)
  54919. {
  54920. if (itemInfo.customComp == 0)
  54921. {
  54922. String mainText (itemInfo.text);
  54923. String endText;
  54924. const int endIndex = mainText.indexOf ("<end>");
  54925. if (endIndex >= 0)
  54926. {
  54927. endText = mainText.substring (endIndex + 5).trim();
  54928. mainText = mainText.substring (0, endIndex);
  54929. }
  54930. getLookAndFeel()
  54931. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54932. itemInfo.isSeparator,
  54933. itemInfo.active,
  54934. isHighlighted,
  54935. itemInfo.isTicked,
  54936. itemInfo.subMenu != 0,
  54937. mainText, endText,
  54938. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54939. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54940. }
  54941. }
  54942. void resized()
  54943. {
  54944. if (getNumChildComponents() > 0)
  54945. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54946. }
  54947. void setHighlighted (bool shouldBeHighlighted)
  54948. {
  54949. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54950. if (isHighlighted != shouldBeHighlighted)
  54951. {
  54952. isHighlighted = shouldBeHighlighted;
  54953. if (itemInfo.customComp != 0)
  54954. {
  54955. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54956. itemInfo.customComp->repaint();
  54957. }
  54958. repaint();
  54959. }
  54960. }
  54961. PopupMenu::Item itemInfo;
  54962. juce_UseDebuggingNewOperator
  54963. private:
  54964. bool isHighlighted;
  54965. ItemComponent (const ItemComponent&);
  54966. ItemComponent& operator= (const ItemComponent&);
  54967. };
  54968. namespace PopupMenuSettings
  54969. {
  54970. static const int scrollZone = 24;
  54971. static const int borderSize = 2;
  54972. static const int timerInterval = 50;
  54973. static const int dismissCommandId = 0x6287345f;
  54974. }
  54975. class PopupMenu::Window : public Component,
  54976. private Timer
  54977. {
  54978. public:
  54979. Window()
  54980. : Component ("menu"),
  54981. owner (0),
  54982. currentChild (0),
  54983. activeSubMenu (0),
  54984. managerOfChosenCommand (0),
  54985. minimumWidth (0),
  54986. maximumNumColumns (7),
  54987. standardItemHeight (0),
  54988. isOver (false),
  54989. hasBeenOver (false),
  54990. isDown (false),
  54991. needsToScroll (false),
  54992. hideOnExit (false),
  54993. disableMouseMoves (false),
  54994. hasAnyJuceCompHadFocus (false),
  54995. numColumns (0),
  54996. contentHeight (0),
  54997. childYOffset (0),
  54998. timeEnteredCurrentChildComp (0),
  54999. scrollAcceleration (1.0)
  55000. {
  55001. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55002. setWantsKeyboardFocus (true);
  55003. setMouseClickGrabsKeyboardFocus (false);
  55004. setOpaque (true);
  55005. setAlwaysOnTop (true);
  55006. Desktop::getInstance().addGlobalMouseListener (this);
  55007. getActiveWindows().add (this);
  55008. }
  55009. ~Window()
  55010. {
  55011. getActiveWindows().removeValue (this);
  55012. Desktop::getInstance().removeGlobalMouseListener (this);
  55013. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55014. activeSubMenu = 0;
  55015. deleteAllChildren();
  55016. }
  55017. static Window* create (const PopupMenu& menu,
  55018. const bool dismissOnMouseUp,
  55019. Window* const owner_,
  55020. const Rectangle<int>& target,
  55021. const int minimumWidth,
  55022. const int maximumNumColumns,
  55023. const int standardItemHeight,
  55024. const bool alignToRectangle,
  55025. const int itemIdThatMustBeVisible,
  55026. ApplicationCommandManager** managerOfChosenCommand,
  55027. Component* const componentAttachedTo)
  55028. {
  55029. if (menu.items.size() > 0)
  55030. {
  55031. int totalItems = 0;
  55032. ScopedPointer <Window> mw (new Window());
  55033. mw->setLookAndFeel (menu.lookAndFeel);
  55034. mw->setWantsKeyboardFocus (false);
  55035. mw->minimumWidth = minimumWidth;
  55036. mw->maximumNumColumns = maximumNumColumns;
  55037. mw->standardItemHeight = standardItemHeight;
  55038. mw->dismissOnMouseUp = dismissOnMouseUp;
  55039. for (int i = 0; i < menu.items.size(); ++i)
  55040. {
  55041. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55042. mw->addItem (*item);
  55043. ++totalItems;
  55044. }
  55045. if (totalItems > 0)
  55046. {
  55047. mw->owner = owner_;
  55048. mw->managerOfChosenCommand = managerOfChosenCommand;
  55049. mw->componentAttachedTo = componentAttachedTo;
  55050. mw->componentAttachedToOriginal = componentAttachedTo;
  55051. mw->calculateWindowPos (target, alignToRectangle);
  55052. mw->setTopLeftPosition (mw->windowPos.getX(),
  55053. mw->windowPos.getY());
  55054. mw->updateYPositions();
  55055. if (itemIdThatMustBeVisible != 0)
  55056. {
  55057. const int y = target.getY() - mw->windowPos.getY();
  55058. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55059. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55060. }
  55061. mw->resizeToBestWindowPos();
  55062. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55063. | mw->getLookAndFeel().getMenuWindowFlags());
  55064. return mw.release();
  55065. }
  55066. }
  55067. return 0;
  55068. }
  55069. void paint (Graphics& g)
  55070. {
  55071. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55072. }
  55073. void paintOverChildren (Graphics& g)
  55074. {
  55075. if (isScrolling())
  55076. {
  55077. LookAndFeel& lf = getLookAndFeel();
  55078. if (isScrollZoneActive (false))
  55079. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55080. if (isScrollZoneActive (true))
  55081. {
  55082. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55083. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55084. }
  55085. }
  55086. }
  55087. bool isScrollZoneActive (bool bottomOne) const
  55088. {
  55089. return isScrolling()
  55090. && (bottomOne
  55091. ? childYOffset < contentHeight - windowPos.getHeight()
  55092. : childYOffset > 0);
  55093. }
  55094. void addItem (const PopupMenu::Item& item)
  55095. {
  55096. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55097. addAndMakeVisible (mic);
  55098. int itemW = 80;
  55099. int itemH = 16;
  55100. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55101. mic->setSize (itemW, jlimit (2, 600, itemH));
  55102. mic->addMouseListener (this, false);
  55103. }
  55104. // hide this and all sub-comps
  55105. void hide (const PopupMenu::Item* const item)
  55106. {
  55107. if (isVisible())
  55108. {
  55109. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55110. activeSubMenu = 0;
  55111. currentChild = 0;
  55112. exitModalState (item != 0 ? item->itemId : 0);
  55113. setVisible (false);
  55114. if (item != 0
  55115. && item->commandManager != 0
  55116. && item->itemId != 0)
  55117. {
  55118. *managerOfChosenCommand = item->commandManager;
  55119. }
  55120. }
  55121. }
  55122. void dismissMenu (const PopupMenu::Item* const item)
  55123. {
  55124. if (owner != 0)
  55125. {
  55126. owner->dismissMenu (item);
  55127. }
  55128. else
  55129. {
  55130. if (item != 0)
  55131. {
  55132. // need a copy of this on the stack as the one passed in will get deleted during this call
  55133. const PopupMenu::Item mi (*item);
  55134. hide (&mi);
  55135. }
  55136. else
  55137. {
  55138. hide (0);
  55139. }
  55140. }
  55141. }
  55142. void mouseMove (const MouseEvent&)
  55143. {
  55144. timerCallback();
  55145. }
  55146. void mouseDown (const MouseEvent&)
  55147. {
  55148. timerCallback();
  55149. }
  55150. void mouseDrag (const MouseEvent&)
  55151. {
  55152. timerCallback();
  55153. }
  55154. void mouseUp (const MouseEvent&)
  55155. {
  55156. timerCallback();
  55157. }
  55158. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55159. {
  55160. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55161. lastMouse = Point<int> (-1, -1);
  55162. }
  55163. bool keyPressed (const KeyPress& key)
  55164. {
  55165. if (key.isKeyCode (KeyPress::downKey))
  55166. {
  55167. selectNextItem (1);
  55168. }
  55169. else if (key.isKeyCode (KeyPress::upKey))
  55170. {
  55171. selectNextItem (-1);
  55172. }
  55173. else if (key.isKeyCode (KeyPress::leftKey))
  55174. {
  55175. if (owner != 0)
  55176. {
  55177. Component::SafePointer<Window> parentWindow (owner);
  55178. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55179. hide (0);
  55180. if (parentWindow != 0)
  55181. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55182. disableTimerUntilMouseMoves();
  55183. }
  55184. else if (componentAttachedTo != 0)
  55185. {
  55186. componentAttachedTo->keyPressed (key);
  55187. }
  55188. }
  55189. else if (key.isKeyCode (KeyPress::rightKey))
  55190. {
  55191. disableTimerUntilMouseMoves();
  55192. if (showSubMenuFor (currentChild))
  55193. {
  55194. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55195. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55196. activeSubMenu->selectNextItem (1);
  55197. }
  55198. else if (componentAttachedTo != 0)
  55199. {
  55200. componentAttachedTo->keyPressed (key);
  55201. }
  55202. }
  55203. else if (key.isKeyCode (KeyPress::returnKey))
  55204. {
  55205. triggerCurrentlyHighlightedItem();
  55206. }
  55207. else if (key.isKeyCode (KeyPress::escapeKey))
  55208. {
  55209. dismissMenu (0);
  55210. }
  55211. else
  55212. {
  55213. return false;
  55214. }
  55215. return true;
  55216. }
  55217. void inputAttemptWhenModal()
  55218. {
  55219. Component::SafePointer<Component> deletionChecker (this);
  55220. timerCallback();
  55221. if (deletionChecker != 0 && ! isOverAnyMenu())
  55222. {
  55223. if (componentAttachedTo != 0)
  55224. {
  55225. // we want to dismiss the menu, but if we do it synchronously, then
  55226. // the mouse-click will be allowed to pass through. That's good, except
  55227. // when the user clicks on the button that orginally popped the menu up,
  55228. // as they'll expect the menu to go away, and in fact it'll just
  55229. // come back. So only dismiss synchronously if they're not on the original
  55230. // comp that we're attached to.
  55231. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55232. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55233. {
  55234. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55235. return;
  55236. }
  55237. }
  55238. dismissMenu (0);
  55239. }
  55240. }
  55241. void handleCommandMessage (int commandId)
  55242. {
  55243. Component::handleCommandMessage (commandId);
  55244. if (commandId == PopupMenuSettings::dismissCommandId)
  55245. dismissMenu (0);
  55246. }
  55247. void timerCallback()
  55248. {
  55249. if (! isVisible())
  55250. return;
  55251. if (componentAttachedTo != componentAttachedToOriginal)
  55252. {
  55253. dismissMenu (0);
  55254. return;
  55255. }
  55256. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55257. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55258. return;
  55259. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55260. // move rather than a real timer callback
  55261. const Point<int> globalMousePos (Desktop::getMousePosition());
  55262. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55263. const uint32 now = Time::getMillisecondCounter();
  55264. if (now > timeEnteredCurrentChildComp + 100
  55265. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55266. && currentChild->isValidComponent()
  55267. && (! disableMouseMoves)
  55268. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55269. {
  55270. showSubMenuFor (currentChild);
  55271. }
  55272. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55273. {
  55274. highlightItemUnderMouse (globalMousePos, localMousePos);
  55275. }
  55276. bool overScrollArea = false;
  55277. if (isScrolling()
  55278. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55279. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55280. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55281. {
  55282. if (now > lastScroll + 20)
  55283. {
  55284. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55285. int amount = 0;
  55286. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55287. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55288. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55289. lastScroll = now;
  55290. }
  55291. overScrollArea = true;
  55292. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55293. }
  55294. else
  55295. {
  55296. scrollAcceleration = 1.0;
  55297. }
  55298. const bool wasDown = isDown;
  55299. bool isOverAny = isOverAnyMenu();
  55300. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55301. {
  55302. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55303. isOverAny = isOverAnyMenu();
  55304. }
  55305. if (hideOnExit && hasBeenOver && ! isOverAny)
  55306. {
  55307. hide (0);
  55308. }
  55309. else
  55310. {
  55311. isDown = hasBeenOver
  55312. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55313. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55314. bool anyFocused = Process::isForegroundProcess();
  55315. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55316. {
  55317. // because no component at all may have focus, our test here will
  55318. // only be triggered when something has focus and then loses it.
  55319. anyFocused = ! hasAnyJuceCompHadFocus;
  55320. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55321. {
  55322. if (ComponentPeer::getPeer (i)->isFocused())
  55323. {
  55324. anyFocused = true;
  55325. hasAnyJuceCompHadFocus = true;
  55326. break;
  55327. }
  55328. }
  55329. }
  55330. if (! anyFocused)
  55331. {
  55332. if (now > lastFocused + 10)
  55333. {
  55334. wasHiddenBecauseOfAppChange() = true;
  55335. dismissMenu (0);
  55336. return; // may have been deleted by the previous call..
  55337. }
  55338. }
  55339. else if (wasDown && now > menuCreationTime + 250
  55340. && ! (isDown || overScrollArea))
  55341. {
  55342. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55343. if (isOver)
  55344. {
  55345. triggerCurrentlyHighlightedItem();
  55346. }
  55347. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55348. {
  55349. dismissMenu (0);
  55350. }
  55351. return; // may have been deleted by the previous calls..
  55352. }
  55353. else
  55354. {
  55355. lastFocused = now;
  55356. }
  55357. }
  55358. }
  55359. static Array<Window*>& getActiveWindows()
  55360. {
  55361. static Array<Window*> activeMenuWindows;
  55362. return activeMenuWindows;
  55363. }
  55364. static bool& wasHiddenBecauseOfAppChange() throw()
  55365. {
  55366. static bool b = false;
  55367. return b;
  55368. }
  55369. juce_UseDebuggingNewOperator
  55370. private:
  55371. Window* owner;
  55372. PopupMenu::ItemComponent* currentChild;
  55373. ScopedPointer <Window> activeSubMenu;
  55374. ApplicationCommandManager** managerOfChosenCommand;
  55375. Component::SafePointer<Component> componentAttachedTo;
  55376. Component* componentAttachedToOriginal;
  55377. Rectangle<int> windowPos;
  55378. Point<int> lastMouse;
  55379. int minimumWidth, maximumNumColumns, standardItemHeight;
  55380. bool isOver, hasBeenOver, isDown, needsToScroll;
  55381. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55382. int numColumns, contentHeight, childYOffset;
  55383. Array <int> columnWidths;
  55384. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55385. double scrollAcceleration;
  55386. bool overlaps (const Rectangle<int>& r) const
  55387. {
  55388. return r.intersects (getBounds())
  55389. || (owner != 0 && owner->overlaps (r));
  55390. }
  55391. bool isOverAnyMenu() const
  55392. {
  55393. return (owner != 0) ? owner->isOverAnyMenu()
  55394. : isOverChildren();
  55395. }
  55396. bool isOverChildren() const
  55397. {
  55398. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55399. return isVisible()
  55400. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55401. }
  55402. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55403. {
  55404. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55405. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55406. if (activeSubMenu != 0)
  55407. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55408. }
  55409. bool treeContains (const Window* const window) const throw()
  55410. {
  55411. const Window* mw = this;
  55412. while (mw->owner != 0)
  55413. mw = mw->owner;
  55414. while (mw != 0)
  55415. {
  55416. if (mw == window)
  55417. return true;
  55418. mw = mw->activeSubMenu;
  55419. }
  55420. return false;
  55421. }
  55422. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55423. {
  55424. const Rectangle<int> mon (Desktop::getInstance()
  55425. .getMonitorAreaContaining (target.getCentre(),
  55426. #if JUCE_MAC
  55427. true));
  55428. #else
  55429. false)); // on windows, don't stop the menu overlapping the taskbar
  55430. #endif
  55431. int x, y, widthToUse, heightToUse;
  55432. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55433. if (alignToRectangle)
  55434. {
  55435. x = target.getX();
  55436. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55437. const int spaceOver = target.getY() - mon.getY();
  55438. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55439. y = target.getBottom();
  55440. else
  55441. y = target.getY() - heightToUse;
  55442. }
  55443. else
  55444. {
  55445. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55446. if (owner != 0)
  55447. {
  55448. if (owner->owner != 0)
  55449. {
  55450. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55451. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55452. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55453. tendTowardsRight = true;
  55454. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55455. tendTowardsRight = false;
  55456. }
  55457. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55458. {
  55459. tendTowardsRight = true;
  55460. }
  55461. }
  55462. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55463. target.getX() - mon.getX()) - 32;
  55464. if (biggestSpace < widthToUse)
  55465. {
  55466. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55467. if (numColumns > 1)
  55468. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55469. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55470. }
  55471. if (tendTowardsRight)
  55472. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55473. else
  55474. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55475. y = target.getY();
  55476. if (target.getCentreY() > mon.getCentreY())
  55477. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55478. }
  55479. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55480. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55481. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55482. // sets this flag if it's big enough to obscure any of its parent menus
  55483. hideOnExit = (owner != 0)
  55484. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55485. }
  55486. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55487. {
  55488. numColumns = 0;
  55489. contentHeight = 0;
  55490. const int maxMenuH = getParentHeight() - 24;
  55491. int totalW;
  55492. do
  55493. {
  55494. ++numColumns;
  55495. totalW = workOutBestSize (maxMenuW);
  55496. if (totalW > maxMenuW)
  55497. {
  55498. numColumns = jmax (1, numColumns - 1);
  55499. totalW = workOutBestSize (maxMenuW); // to update col widths
  55500. break;
  55501. }
  55502. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55503. {
  55504. break;
  55505. }
  55506. } while (numColumns < maximumNumColumns);
  55507. const int actualH = jmin (contentHeight, maxMenuH);
  55508. needsToScroll = contentHeight > actualH;
  55509. width = updateYPositions();
  55510. height = actualH + PopupMenuSettings::borderSize * 2;
  55511. }
  55512. int workOutBestSize (const int maxMenuW)
  55513. {
  55514. int totalW = 0;
  55515. contentHeight = 0;
  55516. int childNum = 0;
  55517. for (int col = 0; col < numColumns; ++col)
  55518. {
  55519. int i, colW = 50, colH = 0;
  55520. const int numChildren = jmin (getNumChildComponents() - childNum,
  55521. (getNumChildComponents() + numColumns - 1) / numColumns);
  55522. for (i = numChildren; --i >= 0;)
  55523. {
  55524. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55525. colH += getChildComponent (childNum + i)->getHeight();
  55526. }
  55527. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55528. columnWidths.set (col, colW);
  55529. totalW += colW;
  55530. contentHeight = jmax (contentHeight, colH);
  55531. childNum += numChildren;
  55532. }
  55533. if (totalW < minimumWidth)
  55534. {
  55535. totalW = minimumWidth;
  55536. for (int col = 0; col < numColumns; ++col)
  55537. columnWidths.set (0, totalW / numColumns);
  55538. }
  55539. return totalW;
  55540. }
  55541. void ensureItemIsVisible (const int itemId, int wantedY)
  55542. {
  55543. jassert (itemId != 0)
  55544. for (int i = getNumChildComponents(); --i >= 0;)
  55545. {
  55546. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55547. if (m != 0
  55548. && m->itemInfo.itemId == itemId
  55549. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55550. {
  55551. const int currentY = m->getY();
  55552. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55553. {
  55554. if (wantedY < 0)
  55555. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55556. jmax (PopupMenuSettings::scrollZone,
  55557. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55558. currentY);
  55559. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55560. int deltaY = wantedY - currentY;
  55561. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55562. jmin (windowPos.getHeight(), mon.getHeight()));
  55563. const int newY = jlimit (mon.getY(),
  55564. mon.getBottom() - windowPos.getHeight(),
  55565. windowPos.getY() + deltaY);
  55566. deltaY -= newY - windowPos.getY();
  55567. childYOffset -= deltaY;
  55568. windowPos.setPosition (windowPos.getX(), newY);
  55569. updateYPositions();
  55570. }
  55571. break;
  55572. }
  55573. }
  55574. }
  55575. void resizeToBestWindowPos()
  55576. {
  55577. Rectangle<int> r (windowPos);
  55578. if (childYOffset < 0)
  55579. {
  55580. r.setBounds (r.getX(), r.getY() - childYOffset,
  55581. r.getWidth(), r.getHeight() + childYOffset);
  55582. }
  55583. else if (childYOffset > 0)
  55584. {
  55585. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55586. if (spaceAtBottom > 0)
  55587. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55588. }
  55589. setBounds (r);
  55590. updateYPositions();
  55591. }
  55592. void alterChildYPos (const int delta)
  55593. {
  55594. if (isScrolling())
  55595. {
  55596. childYOffset += delta;
  55597. if (delta < 0)
  55598. {
  55599. childYOffset = jmax (childYOffset, 0);
  55600. }
  55601. else if (delta > 0)
  55602. {
  55603. childYOffset = jmin (childYOffset,
  55604. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55605. }
  55606. updateYPositions();
  55607. }
  55608. else
  55609. {
  55610. childYOffset = 0;
  55611. }
  55612. resizeToBestWindowPos();
  55613. repaint();
  55614. }
  55615. int updateYPositions()
  55616. {
  55617. int x = 0;
  55618. int childNum = 0;
  55619. for (int col = 0; col < numColumns; ++col)
  55620. {
  55621. const int numChildren = jmin (getNumChildComponents() - childNum,
  55622. (getNumChildComponents() + numColumns - 1) / numColumns);
  55623. const int colW = columnWidths [col];
  55624. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55625. for (int i = 0; i < numChildren; ++i)
  55626. {
  55627. Component* const c = getChildComponent (childNum + i);
  55628. c->setBounds (x, y, colW, c->getHeight());
  55629. y += c->getHeight();
  55630. }
  55631. x += colW;
  55632. childNum += numChildren;
  55633. }
  55634. return x;
  55635. }
  55636. bool isScrolling() const throw()
  55637. {
  55638. return childYOffset != 0 || needsToScroll;
  55639. }
  55640. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55641. {
  55642. if (currentChild->isValidComponent())
  55643. currentChild->setHighlighted (false);
  55644. currentChild = child;
  55645. if (currentChild != 0)
  55646. {
  55647. currentChild->setHighlighted (true);
  55648. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55649. }
  55650. }
  55651. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55652. {
  55653. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55654. activeSubMenu = 0;
  55655. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55656. {
  55657. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55658. dismissOnMouseUp,
  55659. this,
  55660. childComp->getScreenBounds(),
  55661. 0, maximumNumColumns,
  55662. standardItemHeight,
  55663. false, 0, managerOfChosenCommand,
  55664. componentAttachedTo);
  55665. if (activeSubMenu != 0)
  55666. {
  55667. activeSubMenu->setVisible (true);
  55668. activeSubMenu->enterModalState (false);
  55669. activeSubMenu->toFront (false);
  55670. return true;
  55671. }
  55672. }
  55673. return false;
  55674. }
  55675. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55676. {
  55677. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55678. if (isOver)
  55679. hasBeenOver = true;
  55680. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55681. {
  55682. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55683. if (disableMouseMoves && isOver)
  55684. disableMouseMoves = false;
  55685. }
  55686. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55687. return;
  55688. bool isMovingTowardsMenu = false;
  55689. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55690. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55691. {
  55692. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55693. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55694. // extends from the last mouse pos to the submenu's rectangle..
  55695. float subX = (float) activeSubMenu->getScreenX();
  55696. if (activeSubMenu->getX() > getX())
  55697. {
  55698. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55699. }
  55700. else
  55701. {
  55702. lastMouse += Point<int> (2, 0);
  55703. subX += activeSubMenu->getWidth();
  55704. }
  55705. Path areaTowardsSubMenu;
  55706. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55707. (float) lastMouse.getY(),
  55708. subX,
  55709. (float) activeSubMenu->getScreenY(),
  55710. subX,
  55711. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55712. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55713. }
  55714. lastMouse = globalMousePos;
  55715. if (! isMovingTowardsMenu)
  55716. {
  55717. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55718. if (c == this)
  55719. c = 0;
  55720. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55721. if (mic == 0 && c != 0)
  55722. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55723. if (mic != currentChild
  55724. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55725. {
  55726. if (isOver && (c != 0) && (activeSubMenu != 0))
  55727. {
  55728. activeSubMenu->hide (0);
  55729. }
  55730. if (! isOver)
  55731. mic = 0;
  55732. setCurrentlyHighlightedChild (mic);
  55733. }
  55734. }
  55735. }
  55736. void triggerCurrentlyHighlightedItem()
  55737. {
  55738. if (currentChild->isValidComponent()
  55739. && currentChild->itemInfo.canBeTriggered()
  55740. && (currentChild->itemInfo.customComp == 0
  55741. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55742. {
  55743. dismissMenu (&currentChild->itemInfo);
  55744. }
  55745. }
  55746. void selectNextItem (const int delta)
  55747. {
  55748. disableTimerUntilMouseMoves();
  55749. PopupMenu::ItemComponent* mic = 0;
  55750. bool wasLastOne = (currentChild == 0);
  55751. const int numItems = getNumChildComponents();
  55752. for (int i = 0; i < numItems + 1; ++i)
  55753. {
  55754. int index = (delta > 0) ? i : (numItems - 1 - i);
  55755. index = (index + numItems) % numItems;
  55756. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55757. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55758. && wasLastOne)
  55759. break;
  55760. if (mic == currentChild)
  55761. wasLastOne = true;
  55762. }
  55763. setCurrentlyHighlightedChild (mic);
  55764. }
  55765. void disableTimerUntilMouseMoves()
  55766. {
  55767. disableMouseMoves = true;
  55768. if (owner != 0)
  55769. owner->disableTimerUntilMouseMoves();
  55770. }
  55771. Window (const Window&);
  55772. Window& operator= (const Window&);
  55773. };
  55774. PopupMenu::PopupMenu()
  55775. : lookAndFeel (0),
  55776. separatorPending (false)
  55777. {
  55778. }
  55779. PopupMenu::PopupMenu (const PopupMenu& other)
  55780. : lookAndFeel (other.lookAndFeel),
  55781. separatorPending (false)
  55782. {
  55783. items.addCopiesOf (other.items);
  55784. }
  55785. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55786. {
  55787. if (this != &other)
  55788. {
  55789. lookAndFeel = other.lookAndFeel;
  55790. clear();
  55791. items.addCopiesOf (other.items);
  55792. }
  55793. return *this;
  55794. }
  55795. PopupMenu::~PopupMenu()
  55796. {
  55797. clear();
  55798. }
  55799. void PopupMenu::clear()
  55800. {
  55801. items.clear();
  55802. separatorPending = false;
  55803. }
  55804. void PopupMenu::addSeparatorIfPending()
  55805. {
  55806. if (separatorPending)
  55807. {
  55808. separatorPending = false;
  55809. if (items.size() > 0)
  55810. items.add (new Item());
  55811. }
  55812. }
  55813. void PopupMenu::addItem (const int itemResultId,
  55814. const String& itemText,
  55815. const bool isActive,
  55816. const bool isTicked,
  55817. const Image& iconToUse)
  55818. {
  55819. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55820. // didn't pick anything, so you shouldn't use it as the id
  55821. // for an item..
  55822. addSeparatorIfPending();
  55823. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55824. Colours::black, false, 0, 0, 0));
  55825. }
  55826. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55827. const int commandID,
  55828. const String& displayName)
  55829. {
  55830. jassert (commandManager != 0 && commandID != 0);
  55831. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55832. if (registeredInfo != 0)
  55833. {
  55834. ApplicationCommandInfo info (*registeredInfo);
  55835. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55836. addSeparatorIfPending();
  55837. items.add (new Item (commandID,
  55838. displayName.isNotEmpty() ? displayName
  55839. : info.shortName,
  55840. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55841. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55842. Image::null,
  55843. Colours::black,
  55844. false,
  55845. 0, 0,
  55846. commandManager));
  55847. }
  55848. }
  55849. void PopupMenu::addColouredItem (const int itemResultId,
  55850. const String& itemText,
  55851. const Colour& itemTextColour,
  55852. const bool isActive,
  55853. const bool isTicked,
  55854. const Image& iconToUse)
  55855. {
  55856. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55857. // didn't pick anything, so you shouldn't use it as the id
  55858. // for an item..
  55859. addSeparatorIfPending();
  55860. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55861. itemTextColour, true, 0, 0, 0));
  55862. }
  55863. void PopupMenu::addCustomItem (const int itemResultId,
  55864. PopupMenuCustomComponent* const customComponent)
  55865. {
  55866. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55867. // didn't pick anything, so you shouldn't use it as the id
  55868. // for an item..
  55869. addSeparatorIfPending();
  55870. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  55871. Colours::black, false, customComponent, 0, 0));
  55872. }
  55873. class NormalComponentWrapper : public PopupMenuCustomComponent
  55874. {
  55875. public:
  55876. NormalComponentWrapper (Component* const comp,
  55877. const int w, const int h,
  55878. const bool triggerMenuItemAutomaticallyWhenClicked)
  55879. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55880. width (w),
  55881. height (h)
  55882. {
  55883. addAndMakeVisible (comp);
  55884. }
  55885. ~NormalComponentWrapper() {}
  55886. void getIdealSize (int& idealWidth, int& idealHeight)
  55887. {
  55888. idealWidth = width;
  55889. idealHeight = height;
  55890. }
  55891. void resized()
  55892. {
  55893. if (getChildComponent(0) != 0)
  55894. getChildComponent(0)->setBounds (getLocalBounds());
  55895. }
  55896. juce_UseDebuggingNewOperator
  55897. private:
  55898. const int width, height;
  55899. NormalComponentWrapper (const NormalComponentWrapper&);
  55900. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55901. };
  55902. void PopupMenu::addCustomItem (const int itemResultId,
  55903. Component* customComponent,
  55904. int idealWidth, int idealHeight,
  55905. const bool triggerMenuItemAutomaticallyWhenClicked)
  55906. {
  55907. addCustomItem (itemResultId,
  55908. new NormalComponentWrapper (customComponent,
  55909. idealWidth, idealHeight,
  55910. triggerMenuItemAutomaticallyWhenClicked));
  55911. }
  55912. void PopupMenu::addSubMenu (const String& subMenuName,
  55913. const PopupMenu& subMenu,
  55914. const bool isActive,
  55915. const Image& iconToUse,
  55916. const bool isTicked)
  55917. {
  55918. addSeparatorIfPending();
  55919. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55920. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55921. }
  55922. void PopupMenu::addSeparator()
  55923. {
  55924. separatorPending = true;
  55925. }
  55926. class HeaderItemComponent : public PopupMenuCustomComponent
  55927. {
  55928. public:
  55929. HeaderItemComponent (const String& name)
  55930. : PopupMenuCustomComponent (false)
  55931. {
  55932. setName (name);
  55933. }
  55934. ~HeaderItemComponent()
  55935. {
  55936. }
  55937. void paint (Graphics& g)
  55938. {
  55939. Font f (getLookAndFeel().getPopupMenuFont());
  55940. f.setBold (true);
  55941. g.setFont (f);
  55942. g.setColour (findColour (PopupMenu::headerTextColourId));
  55943. g.drawFittedText (getName(),
  55944. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55945. Justification::bottomLeft, 1);
  55946. }
  55947. void getIdealSize (int& idealWidth,
  55948. int& idealHeight)
  55949. {
  55950. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55951. idealHeight += idealHeight / 2;
  55952. idealWidth += idealWidth / 4;
  55953. }
  55954. juce_UseDebuggingNewOperator
  55955. };
  55956. void PopupMenu::addSectionHeader (const String& title)
  55957. {
  55958. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55959. }
  55960. // This invokes any command manager commands and deletes the menu window when it is dismissed
  55961. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  55962. {
  55963. public:
  55964. PopupMenuCompletionCallback()
  55965. : managerOfChosenCommand (0)
  55966. {
  55967. }
  55968. ~PopupMenuCompletionCallback() {}
  55969. void modalStateFinished (int result)
  55970. {
  55971. if (managerOfChosenCommand != 0 && result != 0)
  55972. {
  55973. ApplicationCommandTarget::InvocationInfo info (result);
  55974. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55975. managerOfChosenCommand->invoke (info, true);
  55976. }
  55977. }
  55978. ApplicationCommandManager* managerOfChosenCommand;
  55979. ScopedPointer<Component> component;
  55980. private:
  55981. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  55982. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  55983. };
  55984. int PopupMenu::showMenu (const Rectangle<int>& target,
  55985. const int itemIdThatMustBeVisible,
  55986. const int minimumWidth,
  55987. const int maximumNumColumns,
  55988. const int standardItemHeight,
  55989. const bool alignToRectangle,
  55990. Component* const componentAttachedTo,
  55991. ModalComponentManager::Callback* userCallback)
  55992. {
  55993. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  55994. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55995. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55996. Window::wasHiddenBecauseOfAppChange() = false;
  55997. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  55998. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  55999. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56000. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56001. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56002. &callback->managerOfChosenCommand, componentAttachedTo);
  56003. if (callback->component == 0)
  56004. return 0;
  56005. callbackDeleter.release();
  56006. callback->component->enterModalState (false, userCallbackDeleter.release());
  56007. callback->component->toFront (false); // need to do this after making it modal, or it could
  56008. // be stuck behind other comps that are already modal..
  56009. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56010. if (userCallback != 0)
  56011. return 0;
  56012. const int result = callback->component->runModalLoop();
  56013. if (! Window::wasHiddenBecauseOfAppChange())
  56014. {
  56015. if (prevTopLevel != 0)
  56016. prevTopLevel->toFront (true);
  56017. if (prevFocused != 0)
  56018. prevFocused->grabKeyboardFocus();
  56019. }
  56020. return result;
  56021. }
  56022. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56023. const int minimumWidth,
  56024. const int maximumNumColumns,
  56025. const int standardItemHeight,
  56026. ModalComponentManager::Callback* callback)
  56027. {
  56028. const Point<int> mousePos (Desktop::getMousePosition());
  56029. return showAt (mousePos.getX(), mousePos.getY(),
  56030. itemIdThatMustBeVisible,
  56031. minimumWidth,
  56032. maximumNumColumns,
  56033. standardItemHeight,
  56034. callback);
  56035. }
  56036. int PopupMenu::showAt (const int screenX,
  56037. const int screenY,
  56038. const int itemIdThatMustBeVisible,
  56039. const int minimumWidth,
  56040. const int maximumNumColumns,
  56041. const int standardItemHeight,
  56042. ModalComponentManager::Callback* callback)
  56043. {
  56044. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56045. itemIdThatMustBeVisible,
  56046. minimumWidth, maximumNumColumns,
  56047. standardItemHeight,
  56048. false, 0, callback);
  56049. }
  56050. int PopupMenu::showAt (Component* componentToAttachTo,
  56051. const int itemIdThatMustBeVisible,
  56052. const int minimumWidth,
  56053. const int maximumNumColumns,
  56054. const int standardItemHeight,
  56055. ModalComponentManager::Callback* callback)
  56056. {
  56057. if (componentToAttachTo != 0)
  56058. {
  56059. return showMenu (componentToAttachTo->getScreenBounds(),
  56060. itemIdThatMustBeVisible,
  56061. minimumWidth,
  56062. maximumNumColumns,
  56063. standardItemHeight,
  56064. true, componentToAttachTo, callback);
  56065. }
  56066. else
  56067. {
  56068. return show (itemIdThatMustBeVisible,
  56069. minimumWidth,
  56070. maximumNumColumns,
  56071. standardItemHeight,
  56072. callback);
  56073. }
  56074. }
  56075. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56076. {
  56077. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56078. {
  56079. Window* const pmw = Window::getActiveWindows()[i];
  56080. if (pmw != 0)
  56081. pmw->dismissMenu (0);
  56082. }
  56083. }
  56084. int PopupMenu::getNumItems() const throw()
  56085. {
  56086. int num = 0;
  56087. for (int i = items.size(); --i >= 0;)
  56088. if (! (items.getUnchecked(i))->isSeparator)
  56089. ++num;
  56090. return num;
  56091. }
  56092. bool PopupMenu::containsCommandItem (const int commandID) const
  56093. {
  56094. for (int i = items.size(); --i >= 0;)
  56095. {
  56096. const Item* mi = items.getUnchecked (i);
  56097. if ((mi->itemId == commandID && mi->commandManager != 0)
  56098. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56099. {
  56100. return true;
  56101. }
  56102. }
  56103. return false;
  56104. }
  56105. bool PopupMenu::containsAnyActiveItems() const throw()
  56106. {
  56107. for (int i = items.size(); --i >= 0;)
  56108. {
  56109. const Item* const mi = items.getUnchecked (i);
  56110. if (mi->subMenu != 0)
  56111. {
  56112. if (mi->subMenu->containsAnyActiveItems())
  56113. return true;
  56114. }
  56115. else if (mi->active)
  56116. {
  56117. return true;
  56118. }
  56119. }
  56120. return false;
  56121. }
  56122. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56123. {
  56124. lookAndFeel = newLookAndFeel;
  56125. }
  56126. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56127. : isHighlighted (false),
  56128. isTriggeredAutomatically (isTriggeredAutomatically_)
  56129. {
  56130. }
  56131. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56132. {
  56133. }
  56134. void PopupMenuCustomComponent::triggerMenuItem()
  56135. {
  56136. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56137. if (mic != 0)
  56138. {
  56139. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56140. if (pmw != 0)
  56141. {
  56142. pmw->dismissMenu (&mic->itemInfo);
  56143. }
  56144. else
  56145. {
  56146. // something must have gone wrong with the component hierarchy if this happens..
  56147. jassertfalse;
  56148. }
  56149. }
  56150. else
  56151. {
  56152. // why isn't this component inside a menu? Not much point triggering the item if
  56153. // there's no menu.
  56154. jassertfalse;
  56155. }
  56156. }
  56157. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56158. : subMenu (0),
  56159. itemId (0),
  56160. isSeparator (false),
  56161. isTicked (false),
  56162. isEnabled (false),
  56163. isCustomComponent (false),
  56164. isSectionHeader (false),
  56165. customColour (0),
  56166. customImage (0),
  56167. menu (menu_),
  56168. index (0)
  56169. {
  56170. }
  56171. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56172. {
  56173. }
  56174. bool PopupMenu::MenuItemIterator::next()
  56175. {
  56176. if (index >= menu.items.size())
  56177. return false;
  56178. const Item* const item = menu.items.getUnchecked (index);
  56179. ++index;
  56180. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56181. subMenu = item->subMenu;
  56182. itemId = item->itemId;
  56183. isSeparator = item->isSeparator;
  56184. isTicked = item->isTicked;
  56185. isEnabled = item->active;
  56186. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56187. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56188. customColour = item->usesColour ? &(item->textColour) : 0;
  56189. customImage = item->image;
  56190. commandManager = item->commandManager;
  56191. return true;
  56192. }
  56193. END_JUCE_NAMESPACE
  56194. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56195. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56196. BEGIN_JUCE_NAMESPACE
  56197. ComponentDragger::ComponentDragger()
  56198. : constrainer (0)
  56199. {
  56200. }
  56201. ComponentDragger::~ComponentDragger()
  56202. {
  56203. }
  56204. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56205. ComponentBoundsConstrainer* const constrainer_)
  56206. {
  56207. jassert (componentToDrag->isValidComponent());
  56208. if (componentToDrag != 0)
  56209. {
  56210. constrainer = constrainer_;
  56211. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56212. }
  56213. }
  56214. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56215. {
  56216. jassert (componentToDrag->isValidComponent());
  56217. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56218. if (componentToDrag != 0)
  56219. {
  56220. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56221. const Component* const parentComp = componentToDrag->getParentComponent();
  56222. if (parentComp != 0)
  56223. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56224. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56225. if (constrainer != 0)
  56226. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56227. else
  56228. componentToDrag->setBounds (bounds);
  56229. }
  56230. }
  56231. END_JUCE_NAMESPACE
  56232. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56233. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56234. BEGIN_JUCE_NAMESPACE
  56235. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56236. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56237. class DragImageComponent : public Component,
  56238. public Timer
  56239. {
  56240. public:
  56241. DragImageComponent (const Image& im,
  56242. const String& desc,
  56243. Component* const sourceComponent,
  56244. Component* const mouseDragSource_,
  56245. DragAndDropContainer* const o,
  56246. const Point<int>& imageOffset_)
  56247. : image (im),
  56248. source (sourceComponent),
  56249. mouseDragSource (mouseDragSource_),
  56250. owner (o),
  56251. dragDesc (desc),
  56252. imageOffset (imageOffset_),
  56253. hasCheckedForExternalDrag (false),
  56254. drawImage (true)
  56255. {
  56256. setSize (im.getWidth(), im.getHeight());
  56257. if (mouseDragSource == 0)
  56258. mouseDragSource = source;
  56259. mouseDragSource->addMouseListener (this, false);
  56260. startTimer (200);
  56261. setInterceptsMouseClicks (false, false);
  56262. setAlwaysOnTop (true);
  56263. }
  56264. ~DragImageComponent()
  56265. {
  56266. if (owner->dragImageComponent == this)
  56267. owner->dragImageComponent.release();
  56268. if (mouseDragSource != 0)
  56269. {
  56270. mouseDragSource->removeMouseListener (this);
  56271. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56272. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56273. }
  56274. }
  56275. void paint (Graphics& g)
  56276. {
  56277. if (isOpaque())
  56278. g.fillAll (Colours::white);
  56279. if (drawImage)
  56280. {
  56281. g.setOpacity (1.0f);
  56282. g.drawImageAt (image, 0, 0);
  56283. }
  56284. }
  56285. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56286. {
  56287. Component* hit = getParentComponent();
  56288. if (hit == 0)
  56289. {
  56290. hit = Desktop::getInstance().findComponentAt (screenPos);
  56291. }
  56292. else
  56293. {
  56294. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56295. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56296. }
  56297. // (note: use a local copy of the dragDesc member in case the callback runs
  56298. // a modal loop and deletes this object before the method completes)
  56299. const String dragDescLocal (dragDesc);
  56300. while (hit != 0)
  56301. {
  56302. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56303. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56304. {
  56305. relativePos = hit->globalPositionToRelative (screenPos);
  56306. return ddt;
  56307. }
  56308. hit = hit->getParentComponent();
  56309. }
  56310. return 0;
  56311. }
  56312. void mouseUp (const MouseEvent& e)
  56313. {
  56314. if (e.originalComponent != this)
  56315. {
  56316. if (mouseDragSource != 0)
  56317. mouseDragSource->removeMouseListener (this);
  56318. bool dropAccepted = false;
  56319. DragAndDropTarget* ddt = 0;
  56320. Point<int> relPos;
  56321. if (isVisible())
  56322. {
  56323. setVisible (false);
  56324. ddt = findTarget (e.getScreenPosition(), relPos);
  56325. // fade this component and remove it - it'll be deleted later by the timer callback
  56326. dropAccepted = ddt != 0;
  56327. setVisible (true);
  56328. if (dropAccepted || source == 0)
  56329. {
  56330. fadeOutComponent (120);
  56331. }
  56332. else
  56333. {
  56334. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56335. source->getHeight() / 2)));
  56336. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56337. getHeight() / 2)));
  56338. fadeOutComponent (120,
  56339. target.getX() - ourCentre.getX(),
  56340. target.getY() - ourCentre.getY());
  56341. }
  56342. }
  56343. if (getParentComponent() != 0)
  56344. getParentComponent()->removeChildComponent (this);
  56345. if (dropAccepted && ddt != 0)
  56346. {
  56347. // (note: use a local copy of the dragDesc member in case the callback runs
  56348. // a modal loop and deletes this object before the method completes)
  56349. const String dragDescLocal (dragDesc);
  56350. currentlyOverComp = 0;
  56351. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56352. }
  56353. // careful - this object could now be deleted..
  56354. }
  56355. }
  56356. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56357. {
  56358. // (note: use a local copy of the dragDesc member in case the callback runs
  56359. // a modal loop and deletes this object before it returns)
  56360. const String dragDescLocal (dragDesc);
  56361. Point<int> newPos (screenPos + imageOffset);
  56362. if (getParentComponent() != 0)
  56363. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56364. //if (newX != getX() || newY != getY())
  56365. {
  56366. setTopLeftPosition (newPos.getX(), newPos.getY());
  56367. Point<int> relPos;
  56368. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56369. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56370. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56371. if (ddtComp != currentlyOverComp)
  56372. {
  56373. if (currentlyOverComp != 0 && source != 0
  56374. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56375. {
  56376. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56377. }
  56378. currentlyOverComp = ddtComp;
  56379. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56380. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56381. }
  56382. DragAndDropTarget* target = getCurrentlyOver();
  56383. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56384. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56385. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56386. {
  56387. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56388. {
  56389. hasCheckedForExternalDrag = true;
  56390. StringArray files;
  56391. bool canMoveFiles = false;
  56392. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56393. && files.size() > 0)
  56394. {
  56395. Component::SafePointer<Component> cdw (this);
  56396. setVisible (false);
  56397. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56398. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56399. if (cdw != 0)
  56400. delete this;
  56401. return;
  56402. }
  56403. }
  56404. }
  56405. }
  56406. }
  56407. void mouseDrag (const MouseEvent& e)
  56408. {
  56409. if (e.originalComponent != this)
  56410. updateLocation (true, e.getScreenPosition());
  56411. }
  56412. void timerCallback()
  56413. {
  56414. if (source == 0)
  56415. {
  56416. delete this;
  56417. }
  56418. else if (! isMouseButtonDownAnywhere())
  56419. {
  56420. if (mouseDragSource != 0)
  56421. mouseDragSource->removeMouseListener (this);
  56422. delete this;
  56423. }
  56424. }
  56425. private:
  56426. Image image;
  56427. Component::SafePointer<Component> source;
  56428. Component::SafePointer<Component> mouseDragSource;
  56429. DragAndDropContainer* const owner;
  56430. Component::SafePointer<Component> currentlyOverComp;
  56431. DragAndDropTarget* getCurrentlyOver()
  56432. {
  56433. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56434. }
  56435. String dragDesc;
  56436. const Point<int> imageOffset;
  56437. bool hasCheckedForExternalDrag, drawImage;
  56438. DragImageComponent (const DragImageComponent&);
  56439. DragImageComponent& operator= (const DragImageComponent&);
  56440. };
  56441. DragAndDropContainer::DragAndDropContainer()
  56442. {
  56443. }
  56444. DragAndDropContainer::~DragAndDropContainer()
  56445. {
  56446. dragImageComponent = 0;
  56447. }
  56448. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56449. Component* sourceComponent,
  56450. const Image& dragImage_,
  56451. const bool allowDraggingToExternalWindows,
  56452. const Point<int>* imageOffsetFromMouse)
  56453. {
  56454. Image dragImage (dragImage_);
  56455. if (dragImageComponent == 0)
  56456. {
  56457. Component* const thisComp = dynamic_cast <Component*> (this);
  56458. if (thisComp == 0)
  56459. {
  56460. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56461. return;
  56462. }
  56463. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56464. if (draggingSource == 0 || ! draggingSource->isDragging())
  56465. {
  56466. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56467. return;
  56468. }
  56469. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56470. Point<int> imageOffset;
  56471. if (dragImage.isNull())
  56472. {
  56473. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56474. .convertedToFormat (Image::ARGB);
  56475. dragImage.multiplyAllAlphas (0.6f);
  56476. const int lo = 150;
  56477. const int hi = 400;
  56478. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56479. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56480. for (int y = dragImage.getHeight(); --y >= 0;)
  56481. {
  56482. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56483. for (int x = dragImage.getWidth(); --x >= 0;)
  56484. {
  56485. const int dx = x - clipped.getX();
  56486. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56487. if (distance > lo)
  56488. {
  56489. const float alpha = (distance > hi) ? 0
  56490. : (hi - distance) / (float) (hi - lo)
  56491. + Random::getSystemRandom().nextFloat() * 0.008f;
  56492. dragImage.multiplyAlphaAt (x, y, alpha);
  56493. }
  56494. }
  56495. }
  56496. imageOffset = -clipped;
  56497. }
  56498. else
  56499. {
  56500. if (imageOffsetFromMouse == 0)
  56501. imageOffset = -dragImage.getBounds().getCentre();
  56502. else
  56503. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56504. }
  56505. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56506. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56507. currentDragDesc = sourceDescription;
  56508. if (allowDraggingToExternalWindows)
  56509. {
  56510. if (! Desktop::canUseSemiTransparentWindows())
  56511. dragImageComponent->setOpaque (true);
  56512. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56513. | ComponentPeer::windowIsTemporary
  56514. | ComponentPeer::windowIgnoresKeyPresses);
  56515. }
  56516. else
  56517. thisComp->addChildComponent (dragImageComponent);
  56518. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56519. dragImageComponent->setVisible (true);
  56520. }
  56521. }
  56522. bool DragAndDropContainer::isDragAndDropActive() const
  56523. {
  56524. return dragImageComponent != 0;
  56525. }
  56526. const String DragAndDropContainer::getCurrentDragDescription() const
  56527. {
  56528. return (dragImageComponent != 0) ? currentDragDesc
  56529. : String::empty;
  56530. }
  56531. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56532. {
  56533. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56534. }
  56535. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56536. {
  56537. return false;
  56538. }
  56539. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56540. {
  56541. }
  56542. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56543. {
  56544. }
  56545. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56546. {
  56547. }
  56548. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56549. {
  56550. return true;
  56551. }
  56552. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56553. {
  56554. }
  56555. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56556. {
  56557. }
  56558. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56559. {
  56560. }
  56561. END_JUCE_NAMESPACE
  56562. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56563. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56564. BEGIN_JUCE_NAMESPACE
  56565. class MouseCursor::SharedCursorHandle
  56566. {
  56567. public:
  56568. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56569. : handle (createStandardMouseCursor (type)),
  56570. refCount (1),
  56571. standardType (type),
  56572. isStandard (true)
  56573. {
  56574. }
  56575. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56576. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56577. refCount (1),
  56578. standardType (MouseCursor::NormalCursor),
  56579. isStandard (false)
  56580. {
  56581. }
  56582. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56583. {
  56584. const ScopedLock sl (getLock());
  56585. for (int i = 0; i < getCursors().size(); ++i)
  56586. {
  56587. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56588. if (sc->standardType == type)
  56589. return sc->retain();
  56590. }
  56591. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56592. getCursors().add (sc);
  56593. return sc;
  56594. }
  56595. SharedCursorHandle* retain() throw()
  56596. {
  56597. ++refCount;
  56598. return this;
  56599. }
  56600. void release()
  56601. {
  56602. if (--refCount == 0)
  56603. {
  56604. if (isStandard)
  56605. {
  56606. const ScopedLock sl (getLock());
  56607. getCursors().removeValue (this);
  56608. }
  56609. delete this;
  56610. }
  56611. }
  56612. void* getHandle() const throw() { return handle; }
  56613. juce_UseDebuggingNewOperator
  56614. private:
  56615. void* const handle;
  56616. Atomic <int> refCount;
  56617. const MouseCursor::StandardCursorType standardType;
  56618. const bool isStandard;
  56619. static CriticalSection& getLock()
  56620. {
  56621. static CriticalSection lock;
  56622. return lock;
  56623. }
  56624. static Array <SharedCursorHandle*>& getCursors()
  56625. {
  56626. static Array <SharedCursorHandle*> cursors;
  56627. return cursors;
  56628. }
  56629. ~SharedCursorHandle()
  56630. {
  56631. deleteMouseCursor (handle, isStandard);
  56632. }
  56633. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56634. };
  56635. MouseCursor::MouseCursor()
  56636. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56637. {
  56638. jassert (cursorHandle != 0);
  56639. }
  56640. MouseCursor::MouseCursor (const StandardCursorType type)
  56641. : cursorHandle (SharedCursorHandle::createStandard (type))
  56642. {
  56643. jassert (cursorHandle != 0);
  56644. }
  56645. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56646. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56647. {
  56648. }
  56649. MouseCursor::MouseCursor (const MouseCursor& other)
  56650. : cursorHandle (other.cursorHandle->retain())
  56651. {
  56652. }
  56653. MouseCursor::~MouseCursor()
  56654. {
  56655. cursorHandle->release();
  56656. }
  56657. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56658. {
  56659. other.cursorHandle->retain();
  56660. cursorHandle->release();
  56661. cursorHandle = other.cursorHandle;
  56662. return *this;
  56663. }
  56664. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56665. {
  56666. return getHandle() == other.getHandle();
  56667. }
  56668. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56669. {
  56670. return getHandle() != other.getHandle();
  56671. }
  56672. void* MouseCursor::getHandle() const throw()
  56673. {
  56674. return cursorHandle->getHandle();
  56675. }
  56676. void MouseCursor::showWaitCursor()
  56677. {
  56678. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56679. }
  56680. void MouseCursor::hideWaitCursor()
  56681. {
  56682. Desktop::getInstance().getMainMouseSource().revealCursor();
  56683. }
  56684. END_JUCE_NAMESPACE
  56685. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56686. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56687. BEGIN_JUCE_NAMESPACE
  56688. MouseEvent::MouseEvent (MouseInputSource& source_,
  56689. const Point<int>& position,
  56690. const ModifierKeys& mods_,
  56691. Component* const eventComponent_,
  56692. Component* const originator,
  56693. const Time& eventTime_,
  56694. const Point<int> mouseDownPos_,
  56695. const Time& mouseDownTime_,
  56696. const int numberOfClicks_,
  56697. const bool mouseWasDragged) throw()
  56698. : x (position.getX()),
  56699. y (position.getY()),
  56700. mods (mods_),
  56701. eventComponent (eventComponent_),
  56702. originalComponent (originator),
  56703. eventTime (eventTime_),
  56704. source (source_),
  56705. mouseDownPos (mouseDownPos_),
  56706. mouseDownTime (mouseDownTime_),
  56707. numberOfClicks (numberOfClicks_),
  56708. wasMovedSinceMouseDown (mouseWasDragged)
  56709. {
  56710. }
  56711. MouseEvent::~MouseEvent() throw()
  56712. {
  56713. }
  56714. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56715. {
  56716. if (otherComponent == 0)
  56717. {
  56718. jassertfalse;
  56719. return *this;
  56720. }
  56721. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56722. mods, otherComponent, originalComponent, eventTime,
  56723. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56724. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56725. }
  56726. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56727. {
  56728. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56729. eventTime, mouseDownPos, mouseDownTime,
  56730. numberOfClicks, wasMovedSinceMouseDown);
  56731. }
  56732. bool MouseEvent::mouseWasClicked() const throw()
  56733. {
  56734. return ! wasMovedSinceMouseDown;
  56735. }
  56736. int MouseEvent::getMouseDownX() const throw()
  56737. {
  56738. return mouseDownPos.getX();
  56739. }
  56740. int MouseEvent::getMouseDownY() const throw()
  56741. {
  56742. return mouseDownPos.getY();
  56743. }
  56744. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56745. {
  56746. return mouseDownPos;
  56747. }
  56748. int MouseEvent::getDistanceFromDragStartX() const throw()
  56749. {
  56750. return x - mouseDownPos.getX();
  56751. }
  56752. int MouseEvent::getDistanceFromDragStartY() const throw()
  56753. {
  56754. return y - mouseDownPos.getY();
  56755. }
  56756. int MouseEvent::getDistanceFromDragStart() const throw()
  56757. {
  56758. return mouseDownPos.getDistanceFrom (getPosition());
  56759. }
  56760. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56761. {
  56762. return getPosition() - mouseDownPos;
  56763. }
  56764. int MouseEvent::getLengthOfMousePress() const throw()
  56765. {
  56766. if (mouseDownTime.toMilliseconds() > 0)
  56767. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56768. return 0;
  56769. }
  56770. const Point<int> MouseEvent::getPosition() const throw()
  56771. {
  56772. return Point<int> (x, y);
  56773. }
  56774. int MouseEvent::getScreenX() const
  56775. {
  56776. return getScreenPosition().getX();
  56777. }
  56778. int MouseEvent::getScreenY() const
  56779. {
  56780. return getScreenPosition().getY();
  56781. }
  56782. const Point<int> MouseEvent::getScreenPosition() const
  56783. {
  56784. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56785. }
  56786. int MouseEvent::getMouseDownScreenX() const
  56787. {
  56788. return getMouseDownScreenPosition().getX();
  56789. }
  56790. int MouseEvent::getMouseDownScreenY() const
  56791. {
  56792. return getMouseDownScreenPosition().getY();
  56793. }
  56794. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56795. {
  56796. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56797. }
  56798. int MouseEvent::doubleClickTimeOutMs = 400;
  56799. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56800. {
  56801. doubleClickTimeOutMs = newTime;
  56802. }
  56803. int MouseEvent::getDoubleClickTimeout() throw()
  56804. {
  56805. return doubleClickTimeOutMs;
  56806. }
  56807. END_JUCE_NAMESPACE
  56808. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56809. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56810. BEGIN_JUCE_NAMESPACE
  56811. class MouseInputSourceInternal : public AsyncUpdater
  56812. {
  56813. public:
  56814. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56815. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56816. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56817. mouseEventCounter (0)
  56818. {
  56819. zerostruct (mouseDowns);
  56820. }
  56821. ~MouseInputSourceInternal()
  56822. {
  56823. }
  56824. bool isDragging() const throw()
  56825. {
  56826. return buttonState.isAnyMouseButtonDown();
  56827. }
  56828. Component* getComponentUnderMouse() const
  56829. {
  56830. return static_cast <Component*> (componentUnderMouse);
  56831. }
  56832. const ModifierKeys getCurrentModifiers() const
  56833. {
  56834. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56835. }
  56836. ComponentPeer* getPeer()
  56837. {
  56838. if (! ComponentPeer::isValidPeer (lastPeer))
  56839. lastPeer = 0;
  56840. return lastPeer;
  56841. }
  56842. Component* findComponentAt (const Point<int>& screenPos)
  56843. {
  56844. ComponentPeer* const peer = getPeer();
  56845. if (peer != 0)
  56846. {
  56847. Component* const comp = peer->getComponent();
  56848. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56849. // (the contains() call is needed to test for overlapping desktop windows)
  56850. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56851. return comp->getComponentAt (relativePos);
  56852. }
  56853. return 0;
  56854. }
  56855. const Point<int> getScreenPosition() const throw()
  56856. {
  56857. return lastScreenPos + unboundedMouseOffset;
  56858. }
  56859. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56860. {
  56861. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56862. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56863. }
  56864. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56865. {
  56866. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56867. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56868. }
  56869. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56870. {
  56871. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56872. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56873. }
  56874. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56875. {
  56876. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56877. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56878. }
  56879. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56880. {
  56881. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56882. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56883. }
  56884. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56885. {
  56886. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56887. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56888. }
  56889. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56890. {
  56891. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56892. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56893. }
  56894. // (returns true if the button change caused a modal event loop)
  56895. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56896. {
  56897. if (buttonState == newButtonState)
  56898. return false;
  56899. setScreenPos (screenPos, time, false);
  56900. // (ignore secondary clicks when there's already a button down)
  56901. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56902. {
  56903. buttonState = newButtonState;
  56904. return false;
  56905. }
  56906. const int lastCounter = mouseEventCounter;
  56907. if (buttonState.isAnyMouseButtonDown())
  56908. {
  56909. Component* const current = getComponentUnderMouse();
  56910. if (current != 0)
  56911. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56912. enableUnboundedMouseMovement (false, false);
  56913. }
  56914. buttonState = newButtonState;
  56915. if (buttonState.isAnyMouseButtonDown())
  56916. {
  56917. Desktop::getInstance().incrementMouseClickCounter();
  56918. Component* const current = getComponentUnderMouse();
  56919. if (current != 0)
  56920. {
  56921. registerMouseDown (screenPos, time, current);
  56922. sendMouseDown (current, screenPos, time);
  56923. }
  56924. }
  56925. return lastCounter != mouseEventCounter;
  56926. }
  56927. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56928. {
  56929. Component* current = getComponentUnderMouse();
  56930. if (newComponent != current)
  56931. {
  56932. Component::SafePointer<Component> safeNewComp (newComponent);
  56933. const ModifierKeys originalButtonState (buttonState);
  56934. if (current != 0)
  56935. {
  56936. setButtons (screenPos, time, ModifierKeys());
  56937. sendMouseExit (current, screenPos, time);
  56938. buttonState = originalButtonState;
  56939. }
  56940. componentUnderMouse = safeNewComp;
  56941. current = getComponentUnderMouse();
  56942. if (current != 0)
  56943. sendMouseEnter (current, screenPos, time);
  56944. revealCursor (false);
  56945. setButtons (screenPos, time, originalButtonState);
  56946. }
  56947. }
  56948. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56949. {
  56950. ModifierKeys::updateCurrentModifiers();
  56951. if (newPeer != lastPeer)
  56952. {
  56953. setComponentUnderMouse (0, screenPos, time);
  56954. lastPeer = newPeer;
  56955. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56956. }
  56957. }
  56958. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56959. {
  56960. if (! isDragging())
  56961. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56962. if (newScreenPos != lastScreenPos || forceUpdate)
  56963. {
  56964. cancelPendingUpdate();
  56965. lastScreenPos = newScreenPos;
  56966. Component* const current = getComponentUnderMouse();
  56967. if (current != 0)
  56968. {
  56969. if (isDragging())
  56970. {
  56971. registerMouseDrag (newScreenPos);
  56972. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56973. if (isUnboundedMouseModeOn)
  56974. handleUnboundedDrag (current);
  56975. }
  56976. else
  56977. {
  56978. sendMouseMove (current, newScreenPos, time);
  56979. }
  56980. }
  56981. revealCursor (false);
  56982. }
  56983. }
  56984. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56985. {
  56986. jassert (newPeer != 0);
  56987. lastTime = time;
  56988. ++mouseEventCounter;
  56989. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56990. if (isDragging() && newMods.isAnyMouseButtonDown())
  56991. {
  56992. setScreenPos (screenPos, time, false);
  56993. }
  56994. else
  56995. {
  56996. setPeer (newPeer, screenPos, time);
  56997. ComponentPeer* peer = getPeer();
  56998. if (peer != 0)
  56999. {
  57000. if (setButtons (screenPos, time, newMods))
  57001. return; // some modal events have been dispatched, so the current event is now out-of-date
  57002. peer = getPeer();
  57003. if (peer != 0)
  57004. setScreenPos (screenPos, time, false);
  57005. }
  57006. }
  57007. }
  57008. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57009. {
  57010. jassert (peer != 0);
  57011. lastTime = time;
  57012. ++mouseEventCounter;
  57013. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57014. setPeer (peer, screenPos, time);
  57015. setScreenPos (screenPos, time, false);
  57016. triggerFakeMove();
  57017. if (! isDragging())
  57018. {
  57019. Component* current = getComponentUnderMouse();
  57020. if (current != 0)
  57021. sendMouseWheel (current, screenPos, time, x, y);
  57022. }
  57023. }
  57024. const Time getLastMouseDownTime() const throw()
  57025. {
  57026. return Time (mouseDowns[0].time);
  57027. }
  57028. const Point<int> getLastMouseDownPosition() const throw()
  57029. {
  57030. return mouseDowns[0].position;
  57031. }
  57032. int getNumberOfMultipleClicks() const throw()
  57033. {
  57034. int numClicks = 0;
  57035. if (mouseDowns[0].time != 0)
  57036. {
  57037. if (! mouseMovedSignificantlySincePressed)
  57038. ++numClicks;
  57039. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57040. {
  57041. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57042. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57043. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57044. {
  57045. ++numClicks;
  57046. }
  57047. else
  57048. {
  57049. break;
  57050. }
  57051. }
  57052. }
  57053. return numClicks;
  57054. }
  57055. bool hasMouseMovedSignificantlySincePressed() const throw()
  57056. {
  57057. return mouseMovedSignificantlySincePressed
  57058. || lastTime > mouseDowns[0].time + 300;
  57059. }
  57060. void triggerFakeMove()
  57061. {
  57062. triggerAsyncUpdate();
  57063. }
  57064. void handleAsyncUpdate()
  57065. {
  57066. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57067. }
  57068. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57069. {
  57070. enable = enable && isDragging();
  57071. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57072. if (enable != isUnboundedMouseModeOn)
  57073. {
  57074. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57075. {
  57076. // when released, return the mouse to within the component's bounds
  57077. Component* current = getComponentUnderMouse();
  57078. if (current != 0)
  57079. Desktop::setMousePosition (current->getScreenBounds()
  57080. .getConstrainedPoint (lastScreenPos));
  57081. }
  57082. isUnboundedMouseModeOn = enable;
  57083. unboundedMouseOffset = Point<int>();
  57084. revealCursor (true);
  57085. }
  57086. }
  57087. void handleUnboundedDrag (Component* current)
  57088. {
  57089. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57090. if (! screenArea.contains (lastScreenPos))
  57091. {
  57092. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57093. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57094. Desktop::setMousePosition (componentCentre);
  57095. }
  57096. else if (isCursorVisibleUntilOffscreen
  57097. && (! unboundedMouseOffset.isOrigin())
  57098. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57099. {
  57100. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57101. unboundedMouseOffset = Point<int>();
  57102. }
  57103. }
  57104. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57105. {
  57106. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57107. {
  57108. cursor = MouseCursor::NoCursor;
  57109. forcedUpdate = true;
  57110. }
  57111. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57112. {
  57113. currentCursorHandle = cursor.getHandle();
  57114. cursor.showInWindow (getPeer());
  57115. }
  57116. }
  57117. void hideCursor()
  57118. {
  57119. showMouseCursor (MouseCursor::NoCursor, true);
  57120. }
  57121. void revealCursor (bool forcedUpdate)
  57122. {
  57123. MouseCursor mc (MouseCursor::NormalCursor);
  57124. Component* current = getComponentUnderMouse();
  57125. if (current != 0)
  57126. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57127. showMouseCursor (mc, forcedUpdate);
  57128. }
  57129. int index;
  57130. bool isMouseDevice;
  57131. Point<int> lastScreenPos;
  57132. ModifierKeys buttonState;
  57133. private:
  57134. MouseInputSource& source;
  57135. Component::SafePointer<Component> componentUnderMouse;
  57136. ComponentPeer* lastPeer;
  57137. Point<int> unboundedMouseOffset;
  57138. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57139. void* currentCursorHandle;
  57140. int mouseEventCounter;
  57141. struct RecentMouseDown
  57142. {
  57143. Point<int> position;
  57144. int64 time;
  57145. Component* component;
  57146. };
  57147. RecentMouseDown mouseDowns[4];
  57148. bool mouseMovedSignificantlySincePressed;
  57149. int64 lastTime;
  57150. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57151. {
  57152. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57153. mouseDowns[i] = mouseDowns[i - 1];
  57154. mouseDowns[0].position = screenPos;
  57155. mouseDowns[0].time = time;
  57156. mouseDowns[0].component = component;
  57157. mouseMovedSignificantlySincePressed = false;
  57158. }
  57159. void registerMouseDrag (const Point<int>& screenPos) throw()
  57160. {
  57161. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57162. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57163. }
  57164. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57165. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57166. };
  57167. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57168. {
  57169. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57170. }
  57171. MouseInputSource::~MouseInputSource()
  57172. {
  57173. }
  57174. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57175. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57176. bool MouseInputSource::canHover() const { return isMouse(); }
  57177. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57178. int MouseInputSource::getIndex() const { return pimpl->index; }
  57179. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57180. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57181. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57182. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57183. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57184. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57185. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57186. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57187. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57188. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57189. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57190. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57191. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57192. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57193. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57194. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57195. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57196. {
  57197. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57198. }
  57199. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57200. {
  57201. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57202. }
  57203. END_JUCE_NAMESPACE
  57204. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57205. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57206. BEGIN_JUCE_NAMESPACE
  57207. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57208. : source (0),
  57209. hoverTimeMillisecs (hoverTimeMillisecs_),
  57210. hasJustHovered (false)
  57211. {
  57212. internalTimer.owner = this;
  57213. }
  57214. MouseHoverDetector::~MouseHoverDetector()
  57215. {
  57216. setHoverComponent (0);
  57217. }
  57218. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57219. {
  57220. hoverTimeMillisecs = newTimeInMillisecs;
  57221. }
  57222. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57223. {
  57224. if (source != newSourceComponent)
  57225. {
  57226. internalTimer.stopTimer();
  57227. hasJustHovered = false;
  57228. if (source != 0)
  57229. {
  57230. // ! you need to delete the hover detector before deleting its component
  57231. jassert (source->isValidComponent());
  57232. source->removeMouseListener (&internalTimer);
  57233. }
  57234. source = newSourceComponent;
  57235. if (newSourceComponent != 0)
  57236. newSourceComponent->addMouseListener (&internalTimer, false);
  57237. }
  57238. }
  57239. void MouseHoverDetector::hoverTimerCallback()
  57240. {
  57241. internalTimer.stopTimer();
  57242. if (source != 0)
  57243. {
  57244. const Point<int> pos (source->getMouseXYRelative());
  57245. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57246. {
  57247. hasJustHovered = true;
  57248. mouseHovered (pos.getX(), pos.getY());
  57249. }
  57250. }
  57251. }
  57252. void MouseHoverDetector::checkJustHoveredCallback()
  57253. {
  57254. if (hasJustHovered)
  57255. {
  57256. hasJustHovered = false;
  57257. mouseMovedAfterHover();
  57258. }
  57259. }
  57260. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57261. {
  57262. owner->hoverTimerCallback();
  57263. }
  57264. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57265. {
  57266. stopTimer();
  57267. owner->checkJustHoveredCallback();
  57268. }
  57269. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57270. {
  57271. stopTimer();
  57272. owner->checkJustHoveredCallback();
  57273. }
  57274. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57275. {
  57276. stopTimer();
  57277. owner->checkJustHoveredCallback();
  57278. }
  57279. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57280. {
  57281. stopTimer();
  57282. owner->checkJustHoveredCallback();
  57283. }
  57284. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57285. {
  57286. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57287. {
  57288. lastX = e.x;
  57289. lastY = e.y;
  57290. if (owner->source != 0)
  57291. startTimer (owner->hoverTimeMillisecs);
  57292. owner->checkJustHoveredCallback();
  57293. }
  57294. }
  57295. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57296. {
  57297. stopTimer();
  57298. owner->checkJustHoveredCallback();
  57299. }
  57300. END_JUCE_NAMESPACE
  57301. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57302. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57303. BEGIN_JUCE_NAMESPACE
  57304. void MouseListener::mouseEnter (const MouseEvent&)
  57305. {
  57306. }
  57307. void MouseListener::mouseExit (const MouseEvent&)
  57308. {
  57309. }
  57310. void MouseListener::mouseDown (const MouseEvent&)
  57311. {
  57312. }
  57313. void MouseListener::mouseUp (const MouseEvent&)
  57314. {
  57315. }
  57316. void MouseListener::mouseDrag (const MouseEvent&)
  57317. {
  57318. }
  57319. void MouseListener::mouseMove (const MouseEvent&)
  57320. {
  57321. }
  57322. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57323. {
  57324. }
  57325. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57326. {
  57327. }
  57328. END_JUCE_NAMESPACE
  57329. /*** End of inlined file: juce_MouseListener.cpp ***/
  57330. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57331. BEGIN_JUCE_NAMESPACE
  57332. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57333. const String& buttonTextWhenTrue,
  57334. const String& buttonTextWhenFalse)
  57335. : PropertyComponent (name),
  57336. onText (buttonTextWhenTrue),
  57337. offText (buttonTextWhenFalse)
  57338. {
  57339. addAndMakeVisible (&button);
  57340. button.setClickingTogglesState (false);
  57341. button.addButtonListener (this);
  57342. }
  57343. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57344. const String& name,
  57345. const String& buttonText)
  57346. : PropertyComponent (name),
  57347. onText (buttonText),
  57348. offText (buttonText)
  57349. {
  57350. addAndMakeVisible (&button);
  57351. button.setClickingTogglesState (false);
  57352. button.setButtonText (buttonText);
  57353. button.getToggleStateValue().referTo (valueToControl);
  57354. button.setClickingTogglesState (true);
  57355. }
  57356. BooleanPropertyComponent::~BooleanPropertyComponent()
  57357. {
  57358. }
  57359. void BooleanPropertyComponent::setState (const bool newState)
  57360. {
  57361. button.setToggleState (newState, true);
  57362. }
  57363. bool BooleanPropertyComponent::getState() const
  57364. {
  57365. return button.getToggleState();
  57366. }
  57367. void BooleanPropertyComponent::paint (Graphics& g)
  57368. {
  57369. PropertyComponent::paint (g);
  57370. g.setColour (Colours::white);
  57371. g.fillRect (button.getBounds());
  57372. g.setColour (findColour (ComboBox::outlineColourId));
  57373. g.drawRect (button.getBounds());
  57374. }
  57375. void BooleanPropertyComponent::refresh()
  57376. {
  57377. button.setToggleState (getState(), false);
  57378. button.setButtonText (button.getToggleState() ? onText : offText);
  57379. }
  57380. void BooleanPropertyComponent::buttonClicked (Button*)
  57381. {
  57382. setState (! getState());
  57383. }
  57384. END_JUCE_NAMESPACE
  57385. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57386. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57387. BEGIN_JUCE_NAMESPACE
  57388. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57389. const bool triggerOnMouseDown)
  57390. : PropertyComponent (name)
  57391. {
  57392. addAndMakeVisible (&button);
  57393. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57394. button.addButtonListener (this);
  57395. }
  57396. ButtonPropertyComponent::~ButtonPropertyComponent()
  57397. {
  57398. }
  57399. void ButtonPropertyComponent::refresh()
  57400. {
  57401. button.setButtonText (getButtonText());
  57402. }
  57403. void ButtonPropertyComponent::buttonClicked (Button*)
  57404. {
  57405. buttonClicked();
  57406. }
  57407. END_JUCE_NAMESPACE
  57408. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57409. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57410. BEGIN_JUCE_NAMESPACE
  57411. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57412. public Value::Listener
  57413. {
  57414. public:
  57415. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57416. : sourceValue (sourceValue_),
  57417. mappings (mappings_)
  57418. {
  57419. sourceValue.addListener (this);
  57420. }
  57421. ~RemapperValueSource() {}
  57422. const var getValue() const
  57423. {
  57424. return mappings.indexOf (sourceValue.getValue()) + 1;
  57425. }
  57426. void setValue (const var& newValue)
  57427. {
  57428. const var remappedVal (mappings [(int) newValue - 1]);
  57429. if (remappedVal != sourceValue)
  57430. sourceValue = remappedVal;
  57431. }
  57432. void valueChanged (Value&)
  57433. {
  57434. sendChangeMessage (true);
  57435. }
  57436. juce_UseDebuggingNewOperator
  57437. protected:
  57438. Value sourceValue;
  57439. Array<var> mappings;
  57440. RemapperValueSource (const RemapperValueSource&);
  57441. const RemapperValueSource& operator= (const RemapperValueSource&);
  57442. };
  57443. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57444. : PropertyComponent (name),
  57445. isCustomClass (true)
  57446. {
  57447. }
  57448. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57449. const String& name,
  57450. const StringArray& choices_,
  57451. const Array <var>& correspondingValues)
  57452. : PropertyComponent (name),
  57453. choices (choices_),
  57454. isCustomClass (false)
  57455. {
  57456. // The array of corresponding values must contain one value for each of the items in
  57457. // the choices array!
  57458. jassert (correspondingValues.size() == choices.size());
  57459. createComboBox();
  57460. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57461. }
  57462. ChoicePropertyComponent::~ChoicePropertyComponent()
  57463. {
  57464. }
  57465. void ChoicePropertyComponent::createComboBox()
  57466. {
  57467. addAndMakeVisible (&comboBox);
  57468. for (int i = 0; i < choices.size(); ++i)
  57469. {
  57470. if (choices[i].isNotEmpty())
  57471. comboBox.addItem (choices[i], i + 1);
  57472. else
  57473. comboBox.addSeparator();
  57474. }
  57475. comboBox.setEditableText (false);
  57476. }
  57477. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57478. {
  57479. jassertfalse; // you need to override this method in your subclass!
  57480. }
  57481. int ChoicePropertyComponent::getIndex() const
  57482. {
  57483. jassertfalse; // you need to override this method in your subclass!
  57484. return -1;
  57485. }
  57486. const StringArray& ChoicePropertyComponent::getChoices() const
  57487. {
  57488. return choices;
  57489. }
  57490. void ChoicePropertyComponent::refresh()
  57491. {
  57492. if (isCustomClass)
  57493. {
  57494. if (! comboBox.isVisible())
  57495. {
  57496. createComboBox();
  57497. comboBox.addListener (this);
  57498. }
  57499. comboBox.setSelectedId (getIndex() + 1, true);
  57500. }
  57501. }
  57502. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57503. {
  57504. if (isCustomClass)
  57505. {
  57506. const int newIndex = comboBox.getSelectedId() - 1;
  57507. if (newIndex != getIndex())
  57508. setIndex (newIndex);
  57509. }
  57510. }
  57511. END_JUCE_NAMESPACE
  57512. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57513. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57514. BEGIN_JUCE_NAMESPACE
  57515. PropertyComponent::PropertyComponent (const String& name,
  57516. const int preferredHeight_)
  57517. : Component (name),
  57518. preferredHeight (preferredHeight_)
  57519. {
  57520. jassert (name.isNotEmpty());
  57521. }
  57522. PropertyComponent::~PropertyComponent()
  57523. {
  57524. }
  57525. void PropertyComponent::paint (Graphics& g)
  57526. {
  57527. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57528. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57529. }
  57530. void PropertyComponent::resized()
  57531. {
  57532. if (getNumChildComponents() > 0)
  57533. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57534. }
  57535. void PropertyComponent::enablementChanged()
  57536. {
  57537. repaint();
  57538. }
  57539. END_JUCE_NAMESPACE
  57540. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57541. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57542. BEGIN_JUCE_NAMESPACE
  57543. class PropertyPanel::PropertyHolderComponent : public Component
  57544. {
  57545. public:
  57546. PropertyHolderComponent()
  57547. {
  57548. }
  57549. ~PropertyHolderComponent()
  57550. {
  57551. deleteAllChildren();
  57552. }
  57553. void paint (Graphics&)
  57554. {
  57555. }
  57556. void updateLayout (int width);
  57557. void refreshAll() const;
  57558. private:
  57559. PropertyHolderComponent (const PropertyHolderComponent&);
  57560. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57561. };
  57562. class PropertySectionComponent : public Component
  57563. {
  57564. public:
  57565. PropertySectionComponent (const String& sectionTitle,
  57566. const Array <PropertyComponent*>& newProperties,
  57567. const bool open)
  57568. : Component (sectionTitle),
  57569. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57570. isOpen_ (open)
  57571. {
  57572. for (int i = newProperties.size(); --i >= 0;)
  57573. {
  57574. addAndMakeVisible (newProperties.getUnchecked(i));
  57575. newProperties.getUnchecked(i)->refresh();
  57576. }
  57577. }
  57578. ~PropertySectionComponent()
  57579. {
  57580. deleteAllChildren();
  57581. }
  57582. void paint (Graphics& g)
  57583. {
  57584. if (titleHeight > 0)
  57585. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57586. }
  57587. void resized()
  57588. {
  57589. int y = titleHeight;
  57590. for (int i = getNumChildComponents(); --i >= 0;)
  57591. {
  57592. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57593. if (pec != 0)
  57594. {
  57595. const int prefH = pec->getPreferredHeight();
  57596. pec->setBounds (1, y, getWidth() - 2, prefH);
  57597. y += prefH;
  57598. }
  57599. }
  57600. }
  57601. int getPreferredHeight() const
  57602. {
  57603. int y = titleHeight;
  57604. if (isOpen())
  57605. {
  57606. for (int i = 0; i < getNumChildComponents(); ++i)
  57607. {
  57608. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57609. if (pec != 0)
  57610. y += pec->getPreferredHeight();
  57611. }
  57612. }
  57613. return y;
  57614. }
  57615. void setOpen (const bool open)
  57616. {
  57617. if (isOpen_ != open)
  57618. {
  57619. isOpen_ = open;
  57620. for (int i = 0; i < getNumChildComponents(); ++i)
  57621. {
  57622. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57623. if (pec != 0)
  57624. pec->setVisible (open);
  57625. }
  57626. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57627. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57628. if (pp != 0)
  57629. pp->resized();
  57630. }
  57631. }
  57632. bool isOpen() const
  57633. {
  57634. return isOpen_;
  57635. }
  57636. void refreshAll() const
  57637. {
  57638. for (int i = 0; i < getNumChildComponents(); ++i)
  57639. {
  57640. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57641. if (pec != 0)
  57642. pec->refresh();
  57643. }
  57644. }
  57645. void mouseDown (const MouseEvent&)
  57646. {
  57647. }
  57648. void mouseUp (const MouseEvent& e)
  57649. {
  57650. if (e.getMouseDownX() < titleHeight
  57651. && e.x < titleHeight
  57652. && e.y < titleHeight
  57653. && e.getNumberOfClicks() != 2)
  57654. {
  57655. setOpen (! isOpen());
  57656. }
  57657. }
  57658. void mouseDoubleClick (const MouseEvent& e)
  57659. {
  57660. if (e.y < titleHeight)
  57661. setOpen (! isOpen());
  57662. }
  57663. private:
  57664. int titleHeight;
  57665. bool isOpen_;
  57666. PropertySectionComponent (const PropertySectionComponent&);
  57667. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57668. };
  57669. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57670. {
  57671. int y = 0;
  57672. for (int i = getNumChildComponents(); --i >= 0;)
  57673. {
  57674. PropertySectionComponent* const section
  57675. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57676. if (section != 0)
  57677. {
  57678. const int prefH = section->getPreferredHeight();
  57679. section->setBounds (0, y, width, prefH);
  57680. y += prefH;
  57681. }
  57682. }
  57683. setSize (width, y);
  57684. repaint();
  57685. }
  57686. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57687. {
  57688. for (int i = getNumChildComponents(); --i >= 0;)
  57689. {
  57690. PropertySectionComponent* const section
  57691. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57692. if (section != 0)
  57693. section->refreshAll();
  57694. }
  57695. }
  57696. PropertyPanel::PropertyPanel()
  57697. {
  57698. messageWhenEmpty = TRANS("(nothing selected)");
  57699. addAndMakeVisible (&viewport);
  57700. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57701. viewport.setFocusContainer (true);
  57702. }
  57703. PropertyPanel::~PropertyPanel()
  57704. {
  57705. clear();
  57706. }
  57707. void PropertyPanel::paint (Graphics& g)
  57708. {
  57709. if (propertyHolderComponent->getNumChildComponents() == 0)
  57710. {
  57711. g.setColour (Colours::black.withAlpha (0.5f));
  57712. g.setFont (14.0f);
  57713. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57714. Justification::centred, true);
  57715. }
  57716. }
  57717. void PropertyPanel::resized()
  57718. {
  57719. viewport.setBounds (getLocalBounds());
  57720. updatePropHolderLayout();
  57721. }
  57722. void PropertyPanel::clear()
  57723. {
  57724. if (propertyHolderComponent->getNumChildComponents() > 0)
  57725. {
  57726. propertyHolderComponent->deleteAllChildren();
  57727. repaint();
  57728. }
  57729. }
  57730. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57731. {
  57732. if (propertyHolderComponent->getNumChildComponents() == 0)
  57733. repaint();
  57734. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57735. newProperties,
  57736. true), 0);
  57737. updatePropHolderLayout();
  57738. }
  57739. void PropertyPanel::addSection (const String& sectionTitle,
  57740. const Array <PropertyComponent*>& newProperties,
  57741. const bool shouldBeOpen)
  57742. {
  57743. jassert (sectionTitle.isNotEmpty());
  57744. if (propertyHolderComponent->getNumChildComponents() == 0)
  57745. repaint();
  57746. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57747. newProperties,
  57748. shouldBeOpen), 0);
  57749. updatePropHolderLayout();
  57750. }
  57751. void PropertyPanel::updatePropHolderLayout() const
  57752. {
  57753. const int maxWidth = viewport.getMaximumVisibleWidth();
  57754. propertyHolderComponent->updateLayout (maxWidth);
  57755. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57756. if (maxWidth != newMaxWidth)
  57757. {
  57758. // need to do this twice because of scrollbars changing the size, etc.
  57759. propertyHolderComponent->updateLayout (newMaxWidth);
  57760. }
  57761. }
  57762. void PropertyPanel::refreshAll() const
  57763. {
  57764. propertyHolderComponent->refreshAll();
  57765. }
  57766. const StringArray PropertyPanel::getSectionNames() const
  57767. {
  57768. StringArray s;
  57769. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57770. {
  57771. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57772. if (section != 0 && section->getName().isNotEmpty())
  57773. s.add (section->getName());
  57774. }
  57775. return s;
  57776. }
  57777. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57778. {
  57779. int index = 0;
  57780. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57781. {
  57782. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57783. if (section != 0 && section->getName().isNotEmpty())
  57784. {
  57785. if (index == sectionIndex)
  57786. return section->isOpen();
  57787. ++index;
  57788. }
  57789. }
  57790. return false;
  57791. }
  57792. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57793. {
  57794. int index = 0;
  57795. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57796. {
  57797. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57798. if (section != 0 && section->getName().isNotEmpty())
  57799. {
  57800. if (index == sectionIndex)
  57801. {
  57802. section->setOpen (shouldBeOpen);
  57803. break;
  57804. }
  57805. ++index;
  57806. }
  57807. }
  57808. }
  57809. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57810. {
  57811. int index = 0;
  57812. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57813. {
  57814. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57815. if (section != 0 && section->getName().isNotEmpty())
  57816. {
  57817. if (index == sectionIndex)
  57818. {
  57819. section->setEnabled (shouldBeEnabled);
  57820. break;
  57821. }
  57822. ++index;
  57823. }
  57824. }
  57825. }
  57826. XmlElement* PropertyPanel::getOpennessState() const
  57827. {
  57828. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57829. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57830. const StringArray sections (getSectionNames());
  57831. for (int i = 0; i < sections.size(); ++i)
  57832. {
  57833. if (sections[i].isNotEmpty())
  57834. {
  57835. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57836. e->setAttribute ("name", sections[i]);
  57837. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57838. }
  57839. }
  57840. return xml;
  57841. }
  57842. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57843. {
  57844. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57845. {
  57846. const StringArray sections (getSectionNames());
  57847. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57848. {
  57849. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57850. e->getBoolAttribute ("open"));
  57851. }
  57852. viewport.setViewPosition (viewport.getViewPositionX(),
  57853. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57854. }
  57855. }
  57856. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57857. {
  57858. if (messageWhenEmpty != newMessage)
  57859. {
  57860. messageWhenEmpty = newMessage;
  57861. repaint();
  57862. }
  57863. }
  57864. const String& PropertyPanel::getMessageWhenEmpty() const
  57865. {
  57866. return messageWhenEmpty;
  57867. }
  57868. END_JUCE_NAMESPACE
  57869. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57870. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57871. BEGIN_JUCE_NAMESPACE
  57872. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57873. const double rangeMin,
  57874. const double rangeMax,
  57875. const double interval,
  57876. const double skewFactor)
  57877. : PropertyComponent (name)
  57878. {
  57879. addAndMakeVisible (&slider);
  57880. slider.setRange (rangeMin, rangeMax, interval);
  57881. slider.setSkewFactor (skewFactor);
  57882. slider.setSliderStyle (Slider::LinearBar);
  57883. slider.addListener (this);
  57884. }
  57885. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57886. const String& name,
  57887. const double rangeMin,
  57888. const double rangeMax,
  57889. const double interval,
  57890. const double skewFactor)
  57891. : PropertyComponent (name)
  57892. {
  57893. addAndMakeVisible (&slider);
  57894. slider.setRange (rangeMin, rangeMax, interval);
  57895. slider.setSkewFactor (skewFactor);
  57896. slider.setSliderStyle (Slider::LinearBar);
  57897. slider.getValueObject().referTo (valueToControl);
  57898. }
  57899. SliderPropertyComponent::~SliderPropertyComponent()
  57900. {
  57901. }
  57902. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57903. {
  57904. }
  57905. double SliderPropertyComponent::getValue() const
  57906. {
  57907. return slider.getValue();
  57908. }
  57909. void SliderPropertyComponent::refresh()
  57910. {
  57911. slider.setValue (getValue(), false);
  57912. }
  57913. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57914. {
  57915. if (getValue() != slider.getValue())
  57916. setValue (slider.getValue());
  57917. }
  57918. END_JUCE_NAMESPACE
  57919. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57920. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57921. BEGIN_JUCE_NAMESPACE
  57922. class TextPropLabel : public Label
  57923. {
  57924. TextPropertyComponent& owner;
  57925. int maxChars;
  57926. bool isMultiline;
  57927. public:
  57928. TextPropLabel (TextPropertyComponent& owner_,
  57929. const int maxChars_, const bool isMultiline_)
  57930. : Label (String::empty, String::empty),
  57931. owner (owner_),
  57932. maxChars (maxChars_),
  57933. isMultiline (isMultiline_)
  57934. {
  57935. setEditable (true, true, false);
  57936. setColour (backgroundColourId, Colours::white);
  57937. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57938. }
  57939. ~TextPropLabel()
  57940. {
  57941. }
  57942. TextEditor* createEditorComponent()
  57943. {
  57944. TextEditor* const textEditor = Label::createEditorComponent();
  57945. textEditor->setInputRestrictions (maxChars);
  57946. if (isMultiline)
  57947. {
  57948. textEditor->setMultiLine (true, true);
  57949. textEditor->setReturnKeyStartsNewLine (true);
  57950. }
  57951. return textEditor;
  57952. }
  57953. void textWasEdited()
  57954. {
  57955. owner.textWasEdited();
  57956. }
  57957. };
  57958. TextPropertyComponent::TextPropertyComponent (const String& name,
  57959. const int maxNumChars,
  57960. const bool isMultiLine)
  57961. : PropertyComponent (name)
  57962. {
  57963. createEditor (maxNumChars, isMultiLine);
  57964. }
  57965. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57966. const String& name,
  57967. const int maxNumChars,
  57968. const bool isMultiLine)
  57969. : PropertyComponent (name)
  57970. {
  57971. createEditor (maxNumChars, isMultiLine);
  57972. textEditor->getTextValue().referTo (valueToControl);
  57973. }
  57974. TextPropertyComponent::~TextPropertyComponent()
  57975. {
  57976. deleteAllChildren();
  57977. }
  57978. void TextPropertyComponent::setText (const String& newText)
  57979. {
  57980. textEditor->setText (newText, true);
  57981. }
  57982. const String TextPropertyComponent::getText() const
  57983. {
  57984. return textEditor->getText();
  57985. }
  57986. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57987. {
  57988. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57989. if (isMultiLine)
  57990. {
  57991. textEditor->setJustificationType (Justification::topLeft);
  57992. preferredHeight = 120;
  57993. }
  57994. }
  57995. void TextPropertyComponent::refresh()
  57996. {
  57997. textEditor->setText (getText(), false);
  57998. }
  57999. void TextPropertyComponent::textWasEdited()
  58000. {
  58001. const String newText (textEditor->getText());
  58002. if (getText() != newText)
  58003. setText (newText);
  58004. }
  58005. END_JUCE_NAMESPACE
  58006. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58007. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58008. BEGIN_JUCE_NAMESPACE
  58009. class SimpleDeviceManagerInputLevelMeter : public Component,
  58010. public Timer
  58011. {
  58012. public:
  58013. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58014. : manager (manager_),
  58015. level (0)
  58016. {
  58017. startTimer (50);
  58018. manager->enableInputLevelMeasurement (true);
  58019. }
  58020. ~SimpleDeviceManagerInputLevelMeter()
  58021. {
  58022. manager->enableInputLevelMeasurement (false);
  58023. }
  58024. void timerCallback()
  58025. {
  58026. const float newLevel = (float) manager->getCurrentInputLevel();
  58027. if (std::abs (level - newLevel) > 0.005f)
  58028. {
  58029. level = newLevel;
  58030. repaint();
  58031. }
  58032. }
  58033. void paint (Graphics& g)
  58034. {
  58035. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58036. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58037. }
  58038. private:
  58039. AudioDeviceManager* const manager;
  58040. float level;
  58041. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58042. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58043. };
  58044. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58045. public ListBoxModel
  58046. {
  58047. public:
  58048. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58049. const String& noItemsMessage_,
  58050. const int minNumber_,
  58051. const int maxNumber_)
  58052. : ListBox (String::empty, 0),
  58053. deviceManager (deviceManager_),
  58054. noItemsMessage (noItemsMessage_),
  58055. minNumber (minNumber_),
  58056. maxNumber (maxNumber_)
  58057. {
  58058. items = MidiInput::getDevices();
  58059. setModel (this);
  58060. setOutlineThickness (1);
  58061. }
  58062. ~MidiInputSelectorComponentListBox()
  58063. {
  58064. }
  58065. int getNumRows()
  58066. {
  58067. return items.size();
  58068. }
  58069. void paintListBoxItem (int row,
  58070. Graphics& g,
  58071. int width, int height,
  58072. bool rowIsSelected)
  58073. {
  58074. if (((unsigned int) row) < (unsigned int) items.size())
  58075. {
  58076. if (rowIsSelected)
  58077. g.fillAll (findColour (TextEditor::highlightColourId)
  58078. .withMultipliedAlpha (0.3f));
  58079. const String item (items [row]);
  58080. bool enabled = deviceManager.isMidiInputEnabled (item);
  58081. const int x = getTickX();
  58082. const float tickW = height * 0.75f;
  58083. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58084. enabled, true, true, false);
  58085. g.setFont (height * 0.6f);
  58086. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58087. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58088. }
  58089. }
  58090. void listBoxItemClicked (int row, const MouseEvent& e)
  58091. {
  58092. selectRow (row);
  58093. if (e.x < getTickX())
  58094. flipEnablement (row);
  58095. }
  58096. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58097. {
  58098. flipEnablement (row);
  58099. }
  58100. void returnKeyPressed (int row)
  58101. {
  58102. flipEnablement (row);
  58103. }
  58104. void paint (Graphics& g)
  58105. {
  58106. ListBox::paint (g);
  58107. if (items.size() == 0)
  58108. {
  58109. g.setColour (Colours::grey);
  58110. g.setFont (13.0f);
  58111. g.drawText (noItemsMessage,
  58112. 0, 0, getWidth(), getHeight() / 2,
  58113. Justification::centred, true);
  58114. }
  58115. }
  58116. int getBestHeight (const int preferredHeight)
  58117. {
  58118. const int extra = getOutlineThickness() * 2;
  58119. return jmax (getRowHeight() * 2 + extra,
  58120. jmin (getRowHeight() * getNumRows() + extra,
  58121. preferredHeight));
  58122. }
  58123. juce_UseDebuggingNewOperator
  58124. private:
  58125. AudioDeviceManager& deviceManager;
  58126. const String noItemsMessage;
  58127. StringArray items;
  58128. int minNumber, maxNumber;
  58129. void flipEnablement (const int row)
  58130. {
  58131. if (((unsigned int) row) < (unsigned int) items.size())
  58132. {
  58133. const String item (items [row]);
  58134. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58135. }
  58136. }
  58137. int getTickX() const
  58138. {
  58139. return getRowHeight() + 5;
  58140. }
  58141. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58142. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58143. };
  58144. class AudioDeviceSettingsPanel : public Component,
  58145. public ChangeListener,
  58146. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58147. public ButtonListener
  58148. {
  58149. public:
  58150. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58151. AudioIODeviceType::DeviceSetupDetails& setup_,
  58152. const bool hideAdvancedOptionsWithButton)
  58153. : type (type_),
  58154. setup (setup_)
  58155. {
  58156. if (hideAdvancedOptionsWithButton)
  58157. {
  58158. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58159. showAdvancedSettingsButton->addButtonListener (this);
  58160. }
  58161. type->scanForDevices();
  58162. setup.manager->addChangeListener (this);
  58163. changeListenerCallback (0);
  58164. }
  58165. ~AudioDeviceSettingsPanel()
  58166. {
  58167. setup.manager->removeChangeListener (this);
  58168. }
  58169. void resized()
  58170. {
  58171. const int lx = proportionOfWidth (0.35f);
  58172. const int w = proportionOfWidth (0.4f);
  58173. const int h = 24;
  58174. const int space = 6;
  58175. const int dh = h + space;
  58176. int y = 0;
  58177. if (outputDeviceDropDown != 0)
  58178. {
  58179. outputDeviceDropDown->setBounds (lx, y, w, h);
  58180. if (testButton != 0)
  58181. testButton->setBounds (proportionOfWidth (0.77f),
  58182. outputDeviceDropDown->getY(),
  58183. proportionOfWidth (0.18f),
  58184. h);
  58185. y += dh;
  58186. }
  58187. if (inputDeviceDropDown != 0)
  58188. {
  58189. inputDeviceDropDown->setBounds (lx, y, w, h);
  58190. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58191. inputDeviceDropDown->getY(),
  58192. proportionOfWidth (0.18f),
  58193. h);
  58194. y += dh;
  58195. }
  58196. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58197. if (outputChanList != 0)
  58198. {
  58199. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58200. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58201. y += bh + space;
  58202. }
  58203. if (inputChanList != 0)
  58204. {
  58205. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58206. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58207. y += bh + space;
  58208. }
  58209. y += space * 2;
  58210. if (showAdvancedSettingsButton != 0)
  58211. {
  58212. showAdvancedSettingsButton->changeWidthToFitText (h);
  58213. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58214. }
  58215. if (sampleRateDropDown != 0)
  58216. {
  58217. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58218. || ! showAdvancedSettingsButton->isVisible());
  58219. sampleRateDropDown->setBounds (lx, y, w, h);
  58220. y += dh;
  58221. }
  58222. if (bufferSizeDropDown != 0)
  58223. {
  58224. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58225. || ! showAdvancedSettingsButton->isVisible());
  58226. bufferSizeDropDown->setBounds (lx, y, w, h);
  58227. y += dh;
  58228. }
  58229. if (showUIButton != 0)
  58230. {
  58231. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58232. || ! showAdvancedSettingsButton->isVisible());
  58233. showUIButton->changeWidthToFitText (h);
  58234. showUIButton->setTopLeftPosition (lx, y);
  58235. }
  58236. }
  58237. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58238. {
  58239. if (comboBoxThatHasChanged == 0)
  58240. return;
  58241. AudioDeviceManager::AudioDeviceSetup config;
  58242. setup.manager->getAudioDeviceSetup (config);
  58243. String error;
  58244. if (comboBoxThatHasChanged == outputDeviceDropDown
  58245. || comboBoxThatHasChanged == inputDeviceDropDown)
  58246. {
  58247. if (outputDeviceDropDown != 0)
  58248. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58249. : outputDeviceDropDown->getText();
  58250. if (inputDeviceDropDown != 0)
  58251. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58252. : inputDeviceDropDown->getText();
  58253. if (! type->hasSeparateInputsAndOutputs())
  58254. config.inputDeviceName = config.outputDeviceName;
  58255. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58256. config.useDefaultInputChannels = true;
  58257. else
  58258. config.useDefaultOutputChannels = true;
  58259. error = setup.manager->setAudioDeviceSetup (config, true);
  58260. showCorrectDeviceName (inputDeviceDropDown, true);
  58261. showCorrectDeviceName (outputDeviceDropDown, false);
  58262. updateControlPanelButton();
  58263. resized();
  58264. }
  58265. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58266. {
  58267. if (sampleRateDropDown->getSelectedId() > 0)
  58268. {
  58269. config.sampleRate = sampleRateDropDown->getSelectedId();
  58270. error = setup.manager->setAudioDeviceSetup (config, true);
  58271. }
  58272. }
  58273. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58274. {
  58275. if (bufferSizeDropDown->getSelectedId() > 0)
  58276. {
  58277. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58278. error = setup.manager->setAudioDeviceSetup (config, true);
  58279. }
  58280. }
  58281. if (error.isNotEmpty())
  58282. {
  58283. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58284. "Error when trying to open audio device!",
  58285. error);
  58286. }
  58287. }
  58288. void buttonClicked (Button* button)
  58289. {
  58290. if (button == showAdvancedSettingsButton)
  58291. {
  58292. showAdvancedSettingsButton->setVisible (false);
  58293. resized();
  58294. }
  58295. else if (button == showUIButton)
  58296. {
  58297. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58298. if (device != 0 && device->showControlPanel())
  58299. {
  58300. setup.manager->closeAudioDevice();
  58301. setup.manager->restartLastAudioDevice();
  58302. getTopLevelComponent()->toFront (true);
  58303. }
  58304. }
  58305. else if (button == testButton && testButton != 0)
  58306. {
  58307. setup.manager->playTestSound();
  58308. }
  58309. }
  58310. void updateControlPanelButton()
  58311. {
  58312. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58313. showUIButton = 0;
  58314. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58315. {
  58316. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58317. TRANS ("opens the device's own control panel")));
  58318. showUIButton->addButtonListener (this);
  58319. }
  58320. resized();
  58321. }
  58322. void changeListenerCallback (void*)
  58323. {
  58324. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58325. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58326. {
  58327. if (outputDeviceDropDown == 0)
  58328. {
  58329. outputDeviceDropDown = new ComboBox (String::empty);
  58330. outputDeviceDropDown->addListener (this);
  58331. addAndMakeVisible (outputDeviceDropDown);
  58332. outputDeviceLabel = new Label (String::empty,
  58333. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58334. : TRANS ("device:"));
  58335. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58336. if (setup.maxNumOutputChannels > 0)
  58337. {
  58338. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58339. testButton->addButtonListener (this);
  58340. }
  58341. }
  58342. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58343. }
  58344. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58345. {
  58346. if (inputDeviceDropDown == 0)
  58347. {
  58348. inputDeviceDropDown = new ComboBox (String::empty);
  58349. inputDeviceDropDown->addListener (this);
  58350. addAndMakeVisible (inputDeviceDropDown);
  58351. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58352. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58353. addAndMakeVisible (inputLevelMeter
  58354. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58355. }
  58356. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58357. }
  58358. updateControlPanelButton();
  58359. showCorrectDeviceName (inputDeviceDropDown, true);
  58360. showCorrectDeviceName (outputDeviceDropDown, false);
  58361. if (currentDevice != 0)
  58362. {
  58363. if (setup.maxNumOutputChannels > 0
  58364. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58365. {
  58366. if (outputChanList == 0)
  58367. {
  58368. addAndMakeVisible (outputChanList
  58369. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58370. TRANS ("(no audio output channels found)")));
  58371. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58372. outputChanLabel->attachToComponent (outputChanList, true);
  58373. }
  58374. outputChanList->refresh();
  58375. }
  58376. else
  58377. {
  58378. outputChanLabel = 0;
  58379. outputChanList = 0;
  58380. }
  58381. if (setup.maxNumInputChannels > 0
  58382. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58383. {
  58384. if (inputChanList == 0)
  58385. {
  58386. addAndMakeVisible (inputChanList
  58387. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58388. TRANS ("(no audio input channels found)")));
  58389. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58390. inputChanLabel->attachToComponent (inputChanList, true);
  58391. }
  58392. inputChanList->refresh();
  58393. }
  58394. else
  58395. {
  58396. inputChanLabel = 0;
  58397. inputChanList = 0;
  58398. }
  58399. // sample rate..
  58400. {
  58401. if (sampleRateDropDown == 0)
  58402. {
  58403. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58404. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58405. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58406. }
  58407. else
  58408. {
  58409. sampleRateDropDown->clear();
  58410. sampleRateDropDown->removeListener (this);
  58411. }
  58412. const int numRates = currentDevice->getNumSampleRates();
  58413. for (int i = 0; i < numRates; ++i)
  58414. {
  58415. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58416. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58417. }
  58418. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58419. sampleRateDropDown->addListener (this);
  58420. }
  58421. // buffer size
  58422. {
  58423. if (bufferSizeDropDown == 0)
  58424. {
  58425. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58426. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58427. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58428. }
  58429. else
  58430. {
  58431. bufferSizeDropDown->clear();
  58432. bufferSizeDropDown->removeListener (this);
  58433. }
  58434. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58435. double currentRate = currentDevice->getCurrentSampleRate();
  58436. if (currentRate == 0)
  58437. currentRate = 48000.0;
  58438. for (int i = 0; i < numBufferSizes; ++i)
  58439. {
  58440. const int bs = currentDevice->getBufferSizeSamples (i);
  58441. bufferSizeDropDown->addItem (String (bs)
  58442. + " samples ("
  58443. + String (bs * 1000.0 / currentRate, 1)
  58444. + " ms)",
  58445. bs);
  58446. }
  58447. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58448. bufferSizeDropDown->addListener (this);
  58449. }
  58450. }
  58451. else
  58452. {
  58453. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58454. sampleRateLabel = 0;
  58455. bufferSizeLabel = 0;
  58456. sampleRateDropDown = 0;
  58457. bufferSizeDropDown = 0;
  58458. if (outputDeviceDropDown != 0)
  58459. outputDeviceDropDown->setSelectedId (-1, true);
  58460. if (inputDeviceDropDown != 0)
  58461. inputDeviceDropDown->setSelectedId (-1, true);
  58462. }
  58463. resized();
  58464. setSize (getWidth(), getLowestY() + 4);
  58465. }
  58466. private:
  58467. AudioIODeviceType* const type;
  58468. const AudioIODeviceType::DeviceSetupDetails setup;
  58469. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58470. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58471. ScopedPointer<TextButton> testButton;
  58472. ScopedPointer<Component> inputLevelMeter;
  58473. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58474. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58475. {
  58476. if (box != 0)
  58477. {
  58478. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58479. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58480. box->setSelectedId (index + 1, true);
  58481. if (testButton != 0 && ! isInput)
  58482. testButton->setEnabled (index >= 0);
  58483. }
  58484. }
  58485. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58486. {
  58487. const StringArray devs (type->getDeviceNames (isInputs));
  58488. combo.clear (true);
  58489. for (int i = 0; i < devs.size(); ++i)
  58490. combo.addItem (devs[i], i + 1);
  58491. combo.addItem (TRANS("<< none >>"), -1);
  58492. combo.setSelectedId (-1, true);
  58493. }
  58494. int getLowestY() const
  58495. {
  58496. int y = 0;
  58497. for (int i = getNumChildComponents(); --i >= 0;)
  58498. y = jmax (y, getChildComponent (i)->getBottom());
  58499. return y;
  58500. }
  58501. public:
  58502. class ChannelSelectorListBox : public ListBox,
  58503. public ListBoxModel
  58504. {
  58505. public:
  58506. enum BoxType
  58507. {
  58508. audioInputType,
  58509. audioOutputType
  58510. };
  58511. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58512. const BoxType type_,
  58513. const String& noItemsMessage_)
  58514. : ListBox (String::empty, 0),
  58515. setup (setup_),
  58516. type (type_),
  58517. noItemsMessage (noItemsMessage_)
  58518. {
  58519. refresh();
  58520. setModel (this);
  58521. setOutlineThickness (1);
  58522. }
  58523. ~ChannelSelectorListBox()
  58524. {
  58525. }
  58526. void refresh()
  58527. {
  58528. items.clear();
  58529. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58530. if (currentDevice != 0)
  58531. {
  58532. if (type == audioInputType)
  58533. items = currentDevice->getInputChannelNames();
  58534. else if (type == audioOutputType)
  58535. items = currentDevice->getOutputChannelNames();
  58536. if (setup.useStereoPairs)
  58537. {
  58538. StringArray pairs;
  58539. for (int i = 0; i < items.size(); i += 2)
  58540. {
  58541. const String name (items[i]);
  58542. const String name2 (items[i + 1]);
  58543. String commonBit;
  58544. for (int j = 0; j < name.length(); ++j)
  58545. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58546. commonBit = name.substring (0, j);
  58547. // Make sure we only split the name at a space, because otherwise, things
  58548. // like "input 11" + "input 12" would become "input 11 + 2"
  58549. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58550. commonBit = commonBit.dropLastCharacters (1);
  58551. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58552. }
  58553. items = pairs;
  58554. }
  58555. }
  58556. updateContent();
  58557. repaint();
  58558. }
  58559. int getNumRows()
  58560. {
  58561. return items.size();
  58562. }
  58563. void paintListBoxItem (int row,
  58564. Graphics& g,
  58565. int width, int height,
  58566. bool rowIsSelected)
  58567. {
  58568. if (((unsigned int) row) < (unsigned int) items.size())
  58569. {
  58570. if (rowIsSelected)
  58571. g.fillAll (findColour (TextEditor::highlightColourId)
  58572. .withMultipliedAlpha (0.3f));
  58573. const String item (items [row]);
  58574. bool enabled = false;
  58575. AudioDeviceManager::AudioDeviceSetup config;
  58576. setup.manager->getAudioDeviceSetup (config);
  58577. if (setup.useStereoPairs)
  58578. {
  58579. if (type == audioInputType)
  58580. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58581. else if (type == audioOutputType)
  58582. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58583. }
  58584. else
  58585. {
  58586. if (type == audioInputType)
  58587. enabled = config.inputChannels [row];
  58588. else if (type == audioOutputType)
  58589. enabled = config.outputChannels [row];
  58590. }
  58591. const int x = getTickX();
  58592. const float tickW = height * 0.75f;
  58593. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58594. enabled, true, true, false);
  58595. g.setFont (height * 0.6f);
  58596. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58597. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58598. }
  58599. }
  58600. void listBoxItemClicked (int row, const MouseEvent& e)
  58601. {
  58602. selectRow (row);
  58603. if (e.x < getTickX())
  58604. flipEnablement (row);
  58605. }
  58606. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58607. {
  58608. flipEnablement (row);
  58609. }
  58610. void returnKeyPressed (int row)
  58611. {
  58612. flipEnablement (row);
  58613. }
  58614. void paint (Graphics& g)
  58615. {
  58616. ListBox::paint (g);
  58617. if (items.size() == 0)
  58618. {
  58619. g.setColour (Colours::grey);
  58620. g.setFont (13.0f);
  58621. g.drawText (noItemsMessage,
  58622. 0, 0, getWidth(), getHeight() / 2,
  58623. Justification::centred, true);
  58624. }
  58625. }
  58626. int getBestHeight (int maxHeight)
  58627. {
  58628. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58629. getNumRows())
  58630. + getOutlineThickness() * 2;
  58631. }
  58632. juce_UseDebuggingNewOperator
  58633. private:
  58634. const AudioIODeviceType::DeviceSetupDetails setup;
  58635. const BoxType type;
  58636. const String noItemsMessage;
  58637. StringArray items;
  58638. void flipEnablement (const int row)
  58639. {
  58640. jassert (type == audioInputType || type == audioOutputType);
  58641. if (((unsigned int) row) < (unsigned int) items.size())
  58642. {
  58643. AudioDeviceManager::AudioDeviceSetup config;
  58644. setup.manager->getAudioDeviceSetup (config);
  58645. if (setup.useStereoPairs)
  58646. {
  58647. BigInteger bits;
  58648. BigInteger& original = (type == audioInputType ? config.inputChannels
  58649. : config.outputChannels);
  58650. int i;
  58651. for (i = 0; i < 256; i += 2)
  58652. bits.setBit (i / 2, original [i] || original [i + 1]);
  58653. if (type == audioInputType)
  58654. {
  58655. config.useDefaultInputChannels = false;
  58656. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58657. }
  58658. else
  58659. {
  58660. config.useDefaultOutputChannels = false;
  58661. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58662. }
  58663. for (i = 0; i < 256; ++i)
  58664. original.setBit (i, bits [i / 2]);
  58665. }
  58666. else
  58667. {
  58668. if (type == audioInputType)
  58669. {
  58670. config.useDefaultInputChannels = false;
  58671. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58672. }
  58673. else
  58674. {
  58675. config.useDefaultOutputChannels = false;
  58676. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58677. }
  58678. }
  58679. String error (setup.manager->setAudioDeviceSetup (config, true));
  58680. if (! error.isEmpty())
  58681. {
  58682. //xxx
  58683. }
  58684. }
  58685. }
  58686. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58687. {
  58688. const int numActive = chans.countNumberOfSetBits();
  58689. if (chans [index])
  58690. {
  58691. if (numActive > minNumber)
  58692. chans.setBit (index, false);
  58693. }
  58694. else
  58695. {
  58696. if (numActive >= maxNumber)
  58697. {
  58698. const int firstActiveChan = chans.findNextSetBit();
  58699. chans.setBit (index > firstActiveChan
  58700. ? firstActiveChan : chans.getHighestBit(),
  58701. false);
  58702. }
  58703. chans.setBit (index, true);
  58704. }
  58705. }
  58706. int getTickX() const
  58707. {
  58708. return getRowHeight() + 5;
  58709. }
  58710. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58711. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58712. };
  58713. private:
  58714. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58715. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58716. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58717. };
  58718. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58719. const int minInputChannels_,
  58720. const int maxInputChannels_,
  58721. const int minOutputChannels_,
  58722. const int maxOutputChannels_,
  58723. const bool showMidiInputOptions,
  58724. const bool showMidiOutputSelector,
  58725. const bool showChannelsAsStereoPairs_,
  58726. const bool hideAdvancedOptionsWithButton_)
  58727. : deviceManager (deviceManager_),
  58728. deviceTypeDropDown (0),
  58729. deviceTypeDropDownLabel (0),
  58730. minOutputChannels (minOutputChannels_),
  58731. maxOutputChannels (maxOutputChannels_),
  58732. minInputChannels (minInputChannels_),
  58733. maxInputChannels (maxInputChannels_),
  58734. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58735. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58736. {
  58737. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58738. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58739. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58740. {
  58741. deviceTypeDropDown = new ComboBox (String::empty);
  58742. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58743. {
  58744. deviceTypeDropDown
  58745. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58746. i + 1);
  58747. }
  58748. addAndMakeVisible (deviceTypeDropDown);
  58749. deviceTypeDropDown->addListener (this);
  58750. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58751. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58752. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58753. }
  58754. if (showMidiInputOptions)
  58755. {
  58756. addAndMakeVisible (midiInputsList
  58757. = new MidiInputSelectorComponentListBox (deviceManager,
  58758. TRANS("(no midi inputs available)"),
  58759. 0, 0));
  58760. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58761. midiInputsLabel->setJustificationType (Justification::topRight);
  58762. midiInputsLabel->attachToComponent (midiInputsList, true);
  58763. }
  58764. else
  58765. {
  58766. midiInputsList = 0;
  58767. midiInputsLabel = 0;
  58768. }
  58769. if (showMidiOutputSelector)
  58770. {
  58771. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58772. midiOutputSelector->addListener (this);
  58773. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58774. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58775. }
  58776. else
  58777. {
  58778. midiOutputSelector = 0;
  58779. midiOutputLabel = 0;
  58780. }
  58781. deviceManager_.addChangeListener (this);
  58782. changeListenerCallback (0);
  58783. }
  58784. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58785. {
  58786. deviceManager.removeChangeListener (this);
  58787. }
  58788. void AudioDeviceSelectorComponent::resized()
  58789. {
  58790. const int lx = proportionOfWidth (0.35f);
  58791. const int w = proportionOfWidth (0.4f);
  58792. const int h = 24;
  58793. const int space = 6;
  58794. const int dh = h + space;
  58795. int y = 15;
  58796. if (deviceTypeDropDown != 0)
  58797. {
  58798. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58799. y += dh + space * 2;
  58800. }
  58801. if (audioDeviceSettingsComp != 0)
  58802. {
  58803. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58804. y += audioDeviceSettingsComp->getHeight() + space;
  58805. }
  58806. if (midiInputsList != 0)
  58807. {
  58808. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58809. midiInputsList->setBounds (lx, y, w, bh);
  58810. y += bh + space;
  58811. }
  58812. if (midiOutputSelector != 0)
  58813. midiOutputSelector->setBounds (lx, y, w, h);
  58814. }
  58815. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58816. {
  58817. if (child == audioDeviceSettingsComp)
  58818. resized();
  58819. }
  58820. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58821. {
  58822. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58823. if (device != 0 && device->hasControlPanel())
  58824. {
  58825. if (device->showControlPanel())
  58826. deviceManager.restartLastAudioDevice();
  58827. getTopLevelComponent()->toFront (true);
  58828. }
  58829. }
  58830. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58831. {
  58832. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58833. {
  58834. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58835. if (type != 0)
  58836. {
  58837. audioDeviceSettingsComp = 0;
  58838. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58839. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58840. }
  58841. }
  58842. else if (comboBoxThatHasChanged == midiOutputSelector)
  58843. {
  58844. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58845. }
  58846. }
  58847. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58848. {
  58849. if (deviceTypeDropDown != 0)
  58850. {
  58851. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58852. }
  58853. if (audioDeviceSettingsComp == 0
  58854. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58855. {
  58856. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58857. audioDeviceSettingsComp = 0;
  58858. AudioIODeviceType* const type
  58859. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58860. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58861. if (type != 0)
  58862. {
  58863. AudioIODeviceType::DeviceSetupDetails details;
  58864. details.manager = &deviceManager;
  58865. details.minNumInputChannels = minInputChannels;
  58866. details.maxNumInputChannels = maxInputChannels;
  58867. details.minNumOutputChannels = minOutputChannels;
  58868. details.maxNumOutputChannels = maxOutputChannels;
  58869. details.useStereoPairs = showChannelsAsStereoPairs;
  58870. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58871. if (audioDeviceSettingsComp != 0)
  58872. {
  58873. addAndMakeVisible (audioDeviceSettingsComp);
  58874. audioDeviceSettingsComp->resized();
  58875. }
  58876. }
  58877. }
  58878. if (midiInputsList != 0)
  58879. {
  58880. midiInputsList->updateContent();
  58881. midiInputsList->repaint();
  58882. }
  58883. if (midiOutputSelector != 0)
  58884. {
  58885. midiOutputSelector->clear();
  58886. const StringArray midiOuts (MidiOutput::getDevices());
  58887. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58888. midiOutputSelector->addSeparator();
  58889. for (int i = 0; i < midiOuts.size(); ++i)
  58890. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58891. int current = -1;
  58892. if (deviceManager.getDefaultMidiOutput() != 0)
  58893. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58894. midiOutputSelector->setSelectedId (current, true);
  58895. }
  58896. resized();
  58897. }
  58898. END_JUCE_NAMESPACE
  58899. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58900. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58901. BEGIN_JUCE_NAMESPACE
  58902. BubbleComponent::BubbleComponent()
  58903. : side (0),
  58904. allowablePlacements (above | below | left | right),
  58905. arrowTipX (0.0f),
  58906. arrowTipY (0.0f)
  58907. {
  58908. setInterceptsMouseClicks (false, false);
  58909. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58910. setComponentEffect (&shadow);
  58911. }
  58912. BubbleComponent::~BubbleComponent()
  58913. {
  58914. }
  58915. void BubbleComponent::paint (Graphics& g)
  58916. {
  58917. int x = content.getX();
  58918. int y = content.getY();
  58919. int w = content.getWidth();
  58920. int h = content.getHeight();
  58921. int cw, ch;
  58922. getContentSize (cw, ch);
  58923. if (side == 3)
  58924. x += w - cw;
  58925. else if (side != 1)
  58926. x += (w - cw) / 2;
  58927. w = cw;
  58928. if (side == 2)
  58929. y += h - ch;
  58930. else if (side != 0)
  58931. y += (h - ch) / 2;
  58932. h = ch;
  58933. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58934. (float) x, (float) y,
  58935. (float) w, (float) h);
  58936. const int cx = x + (w - cw) / 2;
  58937. const int cy = y + (h - ch) / 2;
  58938. const int indent = 3;
  58939. g.setOrigin (cx + indent, cy + indent);
  58940. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58941. paintContent (g, cw - indent * 2, ch - indent * 2);
  58942. }
  58943. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58944. {
  58945. allowablePlacements = newPlacement;
  58946. }
  58947. void BubbleComponent::setPosition (Component* componentToPointTo)
  58948. {
  58949. jassert (componentToPointTo->isValidComponent());
  58950. Point<int> pos;
  58951. if (getParentComponent() != 0)
  58952. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58953. else
  58954. pos = componentToPointTo->relativePositionToGlobal (pos);
  58955. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58956. }
  58957. void BubbleComponent::setPosition (const int arrowTipX_,
  58958. const int arrowTipY_)
  58959. {
  58960. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58961. }
  58962. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58963. {
  58964. Rectangle<int> availableSpace;
  58965. if (getParentComponent() != 0)
  58966. {
  58967. availableSpace.setSize (getParentComponent()->getWidth(),
  58968. getParentComponent()->getHeight());
  58969. }
  58970. else
  58971. {
  58972. availableSpace = getParentMonitorArea();
  58973. }
  58974. int x = 0;
  58975. int y = 0;
  58976. int w = 150;
  58977. int h = 30;
  58978. getContentSize (w, h);
  58979. w += 30;
  58980. h += 30;
  58981. const float edgeIndent = 2.0f;
  58982. const int arrowLength = jmin (10, h / 3, w / 3);
  58983. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58984. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58985. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58986. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58987. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58988. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58989. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58990. {
  58991. spaceLeft = spaceRight = 0;
  58992. }
  58993. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58994. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58995. {
  58996. spaceAbove = spaceBelow = 0;
  58997. }
  58998. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58999. {
  59000. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59001. arrowTipX = w * 0.5f;
  59002. content.setSize (w, h - arrowLength);
  59003. if (spaceAbove >= spaceBelow)
  59004. {
  59005. // above
  59006. y = rectangleToPointTo.getY() - h;
  59007. content.setPosition (0, 0);
  59008. arrowTipY = h - edgeIndent;
  59009. side = 2;
  59010. }
  59011. else
  59012. {
  59013. // below
  59014. y = rectangleToPointTo.getBottom();
  59015. content.setPosition (0, arrowLength);
  59016. arrowTipY = edgeIndent;
  59017. side = 0;
  59018. }
  59019. }
  59020. else
  59021. {
  59022. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59023. arrowTipY = h * 0.5f;
  59024. content.setSize (w - arrowLength, h);
  59025. if (spaceLeft > spaceRight)
  59026. {
  59027. // on the left
  59028. x = rectangleToPointTo.getX() - w;
  59029. content.setPosition (0, 0);
  59030. arrowTipX = w - edgeIndent;
  59031. side = 3;
  59032. }
  59033. else
  59034. {
  59035. // on the right
  59036. x = rectangleToPointTo.getRight();
  59037. content.setPosition (arrowLength, 0);
  59038. arrowTipX = edgeIndent;
  59039. side = 1;
  59040. }
  59041. }
  59042. setBounds (x, y, w, h);
  59043. }
  59044. END_JUCE_NAMESPACE
  59045. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59046. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59047. BEGIN_JUCE_NAMESPACE
  59048. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59049. : fadeOutLength (fadeOutLengthMs),
  59050. deleteAfterUse (false)
  59051. {
  59052. }
  59053. BubbleMessageComponent::~BubbleMessageComponent()
  59054. {
  59055. fadeOutComponent (fadeOutLength);
  59056. }
  59057. void BubbleMessageComponent::showAt (int x, int y,
  59058. const String& text,
  59059. const int numMillisecondsBeforeRemoving,
  59060. const bool removeWhenMouseClicked,
  59061. const bool deleteSelfAfterUse)
  59062. {
  59063. textLayout.clear();
  59064. textLayout.setText (text, Font (14.0f));
  59065. textLayout.layout (256, Justification::centredLeft, true);
  59066. setPosition (x, y);
  59067. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59068. }
  59069. void BubbleMessageComponent::showAt (Component* const component,
  59070. const String& text,
  59071. const int numMillisecondsBeforeRemoving,
  59072. const bool removeWhenMouseClicked,
  59073. const bool deleteSelfAfterUse)
  59074. {
  59075. textLayout.clear();
  59076. textLayout.setText (text, Font (14.0f));
  59077. textLayout.layout (256, Justification::centredLeft, true);
  59078. setPosition (component);
  59079. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59080. }
  59081. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59082. const bool removeWhenMouseClicked,
  59083. const bool deleteSelfAfterUse)
  59084. {
  59085. setVisible (true);
  59086. deleteAfterUse = deleteSelfAfterUse;
  59087. if (numMillisecondsBeforeRemoving > 0)
  59088. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59089. else
  59090. expiryTime = 0;
  59091. startTimer (77);
  59092. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59093. if (! (removeWhenMouseClicked && isShowing()))
  59094. mouseClickCounter += 0xfffff;
  59095. repaint();
  59096. }
  59097. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59098. {
  59099. w = textLayout.getWidth() + 16;
  59100. h = textLayout.getHeight() + 16;
  59101. }
  59102. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59103. {
  59104. g.setColour (findColour (TooltipWindow::textColourId));
  59105. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59106. }
  59107. void BubbleMessageComponent::timerCallback()
  59108. {
  59109. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59110. {
  59111. stopTimer();
  59112. setVisible (false);
  59113. if (deleteAfterUse)
  59114. delete this;
  59115. }
  59116. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59117. {
  59118. stopTimer();
  59119. fadeOutComponent (fadeOutLength);
  59120. if (deleteAfterUse)
  59121. delete this;
  59122. }
  59123. }
  59124. END_JUCE_NAMESPACE
  59125. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59126. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59127. BEGIN_JUCE_NAMESPACE
  59128. class ColourComponentSlider : public Slider
  59129. {
  59130. public:
  59131. ColourComponentSlider (const String& name)
  59132. : Slider (name)
  59133. {
  59134. setRange (0.0, 255.0, 1.0);
  59135. }
  59136. ~ColourComponentSlider()
  59137. {
  59138. }
  59139. const String getTextFromValue (double value)
  59140. {
  59141. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59142. }
  59143. double getValueFromText (const String& text)
  59144. {
  59145. return (double) text.getHexValue32();
  59146. }
  59147. private:
  59148. ColourComponentSlider (const ColourComponentSlider&);
  59149. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59150. };
  59151. class ColourSpaceMarker : public Component
  59152. {
  59153. public:
  59154. ColourSpaceMarker()
  59155. {
  59156. setInterceptsMouseClicks (false, false);
  59157. }
  59158. ~ColourSpaceMarker()
  59159. {
  59160. }
  59161. void paint (Graphics& g)
  59162. {
  59163. g.setColour (Colour::greyLevel (0.1f));
  59164. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59165. g.setColour (Colour::greyLevel (0.9f));
  59166. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59167. }
  59168. private:
  59169. ColourSpaceMarker (const ColourSpaceMarker&);
  59170. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59171. };
  59172. class ColourSelector::ColourSpaceView : public Component
  59173. {
  59174. public:
  59175. ColourSpaceView (ColourSelector* owner_,
  59176. float& h_, float& s_, float& v_,
  59177. const int edgeSize)
  59178. : owner (owner_),
  59179. h (h_), s (s_), v (v_),
  59180. lastHue (0.0f),
  59181. edge (edgeSize)
  59182. {
  59183. addAndMakeVisible (&marker);
  59184. setMouseCursor (MouseCursor::CrosshairCursor);
  59185. }
  59186. ~ColourSpaceView()
  59187. {
  59188. }
  59189. void paint (Graphics& g)
  59190. {
  59191. if (colours.isNull())
  59192. {
  59193. const int width = getWidth() / 2;
  59194. const int height = getHeight() / 2;
  59195. colours = Image (Image::RGB, width, height, false);
  59196. Image::BitmapData pixels (colours, true);
  59197. for (int y = 0; y < height; ++y)
  59198. {
  59199. const float val = 1.0f - y / (float) height;
  59200. for (int x = 0; x < width; ++x)
  59201. {
  59202. const float sat = x / (float) width;
  59203. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59204. }
  59205. }
  59206. }
  59207. g.setOpacity (1.0f);
  59208. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59209. 0, 0, colours.getWidth(), colours.getHeight());
  59210. }
  59211. void mouseDown (const MouseEvent& e)
  59212. {
  59213. mouseDrag (e);
  59214. }
  59215. void mouseDrag (const MouseEvent& e)
  59216. {
  59217. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59218. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59219. owner->setSV (sat, val);
  59220. }
  59221. void updateIfNeeded()
  59222. {
  59223. if (lastHue != h)
  59224. {
  59225. lastHue = h;
  59226. colours = Image::null;
  59227. repaint();
  59228. }
  59229. updateMarker();
  59230. }
  59231. void resized()
  59232. {
  59233. colours = Image::null;
  59234. updateMarker();
  59235. }
  59236. private:
  59237. ColourSelector* const owner;
  59238. float& h;
  59239. float& s;
  59240. float& v;
  59241. float lastHue;
  59242. ColourSpaceMarker marker;
  59243. const int edge;
  59244. Image colours;
  59245. void updateMarker()
  59246. {
  59247. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59248. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59249. edge * 2, edge * 2);
  59250. }
  59251. ColourSpaceView (const ColourSpaceView&);
  59252. ColourSpaceView& operator= (const ColourSpaceView&);
  59253. };
  59254. class HueSelectorMarker : public Component
  59255. {
  59256. public:
  59257. HueSelectorMarker()
  59258. {
  59259. setInterceptsMouseClicks (false, false);
  59260. }
  59261. ~HueSelectorMarker()
  59262. {
  59263. }
  59264. void paint (Graphics& g)
  59265. {
  59266. Path p;
  59267. p.addTriangle (1.0f, 1.0f,
  59268. getWidth() * 0.3f, getHeight() * 0.5f,
  59269. 1.0f, getHeight() - 1.0f);
  59270. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59271. getWidth() * 0.7f, getHeight() * 0.5f,
  59272. getWidth() - 1.0f, getHeight() - 1.0f);
  59273. g.setColour (Colours::white.withAlpha (0.75f));
  59274. g.fillPath (p);
  59275. g.setColour (Colours::black.withAlpha (0.75f));
  59276. g.strokePath (p, PathStrokeType (1.2f));
  59277. }
  59278. private:
  59279. HueSelectorMarker (const HueSelectorMarker&);
  59280. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59281. };
  59282. class ColourSelector::HueSelectorComp : public Component
  59283. {
  59284. public:
  59285. HueSelectorComp (ColourSelector* owner_,
  59286. float& h_, float& s_, float& v_,
  59287. const int edgeSize)
  59288. : owner (owner_),
  59289. h (h_), s (s_), v (v_),
  59290. lastHue (0.0f),
  59291. edge (edgeSize)
  59292. {
  59293. addAndMakeVisible (&marker);
  59294. }
  59295. ~HueSelectorComp()
  59296. {
  59297. }
  59298. void paint (Graphics& g)
  59299. {
  59300. const float yScale = 1.0f / (getHeight() - edge * 2);
  59301. const Rectangle<int> clip (g.getClipBounds());
  59302. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59303. {
  59304. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59305. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59306. }
  59307. }
  59308. void resized()
  59309. {
  59310. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59311. getWidth(), edge * 2);
  59312. }
  59313. void mouseDown (const MouseEvent& e)
  59314. {
  59315. mouseDrag (e);
  59316. }
  59317. void mouseDrag (const MouseEvent& e)
  59318. {
  59319. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59320. owner->setHue (hue);
  59321. }
  59322. void updateIfNeeded()
  59323. {
  59324. resized();
  59325. }
  59326. private:
  59327. ColourSelector* const owner;
  59328. float& h;
  59329. float& s;
  59330. float& v;
  59331. float lastHue;
  59332. HueSelectorMarker marker;
  59333. const int edge;
  59334. HueSelectorComp (const HueSelectorComp&);
  59335. HueSelectorComp& operator= (const HueSelectorComp&);
  59336. };
  59337. class ColourSelector::SwatchComponent : public Component
  59338. {
  59339. public:
  59340. SwatchComponent (ColourSelector* owner_, int index_)
  59341. : owner (owner_),
  59342. index (index_)
  59343. {
  59344. }
  59345. ~SwatchComponent()
  59346. {
  59347. }
  59348. void paint (Graphics& g)
  59349. {
  59350. const Colour colour (owner->getSwatchColour (index));
  59351. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59352. Colour (0xffdddddd).overlaidWith (colour),
  59353. Colour (0xffffffff).overlaidWith (colour));
  59354. }
  59355. void mouseDown (const MouseEvent&)
  59356. {
  59357. PopupMenu m;
  59358. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59359. m.addSeparator();
  59360. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59361. const int r = m.showAt (this);
  59362. if (r == 1)
  59363. {
  59364. owner->setCurrentColour (owner->getSwatchColour (index));
  59365. }
  59366. else if (r == 2)
  59367. {
  59368. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59369. {
  59370. owner->setSwatchColour (index, owner->getCurrentColour());
  59371. repaint();
  59372. }
  59373. }
  59374. }
  59375. private:
  59376. ColourSelector* const owner;
  59377. const int index;
  59378. SwatchComponent (const SwatchComponent&);
  59379. SwatchComponent& operator= (const SwatchComponent&);
  59380. };
  59381. ColourSelector::ColourSelector (const int flags_,
  59382. const int edgeGap_,
  59383. const int gapAroundColourSpaceComponent)
  59384. : colour (Colours::white),
  59385. colourSpace (0),
  59386. hueSelector (0),
  59387. flags (flags_),
  59388. edgeGap (edgeGap_)
  59389. {
  59390. // not much point having a selector with no components in it!
  59391. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59392. updateHSV();
  59393. if ((flags & showSliders) != 0)
  59394. {
  59395. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59396. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59397. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59398. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59399. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59400. for (int i = 4; --i >= 0;)
  59401. sliders[i]->addListener (this);
  59402. }
  59403. else
  59404. {
  59405. zeromem (sliders, sizeof (sliders));
  59406. }
  59407. if ((flags & showColourspace) != 0)
  59408. {
  59409. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59410. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59411. }
  59412. update();
  59413. }
  59414. ColourSelector::~ColourSelector()
  59415. {
  59416. dispatchPendingMessages();
  59417. swatchComponents.clear();
  59418. deleteAllChildren();
  59419. }
  59420. const Colour ColourSelector::getCurrentColour() const
  59421. {
  59422. return ((flags & showAlphaChannel) != 0) ? colour
  59423. : colour.withAlpha ((uint8) 0xff);
  59424. }
  59425. void ColourSelector::setCurrentColour (const Colour& c)
  59426. {
  59427. if (c != colour)
  59428. {
  59429. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59430. updateHSV();
  59431. update();
  59432. }
  59433. }
  59434. void ColourSelector::setHue (float newH)
  59435. {
  59436. newH = jlimit (0.0f, 1.0f, newH);
  59437. if (h != newH)
  59438. {
  59439. h = newH;
  59440. colour = Colour (h, s, v, colour.getFloatAlpha());
  59441. update();
  59442. }
  59443. }
  59444. void ColourSelector::setSV (float newS, float newV)
  59445. {
  59446. newS = jlimit (0.0f, 1.0f, newS);
  59447. newV = jlimit (0.0f, 1.0f, newV);
  59448. if (s != newS || v != newV)
  59449. {
  59450. s = newS;
  59451. v = newV;
  59452. colour = Colour (h, s, v, colour.getFloatAlpha());
  59453. update();
  59454. }
  59455. }
  59456. void ColourSelector::updateHSV()
  59457. {
  59458. colour.getHSB (h, s, v);
  59459. }
  59460. void ColourSelector::update()
  59461. {
  59462. if (sliders[0] != 0)
  59463. {
  59464. sliders[0]->setValue ((int) colour.getRed());
  59465. sliders[1]->setValue ((int) colour.getGreen());
  59466. sliders[2]->setValue ((int) colour.getBlue());
  59467. sliders[3]->setValue ((int) colour.getAlpha());
  59468. }
  59469. if (colourSpace != 0)
  59470. {
  59471. colourSpace->updateIfNeeded();
  59472. hueSelector->updateIfNeeded();
  59473. }
  59474. if ((flags & showColourAtTop) != 0)
  59475. repaint (previewArea);
  59476. sendChangeMessage (this);
  59477. }
  59478. void ColourSelector::paint (Graphics& g)
  59479. {
  59480. g.fillAll (findColour (backgroundColourId));
  59481. if ((flags & showColourAtTop) != 0)
  59482. {
  59483. const Colour currentColour (getCurrentColour());
  59484. g.fillCheckerBoard (previewArea, 10, 10,
  59485. Colour (0xffdddddd).overlaidWith (currentColour),
  59486. Colour (0xffffffff).overlaidWith (currentColour));
  59487. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59488. g.setFont (14.0f, true);
  59489. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59490. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59491. Justification::centred, false);
  59492. }
  59493. if ((flags & showSliders) != 0)
  59494. {
  59495. g.setColour (findColour (labelTextColourId));
  59496. g.setFont (11.0f);
  59497. for (int i = 4; --i >= 0;)
  59498. {
  59499. if (sliders[i]->isVisible())
  59500. g.drawText (sliders[i]->getName() + ":",
  59501. 0, sliders[i]->getY(),
  59502. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59503. Justification::centredRight, false);
  59504. }
  59505. }
  59506. }
  59507. void ColourSelector::resized()
  59508. {
  59509. const int swatchesPerRow = 8;
  59510. const int swatchHeight = 22;
  59511. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59512. const int numSwatches = getNumSwatches();
  59513. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59514. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59515. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59516. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59517. int y = topSpace;
  59518. if ((flags & showColourspace) != 0)
  59519. {
  59520. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59521. colourSpace->setBounds (edgeGap, y,
  59522. getWidth() - hueWidth - edgeGap - 4,
  59523. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59524. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59525. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59526. colourSpace->getHeight());
  59527. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59528. }
  59529. if ((flags & showSliders) != 0)
  59530. {
  59531. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59532. for (int i = 0; i < numSliders; ++i)
  59533. {
  59534. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59535. proportionOfWidth (0.72f), sliderHeight - 2);
  59536. y += sliderHeight;
  59537. }
  59538. }
  59539. if (numSwatches > 0)
  59540. {
  59541. const int startX = 8;
  59542. const int xGap = 4;
  59543. const int yGap = 4;
  59544. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59545. y += edgeGap;
  59546. if (swatchComponents.size() != numSwatches)
  59547. {
  59548. swatchComponents.clear();
  59549. for (int i = 0; i < numSwatches; ++i)
  59550. {
  59551. SwatchComponent* const sc = new SwatchComponent (this, i);
  59552. swatchComponents.add (sc);
  59553. addAndMakeVisible (sc);
  59554. }
  59555. }
  59556. int x = startX;
  59557. for (int i = 0; i < swatchComponents.size(); ++i)
  59558. {
  59559. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59560. sc->setBounds (x + xGap / 2,
  59561. y + yGap / 2,
  59562. swatchWidth - xGap,
  59563. swatchHeight - yGap);
  59564. if (((i + 1) % swatchesPerRow) == 0)
  59565. {
  59566. x = startX;
  59567. y += swatchHeight;
  59568. }
  59569. else
  59570. {
  59571. x += swatchWidth;
  59572. }
  59573. }
  59574. }
  59575. }
  59576. void ColourSelector::sliderValueChanged (Slider*)
  59577. {
  59578. if (sliders[0] != 0)
  59579. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59580. (uint8) sliders[1]->getValue(),
  59581. (uint8) sliders[2]->getValue(),
  59582. (uint8) sliders[3]->getValue()));
  59583. }
  59584. int ColourSelector::getNumSwatches() const
  59585. {
  59586. return 0;
  59587. }
  59588. const Colour ColourSelector::getSwatchColour (const int) const
  59589. {
  59590. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59591. return Colours::black;
  59592. }
  59593. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59594. {
  59595. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59596. }
  59597. END_JUCE_NAMESPACE
  59598. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59599. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59600. BEGIN_JUCE_NAMESPACE
  59601. class ShadowWindow : public Component
  59602. {
  59603. Component* owner;
  59604. Image shadowImageSections [12];
  59605. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59606. public:
  59607. ShadowWindow (Component* const owner_,
  59608. const int type_,
  59609. const Image shadowImageSections_ [12])
  59610. : owner (owner_),
  59611. type (type_)
  59612. {
  59613. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59614. shadowImageSections [i] = shadowImageSections_ [i];
  59615. setInterceptsMouseClicks (false, false);
  59616. if (owner_->isOnDesktop())
  59617. {
  59618. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59619. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59620. | ComponentPeer::windowIsTemporary
  59621. | ComponentPeer::windowIgnoresKeyPresses);
  59622. }
  59623. else if (owner_->getParentComponent() != 0)
  59624. {
  59625. owner_->getParentComponent()->addChildComponent (this);
  59626. }
  59627. }
  59628. ~ShadowWindow()
  59629. {
  59630. }
  59631. void paint (Graphics& g)
  59632. {
  59633. const Image& topLeft = shadowImageSections [type * 3];
  59634. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59635. const Image& filler = shadowImageSections [type * 3 + 2];
  59636. g.setOpacity (1.0f);
  59637. if (type < 2)
  59638. {
  59639. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59640. g.drawImage (topLeft,
  59641. 0, 0, topLeft.getWidth(), imH,
  59642. 0, 0, topLeft.getWidth(), imH);
  59643. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59644. g.drawImage (bottomRight,
  59645. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59646. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59647. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59648. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59649. }
  59650. else
  59651. {
  59652. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59653. g.drawImage (topLeft,
  59654. 0, 0, imW, topLeft.getHeight(),
  59655. 0, 0, imW, topLeft.getHeight());
  59656. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59657. g.drawImage (bottomRight,
  59658. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59659. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59660. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59661. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59662. }
  59663. }
  59664. void resized()
  59665. {
  59666. repaint(); // (needed for correct repainting)
  59667. }
  59668. private:
  59669. ShadowWindow (const ShadowWindow&);
  59670. ShadowWindow& operator= (const ShadowWindow&);
  59671. };
  59672. DropShadower::DropShadower (const float alpha_,
  59673. const int xOffset_,
  59674. const int yOffset_,
  59675. const float blurRadius_)
  59676. : owner (0),
  59677. numShadows (0),
  59678. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59679. xOffset (xOffset_),
  59680. yOffset (yOffset_),
  59681. alpha (alpha_),
  59682. blurRadius (blurRadius_),
  59683. inDestructor (false),
  59684. reentrant (false)
  59685. {
  59686. }
  59687. DropShadower::~DropShadower()
  59688. {
  59689. if (owner != 0)
  59690. owner->removeComponentListener (this);
  59691. inDestructor = true;
  59692. deleteShadowWindows();
  59693. }
  59694. void DropShadower::deleteShadowWindows()
  59695. {
  59696. if (numShadows > 0)
  59697. {
  59698. int i;
  59699. for (i = numShadows; --i >= 0;)
  59700. delete shadowWindows[i];
  59701. numShadows = 0;
  59702. }
  59703. }
  59704. void DropShadower::setOwner (Component* componentToFollow)
  59705. {
  59706. if (componentToFollow != owner)
  59707. {
  59708. if (owner != 0)
  59709. owner->removeComponentListener (this);
  59710. // (the component can't be null)
  59711. jassert (componentToFollow != 0);
  59712. owner = componentToFollow;
  59713. jassert (owner != 0);
  59714. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59715. owner->addComponentListener (this);
  59716. updateShadows();
  59717. }
  59718. }
  59719. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59720. {
  59721. updateShadows();
  59722. }
  59723. void DropShadower::componentBroughtToFront (Component&)
  59724. {
  59725. bringShadowWindowsToFront();
  59726. }
  59727. void DropShadower::componentChildrenChanged (Component&)
  59728. {
  59729. }
  59730. void DropShadower::componentParentHierarchyChanged (Component&)
  59731. {
  59732. deleteShadowWindows();
  59733. updateShadows();
  59734. }
  59735. void DropShadower::componentVisibilityChanged (Component&)
  59736. {
  59737. updateShadows();
  59738. }
  59739. void DropShadower::updateShadows()
  59740. {
  59741. if (reentrant || inDestructor || (owner == 0))
  59742. return;
  59743. reentrant = true;
  59744. ComponentPeer* const nw = owner->getPeer();
  59745. const bool isOwnerVisible = owner->isVisible()
  59746. && (nw == 0 || ! nw->isMinimised());
  59747. const bool createShadowWindows = numShadows == 0
  59748. && owner->getWidth() > 0
  59749. && owner->getHeight() > 0
  59750. && isOwnerVisible
  59751. && (Desktop::canUseSemiTransparentWindows()
  59752. || owner->getParentComponent() != 0);
  59753. if (createShadowWindows)
  59754. {
  59755. // keep a cached version of the image to save doing the gaussian too often
  59756. String imageId;
  59757. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59758. const int hash = imageId.hashCode();
  59759. Image bigIm (ImageCache::getFromHashCode (hash));
  59760. if (bigIm.isNull())
  59761. {
  59762. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59763. Graphics bigG (bigIm);
  59764. bigG.setColour (Colours::black.withAlpha (alpha));
  59765. bigG.fillRect (shadowEdge + xOffset,
  59766. shadowEdge + yOffset,
  59767. bigIm.getWidth() - (shadowEdge * 2),
  59768. bigIm.getHeight() - (shadowEdge * 2));
  59769. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59770. blurKernel.createGaussianBlur (blurRadius);
  59771. blurKernel.applyToImage (bigIm, bigIm,
  59772. Rectangle<int> (xOffset, yOffset,
  59773. bigIm.getWidth(), bigIm.getHeight()));
  59774. ImageCache::addImageToCache (bigIm, hash);
  59775. }
  59776. const int iw = bigIm.getWidth();
  59777. const int ih = bigIm.getHeight();
  59778. const int shadowEdge2 = shadowEdge * 2;
  59779. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59780. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59781. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59782. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59783. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59784. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59785. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59786. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59787. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59788. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59789. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59790. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59791. for (int i = 0; i < 4; ++i)
  59792. {
  59793. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59794. ++numShadows;
  59795. }
  59796. }
  59797. if (numShadows > 0)
  59798. {
  59799. for (int i = numShadows; --i >= 0;)
  59800. {
  59801. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59802. shadowWindows[i]->setVisible (isOwnerVisible);
  59803. }
  59804. const int x = owner->getX();
  59805. const int y = owner->getY() - shadowEdge;
  59806. const int w = owner->getWidth();
  59807. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59808. shadowWindows[0]->setBounds (x - shadowEdge,
  59809. y,
  59810. shadowEdge,
  59811. h);
  59812. shadowWindows[1]->setBounds (x + w,
  59813. y,
  59814. shadowEdge,
  59815. h);
  59816. shadowWindows[2]->setBounds (x,
  59817. y,
  59818. w,
  59819. shadowEdge);
  59820. shadowWindows[3]->setBounds (x,
  59821. owner->getBottom(),
  59822. w,
  59823. shadowEdge);
  59824. }
  59825. reentrant = false;
  59826. if (createShadowWindows)
  59827. bringShadowWindowsToFront();
  59828. }
  59829. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59830. const int sx, const int sy)
  59831. {
  59832. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59833. Graphics g (shadowImageSections[num]);
  59834. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59835. }
  59836. void DropShadower::bringShadowWindowsToFront()
  59837. {
  59838. if (! (inDestructor || reentrant))
  59839. {
  59840. updateShadows();
  59841. reentrant = true;
  59842. for (int i = numShadows; --i >= 0;)
  59843. shadowWindows[i]->toBehind (owner);
  59844. reentrant = false;
  59845. }
  59846. }
  59847. END_JUCE_NAMESPACE
  59848. /*** End of inlined file: juce_DropShadower.cpp ***/
  59849. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59850. BEGIN_JUCE_NAMESPACE
  59851. class MagnifyingPeer : public ComponentPeer
  59852. {
  59853. public:
  59854. MagnifyingPeer (Component* const component_,
  59855. MagnifierComponent* const magnifierComp_)
  59856. : ComponentPeer (component_, 0),
  59857. magnifierComp (magnifierComp_)
  59858. {
  59859. }
  59860. ~MagnifyingPeer()
  59861. {
  59862. }
  59863. void* getNativeHandle() const { return 0; }
  59864. void setVisible (bool) {}
  59865. void setTitle (const String&) {}
  59866. void setPosition (int, int) {}
  59867. void setSize (int, int) {}
  59868. void setBounds (int, int, int, int, bool) {}
  59869. void setMinimised (bool) {}
  59870. bool isMinimised() const { return false; }
  59871. void setFullScreen (bool) {}
  59872. bool isFullScreen() const { return false; }
  59873. const BorderSize getFrameSize() const { return BorderSize (0); }
  59874. bool setAlwaysOnTop (bool) { return true; }
  59875. void toFront (bool) {}
  59876. void toBehind (ComponentPeer*) {}
  59877. void setIcon (const Image&) {}
  59878. bool isFocused() const
  59879. {
  59880. return magnifierComp->hasKeyboardFocus (true);
  59881. }
  59882. void grabFocus()
  59883. {
  59884. ComponentPeer* peer = magnifierComp->getPeer();
  59885. if (peer != 0)
  59886. peer->grabFocus();
  59887. }
  59888. void textInputRequired (const Point<int>& position)
  59889. {
  59890. ComponentPeer* peer = magnifierComp->getPeer();
  59891. if (peer != 0)
  59892. peer->textInputRequired (position);
  59893. }
  59894. const Rectangle<int> getBounds() const
  59895. {
  59896. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59897. component->getWidth(), component->getHeight());
  59898. }
  59899. const Point<int> getScreenPosition() const
  59900. {
  59901. return magnifierComp->getScreenPosition();
  59902. }
  59903. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59904. {
  59905. const double zoom = magnifierComp->getScaleFactor();
  59906. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59907. roundToInt (relativePosition.getY() * zoom)));
  59908. }
  59909. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59910. {
  59911. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59912. const double zoom = magnifierComp->getScaleFactor();
  59913. return Point<int> (roundToInt (p.getX() / zoom),
  59914. roundToInt (p.getY() / zoom));
  59915. }
  59916. bool contains (const Point<int>& position, bool) const
  59917. {
  59918. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59919. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59920. }
  59921. void repaint (const Rectangle<int>& area)
  59922. {
  59923. const double zoom = magnifierComp->getScaleFactor();
  59924. magnifierComp->repaint ((int) (area.getX() * zoom),
  59925. (int) (area.getY() * zoom),
  59926. roundToInt (area.getWidth() * zoom) + 1,
  59927. roundToInt (area.getHeight() * zoom) + 1);
  59928. }
  59929. void performAnyPendingRepaintsNow()
  59930. {
  59931. }
  59932. juce_UseDebuggingNewOperator
  59933. private:
  59934. MagnifierComponent* const magnifierComp;
  59935. MagnifyingPeer (const MagnifyingPeer&);
  59936. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59937. };
  59938. class PeerHolderComp : public Component
  59939. {
  59940. public:
  59941. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59942. : magnifierComp (magnifierComp_)
  59943. {
  59944. setVisible (true);
  59945. }
  59946. ~PeerHolderComp()
  59947. {
  59948. }
  59949. ComponentPeer* createNewPeer (int, void*)
  59950. {
  59951. return new MagnifyingPeer (this, magnifierComp);
  59952. }
  59953. void childBoundsChanged (Component* c)
  59954. {
  59955. if (c != 0)
  59956. {
  59957. setSize (c->getWidth(), c->getHeight());
  59958. magnifierComp->childBoundsChanged (this);
  59959. }
  59960. }
  59961. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59962. {
  59963. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59964. Component* const p = magnifierComp->getParentComponent();
  59965. if (p != 0)
  59966. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59967. }
  59968. private:
  59969. MagnifierComponent* const magnifierComp;
  59970. PeerHolderComp (const PeerHolderComp&);
  59971. PeerHolderComp& operator= (const PeerHolderComp&);
  59972. };
  59973. MagnifierComponent::MagnifierComponent (Component* const content_,
  59974. const bool deleteContentCompWhenNoLongerNeeded)
  59975. : content (content_),
  59976. scaleFactor (0.0),
  59977. peer (0),
  59978. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59979. quality (Graphics::lowResamplingQuality),
  59980. mouseSource (0, true)
  59981. {
  59982. holderComp = new PeerHolderComp (this);
  59983. setScaleFactor (1.0);
  59984. }
  59985. MagnifierComponent::~MagnifierComponent()
  59986. {
  59987. delete holderComp;
  59988. if (deleteContent)
  59989. delete content;
  59990. }
  59991. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59992. {
  59993. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59994. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59995. if (scaleFactor != newScaleFactor)
  59996. {
  59997. scaleFactor = newScaleFactor;
  59998. if (scaleFactor == 1.0)
  59999. {
  60000. holderComp->removeFromDesktop();
  60001. peer = 0;
  60002. addChildComponent (content);
  60003. childBoundsChanged (content);
  60004. }
  60005. else
  60006. {
  60007. holderComp->addAndMakeVisible (content);
  60008. holderComp->childBoundsChanged (content);
  60009. childBoundsChanged (holderComp);
  60010. holderComp->addToDesktop (0);
  60011. peer = holderComp->getPeer();
  60012. }
  60013. repaint();
  60014. }
  60015. }
  60016. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60017. {
  60018. quality = newQuality;
  60019. }
  60020. void MagnifierComponent::paint (Graphics& g)
  60021. {
  60022. const int w = holderComp->getWidth();
  60023. const int h = holderComp->getHeight();
  60024. if (w == 0 || h == 0)
  60025. return;
  60026. const Rectangle<int> r (g.getClipBounds());
  60027. const int srcX = (int) (r.getX() / scaleFactor);
  60028. const int srcY = (int) (r.getY() / scaleFactor);
  60029. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60030. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60031. if (scaleFactor >= 1.0)
  60032. {
  60033. ++srcW;
  60034. ++srcH;
  60035. }
  60036. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60037. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60038. {
  60039. Graphics g2 (temp);
  60040. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60041. holderComp->paintEntireComponent (g2);
  60042. }
  60043. g.setImageResamplingQuality (quality);
  60044. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60045. }
  60046. void MagnifierComponent::childBoundsChanged (Component* c)
  60047. {
  60048. if (c != 0)
  60049. setSize (roundToInt (c->getWidth() * scaleFactor),
  60050. roundToInt (c->getHeight() * scaleFactor));
  60051. }
  60052. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60053. {
  60054. if (peer != 0)
  60055. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60056. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60057. }
  60058. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60059. {
  60060. passOnMouseEventToPeer (e);
  60061. }
  60062. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60063. {
  60064. passOnMouseEventToPeer (e);
  60065. }
  60066. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60067. {
  60068. passOnMouseEventToPeer (e);
  60069. }
  60070. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60071. {
  60072. passOnMouseEventToPeer (e);
  60073. }
  60074. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60075. {
  60076. passOnMouseEventToPeer (e);
  60077. }
  60078. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60079. {
  60080. passOnMouseEventToPeer (e);
  60081. }
  60082. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60083. {
  60084. if (peer != 0)
  60085. peer->handleMouseWheel (e.source.getIndex(),
  60086. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60087. ix * 256.0f, iy * 256.0f);
  60088. else
  60089. Component::mouseWheelMove (e, ix, iy);
  60090. }
  60091. int MagnifierComponent::scaleInt (const int n) const
  60092. {
  60093. return roundToInt (n / scaleFactor);
  60094. }
  60095. END_JUCE_NAMESPACE
  60096. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60097. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60098. BEGIN_JUCE_NAMESPACE
  60099. class MidiKeyboardUpDownButton : public Button
  60100. {
  60101. public:
  60102. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60103. const int delta_)
  60104. : Button (String::empty),
  60105. owner (owner_),
  60106. delta (delta_)
  60107. {
  60108. setOpaque (true);
  60109. }
  60110. ~MidiKeyboardUpDownButton()
  60111. {
  60112. }
  60113. void clicked()
  60114. {
  60115. int note = owner->getLowestVisibleKey();
  60116. if (delta < 0)
  60117. note = (note - 1) / 12;
  60118. else
  60119. note = note / 12 + 1;
  60120. owner->setLowestVisibleKey (note * 12);
  60121. }
  60122. void paintButton (Graphics& g,
  60123. bool isMouseOverButton,
  60124. bool isButtonDown)
  60125. {
  60126. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60127. isMouseOverButton, isButtonDown,
  60128. delta > 0);
  60129. }
  60130. private:
  60131. MidiKeyboardComponent* const owner;
  60132. const int delta;
  60133. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60134. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60135. };
  60136. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60137. const Orientation orientation_)
  60138. : state (state_),
  60139. xOffset (0),
  60140. blackNoteLength (1),
  60141. keyWidth (16.0f),
  60142. orientation (orientation_),
  60143. midiChannel (1),
  60144. midiInChannelMask (0xffff),
  60145. velocity (1.0f),
  60146. noteUnderMouse (-1),
  60147. mouseDownNote (-1),
  60148. rangeStart (0),
  60149. rangeEnd (127),
  60150. firstKey (12 * 4),
  60151. canScroll (true),
  60152. mouseDragging (false),
  60153. useMousePositionForVelocity (true),
  60154. keyMappingOctave (6),
  60155. octaveNumForMiddleC (3)
  60156. {
  60157. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60158. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60159. // initialise with a default set of querty key-mappings..
  60160. const char* const keymap = "awsedftgyhujkolp;";
  60161. for (int i = String (keymap).length(); --i >= 0;)
  60162. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60163. setOpaque (true);
  60164. setWantsKeyboardFocus (true);
  60165. state.addListener (this);
  60166. }
  60167. MidiKeyboardComponent::~MidiKeyboardComponent()
  60168. {
  60169. state.removeListener (this);
  60170. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60171. deleteAllChildren();
  60172. }
  60173. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60174. {
  60175. keyWidth = widthInPixels;
  60176. resized();
  60177. }
  60178. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60179. {
  60180. if (orientation != newOrientation)
  60181. {
  60182. orientation = newOrientation;
  60183. resized();
  60184. }
  60185. }
  60186. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60187. const int highestNote)
  60188. {
  60189. jassert (lowestNote >= 0 && lowestNote <= 127);
  60190. jassert (highestNote >= 0 && highestNote <= 127);
  60191. jassert (lowestNote <= highestNote);
  60192. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60193. {
  60194. rangeStart = jlimit (0, 127, lowestNote);
  60195. rangeEnd = jlimit (0, 127, highestNote);
  60196. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60197. resized();
  60198. }
  60199. }
  60200. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60201. {
  60202. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60203. if (noteNumber != firstKey)
  60204. {
  60205. firstKey = noteNumber;
  60206. sendChangeMessage (this);
  60207. resized();
  60208. }
  60209. }
  60210. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60211. {
  60212. if (canScroll != canScroll_)
  60213. {
  60214. canScroll = canScroll_;
  60215. resized();
  60216. }
  60217. }
  60218. void MidiKeyboardComponent::colourChanged()
  60219. {
  60220. repaint();
  60221. }
  60222. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60223. {
  60224. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60225. if (midiChannel != midiChannelNumber)
  60226. {
  60227. resetAnyKeysInUse();
  60228. midiChannel = jlimit (1, 16, midiChannelNumber);
  60229. }
  60230. }
  60231. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60232. {
  60233. midiInChannelMask = midiChannelMask;
  60234. triggerAsyncUpdate();
  60235. }
  60236. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60237. {
  60238. velocity = jlimit (0.0f, 1.0f, velocity_);
  60239. useMousePositionForVelocity = useMousePositionForVelocity_;
  60240. }
  60241. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60242. {
  60243. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60244. static const float blackNoteWidth = 0.7f;
  60245. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60246. 1.0f, 2 - blackNoteWidth * 0.4f,
  60247. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60248. 4.0f, 5 - blackNoteWidth * 0.5f,
  60249. 5.0f, 6 - blackNoteWidth * 0.3f,
  60250. 6.0f };
  60251. static const float widths[] = { 1.0f, blackNoteWidth,
  60252. 1.0f, blackNoteWidth,
  60253. 1.0f, 1.0f, blackNoteWidth,
  60254. 1.0f, blackNoteWidth,
  60255. 1.0f, blackNoteWidth,
  60256. 1.0f };
  60257. const int octave = midiNoteNumber / 12;
  60258. const int note = midiNoteNumber % 12;
  60259. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60260. w = roundToInt (widths [note] * keyWidth_);
  60261. }
  60262. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60263. {
  60264. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60265. int rx, rw;
  60266. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60267. x -= xOffset + rx;
  60268. }
  60269. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60270. {
  60271. int x, y;
  60272. getKeyPos (midiNoteNumber, x, y);
  60273. return x;
  60274. }
  60275. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60276. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60277. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60278. {
  60279. if (! reallyContains (pos.getX(), pos.getY(), false))
  60280. return -1;
  60281. Point<int> p (pos);
  60282. if (orientation != horizontalKeyboard)
  60283. {
  60284. p = Point<int> (p.getY(), p.getX());
  60285. if (orientation == verticalKeyboardFacingLeft)
  60286. p = Point<int> (p.getX(), getWidth() - p.getY());
  60287. else
  60288. p = Point<int> (getHeight() - p.getX(), p.getY());
  60289. }
  60290. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60291. }
  60292. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60293. {
  60294. if (pos.getY() < blackNoteLength)
  60295. {
  60296. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60297. {
  60298. for (int i = 0; i < 5; ++i)
  60299. {
  60300. const int note = octaveStart + blackNotes [i];
  60301. if (note >= rangeStart && note <= rangeEnd)
  60302. {
  60303. int kx, kw;
  60304. getKeyPos (note, kx, kw);
  60305. kx += xOffset;
  60306. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60307. {
  60308. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60309. return note;
  60310. }
  60311. }
  60312. }
  60313. }
  60314. }
  60315. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60316. {
  60317. for (int i = 0; i < 7; ++i)
  60318. {
  60319. const int note = octaveStart + whiteNotes [i];
  60320. if (note >= rangeStart && note <= rangeEnd)
  60321. {
  60322. int kx, kw;
  60323. getKeyPos (note, kx, kw);
  60324. kx += xOffset;
  60325. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60326. {
  60327. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60328. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60329. return note;
  60330. }
  60331. }
  60332. }
  60333. }
  60334. mousePositionVelocity = 0;
  60335. return -1;
  60336. }
  60337. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60338. {
  60339. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60340. {
  60341. int x, w;
  60342. getKeyPos (noteNum, x, w);
  60343. if (orientation == horizontalKeyboard)
  60344. repaint (x, 0, w, getHeight());
  60345. else if (orientation == verticalKeyboardFacingLeft)
  60346. repaint (0, x, getWidth(), w);
  60347. else if (orientation == verticalKeyboardFacingRight)
  60348. repaint (0, getHeight() - x - w, getWidth(), w);
  60349. }
  60350. }
  60351. void MidiKeyboardComponent::paint (Graphics& g)
  60352. {
  60353. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60354. const Colour lineColour (findColour (keySeparatorLineColourId));
  60355. const Colour textColour (findColour (textLabelColourId));
  60356. int x, w, octave;
  60357. for (octave = 0; octave < 128; octave += 12)
  60358. {
  60359. for (int white = 0; white < 7; ++white)
  60360. {
  60361. const int noteNum = octave + whiteNotes [white];
  60362. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60363. {
  60364. getKeyPos (noteNum, x, w);
  60365. if (orientation == horizontalKeyboard)
  60366. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60367. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60368. noteUnderMouse == noteNum,
  60369. lineColour, textColour);
  60370. else if (orientation == verticalKeyboardFacingLeft)
  60371. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60372. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60373. noteUnderMouse == noteNum,
  60374. lineColour, textColour);
  60375. else if (orientation == verticalKeyboardFacingRight)
  60376. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60377. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60378. noteUnderMouse == noteNum,
  60379. lineColour, textColour);
  60380. }
  60381. }
  60382. }
  60383. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60384. if (orientation == verticalKeyboardFacingLeft)
  60385. {
  60386. x1 = getWidth() - 1.0f;
  60387. x2 = getWidth() - 5.0f;
  60388. }
  60389. else if (orientation == verticalKeyboardFacingRight)
  60390. x2 = 5.0f;
  60391. else
  60392. y2 = 5.0f;
  60393. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60394. Colours::transparentBlack, x2, y2, false));
  60395. getKeyPos (rangeEnd, x, w);
  60396. x += w;
  60397. if (orientation == verticalKeyboardFacingLeft)
  60398. g.fillRect (getWidth() - 5, 0, 5, x);
  60399. else if (orientation == verticalKeyboardFacingRight)
  60400. g.fillRect (0, 0, 5, x);
  60401. else
  60402. g.fillRect (0, 0, x, 5);
  60403. g.setColour (lineColour);
  60404. if (orientation == verticalKeyboardFacingLeft)
  60405. g.fillRect (0, 0, 1, x);
  60406. else if (orientation == verticalKeyboardFacingRight)
  60407. g.fillRect (getWidth() - 1, 0, 1, x);
  60408. else
  60409. g.fillRect (0, getHeight() - 1, x, 1);
  60410. const Colour blackNoteColour (findColour (blackNoteColourId));
  60411. for (octave = 0; octave < 128; octave += 12)
  60412. {
  60413. for (int black = 0; black < 5; ++black)
  60414. {
  60415. const int noteNum = octave + blackNotes [black];
  60416. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60417. {
  60418. getKeyPos (noteNum, x, w);
  60419. if (orientation == horizontalKeyboard)
  60420. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60421. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60422. noteUnderMouse == noteNum,
  60423. blackNoteColour);
  60424. else if (orientation == verticalKeyboardFacingLeft)
  60425. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60426. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60427. noteUnderMouse == noteNum,
  60428. blackNoteColour);
  60429. else if (orientation == verticalKeyboardFacingRight)
  60430. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60431. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60432. noteUnderMouse == noteNum,
  60433. blackNoteColour);
  60434. }
  60435. }
  60436. }
  60437. }
  60438. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60439. Graphics& g, int x, int y, int w, int h,
  60440. bool isDown, bool isOver,
  60441. const Colour& lineColour,
  60442. const Colour& textColour)
  60443. {
  60444. Colour c (Colours::transparentWhite);
  60445. if (isDown)
  60446. c = findColour (keyDownOverlayColourId);
  60447. if (isOver)
  60448. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60449. g.setColour (c);
  60450. g.fillRect (x, y, w, h);
  60451. const String text (getWhiteNoteText (midiNoteNumber));
  60452. if (! text.isEmpty())
  60453. {
  60454. g.setColour (textColour);
  60455. Font f (jmin (12.0f, keyWidth * 0.9f));
  60456. f.setHorizontalScale (0.8f);
  60457. g.setFont (f);
  60458. Justification justification (Justification::centredBottom);
  60459. if (orientation == verticalKeyboardFacingLeft)
  60460. justification = Justification::centredLeft;
  60461. else if (orientation == verticalKeyboardFacingRight)
  60462. justification = Justification::centredRight;
  60463. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60464. }
  60465. g.setColour (lineColour);
  60466. if (orientation == horizontalKeyboard)
  60467. g.fillRect (x, y, 1, h);
  60468. else if (orientation == verticalKeyboardFacingLeft)
  60469. g.fillRect (x, y, w, 1);
  60470. else if (orientation == verticalKeyboardFacingRight)
  60471. g.fillRect (x, y + h - 1, w, 1);
  60472. if (midiNoteNumber == rangeEnd)
  60473. {
  60474. if (orientation == horizontalKeyboard)
  60475. g.fillRect (x + w, y, 1, h);
  60476. else if (orientation == verticalKeyboardFacingLeft)
  60477. g.fillRect (x, y + h, w, 1);
  60478. else if (orientation == verticalKeyboardFacingRight)
  60479. g.fillRect (x, y - 1, w, 1);
  60480. }
  60481. }
  60482. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60483. Graphics& g, int x, int y, int w, int h,
  60484. bool isDown, bool isOver,
  60485. const Colour& noteFillColour)
  60486. {
  60487. Colour c (noteFillColour);
  60488. if (isDown)
  60489. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60490. if (isOver)
  60491. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60492. g.setColour (c);
  60493. g.fillRect (x, y, w, h);
  60494. if (isDown)
  60495. {
  60496. g.setColour (noteFillColour);
  60497. g.drawRect (x, y, w, h);
  60498. }
  60499. else
  60500. {
  60501. const int xIndent = jmax (1, jmin (w, h) / 8);
  60502. g.setColour (c.brighter());
  60503. if (orientation == horizontalKeyboard)
  60504. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60505. else if (orientation == verticalKeyboardFacingLeft)
  60506. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60507. else if (orientation == verticalKeyboardFacingRight)
  60508. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60509. }
  60510. }
  60511. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60512. {
  60513. octaveNumForMiddleC = octaveNumForMiddleC_;
  60514. repaint();
  60515. }
  60516. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60517. {
  60518. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60519. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60520. return String::empty;
  60521. }
  60522. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60523. const bool isMouseOver_,
  60524. const bool isButtonDown,
  60525. const bool movesOctavesUp)
  60526. {
  60527. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60528. float angle;
  60529. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60530. angle = movesOctavesUp ? 0.0f : 0.5f;
  60531. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60532. angle = movesOctavesUp ? 0.25f : 0.75f;
  60533. else
  60534. angle = movesOctavesUp ? 0.75f : 0.25f;
  60535. Path path;
  60536. path.lineTo (0.0f, 1.0f);
  60537. path.lineTo (1.0f, 0.5f);
  60538. path.closeSubPath();
  60539. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60540. g.setColour (findColour (upDownButtonArrowColourId)
  60541. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60542. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60543. w - 2.0f,
  60544. h - 2.0f,
  60545. true));
  60546. }
  60547. void MidiKeyboardComponent::resized()
  60548. {
  60549. int w = getWidth();
  60550. int h = getHeight();
  60551. if (w > 0 && h > 0)
  60552. {
  60553. if (orientation != horizontalKeyboard)
  60554. swapVariables (w, h);
  60555. blackNoteLength = roundToInt (h * 0.7f);
  60556. int kx2, kw2;
  60557. getKeyPos (rangeEnd, kx2, kw2);
  60558. kx2 += kw2;
  60559. if (firstKey != rangeStart)
  60560. {
  60561. int kx1, kw1;
  60562. getKeyPos (rangeStart, kx1, kw1);
  60563. if (kx2 - kx1 <= w)
  60564. {
  60565. firstKey = rangeStart;
  60566. sendChangeMessage (this);
  60567. repaint();
  60568. }
  60569. }
  60570. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60571. scrollDown->setVisible (showScrollButtons);
  60572. scrollUp->setVisible (showScrollButtons);
  60573. xOffset = 0;
  60574. if (showScrollButtons)
  60575. {
  60576. const int scrollButtonW = jmin (12, w / 2);
  60577. if (orientation == horizontalKeyboard)
  60578. {
  60579. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60580. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60581. }
  60582. else if (orientation == verticalKeyboardFacingLeft)
  60583. {
  60584. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60585. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60586. }
  60587. else if (orientation == verticalKeyboardFacingRight)
  60588. {
  60589. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60590. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60591. }
  60592. int endOfLastKey, kw;
  60593. getKeyPos (rangeEnd, endOfLastKey, kw);
  60594. endOfLastKey += kw;
  60595. float mousePositionVelocity;
  60596. const int spaceAvailable = w - scrollButtonW * 2;
  60597. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60598. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60599. {
  60600. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60601. sendChangeMessage (this);
  60602. }
  60603. int newOffset = 0;
  60604. getKeyPos (firstKey, newOffset, kw);
  60605. xOffset = newOffset - scrollButtonW;
  60606. }
  60607. else
  60608. {
  60609. firstKey = rangeStart;
  60610. }
  60611. timerCallback();
  60612. repaint();
  60613. }
  60614. }
  60615. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60616. {
  60617. triggerAsyncUpdate();
  60618. }
  60619. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60620. {
  60621. triggerAsyncUpdate();
  60622. }
  60623. void MidiKeyboardComponent::handleAsyncUpdate()
  60624. {
  60625. for (int i = rangeStart; i <= rangeEnd; ++i)
  60626. {
  60627. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60628. {
  60629. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60630. repaintNote (i);
  60631. }
  60632. }
  60633. }
  60634. void MidiKeyboardComponent::resetAnyKeysInUse()
  60635. {
  60636. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60637. {
  60638. state.allNotesOff (midiChannel);
  60639. keysPressed.clear();
  60640. mouseDownNote = -1;
  60641. }
  60642. }
  60643. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60644. {
  60645. float mousePositionVelocity = 0.0f;
  60646. const int newNote = (mouseDragging || isMouseOver())
  60647. ? xyToNote (pos, mousePositionVelocity) : -1;
  60648. if (noteUnderMouse != newNote)
  60649. {
  60650. if (mouseDownNote >= 0)
  60651. {
  60652. state.noteOff (midiChannel, mouseDownNote);
  60653. mouseDownNote = -1;
  60654. }
  60655. if (mouseDragging && newNote >= 0)
  60656. {
  60657. if (! useMousePositionForVelocity)
  60658. mousePositionVelocity = 1.0f;
  60659. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60660. mouseDownNote = newNote;
  60661. }
  60662. repaintNote (noteUnderMouse);
  60663. noteUnderMouse = newNote;
  60664. repaintNote (noteUnderMouse);
  60665. }
  60666. else if (mouseDownNote >= 0 && ! mouseDragging)
  60667. {
  60668. state.noteOff (midiChannel, mouseDownNote);
  60669. mouseDownNote = -1;
  60670. }
  60671. }
  60672. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60673. {
  60674. updateNoteUnderMouse (e.getPosition());
  60675. stopTimer();
  60676. }
  60677. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60678. {
  60679. float mousePositionVelocity;
  60680. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60681. if (newNote >= 0)
  60682. mouseDraggedToKey (newNote, e);
  60683. updateNoteUnderMouse (e.getPosition());
  60684. }
  60685. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60686. {
  60687. return true;
  60688. }
  60689. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60690. {
  60691. }
  60692. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60693. {
  60694. float mousePositionVelocity;
  60695. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60696. mouseDragging = false;
  60697. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60698. {
  60699. repaintNote (noteUnderMouse);
  60700. noteUnderMouse = -1;
  60701. mouseDragging = true;
  60702. updateNoteUnderMouse (e.getPosition());
  60703. startTimer (500);
  60704. }
  60705. }
  60706. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60707. {
  60708. mouseDragging = false;
  60709. updateNoteUnderMouse (e.getPosition());
  60710. stopTimer();
  60711. }
  60712. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60713. {
  60714. updateNoteUnderMouse (e.getPosition());
  60715. }
  60716. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60717. {
  60718. updateNoteUnderMouse (e.getPosition());
  60719. }
  60720. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60721. {
  60722. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60723. }
  60724. void MidiKeyboardComponent::timerCallback()
  60725. {
  60726. updateNoteUnderMouse (getMouseXYRelative());
  60727. }
  60728. void MidiKeyboardComponent::clearKeyMappings()
  60729. {
  60730. resetAnyKeysInUse();
  60731. keyPressNotes.clear();
  60732. keyPresses.clear();
  60733. }
  60734. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60735. const int midiNoteOffsetFromC)
  60736. {
  60737. removeKeyPressForNote (midiNoteOffsetFromC);
  60738. keyPressNotes.add (midiNoteOffsetFromC);
  60739. keyPresses.add (key);
  60740. }
  60741. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60742. {
  60743. for (int i = keyPressNotes.size(); --i >= 0;)
  60744. {
  60745. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60746. {
  60747. keyPressNotes.remove (i);
  60748. keyPresses.remove (i);
  60749. }
  60750. }
  60751. }
  60752. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60753. {
  60754. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60755. keyMappingOctave = newOctaveNumber;
  60756. }
  60757. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60758. {
  60759. bool keyPressUsed = false;
  60760. for (int i = keyPresses.size(); --i >= 0;)
  60761. {
  60762. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60763. if (keyPresses.getReference(i).isCurrentlyDown())
  60764. {
  60765. if (! keysPressed [note])
  60766. {
  60767. keysPressed.setBit (note);
  60768. state.noteOn (midiChannel, note, velocity);
  60769. keyPressUsed = true;
  60770. }
  60771. }
  60772. else
  60773. {
  60774. if (keysPressed [note])
  60775. {
  60776. keysPressed.clearBit (note);
  60777. state.noteOff (midiChannel, note);
  60778. keyPressUsed = true;
  60779. }
  60780. }
  60781. }
  60782. return keyPressUsed;
  60783. }
  60784. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60785. {
  60786. resetAnyKeysInUse();
  60787. }
  60788. END_JUCE_NAMESPACE
  60789. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60790. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60791. #if JUCE_OPENGL
  60792. BEGIN_JUCE_NAMESPACE
  60793. extern void juce_glViewport (const int w, const int h);
  60794. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60795. const int alphaBits_,
  60796. const int depthBufferBits_,
  60797. const int stencilBufferBits_)
  60798. : redBits (bitsPerRGBComponent),
  60799. greenBits (bitsPerRGBComponent),
  60800. blueBits (bitsPerRGBComponent),
  60801. alphaBits (alphaBits_),
  60802. depthBufferBits (depthBufferBits_),
  60803. stencilBufferBits (stencilBufferBits_),
  60804. accumulationBufferRedBits (0),
  60805. accumulationBufferGreenBits (0),
  60806. accumulationBufferBlueBits (0),
  60807. accumulationBufferAlphaBits (0),
  60808. fullSceneAntiAliasingNumSamples (0)
  60809. {
  60810. }
  60811. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60812. : redBits (other.redBits),
  60813. greenBits (other.greenBits),
  60814. blueBits (other.blueBits),
  60815. alphaBits (other.alphaBits),
  60816. depthBufferBits (other.depthBufferBits),
  60817. stencilBufferBits (other.stencilBufferBits),
  60818. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60819. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60820. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60821. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60822. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60823. {
  60824. }
  60825. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60826. {
  60827. redBits = other.redBits;
  60828. greenBits = other.greenBits;
  60829. blueBits = other.blueBits;
  60830. alphaBits = other.alphaBits;
  60831. depthBufferBits = other.depthBufferBits;
  60832. stencilBufferBits = other.stencilBufferBits;
  60833. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60834. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60835. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60836. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60837. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60838. return *this;
  60839. }
  60840. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60841. {
  60842. return redBits == other.redBits
  60843. && greenBits == other.greenBits
  60844. && blueBits == other.blueBits
  60845. && alphaBits == other.alphaBits
  60846. && depthBufferBits == other.depthBufferBits
  60847. && stencilBufferBits == other.stencilBufferBits
  60848. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60849. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60850. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60851. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60852. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60853. }
  60854. static Array<OpenGLContext*> knownContexts;
  60855. OpenGLContext::OpenGLContext() throw()
  60856. {
  60857. knownContexts.add (this);
  60858. }
  60859. OpenGLContext::~OpenGLContext()
  60860. {
  60861. knownContexts.removeValue (this);
  60862. }
  60863. OpenGLContext* OpenGLContext::getCurrentContext()
  60864. {
  60865. for (int i = knownContexts.size(); --i >= 0;)
  60866. {
  60867. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60868. if (oglc->isActive())
  60869. return oglc;
  60870. }
  60871. return 0;
  60872. }
  60873. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60874. {
  60875. public:
  60876. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60877. : ComponentMovementWatcher (owner_),
  60878. owner (owner_),
  60879. wasShowing (false)
  60880. {
  60881. }
  60882. ~OpenGLComponentWatcher() {}
  60883. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60884. {
  60885. owner->updateContextPosition();
  60886. }
  60887. void componentPeerChanged()
  60888. {
  60889. const ScopedLock sl (owner->getContextLock());
  60890. owner->deleteContext();
  60891. }
  60892. void componentVisibilityChanged (Component&)
  60893. {
  60894. const bool isShowingNow = owner->isShowing();
  60895. if (wasShowing != isShowingNow)
  60896. {
  60897. wasShowing = isShowingNow;
  60898. if (! isShowingNow)
  60899. {
  60900. const ScopedLock sl (owner->getContextLock());
  60901. owner->deleteContext();
  60902. }
  60903. }
  60904. }
  60905. juce_UseDebuggingNewOperator
  60906. private:
  60907. OpenGLComponent* const owner;
  60908. bool wasShowing;
  60909. };
  60910. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60911. : type (type_),
  60912. contextToShareListsWith (0),
  60913. needToUpdateViewport (true)
  60914. {
  60915. setOpaque (true);
  60916. componentWatcher = new OpenGLComponentWatcher (this);
  60917. }
  60918. OpenGLComponent::~OpenGLComponent()
  60919. {
  60920. deleteContext();
  60921. componentWatcher = 0;
  60922. }
  60923. void OpenGLComponent::deleteContext()
  60924. {
  60925. const ScopedLock sl (contextLock);
  60926. context = 0;
  60927. }
  60928. void OpenGLComponent::updateContextPosition()
  60929. {
  60930. needToUpdateViewport = true;
  60931. if (getWidth() > 0 && getHeight() > 0)
  60932. {
  60933. Component* const topComp = getTopLevelComponent();
  60934. if (topComp->getPeer() != 0)
  60935. {
  60936. const ScopedLock sl (contextLock);
  60937. if (context != 0)
  60938. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60939. getScreenY() - topComp->getScreenY(),
  60940. getWidth(),
  60941. getHeight(),
  60942. topComp->getHeight());
  60943. }
  60944. }
  60945. }
  60946. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60947. {
  60948. OpenGLPixelFormat pf;
  60949. const ScopedLock sl (contextLock);
  60950. if (context != 0)
  60951. pf = context->getPixelFormat();
  60952. return pf;
  60953. }
  60954. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60955. {
  60956. if (! (preferredPixelFormat == formatToUse))
  60957. {
  60958. const ScopedLock sl (contextLock);
  60959. deleteContext();
  60960. preferredPixelFormat = formatToUse;
  60961. }
  60962. }
  60963. void OpenGLComponent::shareWith (OpenGLContext* c)
  60964. {
  60965. if (contextToShareListsWith != c)
  60966. {
  60967. const ScopedLock sl (contextLock);
  60968. deleteContext();
  60969. contextToShareListsWith = c;
  60970. }
  60971. }
  60972. bool OpenGLComponent::makeCurrentContextActive()
  60973. {
  60974. if (context == 0)
  60975. {
  60976. const ScopedLock sl (contextLock);
  60977. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60978. {
  60979. context = createContext();
  60980. if (context != 0)
  60981. {
  60982. updateContextPosition();
  60983. if (context->makeActive())
  60984. newOpenGLContextCreated();
  60985. }
  60986. }
  60987. }
  60988. return context != 0 && context->makeActive();
  60989. }
  60990. void OpenGLComponent::makeCurrentContextInactive()
  60991. {
  60992. if (context != 0)
  60993. context->makeInactive();
  60994. }
  60995. bool OpenGLComponent::isActiveContext() const throw()
  60996. {
  60997. return context != 0 && context->isActive();
  60998. }
  60999. void OpenGLComponent::swapBuffers()
  61000. {
  61001. if (context != 0)
  61002. context->swapBuffers();
  61003. }
  61004. void OpenGLComponent::paint (Graphics&)
  61005. {
  61006. if (renderAndSwapBuffers())
  61007. {
  61008. ComponentPeer* const peer = getPeer();
  61009. if (peer != 0)
  61010. {
  61011. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61012. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61013. }
  61014. }
  61015. }
  61016. bool OpenGLComponent::renderAndSwapBuffers()
  61017. {
  61018. const ScopedLock sl (contextLock);
  61019. if (! makeCurrentContextActive())
  61020. return false;
  61021. if (needToUpdateViewport)
  61022. {
  61023. needToUpdateViewport = false;
  61024. juce_glViewport (getWidth(), getHeight());
  61025. }
  61026. renderOpenGL();
  61027. swapBuffers();
  61028. return true;
  61029. }
  61030. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61031. {
  61032. Component::internalRepaint (x, y, w, h);
  61033. if (context != 0)
  61034. context->repaint();
  61035. }
  61036. END_JUCE_NAMESPACE
  61037. #endif
  61038. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61039. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61040. BEGIN_JUCE_NAMESPACE
  61041. PreferencesPanel::PreferencesPanel()
  61042. : buttonSize (70)
  61043. {
  61044. }
  61045. PreferencesPanel::~PreferencesPanel()
  61046. {
  61047. currentPage = 0;
  61048. deleteAllChildren();
  61049. }
  61050. void PreferencesPanel::addSettingsPage (const String& title,
  61051. const Drawable* icon,
  61052. const Drawable* overIcon,
  61053. const Drawable* downIcon)
  61054. {
  61055. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61056. button->setImages (icon, overIcon, downIcon);
  61057. button->setRadioGroupId (1);
  61058. button->addButtonListener (this);
  61059. button->setClickingTogglesState (true);
  61060. button->setWantsKeyboardFocus (false);
  61061. addAndMakeVisible (button);
  61062. resized();
  61063. if (currentPage == 0)
  61064. setCurrentPage (title);
  61065. }
  61066. void PreferencesPanel::addSettingsPage (const String& title,
  61067. const void* imageData,
  61068. const int imageDataSize)
  61069. {
  61070. DrawableImage icon, iconOver, iconDown;
  61071. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61072. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61073. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61074. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61075. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61076. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61077. }
  61078. class PrefsDialogWindow : public DialogWindow
  61079. {
  61080. public:
  61081. PrefsDialogWindow (const String& dialogtitle,
  61082. const Colour& backgroundColour)
  61083. : DialogWindow (dialogtitle, backgroundColour, true)
  61084. {
  61085. }
  61086. ~PrefsDialogWindow()
  61087. {
  61088. }
  61089. void closeButtonPressed()
  61090. {
  61091. exitModalState (0);
  61092. }
  61093. private:
  61094. PrefsDialogWindow (const PrefsDialogWindow&);
  61095. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61096. };
  61097. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61098. int dialogWidth,
  61099. int dialogHeight,
  61100. const Colour& backgroundColour)
  61101. {
  61102. setSize (dialogWidth, dialogHeight);
  61103. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61104. dw.setContentComponent (this, true, true);
  61105. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61106. dw.runModalLoop();
  61107. dw.setContentComponent (0, false, false);
  61108. }
  61109. void PreferencesPanel::resized()
  61110. {
  61111. int x = 0;
  61112. for (int i = 0; i < getNumChildComponents(); ++i)
  61113. {
  61114. Component* c = getChildComponent (i);
  61115. if (dynamic_cast <DrawableButton*> (c) == 0)
  61116. {
  61117. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61118. }
  61119. else
  61120. {
  61121. c->setBounds (x, 0, buttonSize, buttonSize);
  61122. x += buttonSize;
  61123. }
  61124. }
  61125. }
  61126. void PreferencesPanel::paint (Graphics& g)
  61127. {
  61128. g.setColour (Colours::grey);
  61129. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61130. }
  61131. void PreferencesPanel::setCurrentPage (const String& pageName)
  61132. {
  61133. if (currentPageName != pageName)
  61134. {
  61135. currentPageName = pageName;
  61136. currentPage = 0;
  61137. currentPage = createComponentForPage (pageName);
  61138. if (currentPage != 0)
  61139. {
  61140. addAndMakeVisible (currentPage);
  61141. currentPage->toBack();
  61142. resized();
  61143. }
  61144. for (int i = 0; i < getNumChildComponents(); ++i)
  61145. {
  61146. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61147. if (db != 0 && db->getName() == pageName)
  61148. {
  61149. db->setToggleState (true, false);
  61150. break;
  61151. }
  61152. }
  61153. }
  61154. }
  61155. void PreferencesPanel::buttonClicked (Button*)
  61156. {
  61157. for (int i = 0; i < getNumChildComponents(); ++i)
  61158. {
  61159. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61160. if (db != 0 && db->getToggleState())
  61161. {
  61162. setCurrentPage (db->getName());
  61163. break;
  61164. }
  61165. }
  61166. }
  61167. END_JUCE_NAMESPACE
  61168. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61169. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61170. #if JUCE_WINDOWS || JUCE_LINUX
  61171. BEGIN_JUCE_NAMESPACE
  61172. SystemTrayIconComponent::SystemTrayIconComponent()
  61173. {
  61174. addToDesktop (0);
  61175. }
  61176. SystemTrayIconComponent::~SystemTrayIconComponent()
  61177. {
  61178. }
  61179. END_JUCE_NAMESPACE
  61180. #endif
  61181. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61182. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61183. BEGIN_JUCE_NAMESPACE
  61184. class AlertWindowTextEditor : public TextEditor
  61185. {
  61186. public:
  61187. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61188. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61189. {
  61190. setSelectAllWhenFocused (true);
  61191. }
  61192. ~AlertWindowTextEditor()
  61193. {
  61194. }
  61195. void returnPressed()
  61196. {
  61197. // pass these up the component hierarchy to be trigger the buttons
  61198. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61199. }
  61200. void escapePressed()
  61201. {
  61202. // pass these up the component hierarchy to be trigger the buttons
  61203. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61204. }
  61205. private:
  61206. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61207. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61208. static juce_wchar getDefaultPasswordChar() throw()
  61209. {
  61210. #if JUCE_LINUX
  61211. return 0x2022;
  61212. #else
  61213. return 0x25cf;
  61214. #endif
  61215. }
  61216. };
  61217. AlertWindow::AlertWindow (const String& title,
  61218. const String& message,
  61219. AlertIconType iconType,
  61220. Component* associatedComponent_)
  61221. : TopLevelWindow (title, true),
  61222. alertIconType (iconType),
  61223. associatedComponent (associatedComponent_)
  61224. {
  61225. if (message.isEmpty())
  61226. text = " "; // to force an update if the message is empty
  61227. setMessage (message);
  61228. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61229. {
  61230. Component* const c = Desktop::getInstance().getComponent (i);
  61231. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61232. {
  61233. setAlwaysOnTop (true);
  61234. break;
  61235. }
  61236. }
  61237. if (! JUCEApplication::isStandaloneApp())
  61238. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61239. lookAndFeelChanged();
  61240. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61241. }
  61242. AlertWindow::~AlertWindow()
  61243. {
  61244. for (int i = customComps.size(); --i >= 0;)
  61245. removeChildComponent ((Component*) customComps[i]);
  61246. deleteAllChildren();
  61247. }
  61248. void AlertWindow::userTriedToCloseWindow()
  61249. {
  61250. exitModalState (0);
  61251. }
  61252. void AlertWindow::setMessage (const String& message)
  61253. {
  61254. const String newMessage (message.substring (0, 2048));
  61255. if (text != newMessage)
  61256. {
  61257. text = newMessage;
  61258. font.setHeight (15.0f);
  61259. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61260. textLayout.setText (getName() + "\n\n", titleFont);
  61261. textLayout.appendText (text, font);
  61262. updateLayout (true);
  61263. repaint();
  61264. }
  61265. }
  61266. void AlertWindow::buttonClicked (Button* button)
  61267. {
  61268. for (int i = 0; i < buttons.size(); i++)
  61269. {
  61270. TextButton* const c = (TextButton*) buttons[i];
  61271. if (button->getName() == c->getName())
  61272. {
  61273. if (c->getParentComponent() != 0)
  61274. c->getParentComponent()->exitModalState (c->getCommandID());
  61275. break;
  61276. }
  61277. }
  61278. }
  61279. void AlertWindow::addButton (const String& name,
  61280. const int returnValue,
  61281. const KeyPress& shortcutKey1,
  61282. const KeyPress& shortcutKey2)
  61283. {
  61284. TextButton* const b = new TextButton (name, String::empty);
  61285. b->setWantsKeyboardFocus (true);
  61286. b->setMouseClickGrabsKeyboardFocus (false);
  61287. b->setCommandToTrigger (0, returnValue, false);
  61288. b->addShortcut (shortcutKey1);
  61289. b->addShortcut (shortcutKey2);
  61290. b->addButtonListener (this);
  61291. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61292. addAndMakeVisible (b, 0);
  61293. buttons.add (b);
  61294. updateLayout (false);
  61295. }
  61296. int AlertWindow::getNumButtons() const
  61297. {
  61298. return buttons.size();
  61299. }
  61300. void AlertWindow::triggerButtonClick (const String& buttonName)
  61301. {
  61302. for (int i = buttons.size(); --i >= 0;)
  61303. {
  61304. TextButton* const b = (TextButton*) buttons[i];
  61305. if (buttonName == b->getName())
  61306. {
  61307. b->triggerClick();
  61308. break;
  61309. }
  61310. }
  61311. }
  61312. void AlertWindow::addTextEditor (const String& name,
  61313. const String& initialContents,
  61314. const String& onScreenLabel,
  61315. const bool isPasswordBox)
  61316. {
  61317. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61318. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61319. tc->setFont (font);
  61320. tc->setText (initialContents);
  61321. tc->setCaretPosition (initialContents.length());
  61322. addAndMakeVisible (tc);
  61323. textBoxes.add (tc);
  61324. allComps.add (tc);
  61325. textboxNames.add (onScreenLabel);
  61326. updateLayout (false);
  61327. }
  61328. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61329. {
  61330. for (int i = textBoxes.size(); --i >= 0;)
  61331. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61332. return ((TextEditor*)textBoxes[i])->getText();
  61333. return String::empty;
  61334. }
  61335. void AlertWindow::addComboBox (const String& name,
  61336. const StringArray& items,
  61337. const String& onScreenLabel)
  61338. {
  61339. ComboBox* const cb = new ComboBox (name);
  61340. for (int i = 0; i < items.size(); ++i)
  61341. cb->addItem (items[i], i + 1);
  61342. addAndMakeVisible (cb);
  61343. cb->setSelectedItemIndex (0);
  61344. comboBoxes.add (cb);
  61345. allComps.add (cb);
  61346. comboBoxNames.add (onScreenLabel);
  61347. updateLayout (false);
  61348. }
  61349. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61350. {
  61351. for (int i = comboBoxes.size(); --i >= 0;)
  61352. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61353. return (ComboBox*) comboBoxes[i];
  61354. return 0;
  61355. }
  61356. class AlertTextComp : public TextEditor
  61357. {
  61358. public:
  61359. AlertTextComp (const String& message,
  61360. const Font& font)
  61361. {
  61362. setReadOnly (true);
  61363. setMultiLine (true, true);
  61364. setCaretVisible (false);
  61365. setScrollbarsShown (true);
  61366. lookAndFeelChanged();
  61367. setWantsKeyboardFocus (false);
  61368. setFont (font);
  61369. setText (message, false);
  61370. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61371. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61372. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61373. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61374. }
  61375. ~AlertTextComp()
  61376. {
  61377. }
  61378. int getPreferredWidth() const throw() { return bestWidth; }
  61379. void updateLayout (const int width)
  61380. {
  61381. TextLayout text;
  61382. text.appendText (getText(), getFont());
  61383. text.layout (width - 8, Justification::topLeft, true);
  61384. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61385. }
  61386. private:
  61387. int bestWidth;
  61388. AlertTextComp (const AlertTextComp&);
  61389. AlertTextComp& operator= (const AlertTextComp&);
  61390. };
  61391. void AlertWindow::addTextBlock (const String& textBlock)
  61392. {
  61393. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61394. textBlocks.add (c);
  61395. allComps.add (c);
  61396. addAndMakeVisible (c);
  61397. updateLayout (false);
  61398. }
  61399. void AlertWindow::addProgressBarComponent (double& progressValue)
  61400. {
  61401. ProgressBar* const pb = new ProgressBar (progressValue);
  61402. progressBars.add (pb);
  61403. allComps.add (pb);
  61404. addAndMakeVisible (pb);
  61405. updateLayout (false);
  61406. }
  61407. void AlertWindow::addCustomComponent (Component* const component)
  61408. {
  61409. customComps.add (component);
  61410. allComps.add (component);
  61411. addAndMakeVisible (component);
  61412. updateLayout (false);
  61413. }
  61414. int AlertWindow::getNumCustomComponents() const
  61415. {
  61416. return customComps.size();
  61417. }
  61418. Component* AlertWindow::getCustomComponent (const int index) const
  61419. {
  61420. return (Component*) customComps [index];
  61421. }
  61422. Component* AlertWindow::removeCustomComponent (const int index)
  61423. {
  61424. Component* const c = getCustomComponent (index);
  61425. if (c != 0)
  61426. {
  61427. customComps.removeValue (c);
  61428. allComps.removeValue (c);
  61429. removeChildComponent (c);
  61430. updateLayout (false);
  61431. }
  61432. return c;
  61433. }
  61434. void AlertWindow::paint (Graphics& g)
  61435. {
  61436. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61437. g.setColour (findColour (textColourId));
  61438. g.setFont (getLookAndFeel().getAlertWindowFont());
  61439. int i;
  61440. for (i = textBoxes.size(); --i >= 0;)
  61441. {
  61442. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61443. g.drawFittedText (textboxNames[i],
  61444. te->getX(), te->getY() - 14,
  61445. te->getWidth(), 14,
  61446. Justification::centredLeft, 1);
  61447. }
  61448. for (i = comboBoxNames.size(); --i >= 0;)
  61449. {
  61450. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61451. g.drawFittedText (comboBoxNames[i],
  61452. cb->getX(), cb->getY() - 14,
  61453. cb->getWidth(), 14,
  61454. Justification::centredLeft, 1);
  61455. }
  61456. for (i = customComps.size(); --i >= 0;)
  61457. {
  61458. const Component* const c = (Component*) customComps[i];
  61459. g.drawFittedText (c->getName(),
  61460. c->getX(), c->getY() - 14,
  61461. c->getWidth(), 14,
  61462. Justification::centredLeft, 1);
  61463. }
  61464. }
  61465. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61466. {
  61467. const int titleH = 24;
  61468. const int iconWidth = 80;
  61469. const int wid = jmax (font.getStringWidth (text),
  61470. font.getStringWidth (getName()));
  61471. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61472. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61473. const int edgeGap = 10;
  61474. const int labelHeight = 18;
  61475. int iconSpace;
  61476. if (alertIconType == NoIcon)
  61477. {
  61478. textLayout.layout (w, Justification::horizontallyCentred, true);
  61479. iconSpace = 0;
  61480. }
  61481. else
  61482. {
  61483. textLayout.layout (w, Justification::left, true);
  61484. iconSpace = iconWidth;
  61485. }
  61486. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61487. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61488. const int textLayoutH = textLayout.getHeight();
  61489. const int textBottom = 16 + titleH + textLayoutH;
  61490. int h = textBottom;
  61491. int buttonW = 40;
  61492. int i;
  61493. for (i = 0; i < buttons.size(); ++i)
  61494. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61495. w = jmax (buttonW, w);
  61496. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61497. if (buttons.size() > 0)
  61498. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61499. for (i = customComps.size(); --i >= 0;)
  61500. {
  61501. Component* c = (Component*) customComps[i];
  61502. w = jmax (w, (c->getWidth() * 100) / 80);
  61503. h += 10 + c->getHeight();
  61504. if (c->getName().isNotEmpty())
  61505. h += labelHeight;
  61506. }
  61507. for (i = textBlocks.size(); --i >= 0;)
  61508. {
  61509. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61510. w = jmax (w, ac->getPreferredWidth());
  61511. }
  61512. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61513. for (i = textBlocks.size(); --i >= 0;)
  61514. {
  61515. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61516. ac->updateLayout ((int) (w * 0.8f));
  61517. h += ac->getHeight() + 10;
  61518. }
  61519. h = jmin (getParentHeight() - 50, h);
  61520. if (onlyIncreaseSize)
  61521. {
  61522. w = jmax (w, getWidth());
  61523. h = jmax (h, getHeight());
  61524. }
  61525. if (! isVisible())
  61526. {
  61527. centreAroundComponent (associatedComponent, w, h);
  61528. }
  61529. else
  61530. {
  61531. const int cx = getX() + getWidth() / 2;
  61532. const int cy = getY() + getHeight() / 2;
  61533. setBounds (cx - w / 2,
  61534. cy - h / 2,
  61535. w, h);
  61536. }
  61537. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61538. const int spacer = 16;
  61539. int totalWidth = -spacer;
  61540. for (i = buttons.size(); --i >= 0;)
  61541. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61542. int x = (w - totalWidth) / 2;
  61543. int y = (int) (getHeight() * 0.95f);
  61544. for (i = 0; i < buttons.size(); ++i)
  61545. {
  61546. TextButton* const c = (TextButton*) buttons[i];
  61547. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61548. c->setTopLeftPosition (x, ny);
  61549. if (ny < y)
  61550. y = ny;
  61551. x += c->getWidth() + spacer;
  61552. c->toFront (false);
  61553. }
  61554. y = textBottom;
  61555. for (i = 0; i < allComps.size(); ++i)
  61556. {
  61557. Component* const c = (Component*) allComps[i];
  61558. h = 22;
  61559. const int comboIndex = comboBoxes.indexOf (c);
  61560. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61561. y += labelHeight;
  61562. const int tbIndex = textBoxes.indexOf (c);
  61563. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61564. y += labelHeight;
  61565. if (customComps.contains (c))
  61566. {
  61567. if (c->getName().isNotEmpty())
  61568. y += labelHeight;
  61569. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61570. h = c->getHeight();
  61571. }
  61572. else if (textBlocks.contains (c))
  61573. {
  61574. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61575. h = c->getHeight();
  61576. }
  61577. else
  61578. {
  61579. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61580. }
  61581. y += h + 10;
  61582. }
  61583. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61584. }
  61585. bool AlertWindow::containsAnyExtraComponents() const
  61586. {
  61587. return textBoxes.size()
  61588. + comboBoxes.size()
  61589. + progressBars.size()
  61590. + customComps.size() > 0;
  61591. }
  61592. void AlertWindow::mouseDown (const MouseEvent&)
  61593. {
  61594. dragger.startDraggingComponent (this, &constrainer);
  61595. }
  61596. void AlertWindow::mouseDrag (const MouseEvent& e)
  61597. {
  61598. dragger.dragComponent (this, e);
  61599. }
  61600. bool AlertWindow::keyPressed (const KeyPress& key)
  61601. {
  61602. for (int i = buttons.size(); --i >= 0;)
  61603. {
  61604. TextButton* const b = (TextButton*) buttons[i];
  61605. if (b->isRegisteredForShortcut (key))
  61606. {
  61607. b->triggerClick();
  61608. return true;
  61609. }
  61610. }
  61611. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61612. {
  61613. exitModalState (0);
  61614. return true;
  61615. }
  61616. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61617. {
  61618. ((TextButton*) buttons.getFirst())->triggerClick();
  61619. return true;
  61620. }
  61621. return false;
  61622. }
  61623. void AlertWindow::lookAndFeelChanged()
  61624. {
  61625. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61626. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61627. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61628. }
  61629. int AlertWindow::getDesktopWindowStyleFlags() const
  61630. {
  61631. return getLookAndFeel().getAlertBoxWindowFlags();
  61632. }
  61633. struct AlertWindowInfo
  61634. {
  61635. String title, message, button1, button2, button3;
  61636. AlertWindow::AlertIconType iconType;
  61637. int numButtons;
  61638. Component::SafePointer<Component> associatedComponent;
  61639. int run() const
  61640. {
  61641. return (int) (pointer_sized_int)
  61642. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61643. }
  61644. private:
  61645. int show() const
  61646. {
  61647. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61648. : LookAndFeel::getDefaultLookAndFeel();
  61649. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61650. iconType, numButtons, associatedComponent));
  61651. jassert (alertBox != 0); // you have to return one of these!
  61652. return alertBox->runModalLoop();
  61653. }
  61654. static void* showCallback (void* userData)
  61655. {
  61656. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61657. }
  61658. };
  61659. void AlertWindow::showMessageBox (AlertIconType iconType,
  61660. const String& title,
  61661. const String& message,
  61662. const String& buttonText,
  61663. Component* associatedComponent)
  61664. {
  61665. AlertWindowInfo info;
  61666. info.title = title;
  61667. info.message = message;
  61668. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61669. info.iconType = iconType;
  61670. info.numButtons = 1;
  61671. info.associatedComponent = associatedComponent;
  61672. info.run();
  61673. }
  61674. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61675. const String& title,
  61676. const String& message,
  61677. const String& button1Text,
  61678. const String& button2Text,
  61679. Component* associatedComponent)
  61680. {
  61681. AlertWindowInfo info;
  61682. info.title = title;
  61683. info.message = message;
  61684. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61685. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61686. info.iconType = iconType;
  61687. info.numButtons = 2;
  61688. info.associatedComponent = associatedComponent;
  61689. return info.run() != 0;
  61690. }
  61691. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61692. const String& title,
  61693. const String& message,
  61694. const String& button1Text,
  61695. const String& button2Text,
  61696. const String& button3Text,
  61697. Component* associatedComponent)
  61698. {
  61699. AlertWindowInfo info;
  61700. info.title = title;
  61701. info.message = message;
  61702. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61703. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61704. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61705. info.iconType = iconType;
  61706. info.numButtons = 3;
  61707. info.associatedComponent = associatedComponent;
  61708. return info.run();
  61709. }
  61710. END_JUCE_NAMESPACE
  61711. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61712. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61713. BEGIN_JUCE_NAMESPACE
  61714. CallOutBox::CallOutBox (Component& contentComponent,
  61715. Component& componentToPointTo,
  61716. Component* const parentComponent)
  61717. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61718. {
  61719. addAndMakeVisible (&content);
  61720. if (parentComponent != 0)
  61721. {
  61722. updatePosition (parentComponent->getLocalBounds(),
  61723. componentToPointTo.getLocalBounds()
  61724. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61725. parentComponent->addAndMakeVisible (this);
  61726. }
  61727. else
  61728. {
  61729. updatePosition (componentToPointTo.getScreenBounds(),
  61730. componentToPointTo.getParentMonitorArea());
  61731. addToDesktop (ComponentPeer::windowIsTemporary);
  61732. }
  61733. }
  61734. CallOutBox::~CallOutBox()
  61735. {
  61736. }
  61737. void CallOutBox::setArrowSize (const float newSize)
  61738. {
  61739. arrowSize = newSize;
  61740. borderSpace = jmax (20, (int) arrowSize);
  61741. refreshPath();
  61742. }
  61743. void CallOutBox::paint (Graphics& g)
  61744. {
  61745. if (background.isNull())
  61746. {
  61747. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61748. Graphics g (background);
  61749. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61750. }
  61751. g.setColour (Colours::black);
  61752. g.drawImageAt (background, 0, 0);
  61753. }
  61754. void CallOutBox::resized()
  61755. {
  61756. content.setTopLeftPosition (borderSpace, borderSpace);
  61757. refreshPath();
  61758. }
  61759. void CallOutBox::moved()
  61760. {
  61761. refreshPath();
  61762. }
  61763. void CallOutBox::childBoundsChanged (Component*)
  61764. {
  61765. updatePosition (targetArea, availableArea);
  61766. }
  61767. bool CallOutBox::hitTest (int x, int y)
  61768. {
  61769. return outline.contains ((float) x, (float) y);
  61770. }
  61771. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61772. void CallOutBox::inputAttemptWhenModal()
  61773. {
  61774. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61775. if (targetArea.contains (mousePos))
  61776. {
  61777. // if you click on the area that originally popped-up the callout, you expect it
  61778. // to get rid of the box, but deleting the box here allows the click to pass through and
  61779. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61780. postCommandMessage (callOutBoxDismissCommandId);
  61781. }
  61782. else
  61783. {
  61784. exitModalState (0);
  61785. setVisible (false);
  61786. }
  61787. }
  61788. void CallOutBox::handleCommandMessage (int commandId)
  61789. {
  61790. Component::handleCommandMessage (commandId);
  61791. if (commandId == callOutBoxDismissCommandId)
  61792. {
  61793. exitModalState (0);
  61794. setVisible (false);
  61795. }
  61796. }
  61797. bool CallOutBox::keyPressed (const KeyPress& key)
  61798. {
  61799. if (key.isKeyCode (KeyPress::escapeKey))
  61800. {
  61801. inputAttemptWhenModal();
  61802. return true;
  61803. }
  61804. return false;
  61805. }
  61806. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61807. {
  61808. targetArea = newAreaToPointTo;
  61809. availableArea = newAreaToFitIn;
  61810. Rectangle<int> bounds (0, 0,
  61811. content.getWidth() + borderSpace * 2,
  61812. content.getHeight() + borderSpace * 2);
  61813. const int hw = bounds.getWidth() / 2;
  61814. const int hh = bounds.getHeight() / 2;
  61815. const float hwReduced = (float) (hw - borderSpace * 3);
  61816. const float hhReduced = (float) (hh - borderSpace * 3);
  61817. const float arrowIndent = borderSpace - arrowSize;
  61818. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61819. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61820. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61821. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61822. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61823. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61824. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61825. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61826. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61827. float nearest = 1.0e9f;
  61828. for (int i = 0; i < 4; ++i)
  61829. {
  61830. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61831. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61832. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61833. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61834. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61835. distanceFromCentre *= 2.0f;
  61836. if (distanceFromCentre < nearest)
  61837. {
  61838. nearest = distanceFromCentre;
  61839. targetPoint = targets[i];
  61840. bounds.setPosition ((int) (centre.getX() - hw),
  61841. (int) (centre.getY() - hh));
  61842. }
  61843. }
  61844. setBounds (bounds);
  61845. }
  61846. void CallOutBox::refreshPath()
  61847. {
  61848. repaint();
  61849. background = Image::null;
  61850. outline.clear();
  61851. const float gap = 4.5f;
  61852. const float cornerSize = 9.0f;
  61853. const float cornerSize2 = 2.0f * cornerSize;
  61854. const float arrowBaseWidth = arrowSize * 0.7f;
  61855. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61856. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61857. outline.startNewSubPath (left + cornerSize, top);
  61858. if (targetY <= top)
  61859. {
  61860. outline.lineTo (targetX - arrowBaseWidth, top);
  61861. outline.lineTo (targetX, targetY);
  61862. outline.lineTo (targetX + arrowBaseWidth, top);
  61863. }
  61864. outline.lineTo (right - cornerSize, top);
  61865. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61866. if (targetX >= right)
  61867. {
  61868. outline.lineTo (right, targetY - arrowBaseWidth);
  61869. outline.lineTo (targetX, targetY);
  61870. outline.lineTo (right, targetY + arrowBaseWidth);
  61871. }
  61872. outline.lineTo (right, bottom - cornerSize);
  61873. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61874. if (targetY >= bottom)
  61875. {
  61876. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61877. outline.lineTo (targetX, targetY);
  61878. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61879. }
  61880. outline.lineTo (left + cornerSize, bottom);
  61881. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61882. if (targetX <= left)
  61883. {
  61884. outline.lineTo (left, targetY + arrowBaseWidth);
  61885. outline.lineTo (targetX, targetY);
  61886. outline.lineTo (left, targetY - arrowBaseWidth);
  61887. }
  61888. outline.lineTo (left, top + cornerSize);
  61889. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61890. outline.closeSubPath();
  61891. }
  61892. END_JUCE_NAMESPACE
  61893. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61894. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61895. BEGIN_JUCE_NAMESPACE
  61896. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61897. static Array <ComponentPeer*> heavyweightPeers;
  61898. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61899. : component (component_),
  61900. styleFlags (styleFlags_),
  61901. lastPaintTime (0),
  61902. constrainer (0),
  61903. lastDragAndDropCompUnderMouse (0),
  61904. fakeMouseMessageSent (false),
  61905. isWindowMinimised (false)
  61906. {
  61907. heavyweightPeers.add (this);
  61908. }
  61909. ComponentPeer::~ComponentPeer()
  61910. {
  61911. heavyweightPeers.removeValue (this);
  61912. Desktop::getInstance().triggerFocusCallback();
  61913. }
  61914. int ComponentPeer::getNumPeers() throw()
  61915. {
  61916. return heavyweightPeers.size();
  61917. }
  61918. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61919. {
  61920. return heavyweightPeers [index];
  61921. }
  61922. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61923. {
  61924. for (int i = heavyweightPeers.size(); --i >= 0;)
  61925. {
  61926. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61927. if (peer->getComponent() == component)
  61928. return peer;
  61929. }
  61930. return 0;
  61931. }
  61932. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61933. {
  61934. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61935. }
  61936. void ComponentPeer::updateCurrentModifiers() throw()
  61937. {
  61938. ModifierKeys::updateCurrentModifiers();
  61939. }
  61940. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61941. {
  61942. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61943. jassert (mouse != 0); // not enough sources!
  61944. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61945. }
  61946. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61947. {
  61948. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61949. jassert (mouse != 0); // not enough sources!
  61950. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61951. }
  61952. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61953. {
  61954. Graphics g (&contextToPaintTo);
  61955. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61956. g.saveState();
  61957. #endif
  61958. JUCE_TRY
  61959. {
  61960. component->paintEntireComponent (g);
  61961. }
  61962. JUCE_CATCH_EXCEPTION
  61963. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61964. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61965. // clearly when things are being repainted.
  61966. {
  61967. g.restoreState();
  61968. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61969. (uint8) Random::getSystemRandom().nextInt (255),
  61970. (uint8) Random::getSystemRandom().nextInt (255),
  61971. (uint8) 0x50));
  61972. }
  61973. #endif
  61974. }
  61975. bool ComponentPeer::handleKeyPress (const int keyCode,
  61976. const juce_wchar textCharacter)
  61977. {
  61978. updateCurrentModifiers();
  61979. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61980. ? Component::getCurrentlyFocusedComponent()
  61981. : component;
  61982. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61983. {
  61984. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61985. if (currentModalComp != 0)
  61986. target = currentModalComp;
  61987. }
  61988. const KeyPress keyInfo (keyCode,
  61989. ModifierKeys::getCurrentModifiers().getRawFlags()
  61990. & ModifierKeys::allKeyboardModifiers,
  61991. textCharacter);
  61992. bool keyWasUsed = false;
  61993. while (target != 0)
  61994. {
  61995. const Component::SafePointer<Component> deletionChecker (target);
  61996. if (target->keyListeners_ != 0)
  61997. {
  61998. for (int i = target->keyListeners_->size(); --i >= 0;)
  61999. {
  62000. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62001. if (keyWasUsed || deletionChecker == 0)
  62002. return keyWasUsed;
  62003. i = jmin (i, target->keyListeners_->size());
  62004. }
  62005. }
  62006. keyWasUsed = target->keyPressed (keyInfo);
  62007. if (keyWasUsed || deletionChecker == 0)
  62008. break;
  62009. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62010. {
  62011. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62012. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62013. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62014. break;
  62015. }
  62016. target = target->parentComponent_;
  62017. }
  62018. return keyWasUsed;
  62019. }
  62020. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62021. {
  62022. updateCurrentModifiers();
  62023. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62024. ? Component::getCurrentlyFocusedComponent()
  62025. : component;
  62026. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62027. {
  62028. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62029. if (currentModalComp != 0)
  62030. target = currentModalComp;
  62031. }
  62032. bool keyWasUsed = false;
  62033. while (target != 0)
  62034. {
  62035. const Component::SafePointer<Component> deletionChecker (target);
  62036. keyWasUsed = target->keyStateChanged (isKeyDown);
  62037. if (keyWasUsed || deletionChecker == 0)
  62038. break;
  62039. if (target->keyListeners_ != 0)
  62040. {
  62041. for (int i = target->keyListeners_->size(); --i >= 0;)
  62042. {
  62043. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62044. if (keyWasUsed || deletionChecker == 0)
  62045. return keyWasUsed;
  62046. i = jmin (i, target->keyListeners_->size());
  62047. }
  62048. }
  62049. target = target->parentComponent_;
  62050. }
  62051. return keyWasUsed;
  62052. }
  62053. void ComponentPeer::handleModifierKeysChange()
  62054. {
  62055. updateCurrentModifiers();
  62056. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62057. if (target == 0)
  62058. target = Component::getCurrentlyFocusedComponent();
  62059. if (target == 0)
  62060. target = component;
  62061. if (target != 0)
  62062. target->internalModifierKeysChanged();
  62063. }
  62064. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62065. {
  62066. Component* const c = Component::getCurrentlyFocusedComponent();
  62067. if (component->isParentOf (c))
  62068. {
  62069. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62070. if (ti != 0 && ti->isTextInputActive())
  62071. return ti;
  62072. }
  62073. return 0;
  62074. }
  62075. void ComponentPeer::handleBroughtToFront()
  62076. {
  62077. updateCurrentModifiers();
  62078. if (component != 0)
  62079. component->internalBroughtToFront();
  62080. }
  62081. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62082. {
  62083. constrainer = newConstrainer;
  62084. }
  62085. void ComponentPeer::handleMovedOrResized()
  62086. {
  62087. jassert (component->isValidComponent());
  62088. updateCurrentModifiers();
  62089. const bool nowMinimised = isMinimised();
  62090. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62091. {
  62092. const Component::SafePointer<Component> deletionChecker (component);
  62093. const Rectangle<int> newBounds (getBounds());
  62094. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62095. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62096. if (wasMoved || wasResized)
  62097. {
  62098. component->bounds_ = newBounds;
  62099. if (wasResized)
  62100. component->repaint();
  62101. component->sendMovedResizedMessages (wasMoved, wasResized);
  62102. if (deletionChecker == 0)
  62103. return;
  62104. }
  62105. }
  62106. if (isWindowMinimised != nowMinimised)
  62107. {
  62108. isWindowMinimised = nowMinimised;
  62109. component->minimisationStateChanged (nowMinimised);
  62110. component->sendVisibilityChangeMessage();
  62111. }
  62112. if (! isFullScreen())
  62113. lastNonFullscreenBounds = component->getBounds();
  62114. }
  62115. void ComponentPeer::handleFocusGain()
  62116. {
  62117. updateCurrentModifiers();
  62118. if (component->isParentOf (lastFocusedComponent))
  62119. {
  62120. Component::currentlyFocusedComponent = lastFocusedComponent;
  62121. Desktop::getInstance().triggerFocusCallback();
  62122. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62123. }
  62124. else
  62125. {
  62126. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62127. component->grabKeyboardFocus();
  62128. else
  62129. Component::bringModalComponentToFront();
  62130. }
  62131. }
  62132. void ComponentPeer::handleFocusLoss()
  62133. {
  62134. updateCurrentModifiers();
  62135. if (component->hasKeyboardFocus (true))
  62136. {
  62137. lastFocusedComponent = Component::currentlyFocusedComponent;
  62138. if (lastFocusedComponent != 0)
  62139. {
  62140. Component::currentlyFocusedComponent = 0;
  62141. Desktop::getInstance().triggerFocusCallback();
  62142. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62143. }
  62144. }
  62145. }
  62146. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62147. {
  62148. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62149. ? static_cast <Component*> (lastFocusedComponent)
  62150. : component;
  62151. }
  62152. void ComponentPeer::handleScreenSizeChange()
  62153. {
  62154. updateCurrentModifiers();
  62155. component->parentSizeChanged();
  62156. handleMovedOrResized();
  62157. }
  62158. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62159. {
  62160. lastNonFullscreenBounds = newBounds;
  62161. }
  62162. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62163. {
  62164. return lastNonFullscreenBounds;
  62165. }
  62166. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62167. const StringArray& files,
  62168. FileDragAndDropTarget* const lastOne)
  62169. {
  62170. while (c != 0)
  62171. {
  62172. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62173. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62174. return t;
  62175. c = c->getParentComponent();
  62176. }
  62177. return 0;
  62178. }
  62179. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62180. {
  62181. updateCurrentModifiers();
  62182. FileDragAndDropTarget* lastTarget
  62183. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62184. FileDragAndDropTarget* newTarget = 0;
  62185. Component* const compUnderMouse = component->getComponentAt (position);
  62186. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62187. {
  62188. lastDragAndDropCompUnderMouse = compUnderMouse;
  62189. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62190. if (newTarget != lastTarget)
  62191. {
  62192. if (lastTarget != 0)
  62193. lastTarget->fileDragExit (files);
  62194. dragAndDropTargetComponent = 0;
  62195. if (newTarget != 0)
  62196. {
  62197. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62198. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62199. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62200. }
  62201. }
  62202. }
  62203. else
  62204. {
  62205. newTarget = lastTarget;
  62206. }
  62207. if (newTarget != 0)
  62208. {
  62209. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62210. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62211. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62212. }
  62213. }
  62214. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62215. {
  62216. handleFileDragMove (files, Point<int> (-1, -1));
  62217. jassert (dragAndDropTargetComponent == 0);
  62218. lastDragAndDropCompUnderMouse = 0;
  62219. }
  62220. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62221. {
  62222. handleFileDragMove (files, position);
  62223. if (dragAndDropTargetComponent != 0)
  62224. {
  62225. FileDragAndDropTarget* const target
  62226. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62227. dragAndDropTargetComponent = 0;
  62228. lastDragAndDropCompUnderMouse = 0;
  62229. if (target != 0)
  62230. {
  62231. Component* const targetComp = dynamic_cast <Component*> (target);
  62232. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62233. {
  62234. targetComp->internalModalInputAttempt();
  62235. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62236. return;
  62237. }
  62238. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62239. target->filesDropped (files, pos.getX(), pos.getY());
  62240. }
  62241. }
  62242. }
  62243. void ComponentPeer::handleUserClosingWindow()
  62244. {
  62245. updateCurrentModifiers();
  62246. component->userTriedToCloseWindow();
  62247. }
  62248. void ComponentPeer::bringModalComponentToFront()
  62249. {
  62250. Component::bringModalComponentToFront();
  62251. }
  62252. void ComponentPeer::clearMaskedRegion()
  62253. {
  62254. maskedRegion.clear();
  62255. }
  62256. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62257. {
  62258. maskedRegion.add (x, y, w, h);
  62259. }
  62260. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62261. {
  62262. StringArray s;
  62263. s.add ("Software Renderer");
  62264. return s;
  62265. }
  62266. int ComponentPeer::getCurrentRenderingEngine() throw()
  62267. {
  62268. return 0;
  62269. }
  62270. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62271. {
  62272. }
  62273. END_JUCE_NAMESPACE
  62274. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62275. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62276. BEGIN_JUCE_NAMESPACE
  62277. DialogWindow::DialogWindow (const String& name,
  62278. const Colour& backgroundColour_,
  62279. const bool escapeKeyTriggersCloseButton_,
  62280. const bool addToDesktop_)
  62281. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62282. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62283. {
  62284. }
  62285. DialogWindow::~DialogWindow()
  62286. {
  62287. }
  62288. void DialogWindow::resized()
  62289. {
  62290. DocumentWindow::resized();
  62291. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62292. if (escapeKeyTriggersCloseButton
  62293. && getCloseButton() != 0
  62294. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62295. {
  62296. getCloseButton()->addShortcut (esc);
  62297. }
  62298. }
  62299. class TempDialogWindow : public DialogWindow
  62300. {
  62301. public:
  62302. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62303. : DialogWindow (title, colour, escapeCloses, true)
  62304. {
  62305. if (! JUCEApplication::isStandaloneApp())
  62306. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62307. }
  62308. ~TempDialogWindow()
  62309. {
  62310. }
  62311. void closeButtonPressed()
  62312. {
  62313. setVisible (false);
  62314. }
  62315. private:
  62316. TempDialogWindow (const TempDialogWindow&);
  62317. TempDialogWindow& operator= (const TempDialogWindow&);
  62318. };
  62319. int DialogWindow::showModalDialog (const String& dialogTitle,
  62320. Component* contentComponent,
  62321. Component* componentToCentreAround,
  62322. const Colour& colour,
  62323. const bool escapeKeyTriggersCloseButton,
  62324. const bool shouldBeResizable,
  62325. const bool useBottomRightCornerResizer)
  62326. {
  62327. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62328. dw.setContentComponent (contentComponent, true, true);
  62329. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62330. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62331. const int result = dw.runModalLoop();
  62332. dw.setContentComponent (0, false);
  62333. return result;
  62334. }
  62335. END_JUCE_NAMESPACE
  62336. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62337. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62338. BEGIN_JUCE_NAMESPACE
  62339. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62340. {
  62341. public:
  62342. ButtonListenerProxy (DocumentWindow& owner_)
  62343. : owner (owner_)
  62344. {
  62345. }
  62346. void buttonClicked (Button* button)
  62347. {
  62348. if (button == owner.getMinimiseButton())
  62349. owner.minimiseButtonPressed();
  62350. else if (button == owner.getMaximiseButton())
  62351. owner.maximiseButtonPressed();
  62352. else if (button == owner.getCloseButton())
  62353. owner.closeButtonPressed();
  62354. }
  62355. juce_UseDebuggingNewOperator
  62356. private:
  62357. DocumentWindow& owner;
  62358. ButtonListenerProxy (const ButtonListenerProxy&);
  62359. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62360. };
  62361. DocumentWindow::DocumentWindow (const String& title,
  62362. const Colour& backgroundColour,
  62363. const int requiredButtons_,
  62364. const bool addToDesktop_)
  62365. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62366. titleBarHeight (26),
  62367. menuBarHeight (24),
  62368. requiredButtons (requiredButtons_),
  62369. #if JUCE_MAC
  62370. positionTitleBarButtonsOnLeft (true),
  62371. #else
  62372. positionTitleBarButtonsOnLeft (false),
  62373. #endif
  62374. drawTitleTextCentred (true),
  62375. menuBarModel (0)
  62376. {
  62377. setResizeLimits (128, 128, 32768, 32768);
  62378. lookAndFeelChanged();
  62379. }
  62380. DocumentWindow::~DocumentWindow()
  62381. {
  62382. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62383. titleBarButtons[i] = 0;
  62384. menuBar = 0;
  62385. }
  62386. void DocumentWindow::repaintTitleBar()
  62387. {
  62388. repaint (getTitleBarArea());
  62389. }
  62390. void DocumentWindow::setName (const String& newName)
  62391. {
  62392. if (newName != getName())
  62393. {
  62394. Component::setName (newName);
  62395. repaintTitleBar();
  62396. }
  62397. }
  62398. void DocumentWindow::setIcon (const Image& imageToUse)
  62399. {
  62400. titleBarIcon = imageToUse;
  62401. repaintTitleBar();
  62402. }
  62403. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62404. {
  62405. titleBarHeight = newHeight;
  62406. resized();
  62407. repaintTitleBar();
  62408. }
  62409. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62410. const bool positionTitleBarButtonsOnLeft_)
  62411. {
  62412. requiredButtons = requiredButtons_;
  62413. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62414. lookAndFeelChanged();
  62415. }
  62416. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62417. {
  62418. drawTitleTextCentred = textShouldBeCentred;
  62419. repaintTitleBar();
  62420. }
  62421. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62422. const int menuBarHeight_)
  62423. {
  62424. if (menuBarModel != menuBarModel_)
  62425. {
  62426. menuBar = 0;
  62427. menuBarModel = menuBarModel_;
  62428. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62429. : getLookAndFeel().getDefaultMenuBarHeight();
  62430. if (menuBarModel != 0)
  62431. {
  62432. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62433. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62434. menuBar->setEnabled (isActiveWindow());
  62435. }
  62436. resized();
  62437. }
  62438. }
  62439. void DocumentWindow::closeButtonPressed()
  62440. {
  62441. /* If you've got a close button, you have to override this method to get
  62442. rid of your window!
  62443. If the window is just a pop-up, you should override this method and make
  62444. it delete the window in whatever way is appropriate for your app. E.g. you
  62445. might just want to call "delete this".
  62446. If your app is centred around this window such that the whole app should quit when
  62447. the window is closed, then you will probably want to use this method as an opportunity
  62448. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62449. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62450. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62451. or closing it via the taskbar icon on Windows).
  62452. */
  62453. jassertfalse;
  62454. }
  62455. void DocumentWindow::minimiseButtonPressed()
  62456. {
  62457. setMinimised (true);
  62458. }
  62459. void DocumentWindow::maximiseButtonPressed()
  62460. {
  62461. setFullScreen (! isFullScreen());
  62462. }
  62463. void DocumentWindow::paint (Graphics& g)
  62464. {
  62465. ResizableWindow::paint (g);
  62466. if (resizableBorder == 0)
  62467. {
  62468. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62469. const BorderSize border (getBorderThickness());
  62470. g.fillRect (0, 0, getWidth(), border.getTop());
  62471. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62472. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62473. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62474. }
  62475. const Rectangle<int> titleBarArea (getTitleBarArea());
  62476. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62477. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62478. int titleSpaceX1 = 6;
  62479. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62480. for (int i = 0; i < 3; ++i)
  62481. {
  62482. if (titleBarButtons[i] != 0)
  62483. {
  62484. if (positionTitleBarButtonsOnLeft)
  62485. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62486. else
  62487. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62488. }
  62489. }
  62490. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62491. titleBarArea.getWidth(),
  62492. titleBarArea.getHeight(),
  62493. titleSpaceX1,
  62494. jmax (1, titleSpaceX2 - titleSpaceX1),
  62495. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62496. ! drawTitleTextCentred);
  62497. }
  62498. void DocumentWindow::resized()
  62499. {
  62500. ResizableWindow::resized();
  62501. if (titleBarButtons[1] != 0)
  62502. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62503. const Rectangle<int> titleBarArea (getTitleBarArea());
  62504. getLookAndFeel()
  62505. .positionDocumentWindowButtons (*this,
  62506. titleBarArea.getX(), titleBarArea.getY(),
  62507. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62508. titleBarButtons[0],
  62509. titleBarButtons[1],
  62510. titleBarButtons[2],
  62511. positionTitleBarButtonsOnLeft);
  62512. if (menuBar != 0)
  62513. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62514. titleBarArea.getWidth(), menuBarHeight);
  62515. }
  62516. const BorderSize DocumentWindow::getBorderThickness()
  62517. {
  62518. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62519. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62520. }
  62521. const BorderSize DocumentWindow::getContentComponentBorder()
  62522. {
  62523. BorderSize border (getBorderThickness());
  62524. border.setTop (border.getTop()
  62525. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62526. + (menuBar != 0 ? menuBarHeight : 0));
  62527. return border;
  62528. }
  62529. int DocumentWindow::getTitleBarHeight() const
  62530. {
  62531. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62532. }
  62533. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62534. {
  62535. const BorderSize border (getBorderThickness());
  62536. return Rectangle<int> (border.getLeft(), border.getTop(),
  62537. getWidth() - border.getLeftAndRight(),
  62538. getTitleBarHeight());
  62539. }
  62540. Button* DocumentWindow::getCloseButton() const throw()
  62541. {
  62542. return titleBarButtons[2];
  62543. }
  62544. Button* DocumentWindow::getMinimiseButton() const throw()
  62545. {
  62546. return titleBarButtons[0];
  62547. }
  62548. Button* DocumentWindow::getMaximiseButton() const throw()
  62549. {
  62550. return titleBarButtons[1];
  62551. }
  62552. int DocumentWindow::getDesktopWindowStyleFlags() const
  62553. {
  62554. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62555. if ((requiredButtons & minimiseButton) != 0)
  62556. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62557. if ((requiredButtons & maximiseButton) != 0)
  62558. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62559. if ((requiredButtons & closeButton) != 0)
  62560. styleFlags |= ComponentPeer::windowHasCloseButton;
  62561. return styleFlags;
  62562. }
  62563. void DocumentWindow::lookAndFeelChanged()
  62564. {
  62565. int i;
  62566. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62567. titleBarButtons[i] = 0;
  62568. if (! isUsingNativeTitleBar())
  62569. {
  62570. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62571. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62572. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62573. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62574. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62575. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62576. for (i = 0; i < 3; ++i)
  62577. {
  62578. if (titleBarButtons[i] != 0)
  62579. {
  62580. if (buttonListener == 0)
  62581. buttonListener = new ButtonListenerProxy (*this);
  62582. titleBarButtons[i]->addButtonListener (buttonListener);
  62583. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62584. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62585. Component::addAndMakeVisible (titleBarButtons[i]);
  62586. }
  62587. }
  62588. if (getCloseButton() != 0)
  62589. {
  62590. #if JUCE_MAC
  62591. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62592. #else
  62593. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62594. #endif
  62595. }
  62596. }
  62597. activeWindowStatusChanged();
  62598. ResizableWindow::lookAndFeelChanged();
  62599. }
  62600. void DocumentWindow::parentHierarchyChanged()
  62601. {
  62602. lookAndFeelChanged();
  62603. }
  62604. void DocumentWindow::activeWindowStatusChanged()
  62605. {
  62606. ResizableWindow::activeWindowStatusChanged();
  62607. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62608. if (titleBarButtons[i] != 0)
  62609. titleBarButtons[i]->setEnabled (isActiveWindow());
  62610. if (menuBar != 0)
  62611. menuBar->setEnabled (isActiveWindow());
  62612. }
  62613. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62614. {
  62615. if (getTitleBarArea().contains (e.x, e.y)
  62616. && getMaximiseButton() != 0)
  62617. {
  62618. getMaximiseButton()->triggerClick();
  62619. }
  62620. }
  62621. void DocumentWindow::userTriedToCloseWindow()
  62622. {
  62623. closeButtonPressed();
  62624. }
  62625. END_JUCE_NAMESPACE
  62626. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62627. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62628. BEGIN_JUCE_NAMESPACE
  62629. ResizableWindow::ResizableWindow (const String& name,
  62630. const bool addToDesktop_)
  62631. : TopLevelWindow (name, addToDesktop_),
  62632. resizeToFitContent (false),
  62633. fullscreen (false),
  62634. lastNonFullScreenPos (50, 50, 256, 256),
  62635. constrainer (0)
  62636. #if JUCE_DEBUG
  62637. , hasBeenResized (false)
  62638. #endif
  62639. {
  62640. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62641. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62642. if (addToDesktop_)
  62643. Component::addToDesktop (getDesktopWindowStyleFlags());
  62644. }
  62645. ResizableWindow::ResizableWindow (const String& name,
  62646. const Colour& backgroundColour_,
  62647. const bool addToDesktop_)
  62648. : TopLevelWindow (name, addToDesktop_),
  62649. resizeToFitContent (false),
  62650. fullscreen (false),
  62651. lastNonFullScreenPos (50, 50, 256, 256),
  62652. constrainer (0)
  62653. #if JUCE_DEBUG
  62654. , hasBeenResized (false)
  62655. #endif
  62656. {
  62657. setBackgroundColour (backgroundColour_);
  62658. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62659. if (addToDesktop_)
  62660. Component::addToDesktop (getDesktopWindowStyleFlags());
  62661. }
  62662. ResizableWindow::~ResizableWindow()
  62663. {
  62664. resizableCorner = 0;
  62665. resizableBorder = 0;
  62666. delete static_cast <Component*> (contentComponent);
  62667. contentComponent = 0;
  62668. // have you been adding your own components directly to this window..? tut tut tut.
  62669. // Read the instructions for using a ResizableWindow!
  62670. jassert (getNumChildComponents() == 0);
  62671. }
  62672. int ResizableWindow::getDesktopWindowStyleFlags() const
  62673. {
  62674. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62675. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62676. styleFlags |= ComponentPeer::windowIsResizable;
  62677. return styleFlags;
  62678. }
  62679. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62680. const bool deleteOldOne,
  62681. const bool resizeToFit)
  62682. {
  62683. resizeToFitContent = resizeToFit;
  62684. if (newContentComponent != static_cast <Component*> (contentComponent))
  62685. {
  62686. if (deleteOldOne)
  62687. delete static_cast <Component*> (contentComponent); // (avoid using a scoped pointer for this, so that it survives
  62688. // external deletion of the content comp)
  62689. else
  62690. removeChildComponent (contentComponent);
  62691. contentComponent = newContentComponent;
  62692. Component::addAndMakeVisible (contentComponent);
  62693. }
  62694. if (resizeToFit)
  62695. childBoundsChanged (contentComponent);
  62696. resized(); // must always be called to position the new content comp
  62697. }
  62698. void ResizableWindow::setContentComponentSize (int width, int height)
  62699. {
  62700. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62701. const BorderSize border (getContentComponentBorder());
  62702. setSize (width + border.getLeftAndRight(),
  62703. height + border.getTopAndBottom());
  62704. }
  62705. const BorderSize ResizableWindow::getBorderThickness()
  62706. {
  62707. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62708. }
  62709. const BorderSize ResizableWindow::getContentComponentBorder()
  62710. {
  62711. return getBorderThickness();
  62712. }
  62713. void ResizableWindow::moved()
  62714. {
  62715. updateLastPos();
  62716. }
  62717. void ResizableWindow::visibilityChanged()
  62718. {
  62719. TopLevelWindow::visibilityChanged();
  62720. updateLastPos();
  62721. }
  62722. void ResizableWindow::resized()
  62723. {
  62724. if (resizableBorder != 0)
  62725. {
  62726. resizableBorder->setVisible (! isFullScreen());
  62727. resizableBorder->setBorderThickness (getBorderThickness());
  62728. resizableBorder->setSize (getWidth(), getHeight());
  62729. resizableBorder->toBack();
  62730. }
  62731. if (resizableCorner != 0)
  62732. {
  62733. resizableCorner->setVisible (! isFullScreen());
  62734. const int resizerSize = 18;
  62735. resizableCorner->setBounds (getWidth() - resizerSize,
  62736. getHeight() - resizerSize,
  62737. resizerSize, resizerSize);
  62738. }
  62739. if (contentComponent != 0)
  62740. contentComponent->setBoundsInset (getContentComponentBorder());
  62741. updateLastPos();
  62742. #if JUCE_DEBUG
  62743. hasBeenResized = true;
  62744. #endif
  62745. }
  62746. void ResizableWindow::childBoundsChanged (Component* child)
  62747. {
  62748. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62749. {
  62750. // not going to look very good if this component has a zero size..
  62751. jassert (child->getWidth() > 0);
  62752. jassert (child->getHeight() > 0);
  62753. const BorderSize borders (getContentComponentBorder());
  62754. setSize (child->getWidth() + borders.getLeftAndRight(),
  62755. child->getHeight() + borders.getTopAndBottom());
  62756. }
  62757. }
  62758. void ResizableWindow::activeWindowStatusChanged()
  62759. {
  62760. const BorderSize border (getContentComponentBorder());
  62761. Rectangle<int> area (getLocalBounds());
  62762. repaint (area.removeFromTop (border.getTop()));
  62763. repaint (area.removeFromLeft (border.getLeft()));
  62764. repaint (area.removeFromRight (border.getRight()));
  62765. repaint (area.removeFromBottom (border.getBottom()));
  62766. }
  62767. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62768. const bool useBottomRightCornerResizer)
  62769. {
  62770. if (shouldBeResizable)
  62771. {
  62772. if (useBottomRightCornerResizer)
  62773. {
  62774. resizableBorder = 0;
  62775. if (resizableCorner == 0)
  62776. {
  62777. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62778. resizableCorner->setAlwaysOnTop (true);
  62779. }
  62780. }
  62781. else
  62782. {
  62783. resizableCorner = 0;
  62784. if (resizableBorder == 0)
  62785. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62786. }
  62787. }
  62788. else
  62789. {
  62790. resizableCorner = 0;
  62791. resizableBorder = 0;
  62792. }
  62793. if (isUsingNativeTitleBar())
  62794. recreateDesktopWindow();
  62795. childBoundsChanged (contentComponent);
  62796. resized();
  62797. }
  62798. bool ResizableWindow::isResizable() const throw()
  62799. {
  62800. return resizableCorner != 0
  62801. || resizableBorder != 0;
  62802. }
  62803. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62804. const int newMinimumHeight,
  62805. const int newMaximumWidth,
  62806. const int newMaximumHeight) throw()
  62807. {
  62808. // if you've set up a custom constrainer then these settings won't have any effect..
  62809. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62810. if (constrainer == 0)
  62811. setConstrainer (&defaultConstrainer);
  62812. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62813. newMaximumWidth, newMaximumHeight);
  62814. setBoundsConstrained (getBounds());
  62815. }
  62816. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62817. {
  62818. if (constrainer != newConstrainer)
  62819. {
  62820. constrainer = newConstrainer;
  62821. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62822. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62823. resizableCorner = 0;
  62824. resizableBorder = 0;
  62825. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62826. ComponentPeer* const peer = getPeer();
  62827. if (peer != 0)
  62828. peer->setConstrainer (newConstrainer);
  62829. }
  62830. }
  62831. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62832. {
  62833. if (constrainer != 0)
  62834. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62835. else
  62836. setBounds (bounds);
  62837. }
  62838. void ResizableWindow::paint (Graphics& g)
  62839. {
  62840. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62841. getBorderThickness(), *this);
  62842. if (! isFullScreen())
  62843. {
  62844. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62845. getBorderThickness(), *this);
  62846. }
  62847. #if JUCE_DEBUG
  62848. /* If this fails, then you've probably written a subclass with a resized()
  62849. callback but forgotten to make it call its parent class's resized() method.
  62850. It's important when you override methods like resized(), moved(),
  62851. etc., that you make sure the base class methods also get called.
  62852. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62853. because your content should all be inside the content component - and it's the
  62854. content component's resized() method that you should be using to do your
  62855. layout.
  62856. */
  62857. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62858. #endif
  62859. }
  62860. void ResizableWindow::lookAndFeelChanged()
  62861. {
  62862. resized();
  62863. if (isOnDesktop())
  62864. {
  62865. Component::addToDesktop (getDesktopWindowStyleFlags());
  62866. ComponentPeer* const peer = getPeer();
  62867. if (peer != 0)
  62868. peer->setConstrainer (constrainer);
  62869. }
  62870. }
  62871. const Colour ResizableWindow::getBackgroundColour() const throw()
  62872. {
  62873. return findColour (backgroundColourId, false);
  62874. }
  62875. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62876. {
  62877. Colour backgroundColour (newColour);
  62878. if (! Desktop::canUseSemiTransparentWindows())
  62879. backgroundColour = newColour.withAlpha (1.0f);
  62880. setColour (backgroundColourId, backgroundColour);
  62881. setOpaque (backgroundColour.isOpaque());
  62882. repaint();
  62883. }
  62884. bool ResizableWindow::isFullScreen() const
  62885. {
  62886. if (isOnDesktop())
  62887. {
  62888. ComponentPeer* const peer = getPeer();
  62889. return peer != 0 && peer->isFullScreen();
  62890. }
  62891. return fullscreen;
  62892. }
  62893. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62894. {
  62895. if (shouldBeFullScreen != isFullScreen())
  62896. {
  62897. updateLastPos();
  62898. fullscreen = shouldBeFullScreen;
  62899. if (isOnDesktop())
  62900. {
  62901. ComponentPeer* const peer = getPeer();
  62902. if (peer != 0)
  62903. {
  62904. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62905. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62906. peer->setFullScreen (shouldBeFullScreen);
  62907. if (! shouldBeFullScreen)
  62908. setBounds (lastPos);
  62909. }
  62910. else
  62911. {
  62912. jassertfalse;
  62913. }
  62914. }
  62915. else
  62916. {
  62917. if (shouldBeFullScreen)
  62918. setBounds (0, 0, getParentWidth(), getParentHeight());
  62919. else
  62920. setBounds (lastNonFullScreenPos);
  62921. }
  62922. resized();
  62923. }
  62924. }
  62925. bool ResizableWindow::isMinimised() const
  62926. {
  62927. ComponentPeer* const peer = getPeer();
  62928. return (peer != 0) && peer->isMinimised();
  62929. }
  62930. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62931. {
  62932. if (shouldMinimise != isMinimised())
  62933. {
  62934. ComponentPeer* const peer = getPeer();
  62935. if (peer != 0)
  62936. {
  62937. updateLastPos();
  62938. peer->setMinimised (shouldMinimise);
  62939. }
  62940. else
  62941. {
  62942. jassertfalse;
  62943. }
  62944. }
  62945. }
  62946. void ResizableWindow::updateLastPos()
  62947. {
  62948. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62949. {
  62950. lastNonFullScreenPos = getBounds();
  62951. }
  62952. }
  62953. void ResizableWindow::parentSizeChanged()
  62954. {
  62955. if (isFullScreen() && getParentComponent() != 0)
  62956. {
  62957. setBounds (0, 0, getParentWidth(), getParentHeight());
  62958. }
  62959. }
  62960. const String ResizableWindow::getWindowStateAsString()
  62961. {
  62962. updateLastPos();
  62963. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62964. }
  62965. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62966. {
  62967. StringArray tokens;
  62968. tokens.addTokens (s, false);
  62969. tokens.removeEmptyStrings();
  62970. tokens.trim();
  62971. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62972. const int firstCoord = fs ? 1 : 0;
  62973. if (tokens.size() != firstCoord + 4)
  62974. return false;
  62975. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62976. tokens[firstCoord + 1].getIntValue(),
  62977. tokens[firstCoord + 2].getIntValue(),
  62978. tokens[firstCoord + 3].getIntValue());
  62979. if (newPos.isEmpty())
  62980. return false;
  62981. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62982. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62983. if (peer != 0)
  62984. peer->getFrameSize().addTo (newPos);
  62985. if (! screen.contains (newPos))
  62986. {
  62987. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62988. jmin (newPos.getHeight(), screen.getHeight()));
  62989. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62990. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62991. }
  62992. if (peer != 0)
  62993. {
  62994. peer->getFrameSize().subtractFrom (newPos);
  62995. peer->setNonFullScreenBounds (newPos);
  62996. }
  62997. lastNonFullScreenPos = newPos;
  62998. setFullScreen (fs);
  62999. if (! fs)
  63000. setBoundsConstrained (newPos);
  63001. return true;
  63002. }
  63003. void ResizableWindow::mouseDown (const MouseEvent&)
  63004. {
  63005. if (! isFullScreen())
  63006. dragger.startDraggingComponent (this, constrainer);
  63007. }
  63008. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63009. {
  63010. if (! isFullScreen())
  63011. dragger.dragComponent (this, e);
  63012. }
  63013. #if JUCE_DEBUG
  63014. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63015. {
  63016. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63017. manages its child components automatically, and if you add your own it'll cause
  63018. trouble. Instead, use setContentComponent() to give it a component which
  63019. will be automatically resized and kept in the right place - then you can add
  63020. subcomponents to the content comp. See the notes for the ResizableWindow class
  63021. for more info.
  63022. If you really know what you're doing and want to avoid this assertion, just call
  63023. Component::addChildComponent directly.
  63024. */
  63025. jassertfalse;
  63026. Component::addChildComponent (child, zOrder);
  63027. }
  63028. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63029. {
  63030. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63031. manages its child components automatically, and if you add your own it'll cause
  63032. trouble. Instead, use setContentComponent() to give it a component which
  63033. will be automatically resized and kept in the right place - then you can add
  63034. subcomponents to the content comp. See the notes for the ResizableWindow class
  63035. for more info.
  63036. If you really know what you're doing and want to avoid this assertion, just call
  63037. Component::addAndMakeVisible directly.
  63038. */
  63039. jassertfalse;
  63040. Component::addAndMakeVisible (child, zOrder);
  63041. }
  63042. #endif
  63043. END_JUCE_NAMESPACE
  63044. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63045. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63046. BEGIN_JUCE_NAMESPACE
  63047. SplashScreen::SplashScreen()
  63048. {
  63049. setOpaque (true);
  63050. }
  63051. SplashScreen::~SplashScreen()
  63052. {
  63053. }
  63054. void SplashScreen::show (const String& title,
  63055. const Image& backgroundImage_,
  63056. const int minimumTimeToDisplayFor,
  63057. const bool useDropShadow,
  63058. const bool removeOnMouseClick)
  63059. {
  63060. backgroundImage = backgroundImage_;
  63061. jassert (backgroundImage_.isValid());
  63062. if (backgroundImage_.isValid())
  63063. {
  63064. setOpaque (! backgroundImage_.hasAlphaChannel());
  63065. show (title,
  63066. backgroundImage_.getWidth(),
  63067. backgroundImage_.getHeight(),
  63068. minimumTimeToDisplayFor,
  63069. useDropShadow,
  63070. removeOnMouseClick);
  63071. }
  63072. }
  63073. void SplashScreen::show (const String& title,
  63074. const int width,
  63075. const int height,
  63076. const int minimumTimeToDisplayFor,
  63077. const bool useDropShadow,
  63078. const bool removeOnMouseClick)
  63079. {
  63080. setName (title);
  63081. setAlwaysOnTop (true);
  63082. setVisible (true);
  63083. centreWithSize (width, height);
  63084. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63085. toFront (false);
  63086. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63087. repaint();
  63088. originalClickCounter = removeOnMouseClick
  63089. ? Desktop::getMouseButtonClickCounter()
  63090. : std::numeric_limits<int>::max();
  63091. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63092. startTimer (50);
  63093. }
  63094. void SplashScreen::paint (Graphics& g)
  63095. {
  63096. g.setOpacity (1.0f);
  63097. g.drawImage (backgroundImage,
  63098. 0, 0, getWidth(), getHeight(),
  63099. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63100. }
  63101. void SplashScreen::timerCallback()
  63102. {
  63103. if (Time::getCurrentTime() > earliestTimeToDelete
  63104. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63105. {
  63106. delete this;
  63107. }
  63108. }
  63109. END_JUCE_NAMESPACE
  63110. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63111. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63112. BEGIN_JUCE_NAMESPACE
  63113. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63114. const bool hasProgressBar,
  63115. const bool hasCancelButton,
  63116. const int timeOutMsWhenCancelling_,
  63117. const String& cancelButtonText)
  63118. : Thread ("Juce Progress Window"),
  63119. progress (0.0),
  63120. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63121. {
  63122. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63123. .createAlertWindow (title, String::empty, cancelButtonText,
  63124. String::empty, String::empty,
  63125. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63126. if (hasProgressBar)
  63127. alertWindow->addProgressBarComponent (progress);
  63128. }
  63129. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63130. {
  63131. stopThread (timeOutMsWhenCancelling);
  63132. }
  63133. bool ThreadWithProgressWindow::runThread (const int priority)
  63134. {
  63135. startThread (priority);
  63136. startTimer (100);
  63137. {
  63138. const ScopedLock sl (messageLock);
  63139. alertWindow->setMessage (message);
  63140. }
  63141. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63142. stopThread (timeOutMsWhenCancelling);
  63143. alertWindow->setVisible (false);
  63144. return finishedNaturally;
  63145. }
  63146. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63147. {
  63148. progress = newProgress;
  63149. }
  63150. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63151. {
  63152. const ScopedLock sl (messageLock);
  63153. message = newStatusMessage;
  63154. }
  63155. void ThreadWithProgressWindow::timerCallback()
  63156. {
  63157. if (! isThreadRunning())
  63158. {
  63159. // thread has finished normally..
  63160. alertWindow->exitModalState (1);
  63161. alertWindow->setVisible (false);
  63162. }
  63163. else
  63164. {
  63165. const ScopedLock sl (messageLock);
  63166. alertWindow->setMessage (message);
  63167. }
  63168. }
  63169. END_JUCE_NAMESPACE
  63170. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63171. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63172. BEGIN_JUCE_NAMESPACE
  63173. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63174. const int millisecondsBeforeTipAppears_)
  63175. : Component ("tooltip"),
  63176. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63177. mouseClicks (0),
  63178. lastHideTime (0),
  63179. lastComponentUnderMouse (0),
  63180. changedCompsSinceShown (true)
  63181. {
  63182. if (Desktop::getInstance().getMainMouseSource().canHover())
  63183. startTimer (123);
  63184. setAlwaysOnTop (true);
  63185. setOpaque (true);
  63186. if (parentComponent != 0)
  63187. parentComponent->addChildComponent (this);
  63188. }
  63189. TooltipWindow::~TooltipWindow()
  63190. {
  63191. hide();
  63192. }
  63193. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63194. {
  63195. millisecondsBeforeTipAppears = newTimeMs;
  63196. }
  63197. void TooltipWindow::paint (Graphics& g)
  63198. {
  63199. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63200. }
  63201. void TooltipWindow::mouseEnter (const MouseEvent&)
  63202. {
  63203. hide();
  63204. }
  63205. void TooltipWindow::showFor (const String& tip)
  63206. {
  63207. jassert (tip.isNotEmpty());
  63208. if (tipShowing != tip)
  63209. repaint();
  63210. tipShowing = tip;
  63211. Point<int> mousePos (Desktop::getMousePosition());
  63212. if (getParentComponent() != 0)
  63213. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63214. int x, y, w, h;
  63215. getLookAndFeel().getTooltipSize (tip, w, h);
  63216. if (mousePos.getX() > getParentWidth() / 2)
  63217. x = mousePos.getX() - (w + 12);
  63218. else
  63219. x = mousePos.getX() + 24;
  63220. if (mousePos.getY() > getParentHeight() / 2)
  63221. y = mousePos.getY() - (h + 6);
  63222. else
  63223. y = mousePos.getY() + 6;
  63224. setBounds (x, y, w, h);
  63225. setVisible (true);
  63226. if (getParentComponent() == 0)
  63227. {
  63228. addToDesktop (ComponentPeer::windowHasDropShadow
  63229. | ComponentPeer::windowIsTemporary
  63230. | ComponentPeer::windowIgnoresKeyPresses);
  63231. }
  63232. toFront (false);
  63233. }
  63234. const String TooltipWindow::getTipFor (Component* const c)
  63235. {
  63236. if (c != 0
  63237. && Process::isForegroundProcess()
  63238. && ! Component::isMouseButtonDownAnywhere())
  63239. {
  63240. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63241. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63242. return ttc->getTooltip();
  63243. }
  63244. return String::empty;
  63245. }
  63246. void TooltipWindow::hide()
  63247. {
  63248. tipShowing = String::empty;
  63249. removeFromDesktop();
  63250. setVisible (false);
  63251. }
  63252. void TooltipWindow::timerCallback()
  63253. {
  63254. const unsigned int now = Time::getApproximateMillisecondCounter();
  63255. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63256. const String newTip (getTipFor (newComp));
  63257. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63258. lastComponentUnderMouse = newComp;
  63259. lastTipUnderMouse = newTip;
  63260. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63261. const bool mouseWasClicked = clickCount > mouseClicks;
  63262. mouseClicks = clickCount;
  63263. const Point<int> mousePos (Desktop::getMousePosition());
  63264. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63265. lastMousePos = mousePos;
  63266. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63267. lastCompChangeTime = now;
  63268. if (isVisible() || now < lastHideTime + 500)
  63269. {
  63270. // if a tip is currently visible (or has just disappeared), update to a new one
  63271. // immediately if needed..
  63272. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63273. {
  63274. if (isVisible())
  63275. {
  63276. lastHideTime = now;
  63277. hide();
  63278. }
  63279. }
  63280. else if (tipChanged)
  63281. {
  63282. showFor (newTip);
  63283. }
  63284. }
  63285. else
  63286. {
  63287. // if there isn't currently a tip, but one is needed, only let it
  63288. // appear after a timeout..
  63289. if (newTip.isNotEmpty()
  63290. && newTip != tipShowing
  63291. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63292. {
  63293. showFor (newTip);
  63294. }
  63295. }
  63296. }
  63297. END_JUCE_NAMESPACE
  63298. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63299. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63300. BEGIN_JUCE_NAMESPACE
  63301. /** Keeps track of the active top level window.
  63302. */
  63303. class TopLevelWindowManager : public Timer,
  63304. public DeletedAtShutdown
  63305. {
  63306. public:
  63307. TopLevelWindowManager()
  63308. : currentActive (0)
  63309. {
  63310. }
  63311. ~TopLevelWindowManager()
  63312. {
  63313. clearSingletonInstance();
  63314. }
  63315. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63316. void timerCallback()
  63317. {
  63318. startTimer (jmin (1731, getTimerInterval() * 2));
  63319. TopLevelWindow* active = 0;
  63320. if (Process::isForegroundProcess())
  63321. {
  63322. active = currentActive;
  63323. Component* const c = Component::getCurrentlyFocusedComponent();
  63324. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63325. if (tlw == 0 && c != 0)
  63326. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63327. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63328. if (tlw != 0)
  63329. active = tlw;
  63330. }
  63331. if (active != currentActive)
  63332. {
  63333. currentActive = active;
  63334. for (int i = windows.size(); --i >= 0;)
  63335. {
  63336. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63337. tlw->setWindowActive (isWindowActive (tlw));
  63338. i = jmin (i, windows.size() - 1);
  63339. }
  63340. Desktop::getInstance().triggerFocusCallback();
  63341. }
  63342. }
  63343. bool addWindow (TopLevelWindow* const w)
  63344. {
  63345. windows.add (w);
  63346. startTimer (10);
  63347. return isWindowActive (w);
  63348. }
  63349. void removeWindow (TopLevelWindow* const w)
  63350. {
  63351. startTimer (10);
  63352. if (currentActive == w)
  63353. currentActive = 0;
  63354. windows.removeValue (w);
  63355. if (windows.size() == 0)
  63356. deleteInstance();
  63357. }
  63358. Array <TopLevelWindow*> windows;
  63359. private:
  63360. TopLevelWindow* currentActive;
  63361. bool isWindowActive (TopLevelWindow* const tlw) const
  63362. {
  63363. return (tlw == currentActive
  63364. || tlw->isParentOf (currentActive)
  63365. || tlw->hasKeyboardFocus (true))
  63366. && tlw->isShowing();
  63367. }
  63368. TopLevelWindowManager (const TopLevelWindowManager&);
  63369. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63370. };
  63371. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63372. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63373. {
  63374. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63375. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63376. }
  63377. TopLevelWindow::TopLevelWindow (const String& name,
  63378. const bool addToDesktop_)
  63379. : Component (name),
  63380. useDropShadow (true),
  63381. useNativeTitleBar (false),
  63382. windowIsActive_ (false)
  63383. {
  63384. setOpaque (true);
  63385. if (addToDesktop_)
  63386. Component::addToDesktop (getDesktopWindowStyleFlags());
  63387. else
  63388. setDropShadowEnabled (true);
  63389. setWantsKeyboardFocus (true);
  63390. setBroughtToFrontOnMouseClick (true);
  63391. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63392. }
  63393. TopLevelWindow::~TopLevelWindow()
  63394. {
  63395. shadower = 0;
  63396. TopLevelWindowManager::getInstance()->removeWindow (this);
  63397. }
  63398. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63399. {
  63400. if (hasKeyboardFocus (true))
  63401. TopLevelWindowManager::getInstance()->timerCallback();
  63402. else
  63403. TopLevelWindowManager::getInstance()->startTimer (10);
  63404. }
  63405. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63406. {
  63407. if (windowIsActive_ != isNowActive)
  63408. {
  63409. windowIsActive_ = isNowActive;
  63410. activeWindowStatusChanged();
  63411. }
  63412. }
  63413. void TopLevelWindow::activeWindowStatusChanged()
  63414. {
  63415. }
  63416. void TopLevelWindow::parentHierarchyChanged()
  63417. {
  63418. setDropShadowEnabled (useDropShadow);
  63419. }
  63420. void TopLevelWindow::visibilityChanged()
  63421. {
  63422. if (isShowing())
  63423. toFront (true);
  63424. }
  63425. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63426. {
  63427. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63428. if (useDropShadow)
  63429. styleFlags |= ComponentPeer::windowHasDropShadow;
  63430. if (useNativeTitleBar)
  63431. styleFlags |= ComponentPeer::windowHasTitleBar;
  63432. return styleFlags;
  63433. }
  63434. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63435. {
  63436. useDropShadow = useShadow;
  63437. if (isOnDesktop())
  63438. {
  63439. shadower = 0;
  63440. Component::addToDesktop (getDesktopWindowStyleFlags());
  63441. }
  63442. else
  63443. {
  63444. if (useShadow && isOpaque())
  63445. {
  63446. if (shadower == 0)
  63447. {
  63448. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63449. if (shadower != 0)
  63450. shadower->setOwner (this);
  63451. }
  63452. }
  63453. else
  63454. {
  63455. shadower = 0;
  63456. }
  63457. }
  63458. }
  63459. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63460. {
  63461. if (useNativeTitleBar != useNativeTitleBar_)
  63462. {
  63463. useNativeTitleBar = useNativeTitleBar_;
  63464. recreateDesktopWindow();
  63465. sendLookAndFeelChange();
  63466. }
  63467. }
  63468. void TopLevelWindow::recreateDesktopWindow()
  63469. {
  63470. if (isOnDesktop())
  63471. {
  63472. Component::addToDesktop (getDesktopWindowStyleFlags());
  63473. toFront (true);
  63474. }
  63475. }
  63476. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63477. {
  63478. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63479. because this class needs to make sure its layout corresponds with settings like whether
  63480. it's got a native title bar or not.
  63481. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63482. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63483. method, then add or remove whatever flags are necessary from this value before returning it.
  63484. */
  63485. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63486. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63487. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63488. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63489. sendLookAndFeelChange();
  63490. }
  63491. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63492. {
  63493. if (c == 0)
  63494. c = TopLevelWindow::getActiveTopLevelWindow();
  63495. if (c == 0)
  63496. {
  63497. centreWithSize (width, height);
  63498. }
  63499. else
  63500. {
  63501. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63502. (c->getHeight() - height) / 2)));
  63503. Rectangle<int> parentArea (c->getParentMonitorArea());
  63504. if (getParentComponent() != 0)
  63505. {
  63506. p = getParentComponent()->globalPositionToRelative (p);
  63507. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63508. }
  63509. parentArea.reduce (12, 12);
  63510. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63511. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63512. width, height);
  63513. }
  63514. }
  63515. int TopLevelWindow::getNumTopLevelWindows() throw()
  63516. {
  63517. return TopLevelWindowManager::getInstance()->windows.size();
  63518. }
  63519. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63520. {
  63521. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63522. }
  63523. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63524. {
  63525. TopLevelWindow* best = 0;
  63526. int bestNumTWLParents = -1;
  63527. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63528. {
  63529. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63530. if (tlw->isActiveWindow())
  63531. {
  63532. int numTWLParents = 0;
  63533. const Component* c = tlw->getParentComponent();
  63534. while (c != 0)
  63535. {
  63536. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63537. ++numTWLParents;
  63538. c = c->getParentComponent();
  63539. }
  63540. if (bestNumTWLParents < numTWLParents)
  63541. {
  63542. best = tlw;
  63543. bestNumTWLParents = numTWLParents;
  63544. }
  63545. }
  63546. }
  63547. return best;
  63548. }
  63549. END_JUCE_NAMESPACE
  63550. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63551. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63552. BEGIN_JUCE_NAMESPACE
  63553. namespace RelativeCoordinateHelpers
  63554. {
  63555. static bool isOrigin (const String& name)
  63556. {
  63557. return name.isEmpty()
  63558. || name == RelativeCoordinate::Strings::parentLeft
  63559. || name == RelativeCoordinate::Strings::parentTop;
  63560. }
  63561. static const String getExtentAnchorName (const bool isHorizontal) throw()
  63562. {
  63563. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  63564. : RelativeCoordinate::Strings::parentBottom;
  63565. }
  63566. static const String getObjectName (const String& fullName)
  63567. {
  63568. return fullName.upToFirstOccurrenceOf (".", false, false);
  63569. }
  63570. static const String getEdgeName (const String& fullName)
  63571. {
  63572. return fullName.fromFirstOccurrenceOf (".", false, false);
  63573. }
  63574. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63575. {
  63576. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  63577. : RelativeCoordinate();
  63578. }
  63579. struct RecursionException : public std::runtime_error
  63580. {
  63581. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  63582. {
  63583. }
  63584. };
  63585. static void skipWhitespace (const juce_wchar* const s, int& i)
  63586. {
  63587. while (CharacterFunctions::isWhitespace (s[i]))
  63588. ++i;
  63589. }
  63590. static void skipComma (const juce_wchar* const s, int& i)
  63591. {
  63592. skipWhitespace (s, i);
  63593. if (s[i] == ',')
  63594. ++i;
  63595. }
  63596. static const String readAnchorName (const juce_wchar* const s, int& i)
  63597. {
  63598. skipWhitespace (s, i);
  63599. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  63600. {
  63601. int start = i;
  63602. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  63603. ++i;
  63604. return String (s + start, i - start);
  63605. }
  63606. return String::empty;
  63607. }
  63608. static double readNumber (const juce_wchar* const s, int& i)
  63609. {
  63610. skipWhitespace (s, i);
  63611. int start = i;
  63612. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  63613. ++i;
  63614. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  63615. ++i;
  63616. if ((s[i] == 'e' || s[i] == 'E')
  63617. && (CharacterFunctions::isDigit (s[i + 1])
  63618. || s[i + 1] == '-'
  63619. || s[i + 1] == '+'))
  63620. {
  63621. i += 2;
  63622. while (CharacterFunctions::isDigit (s[i]))
  63623. ++i;
  63624. }
  63625. const double value = String (s + start, i - start).getDoubleValue();
  63626. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  63627. ++i;
  63628. return value;
  63629. }
  63630. static const RelativeCoordinate readNextCoordinate (const juce_wchar* const s, int& i, const bool isHorizontal)
  63631. {
  63632. String anchor1 (readAnchorName (s, i));
  63633. double value = 0;
  63634. if (anchor1.isNotEmpty())
  63635. {
  63636. skipWhitespace (s, i);
  63637. if (s[i] == '+')
  63638. value = readNumber (s, ++i);
  63639. else if (s[i] == '-')
  63640. value = -readNumber (s, ++i);
  63641. return RelativeCoordinate (value, anchor1);
  63642. }
  63643. else
  63644. {
  63645. value = readNumber (s, i);
  63646. skipWhitespace (s, i);
  63647. if (s[i] == '%')
  63648. {
  63649. value /= 100.0;
  63650. skipWhitespace (s, ++i);
  63651. String anchor2;
  63652. if (s[i] == '*')
  63653. {
  63654. anchor1 = readAnchorName (s, ++i);
  63655. skipWhitespace (s, i);
  63656. if (s[i] == '-' && s[i + 1] == '>')
  63657. {
  63658. i += 2;
  63659. anchor2 = readAnchorName (s, i);
  63660. }
  63661. else
  63662. {
  63663. anchor2 = anchor1;
  63664. anchor1 = String::empty;
  63665. }
  63666. }
  63667. else
  63668. {
  63669. anchor1 = String::empty;
  63670. anchor2 = getExtentAnchorName (isHorizontal);
  63671. }
  63672. return RelativeCoordinate (value, anchor1, anchor2);
  63673. }
  63674. return RelativeCoordinate (value);
  63675. }
  63676. }
  63677. static const String limitedAccuracyString (const double n)
  63678. {
  63679. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  63680. return "0";
  63681. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  63682. }
  63683. }
  63684. const String RelativeCoordinate::Strings::parent ("parent");
  63685. const String RelativeCoordinate::Strings::left ("left");
  63686. const String RelativeCoordinate::Strings::right ("right");
  63687. const String RelativeCoordinate::Strings::top ("top");
  63688. const String RelativeCoordinate::Strings::bottom ("bottom");
  63689. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63690. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63691. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63692. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63693. RelativeCoordinate::RelativeCoordinate()
  63694. : value (0)
  63695. {
  63696. }
  63697. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63698. : value (absoluteDistanceFromOrigin)
  63699. {
  63700. }
  63701. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  63702. : anchor1 (source.trim()),
  63703. value (absoluteDistance)
  63704. {
  63705. }
  63706. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  63707. : anchor1 (pos1.trim()),
  63708. anchor2 (pos2.trim()),
  63709. value (relativeProportion)
  63710. {
  63711. }
  63712. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  63713. : value (0)
  63714. {
  63715. int i = 0;
  63716. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  63717. }
  63718. RelativeCoordinate::~RelativeCoordinate()
  63719. {
  63720. }
  63721. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63722. {
  63723. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  63724. }
  63725. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63726. {
  63727. return ! operator== (other);
  63728. }
  63729. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  63730. {
  63731. return RelativeCoordinate (0.0, anchor1);
  63732. }
  63733. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  63734. {
  63735. return RelativeCoordinate (0.0, anchor2);
  63736. }
  63737. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  63738. {
  63739. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  63740. return 0.0;
  63741. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  63742. }
  63743. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  63744. {
  63745. if (recursionCounter > 150)
  63746. {
  63747. jassertfalse
  63748. throw RelativeCoordinateHelpers::RecursionException();
  63749. }
  63750. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  63751. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  63752. : pos1 + value;
  63753. }
  63754. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  63755. {
  63756. try
  63757. {
  63758. return resolve (nameFinder, 0);
  63759. }
  63760. catch (RelativeCoordinateHelpers::RecursionException&)
  63761. {}
  63762. return 0.0;
  63763. }
  63764. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  63765. {
  63766. try
  63767. {
  63768. (void) resolve (nameFinder, 0);
  63769. }
  63770. catch (RelativeCoordinateHelpers::RecursionException&)
  63771. {
  63772. return true;
  63773. }
  63774. return false;
  63775. }
  63776. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  63777. {
  63778. try
  63779. {
  63780. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  63781. if (isProportional())
  63782. {
  63783. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  63784. if (size != 0)
  63785. value = (newPos - pos1) / size;
  63786. }
  63787. else
  63788. {
  63789. value = newPos - pos1;
  63790. }
  63791. }
  63792. catch (RelativeCoordinateHelpers::RecursionException&)
  63793. {}
  63794. }
  63795. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder,
  63796. const String& proportionalAnchor1, const String& proportionalAnchor2)
  63797. {
  63798. const double oldValue = resolve (nameFinder);
  63799. anchor1 = proportionalAnchor1;
  63800. anchor2 = isProportional() ? String::empty : proportionalAnchor2;
  63801. moveToAbsolute (oldValue, nameFinder);
  63802. }
  63803. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  63804. {
  63805. using namespace RelativeCoordinateHelpers;
  63806. if (isOrigin (anchor1) && ! isProportional())
  63807. return isOrigin (coordName);
  63808. return anchor1 == coordName
  63809. || anchor2 == coordName
  63810. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  63811. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  63812. }
  63813. bool RelativeCoordinate::isDynamic() const
  63814. {
  63815. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  63816. }
  63817. const String RelativeCoordinate::toString() const
  63818. {
  63819. using namespace RelativeCoordinateHelpers;
  63820. if (isProportional())
  63821. {
  63822. const String percent (limitedAccuracyString (value * 100.0));
  63823. if (isOrigin (anchor1))
  63824. {
  63825. if (anchor2 == Strings::parentRight || anchor2 == Strings::parentBottom)
  63826. return percent + "%";
  63827. else
  63828. return percent + "% * " + anchor2;
  63829. }
  63830. else
  63831. return percent + "% * " + anchor1 + " -> " + anchor2;
  63832. }
  63833. else
  63834. {
  63835. if (isOrigin (anchor1))
  63836. return limitedAccuracyString (value);
  63837. else if (value > 0)
  63838. return anchor1 + " + " + limitedAccuracyString (value);
  63839. else if (value < 0)
  63840. return anchor1 + " - " + limitedAccuracyString (-value);
  63841. else
  63842. return anchor1;
  63843. }
  63844. }
  63845. const double RelativeCoordinate::getEditableNumber() const
  63846. {
  63847. return isProportional() ? value * 100.0 : value;
  63848. }
  63849. void RelativeCoordinate::setEditableNumber (const double newValue)
  63850. {
  63851. value = isProportional() ? newValue / 100.0 : newValue;
  63852. }
  63853. const String RelativeCoordinate::getAnchorName1 (const String& returnValueIfOrigin) const
  63854. {
  63855. return RelativeCoordinateHelpers::isOrigin (anchor1) ? returnValueIfOrigin : anchor1;
  63856. }
  63857. const String RelativeCoordinate::getAnchorName2 (const String& returnValueIfOrigin) const
  63858. {
  63859. return RelativeCoordinateHelpers::isOrigin (anchor2) ? returnValueIfOrigin : anchor2;
  63860. }
  63861. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  63862. {
  63863. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  63864. const double oldValue = resolve (nameFinder);
  63865. anchor1 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  63866. moveToAbsolute (oldValue, nameFinder);
  63867. }
  63868. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  63869. {
  63870. jassert (isProportional());
  63871. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  63872. const double oldValue = resolve (nameFinder);
  63873. anchor2 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  63874. moveToAbsolute (oldValue, nameFinder);
  63875. }
  63876. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  63877. {
  63878. using namespace RelativeCoordinateHelpers;
  63879. jassert (oldName.isNotEmpty());
  63880. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  63881. if (newName.isEmpty())
  63882. {
  63883. if (getObjectName (anchor1) == oldName
  63884. || getObjectName (anchor2) == oldName)
  63885. {
  63886. value = resolve (nameFinder);
  63887. anchor1 = String::empty;
  63888. anchor2 = String::empty;
  63889. }
  63890. }
  63891. else
  63892. {
  63893. if (getObjectName (anchor1) == oldName)
  63894. anchor1 = newName + "." + getEdgeName (anchor1);
  63895. if (getObjectName (anchor2) == oldName)
  63896. anchor2 = newName + "." + getEdgeName (anchor2);
  63897. }
  63898. }
  63899. RelativePoint::RelativePoint()
  63900. {
  63901. }
  63902. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63903. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63904. {
  63905. }
  63906. RelativePoint::RelativePoint (const float x_, const float y_)
  63907. : x (x_), y (y_)
  63908. {
  63909. }
  63910. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63911. : x (x_), y (y_)
  63912. {
  63913. }
  63914. RelativePoint::RelativePoint (const String& s)
  63915. {
  63916. int i = 0;
  63917. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63918. RelativeCoordinateHelpers::skipComma (s, i);
  63919. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63920. }
  63921. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63922. {
  63923. return x == other.x && y == other.y;
  63924. }
  63925. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63926. {
  63927. return ! operator== (other);
  63928. }
  63929. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  63930. {
  63931. return Point<float> ((float) x.resolve (nameFinder),
  63932. (float) y.resolve (nameFinder));
  63933. }
  63934. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63935. {
  63936. x.moveToAbsolute (newPos.getX(), nameFinder);
  63937. y.moveToAbsolute (newPos.getY(), nameFinder);
  63938. }
  63939. const String RelativePoint::toString() const
  63940. {
  63941. return x.toString() + ", " + y.toString();
  63942. }
  63943. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63944. {
  63945. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  63946. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  63947. }
  63948. bool RelativePoint::isDynamic() const
  63949. {
  63950. return x.isDynamic() || y.isDynamic();
  63951. }
  63952. RelativeRectangle::RelativeRectangle()
  63953. {
  63954. }
  63955. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63956. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63957. : left (left_), right (right_), top (top_), bottom (bottom_)
  63958. {
  63959. }
  63960. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  63961. : left (rect.getX()),
  63962. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  63963. top (rect.getY()),
  63964. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  63965. {
  63966. }
  63967. RelativeRectangle::RelativeRectangle (const String& s)
  63968. {
  63969. int i = 0;
  63970. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63971. RelativeCoordinateHelpers::skipComma (s, i);
  63972. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63973. RelativeCoordinateHelpers::skipComma (s, i);
  63974. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63975. RelativeCoordinateHelpers::skipComma (s, i);
  63976. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63977. }
  63978. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63979. {
  63980. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  63981. }
  63982. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  63983. {
  63984. return ! operator== (other);
  63985. }
  63986. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  63987. {
  63988. const double l = left.resolve (nameFinder);
  63989. const double r = right.resolve (nameFinder);
  63990. const double t = top.resolve (nameFinder);
  63991. const double b = bottom.resolve (nameFinder);
  63992. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  63993. }
  63994. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63995. {
  63996. left.moveToAbsolute (newPos.getX(), nameFinder);
  63997. right.moveToAbsolute (newPos.getRight(), nameFinder);
  63998. top.moveToAbsolute (newPos.getY(), nameFinder);
  63999. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  64000. }
  64001. const String RelativeRectangle::toString() const
  64002. {
  64003. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64004. }
  64005. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  64006. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  64007. {
  64008. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  64009. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  64010. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  64011. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  64012. }
  64013. RelativePointPath::RelativePointPath()
  64014. : usesNonZeroWinding (true),
  64015. containsDynamicPoints (false)
  64016. {
  64017. }
  64018. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64019. : usesNonZeroWinding (true),
  64020. containsDynamicPoints (false)
  64021. {
  64022. ValueTree state (DrawablePath::valueTreeType);
  64023. other.writeTo (state, 0);
  64024. parse (state);
  64025. }
  64026. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64027. : usesNonZeroWinding (true),
  64028. containsDynamicPoints (false)
  64029. {
  64030. parse (drawable);
  64031. }
  64032. RelativePointPath::RelativePointPath (const Path& path)
  64033. {
  64034. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64035. Path::Iterator i (path);
  64036. while (i.next())
  64037. {
  64038. switch (i.elementType)
  64039. {
  64040. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64041. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64042. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64043. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64044. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64045. default: jassertfalse; break;
  64046. }
  64047. }
  64048. }
  64049. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64050. {
  64051. DrawablePath::ValueTreeWrapper wrapper (state);
  64052. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64053. ValueTree pathTree (wrapper.getPathState());
  64054. pathTree.removeAllChildren (undoManager);
  64055. for (int i = 0; i < elements.size(); ++i)
  64056. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64057. }
  64058. void RelativePointPath::parse (const ValueTree& state)
  64059. {
  64060. DrawablePath::ValueTreeWrapper wrapper (state);
  64061. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64062. RelativePoint points[3];
  64063. const ValueTree pathTree (wrapper.getPathState());
  64064. const int num = pathTree.getNumChildren();
  64065. for (int i = 0; i < num; ++i)
  64066. {
  64067. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64068. const int numCps = e.getNumControlPoints();
  64069. for (int j = 0; j < numCps; ++j)
  64070. {
  64071. points[j] = e.getControlPoint (j);
  64072. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64073. }
  64074. const Identifier type (e.getType());
  64075. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64076. elements.add (new StartSubPath (points[0]));
  64077. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64078. elements.add (new CloseSubPath());
  64079. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64080. elements.add (new LineTo (points[0]));
  64081. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64082. elements.add (new QuadraticTo (points[0], points[1]));
  64083. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64084. elements.add (new CubicTo (points[0], points[1], points[2]));
  64085. else
  64086. jassertfalse;
  64087. }
  64088. }
  64089. RelativePointPath::~RelativePointPath()
  64090. {
  64091. }
  64092. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64093. {
  64094. elements.swapWithArray (other.elements);
  64095. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64096. }
  64097. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  64098. {
  64099. for (int i = 0; i < elements.size(); ++i)
  64100. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64101. }
  64102. bool RelativePointPath::containsAnyDynamicPoints() const
  64103. {
  64104. return containsDynamicPoints;
  64105. }
  64106. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64107. {
  64108. }
  64109. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64110. : ElementBase (startSubPathElement), startPos (pos)
  64111. {
  64112. }
  64113. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64114. {
  64115. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64116. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64117. return v;
  64118. }
  64119. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64120. {
  64121. path.startNewSubPath (startPos.resolve (coordFinder));
  64122. }
  64123. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64124. {
  64125. numPoints = 1;
  64126. return &startPos;
  64127. }
  64128. RelativePointPath::CloseSubPath::CloseSubPath()
  64129. : ElementBase (closeSubPathElement)
  64130. {
  64131. }
  64132. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64133. {
  64134. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64135. }
  64136. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  64137. {
  64138. path.closeSubPath();
  64139. }
  64140. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64141. {
  64142. numPoints = 0;
  64143. return 0;
  64144. }
  64145. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64146. : ElementBase (lineToElement), endPoint (endPoint_)
  64147. {
  64148. }
  64149. const ValueTree RelativePointPath::LineTo::createTree() const
  64150. {
  64151. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64152. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64153. return v;
  64154. }
  64155. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64156. {
  64157. path.lineTo (endPoint.resolve (coordFinder));
  64158. }
  64159. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64160. {
  64161. numPoints = 1;
  64162. return &endPoint;
  64163. }
  64164. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64165. : ElementBase (quadraticToElement)
  64166. {
  64167. controlPoints[0] = controlPoint;
  64168. controlPoints[1] = endPoint;
  64169. }
  64170. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64171. {
  64172. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64173. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64174. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64175. return v;
  64176. }
  64177. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64178. {
  64179. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64180. controlPoints[1].resolve (coordFinder));
  64181. }
  64182. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64183. {
  64184. numPoints = 2;
  64185. return controlPoints;
  64186. }
  64187. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64188. : ElementBase (cubicToElement)
  64189. {
  64190. controlPoints[0] = controlPoint1;
  64191. controlPoints[1] = controlPoint2;
  64192. controlPoints[2] = endPoint;
  64193. }
  64194. const ValueTree RelativePointPath::CubicTo::createTree() const
  64195. {
  64196. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64197. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64198. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64199. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64200. return v;
  64201. }
  64202. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64203. {
  64204. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64205. controlPoints[1].resolve (coordFinder),
  64206. controlPoints[2].resolve (coordFinder));
  64207. }
  64208. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64209. {
  64210. numPoints = 3;
  64211. return controlPoints;
  64212. }
  64213. RelativeParallelogram::RelativeParallelogram()
  64214. {
  64215. }
  64216. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64217. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64218. {
  64219. }
  64220. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64221. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64222. {
  64223. }
  64224. RelativeParallelogram::~RelativeParallelogram()
  64225. {
  64226. }
  64227. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64228. {
  64229. points[0] = topLeft.resolve (coordFinder);
  64230. points[1] = topRight.resolve (coordFinder);
  64231. points[2] = bottomLeft.resolve (coordFinder);
  64232. }
  64233. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64234. {
  64235. resolveThreePoints (points, coordFinder);
  64236. points[3] = points[1] + (points[2] - points[0]);
  64237. }
  64238. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64239. {
  64240. Point<float> points[4];
  64241. resolveFourCorners (points, coordFinder);
  64242. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64243. }
  64244. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64245. {
  64246. Point<float> points[4];
  64247. resolveFourCorners (points, coordFinder);
  64248. path.startNewSubPath (points[0]);
  64249. path.lineTo (points[1]);
  64250. path.lineTo (points[3]);
  64251. path.lineTo (points[2]);
  64252. path.closeSubPath();
  64253. }
  64254. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  64255. {
  64256. Point<float> corners[3];
  64257. resolveThreePoints (corners, coordFinder);
  64258. const Line<float> top (corners[0], corners[1]);
  64259. const Line<float> left (corners[0], corners[2]);
  64260. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64261. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64262. topRight.moveToAbsolute (newTopRight, coordFinder);
  64263. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64264. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64265. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64266. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64267. }
  64268. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64269. {
  64270. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64271. }
  64272. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64273. {
  64274. return ! operator== (other);
  64275. }
  64276. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64277. {
  64278. const Point<float> tr (corners[1] - corners[0]);
  64279. const Point<float> bl (corners[2] - corners[0]);
  64280. target -= corners[0];
  64281. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64282. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64283. }
  64284. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64285. {
  64286. return corners[0]
  64287. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64288. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64289. }
  64290. END_JUCE_NAMESPACE
  64291. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64292. #endif
  64293. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64294. /*** Start of inlined file: juce_Colour.cpp ***/
  64295. BEGIN_JUCE_NAMESPACE
  64296. namespace ColourHelpers
  64297. {
  64298. static uint8 floatAlphaToInt (const float alpha) throw()
  64299. {
  64300. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64301. }
  64302. static void convertHSBtoRGB (float h, float s, float v,
  64303. uint8& r, uint8& g, uint8& b) throw()
  64304. {
  64305. v = jlimit (0.0f, 1.0f, v);
  64306. v *= 255.0f;
  64307. const uint8 intV = (uint8) roundToInt (v);
  64308. if (s <= 0)
  64309. {
  64310. r = intV;
  64311. g = intV;
  64312. b = intV;
  64313. }
  64314. else
  64315. {
  64316. s = jmin (1.0f, s);
  64317. h = jlimit (0.0f, 1.0f, h);
  64318. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64319. const float f = h - std::floor (h);
  64320. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64321. const float y = v * (1.0f - s * f);
  64322. const float z = v * (1.0f - (s * (1.0f - f)));
  64323. if (h < 1.0f)
  64324. {
  64325. r = intV;
  64326. g = (uint8) roundToInt (z);
  64327. b = x;
  64328. }
  64329. else if (h < 2.0f)
  64330. {
  64331. r = (uint8) roundToInt (y);
  64332. g = intV;
  64333. b = x;
  64334. }
  64335. else if (h < 3.0f)
  64336. {
  64337. r = x;
  64338. g = intV;
  64339. b = (uint8) roundToInt (z);
  64340. }
  64341. else if (h < 4.0f)
  64342. {
  64343. r = x;
  64344. g = (uint8) roundToInt (y);
  64345. b = intV;
  64346. }
  64347. else if (h < 5.0f)
  64348. {
  64349. r = (uint8) roundToInt (z);
  64350. g = x;
  64351. b = intV;
  64352. }
  64353. else if (h < 6.0f)
  64354. {
  64355. r = intV;
  64356. g = x;
  64357. b = (uint8) roundToInt (y);
  64358. }
  64359. else
  64360. {
  64361. r = 0;
  64362. g = 0;
  64363. b = 0;
  64364. }
  64365. }
  64366. }
  64367. }
  64368. Colour::Colour() throw()
  64369. : argb (0)
  64370. {
  64371. }
  64372. Colour::Colour (const Colour& other) throw()
  64373. : argb (other.argb)
  64374. {
  64375. }
  64376. Colour& Colour::operator= (const Colour& other) throw()
  64377. {
  64378. argb = other.argb;
  64379. return *this;
  64380. }
  64381. bool Colour::operator== (const Colour& other) const throw()
  64382. {
  64383. return argb.getARGB() == other.argb.getARGB();
  64384. }
  64385. bool Colour::operator!= (const Colour& other) const throw()
  64386. {
  64387. return argb.getARGB() != other.argb.getARGB();
  64388. }
  64389. Colour::Colour (const uint32 argb_) throw()
  64390. : argb (argb_)
  64391. {
  64392. }
  64393. Colour::Colour (const uint8 red,
  64394. const uint8 green,
  64395. const uint8 blue) throw()
  64396. {
  64397. argb.setARGB (0xff, red, green, blue);
  64398. }
  64399. const Colour Colour::fromRGB (const uint8 red,
  64400. const uint8 green,
  64401. const uint8 blue) throw()
  64402. {
  64403. return Colour (red, green, blue);
  64404. }
  64405. Colour::Colour (const uint8 red,
  64406. const uint8 green,
  64407. const uint8 blue,
  64408. const uint8 alpha) throw()
  64409. {
  64410. argb.setARGB (alpha, red, green, blue);
  64411. }
  64412. const Colour Colour::fromRGBA (const uint8 red,
  64413. const uint8 green,
  64414. const uint8 blue,
  64415. const uint8 alpha) throw()
  64416. {
  64417. return Colour (red, green, blue, alpha);
  64418. }
  64419. Colour::Colour (const uint8 red,
  64420. const uint8 green,
  64421. const uint8 blue,
  64422. const float alpha) throw()
  64423. {
  64424. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64425. }
  64426. const Colour Colour::fromRGBAFloat (const uint8 red,
  64427. const uint8 green,
  64428. const uint8 blue,
  64429. const float alpha) throw()
  64430. {
  64431. return Colour (red, green, blue, alpha);
  64432. }
  64433. Colour::Colour (const float hue,
  64434. const float saturation,
  64435. const float brightness,
  64436. const float alpha) throw()
  64437. {
  64438. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64439. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64440. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64441. }
  64442. const Colour Colour::fromHSV (const float hue,
  64443. const float saturation,
  64444. const float brightness,
  64445. const float alpha) throw()
  64446. {
  64447. return Colour (hue, saturation, brightness, alpha);
  64448. }
  64449. Colour::Colour (const float hue,
  64450. const float saturation,
  64451. const float brightness,
  64452. const uint8 alpha) throw()
  64453. {
  64454. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64455. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64456. argb.setARGB (alpha, r, g, b);
  64457. }
  64458. Colour::~Colour() throw()
  64459. {
  64460. }
  64461. const PixelARGB Colour::getPixelARGB() const throw()
  64462. {
  64463. PixelARGB p (argb);
  64464. p.premultiply();
  64465. return p;
  64466. }
  64467. uint32 Colour::getARGB() const throw()
  64468. {
  64469. return argb.getARGB();
  64470. }
  64471. bool Colour::isTransparent() const throw()
  64472. {
  64473. return getAlpha() == 0;
  64474. }
  64475. bool Colour::isOpaque() const throw()
  64476. {
  64477. return getAlpha() == 0xff;
  64478. }
  64479. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64480. {
  64481. PixelARGB newCol (argb);
  64482. newCol.setAlpha (newAlpha);
  64483. return Colour (newCol.getARGB());
  64484. }
  64485. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64486. {
  64487. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64488. PixelARGB newCol (argb);
  64489. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64490. return Colour (newCol.getARGB());
  64491. }
  64492. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64493. {
  64494. jassert (alphaMultiplier >= 0);
  64495. PixelARGB newCol (argb);
  64496. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64497. return Colour (newCol.getARGB());
  64498. }
  64499. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64500. {
  64501. const int destAlpha = getAlpha();
  64502. if (destAlpha > 0)
  64503. {
  64504. const int invA = 0xff - (int) src.getAlpha();
  64505. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64506. if (resA > 0)
  64507. {
  64508. const int da = (invA * destAlpha) / resA;
  64509. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64510. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64511. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64512. (uint8) resA);
  64513. }
  64514. return *this;
  64515. }
  64516. else
  64517. {
  64518. return src;
  64519. }
  64520. }
  64521. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64522. {
  64523. if (proportionOfOther <= 0)
  64524. return *this;
  64525. if (proportionOfOther >= 1.0f)
  64526. return other;
  64527. PixelARGB c1 (getPixelARGB());
  64528. const PixelARGB c2 (other.getPixelARGB());
  64529. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64530. c1.unpremultiply();
  64531. return Colour (c1.getARGB());
  64532. }
  64533. float Colour::getFloatRed() const throw()
  64534. {
  64535. return getRed() / 255.0f;
  64536. }
  64537. float Colour::getFloatGreen() const throw()
  64538. {
  64539. return getGreen() / 255.0f;
  64540. }
  64541. float Colour::getFloatBlue() const throw()
  64542. {
  64543. return getBlue() / 255.0f;
  64544. }
  64545. float Colour::getFloatAlpha() const throw()
  64546. {
  64547. return getAlpha() / 255.0f;
  64548. }
  64549. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64550. {
  64551. const int r = getRed();
  64552. const int g = getGreen();
  64553. const int b = getBlue();
  64554. const int hi = jmax (r, g, b);
  64555. const int lo = jmin (r, g, b);
  64556. if (hi != 0)
  64557. {
  64558. s = (hi - lo) / (float) hi;
  64559. if (s != 0)
  64560. {
  64561. const float invDiff = 1.0f / (hi - lo);
  64562. const float red = (hi - r) * invDiff;
  64563. const float green = (hi - g) * invDiff;
  64564. const float blue = (hi - b) * invDiff;
  64565. if (r == hi)
  64566. h = blue - green;
  64567. else if (g == hi)
  64568. h = 2.0f + red - blue;
  64569. else
  64570. h = 4.0f + green - red;
  64571. h *= 1.0f / 6.0f;
  64572. if (h < 0)
  64573. ++h;
  64574. }
  64575. else
  64576. {
  64577. h = 0;
  64578. }
  64579. }
  64580. else
  64581. {
  64582. s = 0;
  64583. h = 0;
  64584. }
  64585. v = hi / 255.0f;
  64586. }
  64587. float Colour::getHue() const throw()
  64588. {
  64589. float h, s, b;
  64590. getHSB (h, s, b);
  64591. return h;
  64592. }
  64593. const Colour Colour::withHue (const float hue) const throw()
  64594. {
  64595. float h, s, b;
  64596. getHSB (h, s, b);
  64597. return Colour (hue, s, b, getAlpha());
  64598. }
  64599. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64600. {
  64601. float h, s, b;
  64602. getHSB (h, s, b);
  64603. h += amountToRotate;
  64604. h -= std::floor (h);
  64605. return Colour (h, s, b, getAlpha());
  64606. }
  64607. float Colour::getSaturation() const throw()
  64608. {
  64609. float h, s, b;
  64610. getHSB (h, s, b);
  64611. return s;
  64612. }
  64613. const Colour Colour::withSaturation (const float saturation) const throw()
  64614. {
  64615. float h, s, b;
  64616. getHSB (h, s, b);
  64617. return Colour (h, saturation, b, getAlpha());
  64618. }
  64619. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64620. {
  64621. float h, s, b;
  64622. getHSB (h, s, b);
  64623. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64624. }
  64625. float Colour::getBrightness() const throw()
  64626. {
  64627. float h, s, b;
  64628. getHSB (h, s, b);
  64629. return b;
  64630. }
  64631. const Colour Colour::withBrightness (const float brightness) const throw()
  64632. {
  64633. float h, s, b;
  64634. getHSB (h, s, b);
  64635. return Colour (h, s, brightness, getAlpha());
  64636. }
  64637. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64638. {
  64639. float h, s, b;
  64640. getHSB (h, s, b);
  64641. b *= amount;
  64642. if (b > 1.0f)
  64643. b = 1.0f;
  64644. return Colour (h, s, b, getAlpha());
  64645. }
  64646. const Colour Colour::brighter (float amount) const throw()
  64647. {
  64648. amount = 1.0f / (1.0f + amount);
  64649. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64650. (uint8) (255 - (amount * (255 - getGreen()))),
  64651. (uint8) (255 - (amount * (255 - getBlue()))),
  64652. getAlpha());
  64653. }
  64654. const Colour Colour::darker (float amount) const throw()
  64655. {
  64656. amount = 1.0f / (1.0f + amount);
  64657. return Colour ((uint8) (amount * getRed()),
  64658. (uint8) (amount * getGreen()),
  64659. (uint8) (amount * getBlue()),
  64660. getAlpha());
  64661. }
  64662. const Colour Colour::greyLevel (const float brightness) throw()
  64663. {
  64664. const uint8 level
  64665. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64666. return Colour (level, level, level);
  64667. }
  64668. const Colour Colour::contrasting (const float amount) const throw()
  64669. {
  64670. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64671. ? Colours::black
  64672. : Colours::white).withAlpha (amount));
  64673. }
  64674. const Colour Colour::contrasting (const Colour& colour1,
  64675. const Colour& colour2) throw()
  64676. {
  64677. const float b1 = colour1.getBrightness();
  64678. const float b2 = colour2.getBrightness();
  64679. float best = 0.0f;
  64680. float bestDist = 0.0f;
  64681. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64682. {
  64683. const float d1 = std::abs (i - b1);
  64684. const float d2 = std::abs (i - b2);
  64685. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64686. if (dist > bestDist)
  64687. {
  64688. best = i;
  64689. bestDist = dist;
  64690. }
  64691. }
  64692. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64693. .withBrightness (best);
  64694. }
  64695. const String Colour::toString() const
  64696. {
  64697. return String::toHexString ((int) argb.getARGB());
  64698. }
  64699. const Colour Colour::fromString (const String& encodedColourString)
  64700. {
  64701. return Colour ((uint32) encodedColourString.getHexValue32());
  64702. }
  64703. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64704. {
  64705. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64706. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64707. .toUpperCase();
  64708. }
  64709. END_JUCE_NAMESPACE
  64710. /*** End of inlined file: juce_Colour.cpp ***/
  64711. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64712. BEGIN_JUCE_NAMESPACE
  64713. ColourGradient::ColourGradient() throw()
  64714. {
  64715. #if JUCE_DEBUG
  64716. point1.setX (987654.0f);
  64717. #endif
  64718. }
  64719. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64720. const Colour& colour2, const float x2_, const float y2_,
  64721. const bool isRadial_)
  64722. : point1 (x1_, y1_),
  64723. point2 (x2_, y2_),
  64724. isRadial (isRadial_)
  64725. {
  64726. colours.add (ColourPoint (0.0, colour1));
  64727. colours.add (ColourPoint (1.0, colour2));
  64728. }
  64729. ColourGradient::~ColourGradient()
  64730. {
  64731. }
  64732. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  64733. {
  64734. return point1 == other.point1 && point2 == other.point2
  64735. && isRadial == other.isRadial
  64736. && colours == other.colours;
  64737. }
  64738. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  64739. {
  64740. return ! operator== (other);
  64741. }
  64742. void ColourGradient::clearColours()
  64743. {
  64744. colours.clear();
  64745. }
  64746. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  64747. {
  64748. // must be within the two end-points
  64749. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  64750. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  64751. int i;
  64752. for (i = 0; i < colours.size(); ++i)
  64753. if (colours.getReference(i).position > pos)
  64754. break;
  64755. colours.insert (i, ColourPoint (pos, colour));
  64756. return i;
  64757. }
  64758. void ColourGradient::removeColour (int index)
  64759. {
  64760. jassert (index > 0 && index < colours.size() - 1);
  64761. colours.remove (index);
  64762. }
  64763. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  64764. {
  64765. for (int i = 0; i < colours.size(); ++i)
  64766. {
  64767. Colour& c = colours.getReference(i).colour;
  64768. c = c.withMultipliedAlpha (multiplier);
  64769. }
  64770. }
  64771. int ColourGradient::getNumColours() const throw()
  64772. {
  64773. return colours.size();
  64774. }
  64775. double ColourGradient::getColourPosition (const int index) const throw()
  64776. {
  64777. if (((unsigned int) index) < (unsigned int) colours.size())
  64778. return colours.getReference (index).position;
  64779. return 0;
  64780. }
  64781. const Colour ColourGradient::getColour (const int index) const throw()
  64782. {
  64783. if (((unsigned int) index) < (unsigned int) colours.size())
  64784. return colours.getReference (index).colour;
  64785. return Colour();
  64786. }
  64787. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64788. {
  64789. if (((unsigned int) index) < (unsigned int) colours.size())
  64790. colours.getReference (index).colour = newColour;
  64791. }
  64792. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64793. {
  64794. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64795. if (position <= 0 || colours.size() <= 1)
  64796. return colours.getReference(0).colour;
  64797. int i = colours.size() - 1;
  64798. while (position < colours.getReference(i).position)
  64799. --i;
  64800. const ColourPoint& p1 = colours.getReference (i);
  64801. if (i >= colours.size() - 1)
  64802. return p1.colour;
  64803. const ColourPoint& p2 = colours.getReference (i + 1);
  64804. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64805. }
  64806. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64807. {
  64808. #if JUCE_DEBUG
  64809. // trying to use the object without setting its co-ordinates? Have a careful read of
  64810. // the comments for the constructors.
  64811. jassert (point1.getX() != 987654.0f);
  64812. #endif
  64813. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64814. 3 * (int) point1.transformedBy (transform)
  64815. .getDistanceFrom (point2.transformedBy (transform)));
  64816. lookupTable.malloc (numEntries);
  64817. if (colours.size() >= 2)
  64818. {
  64819. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64820. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64821. int index = 0;
  64822. for (int j = 1; j < colours.size(); ++j)
  64823. {
  64824. const ColourPoint& p = colours.getReference (j);
  64825. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64826. const PixelARGB pix2 (p.colour.getPixelARGB());
  64827. for (int i = 0; i < numToDo; ++i)
  64828. {
  64829. jassert (index >= 0 && index < numEntries);
  64830. lookupTable[index] = pix1;
  64831. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64832. ++index;
  64833. }
  64834. pix1 = pix2;
  64835. }
  64836. while (index < numEntries)
  64837. lookupTable [index++] = pix1;
  64838. }
  64839. else
  64840. {
  64841. jassertfalse; // no colours specified!
  64842. }
  64843. return numEntries;
  64844. }
  64845. bool ColourGradient::isOpaque() const throw()
  64846. {
  64847. for (int i = 0; i < colours.size(); ++i)
  64848. if (! colours.getReference(i).colour.isOpaque())
  64849. return false;
  64850. return true;
  64851. }
  64852. bool ColourGradient::isInvisible() const throw()
  64853. {
  64854. for (int i = 0; i < colours.size(); ++i)
  64855. if (! colours.getReference(i).colour.isTransparent())
  64856. return false;
  64857. return true;
  64858. }
  64859. END_JUCE_NAMESPACE
  64860. /*** End of inlined file: juce_ColourGradient.cpp ***/
  64861. /*** Start of inlined file: juce_Colours.cpp ***/
  64862. BEGIN_JUCE_NAMESPACE
  64863. const Colour Colours::transparentBlack (0);
  64864. const Colour Colours::transparentWhite (0x00ffffff);
  64865. const Colour Colours::aliceblue (0xfff0f8ff);
  64866. const Colour Colours::antiquewhite (0xfffaebd7);
  64867. const Colour Colours::aqua (0xff00ffff);
  64868. const Colour Colours::aquamarine (0xff7fffd4);
  64869. const Colour Colours::azure (0xfff0ffff);
  64870. const Colour Colours::beige (0xfff5f5dc);
  64871. const Colour Colours::bisque (0xffffe4c4);
  64872. const Colour Colours::black (0xff000000);
  64873. const Colour Colours::blanchedalmond (0xffffebcd);
  64874. const Colour Colours::blue (0xff0000ff);
  64875. const Colour Colours::blueviolet (0xff8a2be2);
  64876. const Colour Colours::brown (0xffa52a2a);
  64877. const Colour Colours::burlywood (0xffdeb887);
  64878. const Colour Colours::cadetblue (0xff5f9ea0);
  64879. const Colour Colours::chartreuse (0xff7fff00);
  64880. const Colour Colours::chocolate (0xffd2691e);
  64881. const Colour Colours::coral (0xffff7f50);
  64882. const Colour Colours::cornflowerblue (0xff6495ed);
  64883. const Colour Colours::cornsilk (0xfffff8dc);
  64884. const Colour Colours::crimson (0xffdc143c);
  64885. const Colour Colours::cyan (0xff00ffff);
  64886. const Colour Colours::darkblue (0xff00008b);
  64887. const Colour Colours::darkcyan (0xff008b8b);
  64888. const Colour Colours::darkgoldenrod (0xffb8860b);
  64889. const Colour Colours::darkgrey (0xff555555);
  64890. const Colour Colours::darkgreen (0xff006400);
  64891. const Colour Colours::darkkhaki (0xffbdb76b);
  64892. const Colour Colours::darkmagenta (0xff8b008b);
  64893. const Colour Colours::darkolivegreen (0xff556b2f);
  64894. const Colour Colours::darkorange (0xffff8c00);
  64895. const Colour Colours::darkorchid (0xff9932cc);
  64896. const Colour Colours::darkred (0xff8b0000);
  64897. const Colour Colours::darksalmon (0xffe9967a);
  64898. const Colour Colours::darkseagreen (0xff8fbc8f);
  64899. const Colour Colours::darkslateblue (0xff483d8b);
  64900. const Colour Colours::darkslategrey (0xff2f4f4f);
  64901. const Colour Colours::darkturquoise (0xff00ced1);
  64902. const Colour Colours::darkviolet (0xff9400d3);
  64903. const Colour Colours::deeppink (0xffff1493);
  64904. const Colour Colours::deepskyblue (0xff00bfff);
  64905. const Colour Colours::dimgrey (0xff696969);
  64906. const Colour Colours::dodgerblue (0xff1e90ff);
  64907. const Colour Colours::firebrick (0xffb22222);
  64908. const Colour Colours::floralwhite (0xfffffaf0);
  64909. const Colour Colours::forestgreen (0xff228b22);
  64910. const Colour Colours::fuchsia (0xffff00ff);
  64911. const Colour Colours::gainsboro (0xffdcdcdc);
  64912. const Colour Colours::gold (0xffffd700);
  64913. const Colour Colours::goldenrod (0xffdaa520);
  64914. const Colour Colours::grey (0xff808080);
  64915. const Colour Colours::green (0xff008000);
  64916. const Colour Colours::greenyellow (0xffadff2f);
  64917. const Colour Colours::honeydew (0xfff0fff0);
  64918. const Colour Colours::hotpink (0xffff69b4);
  64919. const Colour Colours::indianred (0xffcd5c5c);
  64920. const Colour Colours::indigo (0xff4b0082);
  64921. const Colour Colours::ivory (0xfffffff0);
  64922. const Colour Colours::khaki (0xfff0e68c);
  64923. const Colour Colours::lavender (0xffe6e6fa);
  64924. const Colour Colours::lavenderblush (0xfffff0f5);
  64925. const Colour Colours::lemonchiffon (0xfffffacd);
  64926. const Colour Colours::lightblue (0xffadd8e6);
  64927. const Colour Colours::lightcoral (0xfff08080);
  64928. const Colour Colours::lightcyan (0xffe0ffff);
  64929. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  64930. const Colour Colours::lightgreen (0xff90ee90);
  64931. const Colour Colours::lightgrey (0xffd3d3d3);
  64932. const Colour Colours::lightpink (0xffffb6c1);
  64933. const Colour Colours::lightsalmon (0xffffa07a);
  64934. const Colour Colours::lightseagreen (0xff20b2aa);
  64935. const Colour Colours::lightskyblue (0xff87cefa);
  64936. const Colour Colours::lightslategrey (0xff778899);
  64937. const Colour Colours::lightsteelblue (0xffb0c4de);
  64938. const Colour Colours::lightyellow (0xffffffe0);
  64939. const Colour Colours::lime (0xff00ff00);
  64940. const Colour Colours::limegreen (0xff32cd32);
  64941. const Colour Colours::linen (0xfffaf0e6);
  64942. const Colour Colours::magenta (0xffff00ff);
  64943. const Colour Colours::maroon (0xff800000);
  64944. const Colour Colours::mediumaquamarine (0xff66cdaa);
  64945. const Colour Colours::mediumblue (0xff0000cd);
  64946. const Colour Colours::mediumorchid (0xffba55d3);
  64947. const Colour Colours::mediumpurple (0xff9370db);
  64948. const Colour Colours::mediumseagreen (0xff3cb371);
  64949. const Colour Colours::mediumslateblue (0xff7b68ee);
  64950. const Colour Colours::mediumspringgreen (0xff00fa9a);
  64951. const Colour Colours::mediumturquoise (0xff48d1cc);
  64952. const Colour Colours::mediumvioletred (0xffc71585);
  64953. const Colour Colours::midnightblue (0xff191970);
  64954. const Colour Colours::mintcream (0xfff5fffa);
  64955. const Colour Colours::mistyrose (0xffffe4e1);
  64956. const Colour Colours::navajowhite (0xffffdead);
  64957. const Colour Colours::navy (0xff000080);
  64958. const Colour Colours::oldlace (0xfffdf5e6);
  64959. const Colour Colours::olive (0xff808000);
  64960. const Colour Colours::olivedrab (0xff6b8e23);
  64961. const Colour Colours::orange (0xffffa500);
  64962. const Colour Colours::orangered (0xffff4500);
  64963. const Colour Colours::orchid (0xffda70d6);
  64964. const Colour Colours::palegoldenrod (0xffeee8aa);
  64965. const Colour Colours::palegreen (0xff98fb98);
  64966. const Colour Colours::paleturquoise (0xffafeeee);
  64967. const Colour Colours::palevioletred (0xffdb7093);
  64968. const Colour Colours::papayawhip (0xffffefd5);
  64969. const Colour Colours::peachpuff (0xffffdab9);
  64970. const Colour Colours::peru (0xffcd853f);
  64971. const Colour Colours::pink (0xffffc0cb);
  64972. const Colour Colours::plum (0xffdda0dd);
  64973. const Colour Colours::powderblue (0xffb0e0e6);
  64974. const Colour Colours::purple (0xff800080);
  64975. const Colour Colours::red (0xffff0000);
  64976. const Colour Colours::rosybrown (0xffbc8f8f);
  64977. const Colour Colours::royalblue (0xff4169e1);
  64978. const Colour Colours::saddlebrown (0xff8b4513);
  64979. const Colour Colours::salmon (0xfffa8072);
  64980. const Colour Colours::sandybrown (0xfff4a460);
  64981. const Colour Colours::seagreen (0xff2e8b57);
  64982. const Colour Colours::seashell (0xfffff5ee);
  64983. const Colour Colours::sienna (0xffa0522d);
  64984. const Colour Colours::silver (0xffc0c0c0);
  64985. const Colour Colours::skyblue (0xff87ceeb);
  64986. const Colour Colours::slateblue (0xff6a5acd);
  64987. const Colour Colours::slategrey (0xff708090);
  64988. const Colour Colours::snow (0xfffffafa);
  64989. const Colour Colours::springgreen (0xff00ff7f);
  64990. const Colour Colours::steelblue (0xff4682b4);
  64991. const Colour Colours::tan (0xffd2b48c);
  64992. const Colour Colours::teal (0xff008080);
  64993. const Colour Colours::thistle (0xffd8bfd8);
  64994. const Colour Colours::tomato (0xffff6347);
  64995. const Colour Colours::turquoise (0xff40e0d0);
  64996. const Colour Colours::violet (0xffee82ee);
  64997. const Colour Colours::wheat (0xfff5deb3);
  64998. const Colour Colours::white (0xffffffff);
  64999. const Colour Colours::whitesmoke (0xfff5f5f5);
  65000. const Colour Colours::yellow (0xffffff00);
  65001. const Colour Colours::yellowgreen (0xff9acd32);
  65002. const Colour Colours::findColourForName (const String& colourName,
  65003. const Colour& defaultColour)
  65004. {
  65005. static const int presets[] =
  65006. {
  65007. // (first value is the string's hashcode, second is ARGB)
  65008. 0x05978fff, 0xff000000, /* black */
  65009. 0x06bdcc29, 0xffffffff, /* white */
  65010. 0x002e305a, 0xff0000ff, /* blue */
  65011. 0x00308adf, 0xff808080, /* grey */
  65012. 0x05e0cf03, 0xff008000, /* green */
  65013. 0x0001b891, 0xffff0000, /* red */
  65014. 0xd43c6474, 0xffffff00, /* yellow */
  65015. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65016. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65017. 0x002dcebc, 0xff00ffff, /* aqua */
  65018. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65019. 0x0590228f, 0xfff0ffff, /* azure */
  65020. 0x05947fe4, 0xfff5f5dc, /* beige */
  65021. 0xad388e35, 0xffffe4c4, /* bisque */
  65022. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65023. 0x39129959, 0xff8a2be2, /* blueviolet */
  65024. 0x059a8136, 0xffa52a2a, /* brown */
  65025. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65026. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65027. 0x6b748956, 0xff7fff00, /* chartreuse */
  65028. 0x2903623c, 0xffd2691e, /* chocolate */
  65029. 0x05a74431, 0xffff7f50, /* coral */
  65030. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65031. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65032. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65033. 0x002ed323, 0xff00ffff, /* cyan */
  65034. 0x67cc74d0, 0xff00008b, /* darkblue */
  65035. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65036. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65037. 0x67cecf55, 0xff555555, /* darkgrey */
  65038. 0x920b194d, 0xff006400, /* darkgreen */
  65039. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65040. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65041. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65042. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65043. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65044. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65045. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65046. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65047. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65048. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65049. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65050. 0xc8769375, 0xff9400d3, /* darkviolet */
  65051. 0x25832862, 0xffff1493, /* deeppink */
  65052. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65053. 0x634c8b67, 0xff696969, /* dimgrey */
  65054. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65055. 0xef19e3cb, 0xffb22222, /* firebrick */
  65056. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65057. 0xd086fd06, 0xff228b22, /* forestgreen */
  65058. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65059. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65060. 0x00308060, 0xffffd700, /* gold */
  65061. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65062. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65063. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65064. 0x41892743, 0xffff69b4, /* hotpink */
  65065. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65066. 0xb969fed2, 0xff4b0082, /* indigo */
  65067. 0x05fef6a9, 0xfffffff0, /* ivory */
  65068. 0x06149302, 0xfff0e68c, /* khaki */
  65069. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65070. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65071. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65072. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65073. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65074. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65075. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65076. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65077. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65078. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65079. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65080. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65081. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65082. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65083. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65084. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65085. 0x0032afd5, 0xff00ff00, /* lime */
  65086. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65087. 0x06234efa, 0xfffaf0e6, /* linen */
  65088. 0x316858a9, 0xffff00ff, /* magenta */
  65089. 0xbf8ca470, 0xff800000, /* maroon */
  65090. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65091. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65092. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65093. 0x07556b71, 0xff9370db, /* mediumpurple */
  65094. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65095. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65096. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65097. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65098. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65099. 0x168eb32a, 0xff191970, /* midnightblue */
  65100. 0x4306b960, 0xfff5fffa, /* mintcream */
  65101. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65102. 0xe97218a6, 0xffffdead, /* navajowhite */
  65103. 0x00337bb6, 0xff000080, /* navy */
  65104. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65105. 0x064ee1db, 0xff808000, /* olive */
  65106. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65107. 0xc3de262e, 0xffffa500, /* orange */
  65108. 0x58bebba3, 0xffff4500, /* orangered */
  65109. 0xc3def8a3, 0xffda70d6, /* orchid */
  65110. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65111. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65112. 0x74022737, 0xffafeeee, /* paleturquoise */
  65113. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65114. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65115. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65116. 0x003472f8, 0xffcd853f, /* peru */
  65117. 0x00348176, 0xffffc0cb, /* pink */
  65118. 0x00348d94, 0xffdda0dd, /* plum */
  65119. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65120. 0xc5c507bc, 0xff800080, /* purple */
  65121. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65122. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65123. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65124. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65125. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65126. 0x34636c14, 0xff2e8b57, /* seagreen */
  65127. 0x3507fb41, 0xfffff5ee, /* seashell */
  65128. 0xca348772, 0xffa0522d, /* sienna */
  65129. 0xca37d30d, 0xffc0c0c0, /* silver */
  65130. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65131. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65132. 0x44ab37f8, 0xff708090, /* slategrey */
  65133. 0x0035f183, 0xfffffafa, /* snow */
  65134. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65135. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65136. 0x0001bfa1, 0xffd2b48c, /* tan */
  65137. 0x0036425c, 0xff008080, /* teal */
  65138. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65139. 0xcc41600a, 0xffff6347, /* tomato */
  65140. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65141. 0xcf57947f, 0xffee82ee, /* violet */
  65142. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65143. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65144. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65145. };
  65146. const int hash = colourName.trim().toLowerCase().hashCode();
  65147. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65148. if (presets [i] == hash)
  65149. return Colour (presets [i + 1]);
  65150. return defaultColour;
  65151. }
  65152. END_JUCE_NAMESPACE
  65153. /*** End of inlined file: juce_Colours.cpp ***/
  65154. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65155. BEGIN_JUCE_NAMESPACE
  65156. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65157. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65158. const Path& path, const AffineTransform& transform)
  65159. : bounds (bounds_),
  65160. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65161. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65162. needToCheckEmptinesss (true)
  65163. {
  65164. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65165. int* t = table;
  65166. for (int i = bounds.getHeight(); --i >= 0;)
  65167. {
  65168. *t = 0;
  65169. t += lineStrideElements;
  65170. }
  65171. const int topLimit = bounds.getY() << 8;
  65172. const int heightLimit = bounds.getHeight() << 8;
  65173. const int leftLimit = bounds.getX() << 8;
  65174. const int rightLimit = bounds.getRight() << 8;
  65175. PathFlatteningIterator iter (path, transform);
  65176. while (iter.next())
  65177. {
  65178. int y1 = roundToInt (iter.y1 * 256.0f);
  65179. int y2 = roundToInt (iter.y2 * 256.0f);
  65180. if (y1 != y2)
  65181. {
  65182. y1 -= topLimit;
  65183. y2 -= topLimit;
  65184. const int startY = y1;
  65185. int direction = -1;
  65186. if (y1 > y2)
  65187. {
  65188. swapVariables (y1, y2);
  65189. direction = 1;
  65190. }
  65191. if (y1 < 0)
  65192. y1 = 0;
  65193. if (y2 > heightLimit)
  65194. y2 = heightLimit;
  65195. if (y1 < y2)
  65196. {
  65197. const double startX = 256.0f * iter.x1;
  65198. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65199. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65200. do
  65201. {
  65202. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65203. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65204. if (x < leftLimit)
  65205. x = leftLimit;
  65206. else if (x >= rightLimit)
  65207. x = rightLimit - 1;
  65208. addEdgePoint (x, y1 >> 8, direction * step);
  65209. y1 += step;
  65210. }
  65211. while (y1 < y2);
  65212. }
  65213. }
  65214. }
  65215. sanitiseLevels (path.isUsingNonZeroWinding());
  65216. }
  65217. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65218. : bounds (rectangleToAdd),
  65219. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65220. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65221. needToCheckEmptinesss (true)
  65222. {
  65223. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65224. table[0] = 0;
  65225. const int x1 = rectangleToAdd.getX() << 8;
  65226. const int x2 = rectangleToAdd.getRight() << 8;
  65227. int* t = table;
  65228. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65229. {
  65230. t[0] = 2;
  65231. t[1] = x1;
  65232. t[2] = 255;
  65233. t[3] = x2;
  65234. t[4] = 0;
  65235. t += lineStrideElements;
  65236. }
  65237. }
  65238. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65239. : bounds (rectanglesToAdd.getBounds()),
  65240. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65241. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65242. needToCheckEmptinesss (true)
  65243. {
  65244. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65245. int* t = table;
  65246. for (int i = bounds.getHeight(); --i >= 0;)
  65247. {
  65248. *t = 0;
  65249. t += lineStrideElements;
  65250. }
  65251. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65252. {
  65253. const Rectangle<int>* const r = iter.getRectangle();
  65254. const int x1 = r->getX() << 8;
  65255. const int x2 = r->getRight() << 8;
  65256. int y = r->getY() - bounds.getY();
  65257. for (int j = r->getHeight(); --j >= 0;)
  65258. {
  65259. addEdgePoint (x1, y, 255);
  65260. addEdgePoint (x2, y, -255);
  65261. ++y;
  65262. }
  65263. }
  65264. sanitiseLevels (true);
  65265. }
  65266. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65267. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65268. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65269. 2 + (int) rectangleToAdd.getWidth(),
  65270. 2 + (int) rectangleToAdd.getHeight())),
  65271. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65272. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65273. needToCheckEmptinesss (true)
  65274. {
  65275. jassert (! rectangleToAdd.isEmpty());
  65276. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65277. table[0] = 0;
  65278. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65279. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65280. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65281. jassert (y1 < 256);
  65282. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65283. if (x2 <= x1 || y2 <= y1)
  65284. {
  65285. bounds.setHeight (0);
  65286. return;
  65287. }
  65288. int lineY = 0;
  65289. int* t = table;
  65290. if ((y1 >> 8) == (y2 >> 8))
  65291. {
  65292. t[0] = 2;
  65293. t[1] = x1;
  65294. t[2] = y2 - y1;
  65295. t[3] = x2;
  65296. t[4] = 0;
  65297. ++lineY;
  65298. t += lineStrideElements;
  65299. }
  65300. else
  65301. {
  65302. t[0] = 2;
  65303. t[1] = x1;
  65304. t[2] = 255 - (y1 & 255);
  65305. t[3] = x2;
  65306. t[4] = 0;
  65307. ++lineY;
  65308. t += lineStrideElements;
  65309. while (lineY < (y2 >> 8))
  65310. {
  65311. t[0] = 2;
  65312. t[1] = x1;
  65313. t[2] = 255;
  65314. t[3] = x2;
  65315. t[4] = 0;
  65316. ++lineY;
  65317. t += lineStrideElements;
  65318. }
  65319. jassert (lineY < bounds.getHeight());
  65320. t[0] = 2;
  65321. t[1] = x1;
  65322. t[2] = y2 & 255;
  65323. t[3] = x2;
  65324. t[4] = 0;
  65325. ++lineY;
  65326. t += lineStrideElements;
  65327. }
  65328. while (lineY < bounds.getHeight())
  65329. {
  65330. t[0] = 0;
  65331. t += lineStrideElements;
  65332. ++lineY;
  65333. }
  65334. }
  65335. EdgeTable::EdgeTable (const EdgeTable& other)
  65336. {
  65337. operator= (other);
  65338. }
  65339. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65340. {
  65341. bounds = other.bounds;
  65342. maxEdgesPerLine = other.maxEdgesPerLine;
  65343. lineStrideElements = other.lineStrideElements;
  65344. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65345. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65346. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65347. return *this;
  65348. }
  65349. EdgeTable::~EdgeTable()
  65350. {
  65351. }
  65352. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65353. {
  65354. while (--numLines >= 0)
  65355. {
  65356. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65357. src += srcLineStride;
  65358. dest += destLineStride;
  65359. }
  65360. }
  65361. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65362. {
  65363. // Convert the table from relative windings to absolute levels..
  65364. int* lineStart = table;
  65365. for (int i = bounds.getHeight(); --i >= 0;)
  65366. {
  65367. int* line = lineStart;
  65368. lineStart += lineStrideElements;
  65369. int num = *line;
  65370. if (num == 0)
  65371. continue;
  65372. int level = 0;
  65373. if (useNonZeroWinding)
  65374. {
  65375. while (--num > 0)
  65376. {
  65377. line += 2;
  65378. level += *line;
  65379. int corrected = abs (level);
  65380. if (corrected >> 8)
  65381. corrected = 255;
  65382. *line = corrected;
  65383. }
  65384. }
  65385. else
  65386. {
  65387. while (--num > 0)
  65388. {
  65389. line += 2;
  65390. level += *line;
  65391. int corrected = abs (level);
  65392. if (corrected >> 8)
  65393. {
  65394. corrected &= 511;
  65395. if (corrected >> 8)
  65396. corrected = 511 - corrected;
  65397. }
  65398. *line = corrected;
  65399. }
  65400. }
  65401. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65402. }
  65403. }
  65404. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65405. {
  65406. if (newNumEdgesPerLine != maxEdgesPerLine)
  65407. {
  65408. maxEdgesPerLine = newNumEdgesPerLine;
  65409. jassert (bounds.getHeight() > 0);
  65410. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65411. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65412. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65413. table.swapWith (newTable);
  65414. lineStrideElements = newLineStrideElements;
  65415. }
  65416. }
  65417. void EdgeTable::optimiseTable() throw()
  65418. {
  65419. int maxLineElements = 0;
  65420. for (int i = bounds.getHeight(); --i >= 0;)
  65421. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65422. remapTableForNumEdges (maxLineElements);
  65423. }
  65424. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65425. {
  65426. jassert (y >= 0 && y < bounds.getHeight());
  65427. int* line = table + lineStrideElements * y;
  65428. const int numPoints = line[0];
  65429. int n = numPoints << 1;
  65430. if (n > 0)
  65431. {
  65432. while (n > 0)
  65433. {
  65434. const int cx = line [n - 1];
  65435. if (cx <= x)
  65436. {
  65437. if (cx == x)
  65438. {
  65439. line [n] += winding;
  65440. return;
  65441. }
  65442. break;
  65443. }
  65444. n -= 2;
  65445. }
  65446. if (numPoints >= maxEdgesPerLine)
  65447. {
  65448. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65449. jassert (numPoints < maxEdgesPerLine);
  65450. line = table + lineStrideElements * y;
  65451. }
  65452. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65453. }
  65454. line [n + 1] = x;
  65455. line [n + 2] = winding;
  65456. line[0]++;
  65457. }
  65458. void EdgeTable::translate (float dx, const int dy) throw()
  65459. {
  65460. bounds.translate ((int) std::floor (dx), dy);
  65461. int* lineStart = table;
  65462. const int intDx = (int) (dx * 256.0f);
  65463. for (int i = bounds.getHeight(); --i >= 0;)
  65464. {
  65465. int* line = lineStart;
  65466. lineStart += lineStrideElements;
  65467. int num = *line++;
  65468. while (--num >= 0)
  65469. {
  65470. *line += intDx;
  65471. line += 2;
  65472. }
  65473. }
  65474. }
  65475. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65476. {
  65477. jassert (y >= 0 && y < bounds.getHeight());
  65478. int* dest = table + lineStrideElements * y;
  65479. if (dest[0] == 0)
  65480. return;
  65481. int otherNumPoints = *otherLine;
  65482. if (otherNumPoints == 0)
  65483. {
  65484. *dest = 0;
  65485. return;
  65486. }
  65487. const int right = bounds.getRight() << 8;
  65488. // optimise for the common case where our line lies entirely within a
  65489. // single pair of points, as happens when clipping to a simple rect.
  65490. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65491. {
  65492. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65493. return;
  65494. }
  65495. ++otherLine;
  65496. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65497. int* temp = (int*) alloca (lineSizeBytes);
  65498. memcpy (temp, dest, lineSizeBytes);
  65499. const int* src1 = temp;
  65500. int srcNum1 = *src1++;
  65501. int x1 = *src1++;
  65502. const int* src2 = otherLine;
  65503. int srcNum2 = otherNumPoints;
  65504. int x2 = *src2++;
  65505. int destIndex = 0, destTotal = 0;
  65506. int level1 = 0, level2 = 0;
  65507. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65508. while (srcNum1 > 0 && srcNum2 > 0)
  65509. {
  65510. int nextX;
  65511. if (x1 < x2)
  65512. {
  65513. nextX = x1;
  65514. level1 = *src1++;
  65515. x1 = *src1++;
  65516. --srcNum1;
  65517. }
  65518. else if (x1 == x2)
  65519. {
  65520. nextX = x1;
  65521. level1 = *src1++;
  65522. level2 = *src2++;
  65523. x1 = *src1++;
  65524. x2 = *src2++;
  65525. --srcNum1;
  65526. --srcNum2;
  65527. }
  65528. else
  65529. {
  65530. nextX = x2;
  65531. level2 = *src2++;
  65532. x2 = *src2++;
  65533. --srcNum2;
  65534. }
  65535. if (nextX > lastX)
  65536. {
  65537. if (nextX >= right)
  65538. break;
  65539. lastX = nextX;
  65540. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65541. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  65542. if (nextLevel != lastLevel)
  65543. {
  65544. if (destTotal >= maxEdgesPerLine)
  65545. {
  65546. dest[0] = destTotal;
  65547. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65548. dest = table + lineStrideElements * y;
  65549. }
  65550. ++destTotal;
  65551. lastLevel = nextLevel;
  65552. dest[++destIndex] = nextX;
  65553. dest[++destIndex] = nextLevel;
  65554. }
  65555. }
  65556. }
  65557. if (lastLevel > 0)
  65558. {
  65559. if (destTotal >= maxEdgesPerLine)
  65560. {
  65561. dest[0] = destTotal;
  65562. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65563. dest = table + lineStrideElements * y;
  65564. }
  65565. ++destTotal;
  65566. dest[++destIndex] = right;
  65567. dest[++destIndex] = 0;
  65568. }
  65569. dest[0] = destTotal;
  65570. #if JUCE_DEBUG
  65571. int last = std::numeric_limits<int>::min();
  65572. for (int i = 0; i < dest[0]; ++i)
  65573. {
  65574. jassert (dest[i * 2 + 1] > last);
  65575. last = dest[i * 2 + 1];
  65576. }
  65577. jassert (dest [dest[0] * 2] == 0);
  65578. #endif
  65579. }
  65580. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65581. {
  65582. int* lastItem = dest + (dest[0] * 2 - 1);
  65583. if (x2 < lastItem[0])
  65584. {
  65585. if (x2 <= dest[1])
  65586. {
  65587. dest[0] = 0;
  65588. return;
  65589. }
  65590. while (x2 < lastItem[-2])
  65591. {
  65592. --(dest[0]);
  65593. lastItem -= 2;
  65594. }
  65595. lastItem[0] = x2;
  65596. lastItem[1] = 0;
  65597. }
  65598. if (x1 > dest[1])
  65599. {
  65600. while (lastItem[0] > x1)
  65601. lastItem -= 2;
  65602. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65603. if (itemsRemoved > 0)
  65604. {
  65605. dest[0] -= itemsRemoved;
  65606. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65607. }
  65608. dest[1] = x1;
  65609. }
  65610. }
  65611. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  65612. {
  65613. const Rectangle<int> clipped (r.getIntersection (bounds));
  65614. if (clipped.isEmpty())
  65615. {
  65616. needToCheckEmptinesss = false;
  65617. bounds.setHeight (0);
  65618. }
  65619. else
  65620. {
  65621. const int top = clipped.getY() - bounds.getY();
  65622. const int bottom = clipped.getBottom() - bounds.getY();
  65623. if (bottom < bounds.getHeight())
  65624. bounds.setHeight (bottom);
  65625. if (clipped.getRight() < bounds.getRight())
  65626. bounds.setRight (clipped.getRight());
  65627. for (int i = top; --i >= 0;)
  65628. table [lineStrideElements * i] = 0;
  65629. if (clipped.getX() > bounds.getX())
  65630. {
  65631. const int x1 = clipped.getX() << 8;
  65632. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65633. int* line = table + lineStrideElements * top;
  65634. for (int i = bottom - top; --i >= 0;)
  65635. {
  65636. if (line[0] != 0)
  65637. clipEdgeTableLineToRange (line, x1, x2);
  65638. line += lineStrideElements;
  65639. }
  65640. }
  65641. needToCheckEmptinesss = true;
  65642. }
  65643. }
  65644. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  65645. {
  65646. const Rectangle<int> clipped (r.getIntersection (bounds));
  65647. if (! clipped.isEmpty())
  65648. {
  65649. const int top = clipped.getY() - bounds.getY();
  65650. const int bottom = clipped.getBottom() - bounds.getY();
  65651. //XXX optimise here by shortening the table if it fills top or bottom
  65652. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65653. clipped.getX() << 8, 0,
  65654. clipped.getRight() << 8, 255,
  65655. std::numeric_limits<int>::max(), 0 };
  65656. for (int i = top; i < bottom; ++i)
  65657. intersectWithEdgeTableLine (i, rectLine);
  65658. needToCheckEmptinesss = true;
  65659. }
  65660. }
  65661. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65662. {
  65663. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65664. if (clipped.isEmpty())
  65665. {
  65666. needToCheckEmptinesss = false;
  65667. bounds.setHeight (0);
  65668. }
  65669. else
  65670. {
  65671. const int top = clipped.getY() - bounds.getY();
  65672. const int bottom = clipped.getBottom() - bounds.getY();
  65673. if (bottom < bounds.getHeight())
  65674. bounds.setHeight (bottom);
  65675. if (clipped.getRight() < bounds.getRight())
  65676. bounds.setRight (clipped.getRight());
  65677. int i = 0;
  65678. for (i = top; --i >= 0;)
  65679. table [lineStrideElements * i] = 0;
  65680. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65681. for (i = top; i < bottom; ++i)
  65682. {
  65683. intersectWithEdgeTableLine (i, otherLine);
  65684. otherLine += other.lineStrideElements;
  65685. }
  65686. needToCheckEmptinesss = true;
  65687. }
  65688. }
  65689. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  65690. {
  65691. y -= bounds.getY();
  65692. if (y < 0 || y >= bounds.getHeight())
  65693. return;
  65694. needToCheckEmptinesss = true;
  65695. if (numPixels <= 0)
  65696. {
  65697. table [lineStrideElements * y] = 0;
  65698. return;
  65699. }
  65700. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  65701. int destIndex = 0, lastLevel = 0;
  65702. while (--numPixels >= 0)
  65703. {
  65704. const int alpha = *mask;
  65705. mask += maskStride;
  65706. if (alpha != lastLevel)
  65707. {
  65708. tempLine[++destIndex] = (x << 8);
  65709. tempLine[++destIndex] = alpha;
  65710. lastLevel = alpha;
  65711. }
  65712. ++x;
  65713. }
  65714. if (lastLevel > 0)
  65715. {
  65716. tempLine[++destIndex] = (x << 8);
  65717. tempLine[++destIndex] = 0;
  65718. }
  65719. tempLine[0] = destIndex >> 1;
  65720. intersectWithEdgeTableLine (y, tempLine);
  65721. }
  65722. bool EdgeTable::isEmpty() throw()
  65723. {
  65724. if (needToCheckEmptinesss)
  65725. {
  65726. needToCheckEmptinesss = false;
  65727. int* t = table;
  65728. for (int i = bounds.getHeight(); --i >= 0;)
  65729. {
  65730. if (t[0] > 1)
  65731. return false;
  65732. t += lineStrideElements;
  65733. }
  65734. bounds.setHeight (0);
  65735. }
  65736. return bounds.getHeight() == 0;
  65737. }
  65738. END_JUCE_NAMESPACE
  65739. /*** End of inlined file: juce_EdgeTable.cpp ***/
  65740. /*** Start of inlined file: juce_FillType.cpp ***/
  65741. BEGIN_JUCE_NAMESPACE
  65742. FillType::FillType() throw()
  65743. : colour (0xff000000), image (0)
  65744. {
  65745. }
  65746. FillType::FillType (const Colour& colour_) throw()
  65747. : colour (colour_), image (0)
  65748. {
  65749. }
  65750. FillType::FillType (const ColourGradient& gradient_)
  65751. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  65752. {
  65753. }
  65754. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  65755. : colour (0xff000000), image (image_), transform (transform_)
  65756. {
  65757. }
  65758. FillType::FillType (const FillType& other)
  65759. : colour (other.colour),
  65760. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  65761. image (other.image), transform (other.transform)
  65762. {
  65763. }
  65764. FillType& FillType::operator= (const FillType& other)
  65765. {
  65766. if (this != &other)
  65767. {
  65768. colour = other.colour;
  65769. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65770. image = other.image;
  65771. transform = other.transform;
  65772. }
  65773. return *this;
  65774. }
  65775. FillType::~FillType() throw()
  65776. {
  65777. }
  65778. bool FillType::operator== (const FillType& other) const
  65779. {
  65780. return colour == other.colour && image == other.image
  65781. && transform == other.transform
  65782. && (gradient == other.gradient
  65783. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65784. }
  65785. bool FillType::operator!= (const FillType& other) const
  65786. {
  65787. return ! operator== (other);
  65788. }
  65789. void FillType::setColour (const Colour& newColour) throw()
  65790. {
  65791. gradient = 0;
  65792. image = Image::null;
  65793. colour = newColour;
  65794. }
  65795. void FillType::setGradient (const ColourGradient& newGradient)
  65796. {
  65797. if (gradient != 0)
  65798. {
  65799. *gradient = newGradient;
  65800. }
  65801. else
  65802. {
  65803. image = Image::null;
  65804. gradient = new ColourGradient (newGradient);
  65805. colour = Colours::black;
  65806. }
  65807. }
  65808. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65809. {
  65810. gradient = 0;
  65811. image = image_;
  65812. transform = transform_;
  65813. colour = Colours::black;
  65814. }
  65815. void FillType::setOpacity (const float newOpacity) throw()
  65816. {
  65817. colour = colour.withAlpha (newOpacity);
  65818. }
  65819. bool FillType::isInvisible() const throw()
  65820. {
  65821. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65822. }
  65823. END_JUCE_NAMESPACE
  65824. /*** End of inlined file: juce_FillType.cpp ***/
  65825. /*** Start of inlined file: juce_Graphics.cpp ***/
  65826. BEGIN_JUCE_NAMESPACE
  65827. template <typename Type>
  65828. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65829. {
  65830. const int maxVal = 0x3fffffff;
  65831. return (int) x >= -maxVal && (int) x <= maxVal
  65832. && (int) y >= -maxVal && (int) y <= maxVal
  65833. && (int) w >= -maxVal && (int) w <= maxVal
  65834. && (int) h >= -maxVal && (int) h <= maxVal;
  65835. }
  65836. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65837. {
  65838. }
  65839. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65840. {
  65841. }
  65842. Graphics::Graphics (const Image& imageToDrawOnto)
  65843. : context (imageToDrawOnto.createLowLevelContext()),
  65844. contextToDelete (context),
  65845. saveStatePending (false)
  65846. {
  65847. }
  65848. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  65849. : context (internalContext),
  65850. saveStatePending (false)
  65851. {
  65852. }
  65853. Graphics::~Graphics()
  65854. {
  65855. }
  65856. void Graphics::resetToDefaultState()
  65857. {
  65858. saveStateIfPending();
  65859. context->setFill (FillType());
  65860. context->setFont (Font());
  65861. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  65862. }
  65863. bool Graphics::isVectorDevice() const
  65864. {
  65865. return context->isVectorDevice();
  65866. }
  65867. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  65868. {
  65869. saveStateIfPending();
  65870. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  65871. }
  65872. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  65873. {
  65874. saveStateIfPending();
  65875. return context->clipToRectangleList (clipRegion);
  65876. }
  65877. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  65878. {
  65879. saveStateIfPending();
  65880. context->clipToPath (path, transform);
  65881. return ! context->isClipEmpty();
  65882. }
  65883. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  65884. {
  65885. saveStateIfPending();
  65886. context->clipToImageAlpha (image, transform);
  65887. return ! context->isClipEmpty();
  65888. }
  65889. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  65890. {
  65891. saveStateIfPending();
  65892. context->excludeClipRectangle (rectangleToExclude);
  65893. }
  65894. bool Graphics::isClipEmpty() const
  65895. {
  65896. return context->isClipEmpty();
  65897. }
  65898. const Rectangle<int> Graphics::getClipBounds() const
  65899. {
  65900. return context->getClipBounds();
  65901. }
  65902. void Graphics::saveState()
  65903. {
  65904. saveStateIfPending();
  65905. saveStatePending = true;
  65906. }
  65907. void Graphics::restoreState()
  65908. {
  65909. if (saveStatePending)
  65910. saveStatePending = false;
  65911. else
  65912. context->restoreState();
  65913. }
  65914. void Graphics::saveStateIfPending()
  65915. {
  65916. if (saveStatePending)
  65917. {
  65918. saveStatePending = false;
  65919. context->saveState();
  65920. }
  65921. }
  65922. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  65923. {
  65924. saveStateIfPending();
  65925. context->setOrigin (newOriginX, newOriginY);
  65926. }
  65927. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  65928. {
  65929. return context->clipRegionIntersects (area);
  65930. }
  65931. void Graphics::setColour (const Colour& newColour)
  65932. {
  65933. saveStateIfPending();
  65934. context->setFill (newColour);
  65935. }
  65936. void Graphics::setOpacity (const float newOpacity)
  65937. {
  65938. saveStateIfPending();
  65939. context->setOpacity (newOpacity);
  65940. }
  65941. void Graphics::setGradientFill (const ColourGradient& gradient)
  65942. {
  65943. setFillType (gradient);
  65944. }
  65945. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  65946. {
  65947. saveStateIfPending();
  65948. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  65949. context->setOpacity (opacity);
  65950. }
  65951. void Graphics::setFillType (const FillType& newFill)
  65952. {
  65953. saveStateIfPending();
  65954. context->setFill (newFill);
  65955. }
  65956. void Graphics::setFont (const Font& newFont)
  65957. {
  65958. saveStateIfPending();
  65959. context->setFont (newFont);
  65960. }
  65961. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65962. {
  65963. saveStateIfPending();
  65964. Font f (context->getFont());
  65965. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65966. context->setFont (f);
  65967. }
  65968. const Font Graphics::getCurrentFont() const
  65969. {
  65970. return context->getFont();
  65971. }
  65972. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65973. {
  65974. if (text.isNotEmpty()
  65975. && startX < context->getClipBounds().getRight())
  65976. {
  65977. GlyphArrangement arr;
  65978. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65979. arr.draw (*this);
  65980. }
  65981. }
  65982. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65983. {
  65984. if (text.isNotEmpty())
  65985. {
  65986. GlyphArrangement arr;
  65987. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65988. arr.draw (*this, transform);
  65989. }
  65990. }
  65991. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65992. {
  65993. if (text.isNotEmpty()
  65994. && startX < context->getClipBounds().getRight())
  65995. {
  65996. GlyphArrangement arr;
  65997. arr.addJustifiedText (context->getFont(), text,
  65998. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65999. Justification::left);
  66000. arr.draw (*this);
  66001. }
  66002. }
  66003. void Graphics::drawText (const String& text,
  66004. const int x, const int y, const int width, const int height,
  66005. const Justification& justificationType,
  66006. const bool useEllipsesIfTooBig) const
  66007. {
  66008. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66009. {
  66010. GlyphArrangement arr;
  66011. arr.addCurtailedLineOfText (context->getFont(), text,
  66012. 0.0f, 0.0f, (float) width,
  66013. useEllipsesIfTooBig);
  66014. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66015. (float) x, (float) y, (float) width, (float) height,
  66016. justificationType);
  66017. arr.draw (*this);
  66018. }
  66019. }
  66020. void Graphics::drawFittedText (const String& text,
  66021. const int x, const int y, const int width, const int height,
  66022. const Justification& justification,
  66023. const int maximumNumberOfLines,
  66024. const float minimumHorizontalScale) const
  66025. {
  66026. if (text.isNotEmpty()
  66027. && width > 0 && height > 0
  66028. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66029. {
  66030. GlyphArrangement arr;
  66031. arr.addFittedText (context->getFont(), text,
  66032. (float) x, (float) y, (float) width, (float) height,
  66033. justification,
  66034. maximumNumberOfLines,
  66035. minimumHorizontalScale);
  66036. arr.draw (*this);
  66037. }
  66038. }
  66039. void Graphics::fillRect (int x, int y, int width, int height) const
  66040. {
  66041. // passing in a silly number can cause maths problems in rendering!
  66042. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66043. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66044. }
  66045. void Graphics::fillRect (const Rectangle<int>& r) const
  66046. {
  66047. context->fillRect (r, false);
  66048. }
  66049. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66050. {
  66051. // passing in a silly number can cause maths problems in rendering!
  66052. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66053. Path p;
  66054. p.addRectangle (x, y, width, height);
  66055. fillPath (p);
  66056. }
  66057. void Graphics::setPixel (int x, int y) const
  66058. {
  66059. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66060. }
  66061. void Graphics::fillAll() const
  66062. {
  66063. fillRect (context->getClipBounds());
  66064. }
  66065. void Graphics::fillAll (const Colour& colourToUse) const
  66066. {
  66067. if (! colourToUse.isTransparent())
  66068. {
  66069. const Rectangle<int> clip (context->getClipBounds());
  66070. context->saveState();
  66071. context->setFill (colourToUse);
  66072. context->fillRect (clip, false);
  66073. context->restoreState();
  66074. }
  66075. }
  66076. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66077. {
  66078. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66079. context->fillPath (path, transform);
  66080. }
  66081. void Graphics::strokePath (const Path& path,
  66082. const PathStrokeType& strokeType,
  66083. const AffineTransform& transform) const
  66084. {
  66085. Path stroke;
  66086. strokeType.createStrokedPath (stroke, path, transform);
  66087. fillPath (stroke);
  66088. }
  66089. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66090. const int lineThickness) const
  66091. {
  66092. // passing in a silly number can cause maths problems in rendering!
  66093. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66094. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66095. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66096. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66097. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66098. }
  66099. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66100. {
  66101. // passing in a silly number can cause maths problems in rendering!
  66102. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66103. Path p;
  66104. p.addRectangle (x, y, width, lineThickness);
  66105. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66106. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66107. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66108. fillPath (p);
  66109. }
  66110. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66111. {
  66112. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66113. }
  66114. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66115. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66116. const bool useGradient, const bool sharpEdgeOnOutside) const
  66117. {
  66118. // passing in a silly number can cause maths problems in rendering!
  66119. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66120. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66121. {
  66122. context->saveState();
  66123. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66124. const float ramp = oldOpacity / bevelThickness;
  66125. for (int i = bevelThickness; --i >= 0;)
  66126. {
  66127. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66128. : oldOpacity;
  66129. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66130. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66131. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66132. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66133. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66134. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66135. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66136. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66137. }
  66138. context->restoreState();
  66139. }
  66140. }
  66141. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66142. {
  66143. // passing in a silly number can cause maths problems in rendering!
  66144. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66145. Path p;
  66146. p.addEllipse (x, y, width, height);
  66147. fillPath (p);
  66148. }
  66149. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66150. const float lineThickness) const
  66151. {
  66152. // passing in a silly number can cause maths problems in rendering!
  66153. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66154. Path p;
  66155. p.addEllipse (x, y, width, height);
  66156. strokePath (p, PathStrokeType (lineThickness));
  66157. }
  66158. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66159. {
  66160. // passing in a silly number can cause maths problems in rendering!
  66161. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66162. Path p;
  66163. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66164. fillPath (p);
  66165. }
  66166. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66167. {
  66168. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66169. }
  66170. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66171. const float cornerSize, const float lineThickness) const
  66172. {
  66173. // passing in a silly number can cause maths problems in rendering!
  66174. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66175. Path p;
  66176. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66177. strokePath (p, PathStrokeType (lineThickness));
  66178. }
  66179. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66180. {
  66181. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66182. }
  66183. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66184. {
  66185. Path p;
  66186. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66187. fillPath (p);
  66188. }
  66189. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66190. const int checkWidth, const int checkHeight,
  66191. const Colour& colour1, const Colour& colour2) const
  66192. {
  66193. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66194. if (checkWidth > 0 && checkHeight > 0)
  66195. {
  66196. context->saveState();
  66197. if (colour1 == colour2)
  66198. {
  66199. context->setFill (colour1);
  66200. context->fillRect (area, false);
  66201. }
  66202. else
  66203. {
  66204. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66205. if (! clipped.isEmpty())
  66206. {
  66207. context->clipToRectangle (clipped);
  66208. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66209. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66210. const int startX = area.getX() + checkNumX * checkWidth;
  66211. const int startY = area.getY() + checkNumY * checkHeight;
  66212. const int right = clipped.getRight();
  66213. const int bottom = clipped.getBottom();
  66214. for (int i = 0; i < 2; ++i)
  66215. {
  66216. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66217. int cy = i;
  66218. for (int y = startY; y < bottom; y += checkHeight)
  66219. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66220. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66221. }
  66222. }
  66223. }
  66224. context->restoreState();
  66225. }
  66226. }
  66227. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66228. {
  66229. context->drawVerticalLine (x, top, bottom);
  66230. }
  66231. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66232. {
  66233. context->drawHorizontalLine (y, left, right);
  66234. }
  66235. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66236. {
  66237. context->drawLine (Line<float> (x1, y1, x2, y2));
  66238. }
  66239. void Graphics::drawLine (const float startX, const float startY,
  66240. const float endX, const float endY,
  66241. const float lineThickness) const
  66242. {
  66243. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66244. }
  66245. void Graphics::drawLine (const Line<float>& line) const
  66246. {
  66247. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66248. }
  66249. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66250. {
  66251. Path p;
  66252. p.addLineSegment (line, lineThickness);
  66253. fillPath (p);
  66254. }
  66255. void Graphics::drawDashedLine (const float startX, const float startY,
  66256. const float endX, const float endY,
  66257. const float* const dashLengths,
  66258. const int numDashLengths,
  66259. const float lineThickness) const
  66260. {
  66261. const double dx = endX - startX;
  66262. const double dy = endY - startY;
  66263. const double totalLen = juce_hypot (dx, dy);
  66264. if (totalLen >= 0.5)
  66265. {
  66266. const double onePixAlpha = 1.0 / totalLen;
  66267. double alpha = 0.0;
  66268. float x = startX;
  66269. float y = startY;
  66270. int n = 0;
  66271. while (alpha < 1.0f)
  66272. {
  66273. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66274. n = n % numDashLengths;
  66275. const float oldX = x;
  66276. const float oldY = y;
  66277. x = (float) (startX + dx * alpha);
  66278. y = (float) (startY + dy * alpha);
  66279. if ((n & 1) != 0)
  66280. {
  66281. if (lineThickness != 1.0f)
  66282. drawLine (oldX, oldY, x, y, lineThickness);
  66283. else
  66284. drawLine (oldX, oldY, x, y);
  66285. }
  66286. }
  66287. }
  66288. }
  66289. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66290. {
  66291. saveStateIfPending();
  66292. context->setInterpolationQuality (newQuality);
  66293. }
  66294. void Graphics::drawImageAt (const Image& imageToDraw,
  66295. const int topLeftX, const int topLeftY,
  66296. const bool fillAlphaChannelWithCurrentBrush) const
  66297. {
  66298. const int imageW = imageToDraw.getWidth();
  66299. const int imageH = imageToDraw.getHeight();
  66300. drawImage (imageToDraw,
  66301. topLeftX, topLeftY, imageW, imageH,
  66302. 0, 0, imageW, imageH,
  66303. fillAlphaChannelWithCurrentBrush);
  66304. }
  66305. void Graphics::drawImageWithin (const Image& imageToDraw,
  66306. const int destX, const int destY,
  66307. const int destW, const int destH,
  66308. const RectanglePlacement& placementWithinTarget,
  66309. const bool fillAlphaChannelWithCurrentBrush) const
  66310. {
  66311. // passing in a silly number can cause maths problems in rendering!
  66312. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66313. if (imageToDraw.isValid())
  66314. {
  66315. const int imageW = imageToDraw.getWidth();
  66316. const int imageH = imageToDraw.getHeight();
  66317. if (imageW > 0 && imageH > 0)
  66318. {
  66319. double newX = 0.0, newY = 0.0;
  66320. double newW = imageW;
  66321. double newH = imageH;
  66322. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66323. destX, destY, destW, destH);
  66324. if (newW > 0 && newH > 0)
  66325. {
  66326. drawImage (imageToDraw,
  66327. roundToInt (newX), roundToInt (newY),
  66328. roundToInt (newW), roundToInt (newH),
  66329. 0, 0, imageW, imageH,
  66330. fillAlphaChannelWithCurrentBrush);
  66331. }
  66332. }
  66333. }
  66334. }
  66335. void Graphics::drawImage (const Image& imageToDraw,
  66336. int dx, int dy, int dw, int dh,
  66337. int sx, int sy, int sw, int sh,
  66338. const bool fillAlphaChannelWithCurrentBrush) const
  66339. {
  66340. // passing in a silly number can cause maths problems in rendering!
  66341. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66342. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66343. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66344. {
  66345. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66346. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66347. .translated ((float) dx, (float) dy),
  66348. fillAlphaChannelWithCurrentBrush);
  66349. }
  66350. }
  66351. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66352. const AffineTransform& transform,
  66353. const bool fillAlphaChannelWithCurrentBrush) const
  66354. {
  66355. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66356. {
  66357. if (fillAlphaChannelWithCurrentBrush)
  66358. {
  66359. context->saveState();
  66360. context->clipToImageAlpha (imageToDraw, transform);
  66361. fillAll();
  66362. context->restoreState();
  66363. }
  66364. else
  66365. {
  66366. context->drawImage (imageToDraw, transform, false);
  66367. }
  66368. }
  66369. }
  66370. END_JUCE_NAMESPACE
  66371. /*** End of inlined file: juce_Graphics.cpp ***/
  66372. /*** Start of inlined file: juce_Justification.cpp ***/
  66373. BEGIN_JUCE_NAMESPACE
  66374. Justification::Justification (const Justification& other) throw()
  66375. : flags (other.flags)
  66376. {
  66377. }
  66378. Justification& Justification::operator= (const Justification& other) throw()
  66379. {
  66380. flags = other.flags;
  66381. return *this;
  66382. }
  66383. int Justification::getOnlyVerticalFlags() const throw()
  66384. {
  66385. return flags & (top | bottom | verticallyCentred);
  66386. }
  66387. int Justification::getOnlyHorizontalFlags() const throw()
  66388. {
  66389. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66390. }
  66391. void Justification::applyToRectangle (int& x, int& y,
  66392. const int w, const int h,
  66393. const int spaceX, const int spaceY,
  66394. const int spaceW, const int spaceH) const throw()
  66395. {
  66396. if ((flags & horizontallyCentred) != 0)
  66397. x = spaceX + ((spaceW - w) >> 1);
  66398. else if ((flags & right) != 0)
  66399. x = spaceX + spaceW - w;
  66400. else
  66401. x = spaceX;
  66402. if ((flags & verticallyCentred) != 0)
  66403. y = spaceY + ((spaceH - h) >> 1);
  66404. else if ((flags & bottom) != 0)
  66405. y = spaceY + spaceH - h;
  66406. else
  66407. y = spaceY;
  66408. }
  66409. END_JUCE_NAMESPACE
  66410. /*** End of inlined file: juce_Justification.cpp ***/
  66411. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66412. BEGIN_JUCE_NAMESPACE
  66413. // this will throw an assertion if you try to draw something that's not
  66414. // possible in postscript
  66415. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66416. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66417. #define notPossibleInPostscriptAssert jassertfalse
  66418. #else
  66419. #define notPossibleInPostscriptAssert
  66420. #endif
  66421. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66422. const String& documentTitle,
  66423. const int totalWidth_,
  66424. const int totalHeight_)
  66425. : out (resultingPostScript),
  66426. totalWidth (totalWidth_),
  66427. totalHeight (totalHeight_),
  66428. needToClip (true)
  66429. {
  66430. stateStack.add (new SavedState());
  66431. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66432. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66433. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66434. "\n%%BoundingBox: 0 0 600 824"
  66435. "\n%%Pages: 0"
  66436. "\n%%Creator: Raw Material Software JUCE"
  66437. "\n%%Title: " << documentTitle <<
  66438. "\n%%CreationDate: none"
  66439. "\n%%LanguageLevel: 2"
  66440. "\n%%EndComments"
  66441. "\n%%BeginProlog"
  66442. "\n%%BeginResource: JRes"
  66443. "\n/bd {bind def} bind def"
  66444. "\n/c {setrgbcolor} bd"
  66445. "\n/m {moveto} bd"
  66446. "\n/l {lineto} bd"
  66447. "\n/rl {rlineto} bd"
  66448. "\n/ct {curveto} bd"
  66449. "\n/cp {closepath} bd"
  66450. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66451. "\n/doclip {initclip newpath} bd"
  66452. "\n/endclip {clip newpath} bd"
  66453. "\n%%EndResource"
  66454. "\n%%EndProlog"
  66455. "\n%%BeginSetup"
  66456. "\n%%EndSetup"
  66457. "\n%%Page: 1 1"
  66458. "\n%%BeginPageSetup"
  66459. "\n%%EndPageSetup\n\n"
  66460. << "40 800 translate\n"
  66461. << scale << ' ' << scale << " scale\n\n";
  66462. }
  66463. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66464. {
  66465. }
  66466. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66467. {
  66468. return true;
  66469. }
  66470. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66471. {
  66472. if (x != 0 || y != 0)
  66473. {
  66474. stateStack.getLast()->xOffset += x;
  66475. stateStack.getLast()->yOffset += y;
  66476. needToClip = true;
  66477. }
  66478. }
  66479. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66480. {
  66481. needToClip = true;
  66482. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66483. }
  66484. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66485. {
  66486. needToClip = true;
  66487. return stateStack.getLast()->clip.clipTo (clipRegion);
  66488. }
  66489. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66490. {
  66491. needToClip = true;
  66492. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66493. }
  66494. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66495. {
  66496. writeClip();
  66497. Path p (path);
  66498. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66499. writePath (p);
  66500. out << "clip\n";
  66501. }
  66502. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66503. {
  66504. needToClip = true;
  66505. jassertfalse; // xxx
  66506. }
  66507. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66508. {
  66509. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66510. }
  66511. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66512. {
  66513. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66514. -stateStack.getLast()->yOffset);
  66515. }
  66516. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66517. {
  66518. return stateStack.getLast()->clip.isEmpty();
  66519. }
  66520. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66521. : xOffset (0),
  66522. yOffset (0)
  66523. {
  66524. }
  66525. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66526. {
  66527. }
  66528. void LowLevelGraphicsPostScriptRenderer::saveState()
  66529. {
  66530. stateStack.add (new SavedState (*stateStack.getLast()));
  66531. }
  66532. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66533. {
  66534. jassert (stateStack.size() > 0);
  66535. if (stateStack.size() > 0)
  66536. stateStack.removeLast();
  66537. }
  66538. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66539. {
  66540. if (needToClip)
  66541. {
  66542. needToClip = false;
  66543. out << "doclip ";
  66544. int itemsOnLine = 0;
  66545. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66546. {
  66547. if (++itemsOnLine == 6)
  66548. {
  66549. itemsOnLine = 0;
  66550. out << '\n';
  66551. }
  66552. const Rectangle<int>& r = *i.getRectangle();
  66553. out << r.getX() << ' ' << -r.getY() << ' '
  66554. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66555. }
  66556. out << "endclip\n";
  66557. }
  66558. }
  66559. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66560. {
  66561. Colour c (Colours::white.overlaidWith (colour));
  66562. if (lastColour != c)
  66563. {
  66564. lastColour = c;
  66565. out << String (c.getFloatRed(), 3) << ' '
  66566. << String (c.getFloatGreen(), 3) << ' '
  66567. << String (c.getFloatBlue(), 3) << " c\n";
  66568. }
  66569. }
  66570. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66571. {
  66572. out << String (x, 2) << ' '
  66573. << String (-y, 2) << ' ';
  66574. }
  66575. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66576. {
  66577. out << "newpath ";
  66578. float lastX = 0.0f;
  66579. float lastY = 0.0f;
  66580. int itemsOnLine = 0;
  66581. Path::Iterator i (path);
  66582. while (i.next())
  66583. {
  66584. if (++itemsOnLine == 4)
  66585. {
  66586. itemsOnLine = 0;
  66587. out << '\n';
  66588. }
  66589. switch (i.elementType)
  66590. {
  66591. case Path::Iterator::startNewSubPath:
  66592. writeXY (i.x1, i.y1);
  66593. lastX = i.x1;
  66594. lastY = i.y1;
  66595. out << "m ";
  66596. break;
  66597. case Path::Iterator::lineTo:
  66598. writeXY (i.x1, i.y1);
  66599. lastX = i.x1;
  66600. lastY = i.y1;
  66601. out << "l ";
  66602. break;
  66603. case Path::Iterator::quadraticTo:
  66604. {
  66605. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66606. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66607. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66608. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66609. writeXY (cp1x, cp1y);
  66610. writeXY (cp2x, cp2y);
  66611. writeXY (i.x2, i.y2);
  66612. out << "ct ";
  66613. lastX = i.x2;
  66614. lastY = i.y2;
  66615. }
  66616. break;
  66617. case Path::Iterator::cubicTo:
  66618. writeXY (i.x1, i.y1);
  66619. writeXY (i.x2, i.y2);
  66620. writeXY (i.x3, i.y3);
  66621. out << "ct ";
  66622. lastX = i.x3;
  66623. lastY = i.y3;
  66624. break;
  66625. case Path::Iterator::closePath:
  66626. out << "cp ";
  66627. break;
  66628. default:
  66629. jassertfalse;
  66630. break;
  66631. }
  66632. }
  66633. out << '\n';
  66634. }
  66635. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66636. {
  66637. out << "[ "
  66638. << trans.mat00 << ' '
  66639. << trans.mat10 << ' '
  66640. << trans.mat01 << ' '
  66641. << trans.mat11 << ' '
  66642. << trans.mat02 << ' '
  66643. << trans.mat12 << " ] concat ";
  66644. }
  66645. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66646. {
  66647. stateStack.getLast()->fillType = fillType;
  66648. }
  66649. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66650. {
  66651. }
  66652. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66653. {
  66654. }
  66655. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66656. {
  66657. if (stateStack.getLast()->fillType.isColour())
  66658. {
  66659. writeClip();
  66660. writeColour (stateStack.getLast()->fillType.colour);
  66661. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66662. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66663. }
  66664. else
  66665. {
  66666. Path p;
  66667. p.addRectangle (r);
  66668. fillPath (p, AffineTransform::identity);
  66669. }
  66670. }
  66671. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66672. {
  66673. if (stateStack.getLast()->fillType.isColour())
  66674. {
  66675. writeClip();
  66676. Path p (path);
  66677. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66678. (float) stateStack.getLast()->yOffset));
  66679. writePath (p);
  66680. writeColour (stateStack.getLast()->fillType.colour);
  66681. out << "fill\n";
  66682. }
  66683. else if (stateStack.getLast()->fillType.isGradient())
  66684. {
  66685. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66686. // postscript can't do semi-transparent ones.
  66687. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66688. writeClip();
  66689. out << "gsave ";
  66690. {
  66691. Path p (path);
  66692. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66693. writePath (p);
  66694. out << "clip\n";
  66695. }
  66696. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66697. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66698. // time-being, this just fills it with the average colour..
  66699. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66700. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66701. out << "grestore\n";
  66702. }
  66703. }
  66704. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66705. const int sx, const int sy,
  66706. const int maxW, const int maxH) const
  66707. {
  66708. out << "{<\n";
  66709. const int w = jmin (maxW, im.getWidth());
  66710. const int h = jmin (maxH, im.getHeight());
  66711. int charsOnLine = 0;
  66712. const Image::BitmapData srcData (im, 0, 0, w, h);
  66713. Colour pixel;
  66714. for (int y = h; --y >= 0;)
  66715. {
  66716. for (int x = 0; x < w; ++x)
  66717. {
  66718. const uint8* pixelData = srcData.getPixelPointer (x, y);
  66719. if (x >= sx && y >= sy)
  66720. {
  66721. if (im.isARGB())
  66722. {
  66723. PixelARGB p (*(const PixelARGB*) pixelData);
  66724. p.unpremultiply();
  66725. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  66726. }
  66727. else if (im.isRGB())
  66728. {
  66729. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  66730. }
  66731. else
  66732. {
  66733. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  66734. }
  66735. }
  66736. else
  66737. {
  66738. pixel = Colours::transparentWhite;
  66739. }
  66740. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  66741. out << String::toHexString (pixelValues, 3, 0);
  66742. charsOnLine += 3;
  66743. if (charsOnLine > 100)
  66744. {
  66745. out << '\n';
  66746. charsOnLine = 0;
  66747. }
  66748. }
  66749. }
  66750. out << "\n>}\n";
  66751. }
  66752. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  66753. {
  66754. const int w = sourceImage.getWidth();
  66755. const int h = sourceImage.getHeight();
  66756. writeClip();
  66757. out << "gsave ";
  66758. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  66759. .scaled (1.0f, -1.0f));
  66760. RectangleList imageClip;
  66761. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  66762. out << "newpath ";
  66763. int itemsOnLine = 0;
  66764. for (RectangleList::Iterator i (imageClip); i.next();)
  66765. {
  66766. if (++itemsOnLine == 6)
  66767. {
  66768. out << '\n';
  66769. itemsOnLine = 0;
  66770. }
  66771. const Rectangle<int>& r = *i.getRectangle();
  66772. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66773. }
  66774. out << " clip newpath\n";
  66775. out << w << ' ' << h << " scale\n";
  66776. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66777. writeImage (sourceImage, 0, 0, w, h);
  66778. out << "false 3 colorimage grestore\n";
  66779. needToClip = true;
  66780. }
  66781. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66782. {
  66783. Path p;
  66784. p.addLineSegment (line, 1.0f);
  66785. fillPath (p, AffineTransform::identity);
  66786. }
  66787. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66788. {
  66789. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66790. }
  66791. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66792. {
  66793. drawLine (Line<float> (left, (float) y, right, (float) y));
  66794. }
  66795. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66796. {
  66797. stateStack.getLast()->font = newFont;
  66798. }
  66799. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66800. {
  66801. return stateStack.getLast()->font;
  66802. }
  66803. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66804. {
  66805. Path p;
  66806. Font& font = stateStack.getLast()->font;
  66807. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66808. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66809. }
  66810. END_JUCE_NAMESPACE
  66811. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66812. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66813. BEGIN_JUCE_NAMESPACE
  66814. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  66815. #define JUCE_USE_SSE_INSTRUCTIONS 1
  66816. #endif
  66817. #if JUCE_MSVC
  66818. #pragma warning (push)
  66819. #pragma warning (disable: 4127) // "expression is constant" warning
  66820. #if JUCE_DEBUG
  66821. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  66822. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  66823. #endif
  66824. #endif
  66825. namespace SoftwareRendererClasses
  66826. {
  66827. template <class PixelType, bool replaceExisting = false>
  66828. class SolidColourEdgeTableRenderer
  66829. {
  66830. public:
  66831. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  66832. : data (data_),
  66833. sourceColour (colour)
  66834. {
  66835. if (sizeof (PixelType) == 3)
  66836. {
  66837. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  66838. && sourceColour.getGreen() == sourceColour.getBlue();
  66839. filler[0].set (sourceColour);
  66840. filler[1].set (sourceColour);
  66841. filler[2].set (sourceColour);
  66842. filler[3].set (sourceColour);
  66843. }
  66844. }
  66845. forcedinline void setEdgeTableYPos (const int y) throw()
  66846. {
  66847. linePixels = (PixelType*) data.getLinePointer (y);
  66848. }
  66849. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66850. {
  66851. if (replaceExisting)
  66852. linePixels[x].set (sourceColour);
  66853. else
  66854. linePixels[x].blend (sourceColour, alphaLevel);
  66855. }
  66856. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66857. {
  66858. if (replaceExisting)
  66859. linePixels[x].set (sourceColour);
  66860. else
  66861. linePixels[x].blend (sourceColour);
  66862. }
  66863. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  66864. {
  66865. PixelARGB p (sourceColour);
  66866. p.multiplyAlpha (alphaLevel);
  66867. PixelType* dest = linePixels + x;
  66868. if (replaceExisting || p.getAlpha() >= 0xff)
  66869. replaceLine (dest, p, width);
  66870. else
  66871. blendLine (dest, p, width);
  66872. }
  66873. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  66874. {
  66875. PixelType* dest = linePixels + x;
  66876. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  66877. replaceLine (dest, sourceColour, width);
  66878. else
  66879. blendLine (dest, sourceColour, width);
  66880. }
  66881. private:
  66882. const Image::BitmapData& data;
  66883. PixelType* linePixels;
  66884. PixelARGB sourceColour;
  66885. PixelRGB filler [4];
  66886. bool areRGBComponentsEqual;
  66887. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  66888. {
  66889. do
  66890. {
  66891. dest->blend (colour);
  66892. ++dest;
  66893. } while (--width > 0);
  66894. }
  66895. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  66896. {
  66897. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  66898. {
  66899. memset (dest, colour.getRed(), width * 3);
  66900. }
  66901. else
  66902. {
  66903. if (width >> 5)
  66904. {
  66905. const int* const intFiller = (const int*) filler;
  66906. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  66907. {
  66908. dest->set (colour);
  66909. ++dest;
  66910. --width;
  66911. }
  66912. while (width > 4)
  66913. {
  66914. ((int*) dest) [0] = intFiller[0];
  66915. ((int*) dest) [1] = intFiller[1];
  66916. ((int*) dest) [2] = intFiller[2];
  66917. dest = (PixelRGB*) (((uint8*) dest) + 12);
  66918. width -= 4;
  66919. }
  66920. }
  66921. while (--width >= 0)
  66922. {
  66923. dest->set (colour);
  66924. ++dest;
  66925. }
  66926. }
  66927. }
  66928. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  66929. {
  66930. memset (dest, colour.getAlpha(), width);
  66931. }
  66932. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  66933. {
  66934. do
  66935. {
  66936. dest->set (colour);
  66937. ++dest;
  66938. } while (--width > 0);
  66939. }
  66940. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  66941. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  66942. };
  66943. class LinearGradientPixelGenerator
  66944. {
  66945. public:
  66946. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  66947. : lookupTable (lookupTable_), numEntries (numEntries_)
  66948. {
  66949. jassert (numEntries_ >= 0);
  66950. Point<float> p1 (gradient.point1);
  66951. Point<float> p2 (gradient.point2);
  66952. if (! transform.isIdentity())
  66953. {
  66954. const Line<float> l (p2, p1);
  66955. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  66956. p1.applyTransform (transform);
  66957. p2.applyTransform (transform);
  66958. p3.applyTransform (transform);
  66959. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  66960. }
  66961. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66962. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66963. if (vertical)
  66964. {
  66965. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66966. start = roundToInt (p1.getY() * scale);
  66967. }
  66968. else if (horizontal)
  66969. {
  66970. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66971. start = roundToInt (p1.getX() * scale);
  66972. }
  66973. else
  66974. {
  66975. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66976. yTerm = p1.getY() - p1.getX() / grad;
  66977. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66978. grad *= scale;
  66979. }
  66980. }
  66981. forcedinline void setY (const int y) throw()
  66982. {
  66983. if (vertical)
  66984. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66985. else if (! horizontal)
  66986. start = roundToInt ((y - yTerm) * grad);
  66987. }
  66988. inline const PixelARGB getPixel (const int x) const throw()
  66989. {
  66990. return vertical ? linePix
  66991. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66992. }
  66993. private:
  66994. const PixelARGB* const lookupTable;
  66995. const int numEntries;
  66996. PixelARGB linePix;
  66997. int start, scale;
  66998. double grad, yTerm;
  66999. bool vertical, horizontal;
  67000. enum { numScaleBits = 12 };
  67001. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67002. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67003. };
  67004. class RadialGradientPixelGenerator
  67005. {
  67006. public:
  67007. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67008. const PixelARGB* const lookupTable_, const int numEntries_)
  67009. : lookupTable (lookupTable_),
  67010. numEntries (numEntries_),
  67011. gx1 (gradient.point1.getX()),
  67012. gy1 (gradient.point1.getY())
  67013. {
  67014. jassert (numEntries_ >= 0);
  67015. const Point<float> diff (gradient.point1 - gradient.point2);
  67016. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67017. invScale = numEntries / std::sqrt (maxDist);
  67018. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67019. }
  67020. forcedinline void setY (const int y) throw()
  67021. {
  67022. dy = y - gy1;
  67023. dy *= dy;
  67024. }
  67025. inline const PixelARGB getPixel (const int px) const throw()
  67026. {
  67027. double x = px - gx1;
  67028. x *= x;
  67029. x += dy;
  67030. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67031. }
  67032. protected:
  67033. const PixelARGB* const lookupTable;
  67034. const int numEntries;
  67035. const double gx1, gy1;
  67036. double maxDist, invScale, dy;
  67037. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67038. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67039. };
  67040. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67041. {
  67042. public:
  67043. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67044. const PixelARGB* const lookupTable_, const int numEntries_)
  67045. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67046. inverseTransform (transform.inverted())
  67047. {
  67048. tM10 = inverseTransform.mat10;
  67049. tM00 = inverseTransform.mat00;
  67050. }
  67051. forcedinline void setY (const int y) throw()
  67052. {
  67053. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67054. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67055. }
  67056. inline const PixelARGB getPixel (const int px) const throw()
  67057. {
  67058. double x = px;
  67059. const double y = tM10 * x + lineYM11;
  67060. x = tM00 * x + lineYM01;
  67061. x *= x;
  67062. x += y * y;
  67063. if (x >= maxDist)
  67064. return lookupTable [numEntries];
  67065. else
  67066. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67067. }
  67068. private:
  67069. double tM10, tM00, lineYM01, lineYM11;
  67070. const AffineTransform inverseTransform;
  67071. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67072. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67073. };
  67074. template <class PixelType, class GradientType>
  67075. class GradientEdgeTableRenderer : public GradientType
  67076. {
  67077. public:
  67078. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67079. const PixelARGB* const lookupTable_, const int numEntries_)
  67080. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67081. destData (destData_)
  67082. {
  67083. }
  67084. forcedinline void setEdgeTableYPos (const int y) throw()
  67085. {
  67086. linePixels = (PixelType*) destData.getLinePointer (y);
  67087. GradientType::setY (y);
  67088. }
  67089. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67090. {
  67091. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67092. }
  67093. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67094. {
  67095. linePixels[x].blend (GradientType::getPixel (x));
  67096. }
  67097. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67098. {
  67099. PixelType* dest = linePixels + x;
  67100. if (alphaLevel < 0xff)
  67101. {
  67102. do
  67103. {
  67104. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67105. } while (--width > 0);
  67106. }
  67107. else
  67108. {
  67109. do
  67110. {
  67111. (dest++)->blend (GradientType::getPixel (x++));
  67112. } while (--width > 0);
  67113. }
  67114. }
  67115. void handleEdgeTableLineFull (int x, int width) const throw()
  67116. {
  67117. PixelType* dest = linePixels + x;
  67118. do
  67119. {
  67120. (dest++)->blend (GradientType::getPixel (x++));
  67121. } while (--width > 0);
  67122. }
  67123. private:
  67124. const Image::BitmapData& destData;
  67125. PixelType* linePixels;
  67126. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67127. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67128. };
  67129. static forcedinline int safeModulo (int n, const int divisor) throw()
  67130. {
  67131. jassert (divisor > 0);
  67132. n %= divisor;
  67133. return (n < 0) ? (n + divisor) : n;
  67134. }
  67135. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67136. class ImageFillEdgeTableRenderer
  67137. {
  67138. public:
  67139. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67140. const Image::BitmapData& srcData_,
  67141. const int extraAlpha_,
  67142. const int x, const int y)
  67143. : destData (destData_),
  67144. srcData (srcData_),
  67145. extraAlpha (extraAlpha_ + 1),
  67146. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67147. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67148. {
  67149. }
  67150. forcedinline void setEdgeTableYPos (int y) throw()
  67151. {
  67152. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67153. y -= yOffset;
  67154. if (repeatPattern)
  67155. {
  67156. jassert (y >= 0);
  67157. y %= srcData.height;
  67158. }
  67159. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67160. }
  67161. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67162. {
  67163. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67164. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67165. }
  67166. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67167. {
  67168. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67169. }
  67170. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67171. {
  67172. DestPixelType* dest = linePixels + x;
  67173. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67174. x -= xOffset;
  67175. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67176. if (alphaLevel < 0xfe)
  67177. {
  67178. do
  67179. {
  67180. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67181. } while (--width > 0);
  67182. }
  67183. else
  67184. {
  67185. if (repeatPattern)
  67186. {
  67187. do
  67188. {
  67189. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67190. } while (--width > 0);
  67191. }
  67192. else
  67193. {
  67194. copyRow (dest, sourceLineStart + x, width);
  67195. }
  67196. }
  67197. }
  67198. void handleEdgeTableLineFull (int x, int width) const throw()
  67199. {
  67200. DestPixelType* dest = linePixels + x;
  67201. x -= xOffset;
  67202. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67203. if (extraAlpha < 0xfe)
  67204. {
  67205. do
  67206. {
  67207. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67208. } while (--width > 0);
  67209. }
  67210. else
  67211. {
  67212. if (repeatPattern)
  67213. {
  67214. do
  67215. {
  67216. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67217. } while (--width > 0);
  67218. }
  67219. else
  67220. {
  67221. copyRow (dest, sourceLineStart + x, width);
  67222. }
  67223. }
  67224. }
  67225. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67226. {
  67227. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67228. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67229. uint8* mask = (uint8*) (s + x - xOffset);
  67230. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67231. mask += PixelARGB::indexA;
  67232. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67233. }
  67234. private:
  67235. const Image::BitmapData& destData;
  67236. const Image::BitmapData& srcData;
  67237. const int extraAlpha, xOffset, yOffset;
  67238. DestPixelType* linePixels;
  67239. SrcPixelType* sourceLineStart;
  67240. template <class PixelType1, class PixelType2>
  67241. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67242. {
  67243. do
  67244. {
  67245. dest++ ->blend (*src++);
  67246. } while (--width > 0);
  67247. }
  67248. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67249. {
  67250. memcpy (dest, src, width * sizeof (PixelRGB));
  67251. }
  67252. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67253. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67254. };
  67255. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67256. class TransformedImageFillEdgeTableRenderer
  67257. {
  67258. public:
  67259. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67260. const Image::BitmapData& srcData_,
  67261. const AffineTransform& transform,
  67262. const int extraAlpha_,
  67263. const bool betterQuality_)
  67264. : interpolator (transform),
  67265. destData (destData_),
  67266. srcData (srcData_),
  67267. extraAlpha (extraAlpha_ + 1),
  67268. betterQuality (betterQuality_),
  67269. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67270. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67271. maxX (srcData_.width - 1),
  67272. maxY (srcData_.height - 1),
  67273. scratchSize (2048)
  67274. {
  67275. scratchBuffer.malloc (scratchSize);
  67276. }
  67277. ~TransformedImageFillEdgeTableRenderer()
  67278. {
  67279. }
  67280. forcedinline void setEdgeTableYPos (const int newY) throw()
  67281. {
  67282. y = newY;
  67283. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67284. }
  67285. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67286. {
  67287. alphaLevel *= extraAlpha;
  67288. alphaLevel >>= 8;
  67289. SrcPixelType p;
  67290. generate (&p, x, 1);
  67291. linePixels[x].blend (p, alphaLevel);
  67292. }
  67293. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67294. {
  67295. SrcPixelType p;
  67296. generate (&p, x, 1);
  67297. linePixels[x].blend (p, extraAlpha);
  67298. }
  67299. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67300. {
  67301. if (width > scratchSize)
  67302. {
  67303. scratchSize = width;
  67304. scratchBuffer.malloc (scratchSize);
  67305. }
  67306. SrcPixelType* span = scratchBuffer;
  67307. generate (span, x, width);
  67308. DestPixelType* dest = linePixels + x;
  67309. alphaLevel *= extraAlpha;
  67310. alphaLevel >>= 8;
  67311. if (alphaLevel < 0xfe)
  67312. {
  67313. do
  67314. {
  67315. dest++ ->blend (*span++, alphaLevel);
  67316. } while (--width > 0);
  67317. }
  67318. else
  67319. {
  67320. do
  67321. {
  67322. dest++ ->blend (*span++);
  67323. } while (--width > 0);
  67324. }
  67325. }
  67326. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67327. {
  67328. handleEdgeTableLine (x, width, 255);
  67329. }
  67330. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67331. {
  67332. if (width > scratchSize)
  67333. {
  67334. scratchSize = width;
  67335. scratchBuffer.malloc (scratchSize);
  67336. }
  67337. y = y_;
  67338. generate (scratchBuffer, x, width);
  67339. et.clipLineToMask (x, y_,
  67340. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67341. sizeof (SrcPixelType), width);
  67342. }
  67343. private:
  67344. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67345. {
  67346. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67347. do
  67348. {
  67349. int hiResX, hiResY;
  67350. this->interpolator.next (hiResX, hiResY);
  67351. hiResX += pixelOffsetInt;
  67352. hiResY += pixelOffsetInt;
  67353. int loResX = hiResX >> 8;
  67354. int loResY = hiResY >> 8;
  67355. if (repeatPattern)
  67356. {
  67357. loResX = safeModulo (loResX, srcData.width);
  67358. loResY = safeModulo (loResY, srcData.height);
  67359. }
  67360. if (betterQuality
  67361. && ((unsigned int) loResX) < (unsigned int) maxX
  67362. && ((unsigned int) loResY) < (unsigned int) maxY)
  67363. {
  67364. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67365. hiResX &= 255;
  67366. hiResY &= 255;
  67367. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67368. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67369. c[0] += weight * src[0];
  67370. c[1] += weight * src[1];
  67371. c[2] += weight * src[2];
  67372. c[3] += weight * src[3];
  67373. weight = hiResX * (256 - hiResY);
  67374. c[0] += weight * src[4];
  67375. c[1] += weight * src[5];
  67376. c[2] += weight * src[6];
  67377. c[3] += weight * src[7];
  67378. src += this->srcData.lineStride;
  67379. weight = (256 - hiResX) * hiResY;
  67380. c[0] += weight * src[0];
  67381. c[1] += weight * src[1];
  67382. c[2] += weight * src[2];
  67383. c[3] += weight * src[3];
  67384. weight = hiResX * hiResY;
  67385. c[0] += weight * src[4];
  67386. c[1] += weight * src[5];
  67387. c[2] += weight * src[6];
  67388. c[3] += weight * src[7];
  67389. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67390. (uint8) (c[PixelARGB::indexR] >> 16),
  67391. (uint8) (c[PixelARGB::indexG] >> 16),
  67392. (uint8) (c[PixelARGB::indexB] >> 16));
  67393. }
  67394. else
  67395. {
  67396. if (! repeatPattern)
  67397. {
  67398. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67399. if (loResX < 0) loResX = 0;
  67400. if (loResY < 0) loResY = 0;
  67401. if (loResX > maxX) loResX = maxX;
  67402. if (loResY > maxY) loResY = maxY;
  67403. }
  67404. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67405. }
  67406. ++dest;
  67407. } while (--numPixels > 0);
  67408. }
  67409. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67410. {
  67411. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67412. do
  67413. {
  67414. int hiResX, hiResY;
  67415. this->interpolator.next (hiResX, hiResY);
  67416. hiResX += pixelOffsetInt;
  67417. hiResY += pixelOffsetInt;
  67418. int loResX = hiResX >> 8;
  67419. int loResY = hiResY >> 8;
  67420. if (repeatPattern)
  67421. {
  67422. loResX = safeModulo (loResX, srcData.width);
  67423. loResY = safeModulo (loResY, srcData.height);
  67424. }
  67425. if (betterQuality
  67426. && ((unsigned int) loResX) < (unsigned int) maxX
  67427. && ((unsigned int) loResY) < (unsigned int) maxY)
  67428. {
  67429. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67430. hiResX &= 255;
  67431. hiResY &= 255;
  67432. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67433. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  67434. c[0] += weight * src[0];
  67435. c[1] += weight * src[1];
  67436. c[2] += weight * src[2];
  67437. weight = hiResX * (256 - hiResY);
  67438. c[0] += weight * src[3];
  67439. c[1] += weight * src[4];
  67440. c[2] += weight * src[5];
  67441. src += this->srcData.lineStride;
  67442. weight = (256 - hiResX) * hiResY;
  67443. c[0] += weight * src[0];
  67444. c[1] += weight * src[1];
  67445. c[2] += weight * src[2];
  67446. weight = hiResX * hiResY;
  67447. c[0] += weight * src[3];
  67448. c[1] += weight * src[4];
  67449. c[2] += weight * src[5];
  67450. dest->setARGB ((uint8) 255,
  67451. (uint8) (c[PixelRGB::indexR] >> 16),
  67452. (uint8) (c[PixelRGB::indexG] >> 16),
  67453. (uint8) (c[PixelRGB::indexB] >> 16));
  67454. }
  67455. else
  67456. {
  67457. if (! repeatPattern)
  67458. {
  67459. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67460. if (loResX < 0) loResX = 0;
  67461. if (loResY < 0) loResY = 0;
  67462. if (loResX > maxX) loResX = maxX;
  67463. if (loResY > maxY) loResY = maxY;
  67464. }
  67465. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  67466. }
  67467. ++dest;
  67468. } while (--numPixels > 0);
  67469. }
  67470. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  67471. {
  67472. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67473. do
  67474. {
  67475. int hiResX, hiResY;
  67476. this->interpolator.next (hiResX, hiResY);
  67477. hiResX += pixelOffsetInt;
  67478. hiResY += pixelOffsetInt;
  67479. int loResX = hiResX >> 8;
  67480. int loResY = hiResY >> 8;
  67481. if (repeatPattern)
  67482. {
  67483. loResX = safeModulo (loResX, srcData.width);
  67484. loResY = safeModulo (loResY, srcData.height);
  67485. }
  67486. if (betterQuality
  67487. && ((unsigned int) loResX) < (unsigned int) maxX
  67488. && ((unsigned int) loResY) < (unsigned int) maxY)
  67489. {
  67490. hiResX &= 255;
  67491. hiResY &= 255;
  67492. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67493. uint32 c = 256 * 128;
  67494. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  67495. c += src[1] * (hiResX * (256 - hiResY));
  67496. src += this->srcData.lineStride;
  67497. c += src[0] * ((256 - hiResX) * hiResY);
  67498. c += src[1] * (hiResX * hiResY);
  67499. *((uint8*) dest) = (uint8) c;
  67500. }
  67501. else
  67502. {
  67503. if (! repeatPattern)
  67504. {
  67505. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67506. if (loResX < 0) loResX = 0;
  67507. if (loResY < 0) loResY = 0;
  67508. if (loResX > maxX) loResX = maxX;
  67509. if (loResY > maxY) loResY = maxY;
  67510. }
  67511. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  67512. }
  67513. ++dest;
  67514. } while (--numPixels > 0);
  67515. }
  67516. class TransformedImageSpanInterpolator
  67517. {
  67518. public:
  67519. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  67520. : inverseTransform (transform.inverted())
  67521. {}
  67522. void setStartOfLine (float x, float y, const int numPixels) throw()
  67523. {
  67524. float x1 = x, y1 = y;
  67525. x += numPixels;
  67526. inverseTransform.transformPoints (x1, y1, x, y);
  67527. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  67528. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  67529. }
  67530. void next (int& x, int& y) throw()
  67531. {
  67532. x = xBresenham.n;
  67533. xBresenham.stepToNext();
  67534. y = yBresenham.n;
  67535. yBresenham.stepToNext();
  67536. }
  67537. private:
  67538. class BresenhamInterpolator
  67539. {
  67540. public:
  67541. BresenhamInterpolator() throw() {}
  67542. void set (const int n1, const int n2, const int numSteps_) throw()
  67543. {
  67544. numSteps = jmax (1, numSteps_);
  67545. step = (n2 - n1) / numSteps;
  67546. remainder = modulo = (n2 - n1) % numSteps;
  67547. n = n1;
  67548. if (modulo <= 0)
  67549. {
  67550. modulo += numSteps;
  67551. remainder += numSteps;
  67552. --step;
  67553. }
  67554. modulo -= numSteps;
  67555. }
  67556. forcedinline void stepToNext() throw()
  67557. {
  67558. modulo += remainder;
  67559. n += step;
  67560. if (modulo > 0)
  67561. {
  67562. modulo -= numSteps;
  67563. ++n;
  67564. }
  67565. }
  67566. int n;
  67567. private:
  67568. int numSteps, step, modulo, remainder;
  67569. };
  67570. const AffineTransform inverseTransform;
  67571. BresenhamInterpolator xBresenham, yBresenham;
  67572. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  67573. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  67574. };
  67575. TransformedImageSpanInterpolator interpolator;
  67576. const Image::BitmapData& destData;
  67577. const Image::BitmapData& srcData;
  67578. const int extraAlpha;
  67579. const bool betterQuality;
  67580. const float pixelOffset;
  67581. const int pixelOffsetInt, maxX, maxY;
  67582. int y;
  67583. DestPixelType* linePixels;
  67584. HeapBlock <SrcPixelType> scratchBuffer;
  67585. int scratchSize;
  67586. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  67587. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  67588. };
  67589. class ClipRegionBase : public ReferenceCountedObject
  67590. {
  67591. public:
  67592. ClipRegionBase() {}
  67593. virtual ~ClipRegionBase() {}
  67594. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67595. virtual const Ptr clone() const = 0;
  67596. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67597. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67598. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67599. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67600. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67601. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67602. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67603. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67604. virtual const Rectangle<int> getClipBounds() const = 0;
  67605. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67606. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67607. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67608. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67609. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67610. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67611. protected:
  67612. template <class Iterator>
  67613. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67614. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67615. {
  67616. switch (destData.pixelFormat)
  67617. {
  67618. case Image::ARGB:
  67619. switch (srcData.pixelFormat)
  67620. {
  67621. case Image::ARGB:
  67622. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67623. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67624. break;
  67625. case Image::RGB:
  67626. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67627. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67628. break;
  67629. default:
  67630. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67631. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67632. break;
  67633. }
  67634. break;
  67635. case Image::RGB:
  67636. switch (srcData.pixelFormat)
  67637. {
  67638. case Image::ARGB:
  67639. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67640. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67641. break;
  67642. case Image::RGB:
  67643. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67644. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67645. break;
  67646. default:
  67647. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67648. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67649. break;
  67650. }
  67651. break;
  67652. default:
  67653. switch (srcData.pixelFormat)
  67654. {
  67655. case Image::ARGB:
  67656. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67657. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67658. break;
  67659. case Image::RGB:
  67660. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67661. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67662. break;
  67663. default:
  67664. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67665. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67666. break;
  67667. }
  67668. break;
  67669. }
  67670. }
  67671. template <class Iterator>
  67672. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  67673. {
  67674. switch (destData.pixelFormat)
  67675. {
  67676. case Image::ARGB:
  67677. switch (srcData.pixelFormat)
  67678. {
  67679. case Image::ARGB:
  67680. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67681. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67682. break;
  67683. case Image::RGB:
  67684. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67685. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67686. break;
  67687. default:
  67688. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67689. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67690. break;
  67691. }
  67692. break;
  67693. case Image::RGB:
  67694. switch (srcData.pixelFormat)
  67695. {
  67696. case Image::ARGB:
  67697. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67698. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67699. break;
  67700. case Image::RGB:
  67701. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67702. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67703. break;
  67704. default:
  67705. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67706. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67707. break;
  67708. }
  67709. break;
  67710. default:
  67711. switch (srcData.pixelFormat)
  67712. {
  67713. case Image::ARGB:
  67714. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67715. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67716. break;
  67717. case Image::RGB:
  67718. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67719. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67720. break;
  67721. default:
  67722. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67723. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67724. break;
  67725. }
  67726. break;
  67727. }
  67728. }
  67729. template <class Iterator, class DestPixelType>
  67730. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  67731. {
  67732. jassert (destData.pixelStride == sizeof (DestPixelType));
  67733. if (replaceContents)
  67734. {
  67735. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  67736. iter.iterate (r);
  67737. }
  67738. else
  67739. {
  67740. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  67741. iter.iterate (r);
  67742. }
  67743. }
  67744. template <class Iterator, class DestPixelType>
  67745. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  67746. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  67747. {
  67748. jassert (destData.pixelStride == sizeof (DestPixelType));
  67749. if (g.isRadial)
  67750. {
  67751. if (isIdentity)
  67752. {
  67753. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67754. iter.iterate (renderer);
  67755. }
  67756. else
  67757. {
  67758. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67759. iter.iterate (renderer);
  67760. }
  67761. }
  67762. else
  67763. {
  67764. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67765. iter.iterate (renderer);
  67766. }
  67767. }
  67768. };
  67769. class ClipRegion_EdgeTable : public ClipRegionBase
  67770. {
  67771. public:
  67772. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67773. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  67774. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  67775. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  67776. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  67777. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  67778. ~ClipRegion_EdgeTable() {}
  67779. const Ptr clone() const
  67780. {
  67781. return new ClipRegion_EdgeTable (*this);
  67782. }
  67783. const Ptr applyClipTo (const Ptr& target) const
  67784. {
  67785. return target->clipToEdgeTable (edgeTable);
  67786. }
  67787. const Ptr clipToRectangle (const Rectangle<int>& r)
  67788. {
  67789. edgeTable.clipToRectangle (r);
  67790. return edgeTable.isEmpty() ? 0 : this;
  67791. }
  67792. const Ptr clipToRectangleList (const RectangleList& r)
  67793. {
  67794. RectangleList inverse (edgeTable.getMaximumBounds());
  67795. if (inverse.subtract (r))
  67796. for (RectangleList::Iterator iter (inverse); iter.next();)
  67797. edgeTable.excludeRectangle (*iter.getRectangle());
  67798. return edgeTable.isEmpty() ? 0 : this;
  67799. }
  67800. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67801. {
  67802. edgeTable.excludeRectangle (r);
  67803. return edgeTable.isEmpty() ? 0 : this;
  67804. }
  67805. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67806. {
  67807. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  67808. edgeTable.clipToEdgeTable (et);
  67809. return edgeTable.isEmpty() ? 0 : this;
  67810. }
  67811. const Ptr clipToEdgeTable (const EdgeTable& et)
  67812. {
  67813. edgeTable.clipToEdgeTable (et);
  67814. return edgeTable.isEmpty() ? 0 : this;
  67815. }
  67816. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  67817. {
  67818. const Image::BitmapData srcData (image, false);
  67819. if (transform.isOnlyTranslation())
  67820. {
  67821. // If our translation doesn't involve any distortion, just use a simple blit..
  67822. const int tx = (int) (transform.getTranslationX() * 256.0f);
  67823. const int ty = (int) (transform.getTranslationY() * 256.0f);
  67824. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67825. {
  67826. const int imageX = ((tx + 128) >> 8);
  67827. const int imageY = ((ty + 128) >> 8);
  67828. if (image.getFormat() == Image::ARGB)
  67829. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  67830. else
  67831. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  67832. return edgeTable.isEmpty() ? 0 : this;
  67833. }
  67834. }
  67835. if (transform.isSingularity())
  67836. return 0;
  67837. {
  67838. Path p;
  67839. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  67840. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  67841. edgeTable.clipToEdgeTable (et2);
  67842. }
  67843. if (! edgeTable.isEmpty())
  67844. {
  67845. if (image.getFormat() == Image::ARGB)
  67846. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  67847. else
  67848. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  67849. }
  67850. return edgeTable.isEmpty() ? 0 : this;
  67851. }
  67852. bool clipRegionIntersects (const Rectangle<int>& r) const
  67853. {
  67854. return edgeTable.getMaximumBounds().intersects (r);
  67855. }
  67856. const Rectangle<int> getClipBounds() const
  67857. {
  67858. return edgeTable.getMaximumBounds();
  67859. }
  67860. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67861. {
  67862. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  67863. const Rectangle<int> clipped (totalClip.getIntersection (area));
  67864. if (! clipped.isEmpty())
  67865. {
  67866. ClipRegion_EdgeTable et (clipped);
  67867. et.edgeTable.clipToEdgeTable (edgeTable);
  67868. et.fillAllWithColour (destData, colour, replaceContents);
  67869. }
  67870. }
  67871. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67872. {
  67873. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  67874. const Rectangle<float> clipped (totalClip.getIntersection (area));
  67875. if (! clipped.isEmpty())
  67876. {
  67877. ClipRegion_EdgeTable et (clipped);
  67878. et.edgeTable.clipToEdgeTable (edgeTable);
  67879. et.fillAllWithColour (destData, colour, false);
  67880. }
  67881. }
  67882. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67883. {
  67884. switch (destData.pixelFormat)
  67885. {
  67886. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67887. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67888. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67889. }
  67890. }
  67891. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67892. {
  67893. HeapBlock <PixelARGB> lookupTable;
  67894. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67895. jassert (numLookupEntries > 0);
  67896. switch (destData.pixelFormat)
  67897. {
  67898. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67899. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67900. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67901. }
  67902. }
  67903. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67904. {
  67905. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67906. }
  67907. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67908. {
  67909. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  67910. }
  67911. EdgeTable edgeTable;
  67912. private:
  67913. template <class SrcPixelType>
  67914. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  67915. {
  67916. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  67917. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  67918. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  67919. edgeTable.getMaximumBounds().getWidth());
  67920. }
  67921. template <class SrcPixelType>
  67922. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  67923. {
  67924. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  67925. edgeTable.clipToRectangle (r);
  67926. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  67927. for (int y = 0; y < r.getHeight(); ++y)
  67928. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  67929. }
  67930. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  67931. };
  67932. class ClipRegion_RectangleList : public ClipRegionBase
  67933. {
  67934. public:
  67935. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  67936. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  67937. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  67938. ~ClipRegion_RectangleList() {}
  67939. const Ptr clone() const
  67940. {
  67941. return new ClipRegion_RectangleList (*this);
  67942. }
  67943. const Ptr applyClipTo (const Ptr& target) const
  67944. {
  67945. return target->clipToRectangleList (clip);
  67946. }
  67947. const Ptr clipToRectangle (const Rectangle<int>& r)
  67948. {
  67949. clip.clipTo (r);
  67950. return clip.isEmpty() ? 0 : this;
  67951. }
  67952. const Ptr clipToRectangleList (const RectangleList& r)
  67953. {
  67954. clip.clipTo (r);
  67955. return clip.isEmpty() ? 0 : this;
  67956. }
  67957. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67958. {
  67959. clip.subtract (r);
  67960. return clip.isEmpty() ? 0 : this;
  67961. }
  67962. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67963. {
  67964. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67965. }
  67966. const Ptr clipToEdgeTable (const EdgeTable& et)
  67967. {
  67968. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67969. }
  67970. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  67971. {
  67972. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  67973. }
  67974. bool clipRegionIntersects (const Rectangle<int>& r) const
  67975. {
  67976. return clip.intersects (r);
  67977. }
  67978. const Rectangle<int> getClipBounds() const
  67979. {
  67980. return clip.getBounds();
  67981. }
  67982. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67983. {
  67984. SubRectangleIterator iter (clip, area);
  67985. switch (destData.pixelFormat)
  67986. {
  67987. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67988. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67989. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67990. }
  67991. }
  67992. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67993. {
  67994. SubRectangleIteratorFloat iter (clip, area);
  67995. switch (destData.pixelFormat)
  67996. {
  67997. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67998. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67999. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68000. }
  68001. }
  68002. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68003. {
  68004. switch (destData.pixelFormat)
  68005. {
  68006. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68007. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68008. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68009. }
  68010. }
  68011. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68012. {
  68013. HeapBlock <PixelARGB> lookupTable;
  68014. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68015. jassert (numLookupEntries > 0);
  68016. switch (destData.pixelFormat)
  68017. {
  68018. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68019. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68020. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68021. }
  68022. }
  68023. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68024. {
  68025. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68026. }
  68027. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68028. {
  68029. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68030. }
  68031. RectangleList clip;
  68032. template <class Renderer>
  68033. void iterate (Renderer& r) const throw()
  68034. {
  68035. RectangleList::Iterator iter (clip);
  68036. while (iter.next())
  68037. {
  68038. const Rectangle<int> rect (*iter.getRectangle());
  68039. const int x = rect.getX();
  68040. const int w = rect.getWidth();
  68041. jassert (w > 0);
  68042. const int bottom = rect.getBottom();
  68043. for (int y = rect.getY(); y < bottom; ++y)
  68044. {
  68045. r.setEdgeTableYPos (y);
  68046. r.handleEdgeTableLineFull (x, w);
  68047. }
  68048. }
  68049. }
  68050. private:
  68051. class SubRectangleIterator
  68052. {
  68053. public:
  68054. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68055. : clip (clip_), area (area_)
  68056. {
  68057. }
  68058. template <class Renderer>
  68059. void iterate (Renderer& r) const throw()
  68060. {
  68061. RectangleList::Iterator iter (clip);
  68062. while (iter.next())
  68063. {
  68064. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68065. if (! rect.isEmpty())
  68066. {
  68067. const int x = rect.getX();
  68068. const int w = rect.getWidth();
  68069. const int bottom = rect.getBottom();
  68070. for (int y = rect.getY(); y < bottom; ++y)
  68071. {
  68072. r.setEdgeTableYPos (y);
  68073. r.handleEdgeTableLineFull (x, w);
  68074. }
  68075. }
  68076. }
  68077. }
  68078. private:
  68079. const RectangleList& clip;
  68080. const Rectangle<int> area;
  68081. SubRectangleIterator (const SubRectangleIterator&);
  68082. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68083. };
  68084. class SubRectangleIteratorFloat
  68085. {
  68086. public:
  68087. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68088. : clip (clip_), area (area_)
  68089. {
  68090. }
  68091. template <class Renderer>
  68092. void iterate (Renderer& r) const throw()
  68093. {
  68094. int left = roundToInt (area.getX() * 256.0f);
  68095. int top = roundToInt (area.getY() * 256.0f);
  68096. int right = roundToInt (area.getRight() * 256.0f);
  68097. int bottom = roundToInt (area.getBottom() * 256.0f);
  68098. int totalTop, totalLeft, totalBottom, totalRight;
  68099. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68100. if ((top >> 8) == (bottom >> 8))
  68101. {
  68102. topAlpha = bottom - top;
  68103. bottomAlpha = 0;
  68104. totalTop = top >> 8;
  68105. totalBottom = bottom = top = totalTop + 1;
  68106. }
  68107. else
  68108. {
  68109. if ((top & 255) == 0)
  68110. {
  68111. topAlpha = 0;
  68112. top = totalTop = (top >> 8);
  68113. }
  68114. else
  68115. {
  68116. topAlpha = 255 - (top & 255);
  68117. totalTop = (top >> 8);
  68118. top = totalTop + 1;
  68119. }
  68120. bottomAlpha = bottom & 255;
  68121. bottom >>= 8;
  68122. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68123. }
  68124. if ((left >> 8) == (right >> 8))
  68125. {
  68126. leftAlpha = right - left;
  68127. rightAlpha = 0;
  68128. totalLeft = (left >> 8);
  68129. totalRight = right = left = totalLeft + 1;
  68130. }
  68131. else
  68132. {
  68133. if ((left & 255) == 0)
  68134. {
  68135. leftAlpha = 0;
  68136. left = totalLeft = (left >> 8);
  68137. }
  68138. else
  68139. {
  68140. leftAlpha = 255 - (left & 255);
  68141. totalLeft = (left >> 8);
  68142. left = totalLeft + 1;
  68143. }
  68144. rightAlpha = right & 255;
  68145. right >>= 8;
  68146. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68147. }
  68148. RectangleList::Iterator iter (clip);
  68149. while (iter.next())
  68150. {
  68151. const int clipLeft = iter.getRectangle()->getX();
  68152. const int clipRight = iter.getRectangle()->getRight();
  68153. const int clipTop = iter.getRectangle()->getY();
  68154. const int clipBottom = iter.getRectangle()->getBottom();
  68155. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68156. {
  68157. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68158. {
  68159. if (topAlpha != 0 && totalTop >= clipTop)
  68160. {
  68161. r.setEdgeTableYPos (totalTop);
  68162. r.handleEdgeTablePixel (left, topAlpha);
  68163. }
  68164. const int endY = jmin (bottom, clipBottom);
  68165. for (int y = jmax (clipTop, top); y < endY; ++y)
  68166. {
  68167. r.setEdgeTableYPos (y);
  68168. r.handleEdgeTablePixelFull (left);
  68169. }
  68170. if (bottomAlpha != 0 && bottom < clipBottom)
  68171. {
  68172. r.setEdgeTableYPos (bottom);
  68173. r.handleEdgeTablePixel (left, bottomAlpha);
  68174. }
  68175. }
  68176. else
  68177. {
  68178. const int clippedLeft = jmax (left, clipLeft);
  68179. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68180. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68181. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68182. if (topAlpha != 0 && totalTop >= clipTop)
  68183. {
  68184. r.setEdgeTableYPos (totalTop);
  68185. if (doLeftAlpha)
  68186. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68187. if (clippedWidth > 0)
  68188. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68189. if (doRightAlpha)
  68190. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68191. }
  68192. const int endY = jmin (bottom, clipBottom);
  68193. for (int y = jmax (clipTop, top); y < endY; ++y)
  68194. {
  68195. r.setEdgeTableYPos (y);
  68196. if (doLeftAlpha)
  68197. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68198. if (clippedWidth > 0)
  68199. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68200. if (doRightAlpha)
  68201. r.handleEdgeTablePixel (right, rightAlpha);
  68202. }
  68203. if (bottomAlpha != 0 && bottom < clipBottom)
  68204. {
  68205. r.setEdgeTableYPos (bottom);
  68206. if (doLeftAlpha)
  68207. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68208. if (clippedWidth > 0)
  68209. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68210. if (doRightAlpha)
  68211. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68212. }
  68213. }
  68214. }
  68215. }
  68216. }
  68217. private:
  68218. const RectangleList& clip;
  68219. const Rectangle<float>& area;
  68220. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68221. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68222. };
  68223. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68224. };
  68225. }
  68226. class LowLevelGraphicsSoftwareRenderer::SavedState
  68227. {
  68228. public:
  68229. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68230. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68231. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68232. {
  68233. }
  68234. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68235. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68236. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68237. {
  68238. }
  68239. SavedState (const SavedState& other)
  68240. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68241. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68242. {
  68243. }
  68244. ~SavedState()
  68245. {
  68246. }
  68247. void setOrigin (const int x, const int y) throw()
  68248. {
  68249. xOffset += x;
  68250. yOffset += y;
  68251. }
  68252. bool clipToRectangle (const Rectangle<int>& r)
  68253. {
  68254. if (clip != 0)
  68255. {
  68256. cloneClipIfMultiplyReferenced();
  68257. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68258. }
  68259. return clip != 0;
  68260. }
  68261. bool clipToRectangleList (const RectangleList& r)
  68262. {
  68263. if (clip != 0)
  68264. {
  68265. cloneClipIfMultiplyReferenced();
  68266. RectangleList offsetList (r);
  68267. offsetList.offsetAll (xOffset, yOffset);
  68268. clip = clip->clipToRectangleList (offsetList);
  68269. }
  68270. return clip != 0;
  68271. }
  68272. bool excludeClipRectangle (const Rectangle<int>& r)
  68273. {
  68274. if (clip != 0)
  68275. {
  68276. cloneClipIfMultiplyReferenced();
  68277. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68278. }
  68279. return clip != 0;
  68280. }
  68281. void clipToPath (const Path& p, const AffineTransform& transform)
  68282. {
  68283. if (clip != 0)
  68284. {
  68285. cloneClipIfMultiplyReferenced();
  68286. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68287. }
  68288. }
  68289. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68290. {
  68291. if (clip != 0)
  68292. {
  68293. if (image.hasAlphaChannel())
  68294. {
  68295. cloneClipIfMultiplyReferenced();
  68296. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68297. interpolationQuality != Graphics::lowResamplingQuality);
  68298. }
  68299. else
  68300. {
  68301. Path p;
  68302. p.addRectangle (image.getBounds());
  68303. clipToPath (p, t);
  68304. }
  68305. }
  68306. }
  68307. bool clipRegionIntersects (const Rectangle<int>& r) const
  68308. {
  68309. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68310. }
  68311. const Rectangle<int> getClipBounds() const
  68312. {
  68313. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68314. }
  68315. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68316. {
  68317. if (clip != 0)
  68318. {
  68319. if (fillType.isColour())
  68320. {
  68321. Image::BitmapData destData (image, true);
  68322. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68323. }
  68324. else
  68325. {
  68326. const Rectangle<int> totalClip (clip->getClipBounds());
  68327. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68328. if (! clipped.isEmpty())
  68329. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68330. }
  68331. }
  68332. }
  68333. void fillRect (Image& image, const Rectangle<float>& r)
  68334. {
  68335. if (clip != 0)
  68336. {
  68337. if (fillType.isColour())
  68338. {
  68339. Image::BitmapData destData (image, true);
  68340. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68341. }
  68342. else
  68343. {
  68344. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68345. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68346. if (! clipped.isEmpty())
  68347. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68348. }
  68349. }
  68350. }
  68351. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68352. {
  68353. if (clip != 0)
  68354. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68355. }
  68356. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68357. {
  68358. if (clip != 0)
  68359. {
  68360. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68361. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68362. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68363. fillShape (image, shapeToFill, false);
  68364. }
  68365. }
  68366. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68367. {
  68368. jassert (clip != 0);
  68369. shapeToFill = clip->applyClipTo (shapeToFill);
  68370. if (shapeToFill != 0)
  68371. {
  68372. Image::BitmapData destData (image, true);
  68373. if (fillType.isGradient())
  68374. {
  68375. jassert (! replaceContents); // that option is just for solid colours
  68376. ColourGradient g2 (*(fillType.gradient));
  68377. g2.multiplyOpacity (fillType.getOpacity());
  68378. g2.point1.addXY (-0.5f, -0.5f);
  68379. g2.point2.addXY (-0.5f, -0.5f);
  68380. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68381. const bool isIdentity = transform.isOnlyTranslation();
  68382. if (isIdentity)
  68383. {
  68384. // If our translation doesn't involve any distortion, we can speed it up..
  68385. g2.point1.applyTransform (transform);
  68386. g2.point2.applyTransform (transform);
  68387. transform = AffineTransform::identity;
  68388. }
  68389. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68390. }
  68391. else if (fillType.isTiledImage())
  68392. {
  68393. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68394. }
  68395. else
  68396. {
  68397. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68398. }
  68399. }
  68400. }
  68401. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68402. {
  68403. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68404. const Image::BitmapData destData (destImage, true);
  68405. const Image::BitmapData srcData (sourceImage, false);
  68406. const int alpha = fillType.colour.getAlpha();
  68407. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68408. if (transform.isOnlyTranslation())
  68409. {
  68410. // If our translation doesn't involve any distortion, just use a simple blit..
  68411. int tx = (int) (transform.getTranslationX() * 256.0f);
  68412. int ty = (int) (transform.getTranslationY() * 256.0f);
  68413. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68414. {
  68415. tx = ((tx + 128) >> 8);
  68416. ty = ((ty + 128) >> 8);
  68417. if (tiledFillClipRegion != 0)
  68418. {
  68419. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68420. }
  68421. else
  68422. {
  68423. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68424. c = clip->applyClipTo (c);
  68425. if (c != 0)
  68426. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68427. }
  68428. return;
  68429. }
  68430. }
  68431. if (transform.isSingularity())
  68432. return;
  68433. if (tiledFillClipRegion != 0)
  68434. {
  68435. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68436. }
  68437. else
  68438. {
  68439. Path p;
  68440. p.addRectangle (sourceImage.getBounds());
  68441. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68442. c = c->clipToPath (p, transform);
  68443. if (c != 0)
  68444. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68445. }
  68446. }
  68447. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68448. int xOffset, yOffset;
  68449. Font font;
  68450. FillType fillType;
  68451. Graphics::ResamplingQuality interpolationQuality;
  68452. private:
  68453. void cloneClipIfMultiplyReferenced()
  68454. {
  68455. if (clip->getReferenceCount() > 1)
  68456. clip = clip->clone();
  68457. }
  68458. SavedState& operator= (const SavedState&);
  68459. };
  68460. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68461. : image (image_)
  68462. {
  68463. currentState = new SavedState (image_.getBounds(), 0, 0);
  68464. }
  68465. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68466. const RectangleList& initialClip)
  68467. : image (image_)
  68468. {
  68469. currentState = new SavedState (initialClip, xOffset, yOffset);
  68470. }
  68471. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68472. {
  68473. }
  68474. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68475. {
  68476. return false;
  68477. }
  68478. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68479. {
  68480. currentState->setOrigin (x, y);
  68481. }
  68482. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68483. {
  68484. return currentState->clipToRectangle (r);
  68485. }
  68486. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68487. {
  68488. return currentState->clipToRectangleList (clipRegion);
  68489. }
  68490. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68491. {
  68492. currentState->excludeClipRectangle (r);
  68493. }
  68494. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68495. {
  68496. currentState->clipToPath (path, transform);
  68497. }
  68498. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68499. {
  68500. currentState->clipToImageAlpha (sourceImage, transform);
  68501. }
  68502. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68503. {
  68504. return currentState->clipRegionIntersects (r);
  68505. }
  68506. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68507. {
  68508. return currentState->getClipBounds();
  68509. }
  68510. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68511. {
  68512. return currentState->clip == 0;
  68513. }
  68514. void LowLevelGraphicsSoftwareRenderer::saveState()
  68515. {
  68516. stateStack.add (new SavedState (*currentState));
  68517. }
  68518. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68519. {
  68520. SavedState* const top = stateStack.getLast();
  68521. if (top != 0)
  68522. {
  68523. currentState = top;
  68524. stateStack.removeLast (1, false);
  68525. }
  68526. else
  68527. {
  68528. jassertfalse; // trying to pop with an empty stack!
  68529. }
  68530. }
  68531. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  68532. {
  68533. currentState->fillType = fillType;
  68534. }
  68535. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  68536. {
  68537. currentState->fillType.setOpacity (newOpacity);
  68538. }
  68539. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  68540. {
  68541. currentState->interpolationQuality = quality;
  68542. }
  68543. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  68544. {
  68545. currentState->fillRect (image, r, replaceExistingContents);
  68546. }
  68547. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  68548. {
  68549. currentState->fillPath (image, path, transform);
  68550. }
  68551. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  68552. {
  68553. currentState->renderImage (image, sourceImage, transform,
  68554. fillEntireClipAsTiles ? currentState->clip : 0);
  68555. }
  68556. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  68557. {
  68558. Path p;
  68559. p.addLineSegment (line, 1.0f);
  68560. fillPath (p, AffineTransform::identity);
  68561. }
  68562. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  68563. {
  68564. if (bottom > top)
  68565. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  68566. }
  68567. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  68568. {
  68569. if (right > left)
  68570. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  68571. }
  68572. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  68573. {
  68574. public:
  68575. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  68576. ~CachedGlyph() {}
  68577. void draw (SavedState& state, Image& image, const float x, const float y) const
  68578. {
  68579. if (edgeTable != 0)
  68580. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  68581. }
  68582. void generate (const Font& newFont, const int glyphNumber)
  68583. {
  68584. font = newFont;
  68585. glyph = glyphNumber;
  68586. edgeTable = 0;
  68587. Path glyphPath;
  68588. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  68589. if (! glyphPath.isEmpty())
  68590. {
  68591. const float fontHeight = font.getHeight();
  68592. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  68593. #if JUCE_MAC || JUCE_IOS
  68594. .translated (0.0f, -0.5f)
  68595. #endif
  68596. );
  68597. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  68598. glyphPath, transform);
  68599. }
  68600. }
  68601. int glyph, lastAccessCount;
  68602. Font font;
  68603. juce_UseDebuggingNewOperator
  68604. private:
  68605. ScopedPointer <EdgeTable> edgeTable;
  68606. CachedGlyph (const CachedGlyph&);
  68607. CachedGlyph& operator= (const CachedGlyph&);
  68608. };
  68609. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  68610. {
  68611. public:
  68612. GlyphCache()
  68613. : accessCounter (0), hits (0), misses (0)
  68614. {
  68615. for (int i = 120; --i >= 0;)
  68616. glyphs.add (new CachedGlyph());
  68617. }
  68618. ~GlyphCache()
  68619. {
  68620. clearSingletonInstance();
  68621. }
  68622. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  68623. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  68624. {
  68625. ++accessCounter;
  68626. int oldestCounter = std::numeric_limits<int>::max();
  68627. CachedGlyph* oldest = 0;
  68628. for (int i = glyphs.size(); --i >= 0;)
  68629. {
  68630. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  68631. if (glyph->glyph == glyphNumber && glyph->font == font)
  68632. {
  68633. ++hits;
  68634. glyph->lastAccessCount = accessCounter;
  68635. glyph->draw (state, image, x, y);
  68636. return;
  68637. }
  68638. if (glyph->lastAccessCount <= oldestCounter)
  68639. {
  68640. oldestCounter = glyph->lastAccessCount;
  68641. oldest = glyph;
  68642. }
  68643. }
  68644. if (hits + ++misses > (glyphs.size() << 4))
  68645. {
  68646. if (misses * 2 > hits)
  68647. {
  68648. for (int i = 32; --i >= 0;)
  68649. glyphs.add (new CachedGlyph());
  68650. }
  68651. hits = misses = 0;
  68652. oldest = glyphs.getLast();
  68653. }
  68654. jassert (oldest != 0);
  68655. oldest->lastAccessCount = accessCounter;
  68656. oldest->generate (font, glyphNumber);
  68657. oldest->draw (state, image, x, y);
  68658. }
  68659. juce_UseDebuggingNewOperator
  68660. private:
  68661. friend class OwnedArray <CachedGlyph>;
  68662. OwnedArray <CachedGlyph> glyphs;
  68663. int accessCounter, hits, misses;
  68664. GlyphCache (const GlyphCache&);
  68665. GlyphCache& operator= (const GlyphCache&);
  68666. };
  68667. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  68668. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  68669. {
  68670. currentState->font = newFont;
  68671. }
  68672. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  68673. {
  68674. return currentState->font;
  68675. }
  68676. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  68677. {
  68678. Font& f = currentState->font;
  68679. if (transform.isOnlyTranslation())
  68680. {
  68681. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  68682. transform.getTranslationX(),
  68683. transform.getTranslationY());
  68684. }
  68685. else
  68686. {
  68687. Path p;
  68688. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  68689. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  68690. }
  68691. }
  68692. #if JUCE_MSVC
  68693. #pragma warning (pop)
  68694. #if JUCE_DEBUG
  68695. #pragma optimize ("", on) // resets optimisations to the project defaults
  68696. #endif
  68697. #endif
  68698. END_JUCE_NAMESPACE
  68699. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  68700. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  68701. BEGIN_JUCE_NAMESPACE
  68702. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  68703. : flags (other.flags)
  68704. {
  68705. }
  68706. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  68707. {
  68708. flags = other.flags;
  68709. return *this;
  68710. }
  68711. void RectanglePlacement::applyTo (double& x, double& y,
  68712. double& w, double& h,
  68713. const double dx, const double dy,
  68714. const double dw, const double dh) const throw()
  68715. {
  68716. if (w == 0 || h == 0)
  68717. return;
  68718. if ((flags & stretchToFit) != 0)
  68719. {
  68720. x = dx;
  68721. y = dy;
  68722. w = dw;
  68723. h = dh;
  68724. }
  68725. else
  68726. {
  68727. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  68728. : jmin (dw / w, dh / h);
  68729. if ((flags & onlyReduceInSize) != 0)
  68730. scale = jmin (scale, 1.0);
  68731. if ((flags & onlyIncreaseInSize) != 0)
  68732. scale = jmax (scale, 1.0);
  68733. w *= scale;
  68734. h *= scale;
  68735. if ((flags & xLeft) != 0)
  68736. x = dx;
  68737. else if ((flags & xRight) != 0)
  68738. x = dx + dw - w;
  68739. else
  68740. x = dx + (dw - w) * 0.5;
  68741. if ((flags & yTop) != 0)
  68742. y = dy;
  68743. else if ((flags & yBottom) != 0)
  68744. y = dy + dh - h;
  68745. else
  68746. y = dy + (dh - h) * 0.5;
  68747. }
  68748. }
  68749. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  68750. float w, float h,
  68751. const float dx, const float dy,
  68752. const float dw, const float dh) const throw()
  68753. {
  68754. if (w == 0 || h == 0)
  68755. return AffineTransform::identity;
  68756. const float scaleX = dw / w;
  68757. const float scaleY = dh / h;
  68758. if ((flags & stretchToFit) != 0)
  68759. return AffineTransform::translation (-x, -y)
  68760. .scaled (scaleX, scaleY)
  68761. .translated (dx, dy);
  68762. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  68763. : jmin (scaleX, scaleY);
  68764. if ((flags & onlyReduceInSize) != 0)
  68765. scale = jmin (scale, 1.0f);
  68766. if ((flags & onlyIncreaseInSize) != 0)
  68767. scale = jmax (scale, 1.0f);
  68768. w *= scale;
  68769. h *= scale;
  68770. float newX = dx;
  68771. if ((flags & xRight) != 0)
  68772. newX += dw - w; // right
  68773. else if ((flags & xLeft) == 0)
  68774. newX += (dw - w) / 2.0f; // centre
  68775. float newY = dy;
  68776. if ((flags & yBottom) != 0)
  68777. newY += dh - h; // bottom
  68778. else if ((flags & yTop) == 0)
  68779. newY += (dh - h) / 2.0f; // centre
  68780. return AffineTransform::translation (-x, -y)
  68781. .scaled (scale, scale)
  68782. .translated (newX, newY);
  68783. }
  68784. END_JUCE_NAMESPACE
  68785. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  68786. /*** Start of inlined file: juce_Drawable.cpp ***/
  68787. BEGIN_JUCE_NAMESPACE
  68788. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  68789. const AffineTransform& transform_,
  68790. const float opacity_) throw()
  68791. : g (g_),
  68792. transform (transform_),
  68793. opacity (opacity_)
  68794. {
  68795. }
  68796. Drawable::Drawable()
  68797. : parent (0)
  68798. {
  68799. }
  68800. Drawable::~Drawable()
  68801. {
  68802. }
  68803. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  68804. {
  68805. render (RenderingContext (g, transform, opacity));
  68806. }
  68807. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  68808. {
  68809. draw (g, opacity, AffineTransform::translation (x, y));
  68810. }
  68811. void Drawable::drawWithin (Graphics& g,
  68812. const int destX,
  68813. const int destY,
  68814. const int destW,
  68815. const int destH,
  68816. const RectanglePlacement& placement,
  68817. const float opacity) const
  68818. {
  68819. if (destW > 0 && destH > 0)
  68820. {
  68821. Rectangle<float> bounds (getBounds());
  68822. draw (g, opacity,
  68823. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  68824. (float) destX, (float) destY,
  68825. (float) destW, (float) destH));
  68826. }
  68827. }
  68828. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  68829. {
  68830. Drawable* result = 0;
  68831. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  68832. if (image.isValid())
  68833. {
  68834. DrawableImage* const di = new DrawableImage();
  68835. di->setImage (image);
  68836. result = di;
  68837. }
  68838. else
  68839. {
  68840. const String asString (String::createStringFromData (data, (int) numBytes));
  68841. XmlDocument doc (asString);
  68842. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  68843. if (outer != 0 && outer->hasTagName ("svg"))
  68844. {
  68845. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  68846. if (svg != 0)
  68847. result = Drawable::createFromSVG (*svg);
  68848. }
  68849. }
  68850. return result;
  68851. }
  68852. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  68853. {
  68854. MemoryOutputStream mo;
  68855. mo.writeFromInputStream (dataSource, -1);
  68856. return createFromImageData (mo.getData(), mo.getDataSize());
  68857. }
  68858. Drawable* Drawable::createFromImageFile (const File& file)
  68859. {
  68860. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  68861. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  68862. }
  68863. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68864. {
  68865. return createChildFromValueTree (0, tree, imageProvider);
  68866. }
  68867. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  68868. {
  68869. const Identifier type (tree.getType());
  68870. Drawable* d = 0;
  68871. if (type == DrawablePath::valueTreeType)
  68872. d = new DrawablePath();
  68873. else if (type == DrawableComposite::valueTreeType)
  68874. d = new DrawableComposite();
  68875. else if (type == DrawableImage::valueTreeType)
  68876. d = new DrawableImage();
  68877. else if (type == DrawableText::valueTreeType)
  68878. d = new DrawableText();
  68879. if (d != 0)
  68880. {
  68881. d->parent = parent;
  68882. d->refreshFromValueTree (tree, imageProvider);
  68883. }
  68884. return d;
  68885. }
  68886. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  68887. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  68888. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  68889. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  68890. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  68891. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  68892. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  68893. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  68894. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  68895. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  68896. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  68897. : state (state_)
  68898. {
  68899. }
  68900. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  68901. {
  68902. }
  68903. const String Drawable::ValueTreeWrapperBase::getID() const
  68904. {
  68905. return state [idProperty];
  68906. }
  68907. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  68908. {
  68909. if (newID.isEmpty())
  68910. state.removeProperty (idProperty, undoManager);
  68911. else
  68912. state.setProperty (idProperty, newID, undoManager);
  68913. }
  68914. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  68915. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  68916. {
  68917. const String newType (v[type].toString());
  68918. if (newType == "solid")
  68919. {
  68920. const String colourString (v [colour].toString());
  68921. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  68922. : (uint32) colourString.getHexValue32()));
  68923. }
  68924. else if (newType == "gradient")
  68925. {
  68926. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  68927. ColourGradient g;
  68928. if (gp1 != 0) *gp1 = p1;
  68929. if (gp2 != 0) *gp2 = p2;
  68930. if (gp3 != 0) *gp3 = p3;
  68931. g.point1 = p1.resolve (nameFinder);
  68932. g.point2 = p2.resolve (nameFinder);
  68933. g.isRadial = v[radial];
  68934. StringArray colourSteps;
  68935. colourSteps.addTokens (v[colours].toString(), false);
  68936. for (int i = 0; i < colourSteps.size() / 2; ++i)
  68937. g.addColour (colourSteps[i * 2].getDoubleValue(),
  68938. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  68939. FillType fillType (g);
  68940. if (g.isRadial)
  68941. {
  68942. const Point<float> point3 (p3.resolve (nameFinder));
  68943. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68944. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68945. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  68946. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  68947. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  68948. }
  68949. return fillType;
  68950. }
  68951. else if (newType == "image")
  68952. {
  68953. Image im;
  68954. if (imageProvider != 0)
  68955. im = imageProvider->getImageForIdentifier (v[imageId]);
  68956. FillType f (im, AffineTransform::identity);
  68957. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  68958. return f;
  68959. }
  68960. jassertfalse;
  68961. return FillType();
  68962. }
  68963. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  68964. {
  68965. const ColourGradient& g = *fillType.gradient;
  68966. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68967. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68968. return point3Source.transformedBy (fillType.transform);
  68969. }
  68970. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  68971. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  68972. ImageProvider* imageProvider, UndoManager* const undoManager)
  68973. {
  68974. if (fillType.isColour())
  68975. {
  68976. v.setProperty (type, "solid", undoManager);
  68977. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68978. }
  68979. else if (fillType.isGradient())
  68980. {
  68981. v.setProperty (type, "gradient", undoManager);
  68982. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68983. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68984. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  68985. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68986. String s;
  68987. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68988. s << ' ' << fillType.gradient->getColourPosition (i)
  68989. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68990. v.setProperty (colours, s.trimStart(), undoManager);
  68991. }
  68992. else if (fillType.isTiledImage())
  68993. {
  68994. v.setProperty (type, "image", undoManager);
  68995. if (imageProvider != 0)
  68996. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68997. if (fillType.getOpacity() < 1.0f)
  68998. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68999. else
  69000. v.removeProperty (imageOpacity, undoManager);
  69001. }
  69002. else
  69003. {
  69004. jassertfalse;
  69005. }
  69006. }
  69007. END_JUCE_NAMESPACE
  69008. /*** End of inlined file: juce_Drawable.cpp ***/
  69009. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69010. BEGIN_JUCE_NAMESPACE
  69011. DrawableComposite::DrawableComposite()
  69012. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69013. {
  69014. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69015. RelativeCoordinate (100.0),
  69016. RelativeCoordinate (0.0),
  69017. RelativeCoordinate (100.0)));
  69018. }
  69019. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69020. {
  69021. bounds = other.bounds;
  69022. for (int i = 0; i < other.drawables.size(); ++i)
  69023. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69024. markersX.addCopiesOf (other.markersX);
  69025. markersY.addCopiesOf (other.markersY);
  69026. }
  69027. DrawableComposite::~DrawableComposite()
  69028. {
  69029. }
  69030. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69031. {
  69032. if (drawable != 0)
  69033. {
  69034. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69035. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69036. drawables.insert (index, drawable);
  69037. drawable->parent = this;
  69038. }
  69039. }
  69040. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69041. {
  69042. insertDrawable (drawable.createCopy(), index);
  69043. }
  69044. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69045. {
  69046. drawables.remove (index, deleteDrawable);
  69047. }
  69048. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69049. {
  69050. for (int i = drawables.size(); --i >= 0;)
  69051. if (drawables.getUnchecked(i)->getName() == name)
  69052. return drawables.getUnchecked(i);
  69053. return 0;
  69054. }
  69055. void DrawableComposite::bringToFront (const int index)
  69056. {
  69057. if (index >= 0 && index < drawables.size() - 1)
  69058. drawables.move (index, -1);
  69059. }
  69060. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69061. {
  69062. bounds = newBoundingBox;
  69063. }
  69064. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69065. : name (other.name), position (other.position)
  69066. {
  69067. }
  69068. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69069. : name (name_), position (position_)
  69070. {
  69071. }
  69072. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69073. {
  69074. return name != other.name || position != other.position;
  69075. }
  69076. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69077. const char* const DrawableComposite::contentRightMarkerName ("right");
  69078. const char* const DrawableComposite::contentTopMarkerName ("top");
  69079. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69080. const RelativeRectangle DrawableComposite::getContentArea() const
  69081. {
  69082. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69083. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69084. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69085. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69086. }
  69087. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69088. {
  69089. setMarker (contentLeftMarkerName, true, newArea.left);
  69090. setMarker (contentRightMarkerName, true, newArea.right);
  69091. setMarker (contentTopMarkerName, false, newArea.top);
  69092. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69093. }
  69094. void DrawableComposite::resetBoundingBoxToContentArea()
  69095. {
  69096. const RelativeRectangle content (getContentArea());
  69097. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69098. RelativePoint (content.right, content.top),
  69099. RelativePoint (content.left, content.bottom)));
  69100. }
  69101. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69102. {
  69103. const Rectangle<float> bounds (getUntransformedBounds (false));
  69104. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69105. RelativeCoordinate (bounds.getRight()),
  69106. RelativeCoordinate (bounds.getY()),
  69107. RelativeCoordinate (bounds.getBottom())));
  69108. resetBoundingBoxToContentArea();
  69109. }
  69110. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69111. {
  69112. return (xAxis ? markersX : markersY).size();
  69113. }
  69114. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69115. {
  69116. return (xAxis ? markersX : markersY) [index];
  69117. }
  69118. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69119. {
  69120. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69121. for (int i = 0; i < markers.size(); ++i)
  69122. {
  69123. Marker* const m = markers.getUnchecked(i);
  69124. if (m->name == name)
  69125. {
  69126. if (m->position != position)
  69127. {
  69128. m->position = position;
  69129. invalidatePoints();
  69130. }
  69131. return;
  69132. }
  69133. }
  69134. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69135. invalidatePoints();
  69136. }
  69137. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69138. {
  69139. jassert (index >= 2);
  69140. if (index >= 2)
  69141. (xAxis ? markersX : markersY).remove (index);
  69142. }
  69143. const AffineTransform DrawableComposite::calculateTransform() const
  69144. {
  69145. Point<float> resolved[3];
  69146. bounds.resolveThreePoints (resolved, parent);
  69147. const Rectangle<float> content (getContentArea().resolve (parent));
  69148. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69149. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69150. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69151. }
  69152. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69153. {
  69154. if (drawables.size() > 0 && context.opacity > 0)
  69155. {
  69156. if (context.opacity >= 1.0f || drawables.size() == 1)
  69157. {
  69158. Drawable::RenderingContext contextCopy (context);
  69159. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69160. for (int i = 0; i < drawables.size(); ++i)
  69161. drawables.getUnchecked(i)->render (contextCopy);
  69162. }
  69163. else
  69164. {
  69165. // To correctly render a whole composite layer with an overall transparency,
  69166. // we need to render everything opaquely into a temp buffer, then blend that
  69167. // with the target opacity...
  69168. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69169. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69170. {
  69171. Graphics tempG (tempImage);
  69172. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69173. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69174. render (tempContext);
  69175. }
  69176. context.g.setOpacity (context.opacity);
  69177. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69178. }
  69179. }
  69180. }
  69181. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  69182. {
  69183. if (objectName == RelativeCoordinate::Strings::parent)
  69184. {
  69185. if (edge == RelativeCoordinate::Strings::right || edge == RelativeCoordinate::Strings::bottom)
  69186. {
  69187. jassertfalse; // a Drawable doesn't have a fixed right-hand or bottom edge - use a marker instead if you need a point of reference.
  69188. return RelativeCoordinate (100.0);
  69189. }
  69190. }
  69191. int i;
  69192. for (i = 0; i < markersX.size(); ++i)
  69193. {
  69194. Marker* const m = markersX.getUnchecked(i);
  69195. if (m->name == objectName)
  69196. return m->position;
  69197. }
  69198. for (i = 0; i < markersY.size(); ++i)
  69199. {
  69200. Marker* const m = markersY.getUnchecked(i);
  69201. if (m->name == objectName)
  69202. return m->position;
  69203. }
  69204. return RelativeCoordinate();
  69205. }
  69206. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69207. {
  69208. Rectangle<float> bounds;
  69209. int i;
  69210. for (i = 0; i < drawables.size(); ++i)
  69211. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69212. if (includeMarkers)
  69213. {
  69214. if (markersX.size() > 0)
  69215. {
  69216. float minX = std::numeric_limits<float>::max();
  69217. float maxX = std::numeric_limits<float>::min();
  69218. for (i = markersX.size(); --i >= 0;)
  69219. {
  69220. const Marker* m = markersX.getUnchecked(i);
  69221. const float pos = (float) m->position.resolve (this);
  69222. minX = jmin (minX, pos);
  69223. maxX = jmax (maxX, pos);
  69224. }
  69225. if (minX <= maxX)
  69226. {
  69227. if (bounds.getHeight() > 0)
  69228. {
  69229. minX = jmin (minX, bounds.getX());
  69230. maxX = jmax (maxX, bounds.getRight());
  69231. }
  69232. bounds.setLeft (minX);
  69233. bounds.setWidth (maxX - minX);
  69234. }
  69235. }
  69236. if (markersY.size() > 0)
  69237. {
  69238. float minY = std::numeric_limits<float>::max();
  69239. float maxY = std::numeric_limits<float>::min();
  69240. for (i = markersY.size(); --i >= 0;)
  69241. {
  69242. const Marker* m = markersY.getUnchecked(i);
  69243. const float pos = (float) m->position.resolve (this);
  69244. minY = jmin (minY, pos);
  69245. maxY = jmax (maxY, pos);
  69246. }
  69247. if (minY <= maxY)
  69248. {
  69249. if (bounds.getHeight() > 0)
  69250. {
  69251. minY = jmin (minY, bounds.getY());
  69252. maxY = jmax (maxY, bounds.getBottom());
  69253. }
  69254. bounds.setTop (minY);
  69255. bounds.setHeight (maxY - minY);
  69256. }
  69257. }
  69258. }
  69259. return bounds;
  69260. }
  69261. const Rectangle<float> DrawableComposite::getBounds() const
  69262. {
  69263. return getUntransformedBounds (true).transformed (calculateTransform());
  69264. }
  69265. bool DrawableComposite::hitTest (float x, float y) const
  69266. {
  69267. calculateTransform().inverted().transformPoint (x, y);
  69268. for (int i = 0; i < drawables.size(); ++i)
  69269. if (drawables.getUnchecked(i)->hitTest (x, y))
  69270. return true;
  69271. return false;
  69272. }
  69273. Drawable* DrawableComposite::createCopy() const
  69274. {
  69275. return new DrawableComposite (*this);
  69276. }
  69277. void DrawableComposite::invalidatePoints()
  69278. {
  69279. for (int i = 0; i < drawables.size(); ++i)
  69280. drawables.getUnchecked(i)->invalidatePoints();
  69281. }
  69282. const Identifier DrawableComposite::valueTreeType ("Group");
  69283. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69284. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69285. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69286. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69287. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69288. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69289. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69290. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69291. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69292. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69293. : ValueTreeWrapperBase (state_)
  69294. {
  69295. jassert (state.hasType (valueTreeType));
  69296. }
  69297. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69298. {
  69299. return state.getChildWithName (childGroupTag);
  69300. }
  69301. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69302. {
  69303. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69304. }
  69305. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69306. {
  69307. return getChildList().getNumChildren();
  69308. }
  69309. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69310. {
  69311. return getChildList().getChild (index);
  69312. }
  69313. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69314. {
  69315. if (getID() == objectId)
  69316. return state;
  69317. if (! recursive)
  69318. {
  69319. return getChildList().getChildWithProperty (idProperty, objectId);
  69320. }
  69321. else
  69322. {
  69323. const ValueTree childList (getChildList());
  69324. for (int i = getNumDrawables(); --i >= 0;)
  69325. {
  69326. const ValueTree& child = childList.getChild (i);
  69327. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69328. return child;
  69329. if (child.hasType (DrawableComposite::valueTreeType))
  69330. {
  69331. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69332. if (v.isValid())
  69333. return v;
  69334. }
  69335. }
  69336. return ValueTree::invalid;
  69337. }
  69338. }
  69339. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69340. {
  69341. return getChildList().indexOf (item);
  69342. }
  69343. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69344. {
  69345. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69346. }
  69347. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69348. {
  69349. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69350. }
  69351. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69352. {
  69353. getChildList().removeChild (child, undoManager);
  69354. }
  69355. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69356. {
  69357. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69358. state.getProperty (topRight, "100, 0"),
  69359. state.getProperty (bottomLeft, "0, 100"));
  69360. }
  69361. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69362. {
  69363. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69364. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69365. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69366. }
  69367. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69368. {
  69369. const RelativeRectangle content (getContentArea());
  69370. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69371. RelativePoint (content.right, content.top),
  69372. RelativePoint (content.left, content.bottom)), undoManager);
  69373. }
  69374. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69375. {
  69376. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69377. getMarker (true, getMarkerState (true, 1)).position,
  69378. getMarker (false, getMarkerState (false, 0)).position,
  69379. getMarker (false, getMarkerState (false, 1)).position);
  69380. }
  69381. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69382. {
  69383. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69384. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69385. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69386. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69387. }
  69388. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69389. {
  69390. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69391. }
  69392. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69393. {
  69394. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69395. }
  69396. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69397. {
  69398. return getMarkerList (xAxis).getNumChildren();
  69399. }
  69400. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69401. {
  69402. return getMarkerList (xAxis).getChild (index);
  69403. }
  69404. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69405. {
  69406. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69407. }
  69408. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69409. {
  69410. return state.isAChildOf (getMarkerList (xAxis));
  69411. }
  69412. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69413. {
  69414. jassert (containsMarker (xAxis, state));
  69415. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  69416. }
  69417. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69418. {
  69419. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69420. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69421. if (marker.isValid())
  69422. {
  69423. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69424. }
  69425. else
  69426. {
  69427. marker = ValueTree (markerTag);
  69428. marker.setProperty (nameProperty, m.name, 0);
  69429. marker.setProperty (posProperty, m.position.toString(), 0);
  69430. markerList.addChild (marker, -1, undoManager);
  69431. }
  69432. }
  69433. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  69434. {
  69435. if (state [nameProperty].toString() != contentLeftMarkerName
  69436. && state [nameProperty].toString() != contentRightMarkerName
  69437. && state [nameProperty].toString() != contentTopMarkerName
  69438. && state [nameProperty].toString() != contentBottomMarkerName)
  69439. return getMarkerList (xAxis).removeChild (state, undoManager);
  69440. }
  69441. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69442. {
  69443. const ValueTreeWrapper wrapper (tree);
  69444. setName (wrapper.getID());
  69445. Rectangle<float> damage;
  69446. bool redrawAll = false;
  69447. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  69448. if (bounds != newBounds)
  69449. {
  69450. redrawAll = true;
  69451. damage = getBounds();
  69452. bounds = newBounds;
  69453. }
  69454. const int numMarkersX = wrapper.getNumMarkers (true);
  69455. const int numMarkersY = wrapper.getNumMarkers (false);
  69456. // Remove deleted markers...
  69457. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  69458. {
  69459. if (! redrawAll)
  69460. {
  69461. redrawAll = true;
  69462. damage = getBounds();
  69463. }
  69464. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  69465. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  69466. }
  69467. // Update markers and add new ones..
  69468. int i;
  69469. for (i = 0; i < numMarkersX; ++i)
  69470. {
  69471. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  69472. Marker* m = markersX[i];
  69473. if (m == 0 || newMarker != *m)
  69474. {
  69475. if (! redrawAll)
  69476. {
  69477. redrawAll = true;
  69478. damage = getBounds();
  69479. }
  69480. if (m == 0)
  69481. markersX.add (new Marker (newMarker));
  69482. else
  69483. *m = newMarker;
  69484. }
  69485. }
  69486. for (i = 0; i < numMarkersY; ++i)
  69487. {
  69488. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  69489. Marker* m = markersY[i];
  69490. if (m == 0 || newMarker != *m)
  69491. {
  69492. if (! redrawAll)
  69493. {
  69494. redrawAll = true;
  69495. damage = getBounds();
  69496. }
  69497. if (m == 0)
  69498. markersY.add (new Marker (newMarker));
  69499. else
  69500. *m = newMarker;
  69501. }
  69502. }
  69503. // Remove deleted drawables..
  69504. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  69505. {
  69506. Drawable* const d = drawables.getUnchecked(i);
  69507. if (! redrawAll)
  69508. damage = damage.getUnion (d->getBounds());
  69509. d->parent = 0;
  69510. drawables.remove (i);
  69511. }
  69512. // Update drawables and add new ones..
  69513. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  69514. {
  69515. const ValueTree newDrawable (wrapper.getDrawableState (i));
  69516. Drawable* d = drawables[i];
  69517. if (d != 0)
  69518. {
  69519. if (newDrawable.hasType (d->getValueTreeType()))
  69520. {
  69521. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  69522. if (! redrawAll)
  69523. damage = damage.getUnion (area);
  69524. }
  69525. else
  69526. {
  69527. if (! redrawAll)
  69528. damage = damage.getUnion (d->getBounds());
  69529. d = createChildFromValueTree (this, newDrawable, imageProvider);
  69530. drawables.set (i, d);
  69531. if (! redrawAll)
  69532. damage = damage.getUnion (d->getBounds());
  69533. }
  69534. }
  69535. else
  69536. {
  69537. d = createChildFromValueTree (this, newDrawable, imageProvider);
  69538. drawables.set (i, d);
  69539. if (! redrawAll)
  69540. damage = damage.getUnion (d->getBounds());
  69541. }
  69542. }
  69543. if (redrawAll)
  69544. damage = damage.getUnion (getBounds());
  69545. else if (! damage.isEmpty())
  69546. damage = damage.transformed (calculateTransform());
  69547. return damage;
  69548. }
  69549. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  69550. {
  69551. ValueTree tree (valueTreeType);
  69552. ValueTreeWrapper v (tree);
  69553. v.setID (getName(), 0);
  69554. v.setBoundingBox (bounds, 0);
  69555. int i;
  69556. for (i = 0; i < drawables.size(); ++i)
  69557. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  69558. for (i = 0; i < markersX.size(); ++i)
  69559. v.setMarker (true, *markersX.getUnchecked(i), 0);
  69560. for (i = 0; i < markersY.size(); ++i)
  69561. v.setMarker (false, *markersY.getUnchecked(i), 0);
  69562. return tree;
  69563. }
  69564. END_JUCE_NAMESPACE
  69565. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  69566. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  69567. BEGIN_JUCE_NAMESPACE
  69568. DrawableImage::DrawableImage()
  69569. : image (0),
  69570. opacity (1.0f),
  69571. overlayColour (0x00000000)
  69572. {
  69573. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  69574. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  69575. }
  69576. DrawableImage::DrawableImage (const DrawableImage& other)
  69577. : image (other.image),
  69578. opacity (other.opacity),
  69579. overlayColour (other.overlayColour),
  69580. bounds (other.bounds)
  69581. {
  69582. }
  69583. DrawableImage::~DrawableImage()
  69584. {
  69585. }
  69586. void DrawableImage::setImage (const Image& imageToUse)
  69587. {
  69588. image = imageToUse;
  69589. if (image.isValid())
  69590. {
  69591. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  69592. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  69593. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  69594. }
  69595. }
  69596. void DrawableImage::setOpacity (const float newOpacity)
  69597. {
  69598. opacity = newOpacity;
  69599. }
  69600. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  69601. {
  69602. overlayColour = newOverlayColour;
  69603. }
  69604. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  69605. {
  69606. bounds = newBounds;
  69607. }
  69608. const AffineTransform DrawableImage::calculateTransform() const
  69609. {
  69610. if (image.isNull())
  69611. return AffineTransform::identity;
  69612. Point<float> resolved[3];
  69613. bounds.resolveThreePoints (resolved, parent);
  69614. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  69615. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  69616. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  69617. tr.getX(), tr.getY(),
  69618. bl.getX(), bl.getY());
  69619. }
  69620. void DrawableImage::render (const Drawable::RenderingContext& context) const
  69621. {
  69622. if (image.isValid())
  69623. {
  69624. const AffineTransform t (calculateTransform().followedBy (context.transform));
  69625. if (opacity > 0.0f && ! overlayColour.isOpaque())
  69626. {
  69627. context.g.setOpacity (context.opacity * opacity);
  69628. context.g.drawImageTransformed (image, t, false);
  69629. }
  69630. if (! overlayColour.isTransparent())
  69631. {
  69632. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  69633. context.g.drawImageTransformed (image, t, true);
  69634. }
  69635. }
  69636. }
  69637. const Rectangle<float> DrawableImage::getBounds() const
  69638. {
  69639. if (image.isNull())
  69640. return Rectangle<float>();
  69641. return bounds.getBounds (parent);
  69642. }
  69643. bool DrawableImage::hitTest (float x, float y) const
  69644. {
  69645. if (image.isNull())
  69646. return false;
  69647. calculateTransform().inverted().transformPoint (x, y);
  69648. const int ix = roundToInt (x);
  69649. const int iy = roundToInt (y);
  69650. return ix >= 0
  69651. && iy >= 0
  69652. && ix < image.getWidth()
  69653. && iy < image.getHeight()
  69654. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  69655. }
  69656. Drawable* DrawableImage::createCopy() const
  69657. {
  69658. return new DrawableImage (*this);
  69659. }
  69660. void DrawableImage::invalidatePoints()
  69661. {
  69662. }
  69663. const Identifier DrawableImage::valueTreeType ("Image");
  69664. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  69665. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  69666. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  69667. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  69668. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  69669. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69670. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69671. : ValueTreeWrapperBase (state_)
  69672. {
  69673. jassert (state.hasType (valueTreeType));
  69674. }
  69675. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  69676. {
  69677. return state [image];
  69678. }
  69679. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  69680. {
  69681. return state.getPropertyAsValue (image, undoManager);
  69682. }
  69683. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  69684. {
  69685. state.setProperty (image, newIdentifier, undoManager);
  69686. }
  69687. float DrawableImage::ValueTreeWrapper::getOpacity() const
  69688. {
  69689. return (float) state.getProperty (opacity, 1.0);
  69690. }
  69691. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  69692. {
  69693. if (! state.hasProperty (opacity))
  69694. state.setProperty (opacity, 1.0, undoManager);
  69695. return state.getPropertyAsValue (opacity, undoManager);
  69696. }
  69697. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  69698. {
  69699. state.setProperty (opacity, newOpacity, undoManager);
  69700. }
  69701. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  69702. {
  69703. return Colour (state [overlay].toString().getHexValue32());
  69704. }
  69705. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  69706. {
  69707. if (newColour.isTransparent())
  69708. state.removeProperty (overlay, undoManager);
  69709. else
  69710. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  69711. }
  69712. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  69713. {
  69714. return state.getPropertyAsValue (overlay, undoManager);
  69715. }
  69716. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  69717. {
  69718. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69719. state.getProperty (topRight, "100, 0"),
  69720. state.getProperty (bottomLeft, "0, 100"));
  69721. }
  69722. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69723. {
  69724. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69725. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69726. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69727. }
  69728. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69729. {
  69730. const ValueTreeWrapper controller (tree);
  69731. setName (controller.getID());
  69732. const float newOpacity = controller.getOpacity();
  69733. const Colour newOverlayColour (controller.getOverlayColour());
  69734. Image newImage;
  69735. const var imageIdentifier (controller.getImageIdentifier());
  69736. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  69737. if (imageProvider != 0)
  69738. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  69739. const RelativeParallelogram newBounds (controller.getBoundingBox());
  69740. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  69741. {
  69742. const Rectangle<float> damage (getBounds());
  69743. opacity = newOpacity;
  69744. overlayColour = newOverlayColour;
  69745. bounds = newBounds;
  69746. image = newImage;
  69747. return damage.getUnion (getBounds());
  69748. }
  69749. return Rectangle<float>();
  69750. }
  69751. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  69752. {
  69753. ValueTree tree (valueTreeType);
  69754. ValueTreeWrapper v (tree);
  69755. v.setID (getName(), 0);
  69756. v.setOpacity (opacity, 0);
  69757. v.setOverlayColour (overlayColour, 0);
  69758. v.setBoundingBox (bounds, 0);
  69759. if (image.isValid())
  69760. {
  69761. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  69762. if (imageProvider != 0)
  69763. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  69764. }
  69765. return tree;
  69766. }
  69767. END_JUCE_NAMESPACE
  69768. /*** End of inlined file: juce_DrawableImage.cpp ***/
  69769. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  69770. BEGIN_JUCE_NAMESPACE
  69771. DrawablePath::DrawablePath()
  69772. : mainFill (Colours::black),
  69773. strokeFill (Colours::black),
  69774. strokeType (0.0f),
  69775. pathNeedsUpdating (true),
  69776. strokeNeedsUpdating (true)
  69777. {
  69778. }
  69779. DrawablePath::DrawablePath (const DrawablePath& other)
  69780. : mainFill (other.mainFill),
  69781. strokeFill (other.strokeFill),
  69782. strokeType (other.strokeType),
  69783. pathNeedsUpdating (true),
  69784. strokeNeedsUpdating (true)
  69785. {
  69786. if (other.relativePath != 0)
  69787. relativePath = new RelativePointPath (*other.relativePath);
  69788. else
  69789. path = other.path;
  69790. }
  69791. DrawablePath::~DrawablePath()
  69792. {
  69793. }
  69794. void DrawablePath::setPath (const Path& newPath)
  69795. {
  69796. path = newPath;
  69797. strokeNeedsUpdating = true;
  69798. }
  69799. void DrawablePath::setFill (const FillType& newFill)
  69800. {
  69801. mainFill = newFill;
  69802. }
  69803. void DrawablePath::setStrokeFill (const FillType& newFill)
  69804. {
  69805. strokeFill = newFill;
  69806. }
  69807. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  69808. {
  69809. strokeType = newStrokeType;
  69810. strokeNeedsUpdating = true;
  69811. }
  69812. void DrawablePath::setStrokeThickness (const float newThickness)
  69813. {
  69814. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69815. }
  69816. void DrawablePath::updatePath() const
  69817. {
  69818. if (pathNeedsUpdating)
  69819. {
  69820. pathNeedsUpdating = false;
  69821. if (relativePath != 0)
  69822. {
  69823. path.clear();
  69824. relativePath->createPath (path, parent);
  69825. strokeNeedsUpdating = true;
  69826. }
  69827. }
  69828. }
  69829. void DrawablePath::updateStroke() const
  69830. {
  69831. if (strokeNeedsUpdating)
  69832. {
  69833. strokeNeedsUpdating = false;
  69834. updatePath();
  69835. stroke.clear();
  69836. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  69837. }
  69838. }
  69839. const Path& DrawablePath::getPath() const
  69840. {
  69841. updatePath();
  69842. return path;
  69843. }
  69844. const Path& DrawablePath::getStrokePath() const
  69845. {
  69846. updateStroke();
  69847. return stroke;
  69848. }
  69849. bool DrawablePath::isStrokeVisible() const throw()
  69850. {
  69851. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69852. }
  69853. void DrawablePath::invalidatePoints()
  69854. {
  69855. pathNeedsUpdating = true;
  69856. strokeNeedsUpdating = true;
  69857. }
  69858. void DrawablePath::render (const Drawable::RenderingContext& context) const
  69859. {
  69860. {
  69861. FillType f (mainFill);
  69862. if (f.isGradient())
  69863. f.gradient->multiplyOpacity (context.opacity);
  69864. f.transform = f.transform.followedBy (context.transform);
  69865. context.g.setFillType (f);
  69866. context.g.fillPath (getPath(), context.transform);
  69867. }
  69868. if (isStrokeVisible())
  69869. {
  69870. FillType f (strokeFill);
  69871. if (f.isGradient())
  69872. f.gradient->multiplyOpacity (context.opacity);
  69873. f.transform = f.transform.followedBy (context.transform);
  69874. context.g.setFillType (f);
  69875. context.g.fillPath (getStrokePath(), context.transform);
  69876. }
  69877. }
  69878. const Rectangle<float> DrawablePath::getBounds() const
  69879. {
  69880. if (isStrokeVisible())
  69881. return getStrokePath().getBounds();
  69882. else
  69883. return getPath().getBounds();
  69884. }
  69885. bool DrawablePath::hitTest (float x, float y) const
  69886. {
  69887. return getPath().contains (x, y)
  69888. || (isStrokeVisible() && getStrokePath().contains (x, y));
  69889. }
  69890. Drawable* DrawablePath::createCopy() const
  69891. {
  69892. return new DrawablePath (*this);
  69893. }
  69894. const Identifier DrawablePath::valueTreeType ("Path");
  69895. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  69896. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  69897. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  69898. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  69899. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  69900. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  69901. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  69902. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  69903. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  69904. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  69905. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69906. : ValueTreeWrapperBase (state_)
  69907. {
  69908. jassert (state.hasType (valueTreeType));
  69909. }
  69910. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  69911. {
  69912. return state.getOrCreateChildWithName (path, 0);
  69913. }
  69914. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  69915. {
  69916. ValueTree v (state.getChildWithName (fill));
  69917. if (v.isValid())
  69918. return v;
  69919. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69920. return getMainFillState();
  69921. }
  69922. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  69923. {
  69924. ValueTree v (state.getChildWithName (stroke));
  69925. if (v.isValid())
  69926. return v;
  69927. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69928. return getStrokeFillState();
  69929. }
  69930. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69931. ImageProvider* imageProvider) const
  69932. {
  69933. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69934. }
  69935. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  69936. const RelativePoint* gp2, const RelativePoint* gp3,
  69937. ImageProvider* imageProvider, UndoManager* undoManager)
  69938. {
  69939. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69940. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69941. }
  69942. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69943. ImageProvider* imageProvider) const
  69944. {
  69945. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69946. }
  69947. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  69948. const RelativePoint* gp2, const RelativePoint* gp3,
  69949. ImageProvider* imageProvider, UndoManager* undoManager)
  69950. {
  69951. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69952. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69953. }
  69954. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  69955. {
  69956. const String jointStyleString (state [jointStyle].toString());
  69957. const String capStyleString (state [capStyle].toString());
  69958. return PathStrokeType (state [strokeWidth],
  69959. jointStyleString == "curved" ? PathStrokeType::curved
  69960. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69961. : PathStrokeType::mitered),
  69962. capStyleString == "square" ? PathStrokeType::square
  69963. : (capStyleString == "round" ? PathStrokeType::rounded
  69964. : PathStrokeType::butt));
  69965. }
  69966. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69967. {
  69968. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69969. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69970. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69971. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69972. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69973. }
  69974. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69975. {
  69976. return state [nonZeroWinding];
  69977. }
  69978. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69979. {
  69980. state.setProperty (nonZeroWinding, b, undoManager);
  69981. }
  69982. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  69983. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69984. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69985. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69986. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69987. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69988. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  69989. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  69990. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  69991. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69992. : state (state_)
  69993. {
  69994. }
  69995. DrawablePath::ValueTreeWrapper::Element::~Element()
  69996. {
  69997. }
  69998. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69999. {
  70000. return ValueTreeWrapper (state.getParent().getParent());
  70001. }
  70002. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70003. {
  70004. return Element (state.getSibling (-1));
  70005. }
  70006. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70007. {
  70008. const Identifier i (state.getType());
  70009. if (i == startSubPathElement || i == lineToElement) return 1;
  70010. if (i == quadraticToElement) return 2;
  70011. if (i == cubicToElement) return 3;
  70012. return 0;
  70013. }
  70014. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70015. {
  70016. jassert (index >= 0 && index < getNumControlPoints());
  70017. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70018. }
  70019. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70020. {
  70021. jassert (index >= 0 && index < getNumControlPoints());
  70022. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70023. }
  70024. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70025. {
  70026. jassert (index >= 0 && index < getNumControlPoints());
  70027. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70028. }
  70029. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70030. {
  70031. const Identifier i (state.getType());
  70032. if (i == startSubPathElement)
  70033. return getControlPoint (0);
  70034. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70035. return getPreviousElement().getEndPoint();
  70036. }
  70037. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70038. {
  70039. const Identifier i (state.getType());
  70040. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70041. if (i == quadraticToElement) return getControlPoint (1);
  70042. if (i == cubicToElement) return getControlPoint (2);
  70043. jassert (i == closeSubPathElement);
  70044. return RelativePoint();
  70045. }
  70046. float DrawablePath::ValueTreeWrapper::Element::getLength (RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  70047. {
  70048. const Identifier i (state.getType());
  70049. if (i == lineToElement || i == closeSubPathElement)
  70050. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70051. if (i == cubicToElement)
  70052. {
  70053. Path p;
  70054. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70055. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70056. return p.getLength();
  70057. }
  70058. if (i == quadraticToElement)
  70059. {
  70060. Path p;
  70061. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70062. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70063. return p.getLength();
  70064. }
  70065. jassert (i == startSubPathElement);
  70066. return 0;
  70067. }
  70068. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70069. {
  70070. return state [mode].toString();
  70071. }
  70072. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70073. {
  70074. if (state.hasType (cubicToElement))
  70075. state.setProperty (mode, newMode, undoManager);
  70076. }
  70077. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70078. {
  70079. const Identifier i (state.getType());
  70080. if (i == quadraticToElement || i == cubicToElement)
  70081. {
  70082. ValueTree newState (lineToElement);
  70083. Element e (newState);
  70084. e.setControlPoint (0, getEndPoint(), undoManager);
  70085. state = newState;
  70086. }
  70087. }
  70088. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  70089. {
  70090. const Identifier i (state.getType());
  70091. if (i == lineToElement || i == quadraticToElement)
  70092. {
  70093. ValueTree newState (cubicToElement);
  70094. Element e (newState);
  70095. const RelativePoint start (getStartPoint());
  70096. const RelativePoint end (getEndPoint());
  70097. const Point<float> startResolved (start.resolve (nameFinder));
  70098. const Point<float> endResolved (end.resolve (nameFinder));
  70099. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70100. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70101. e.setControlPoint (2, end, undoManager);
  70102. state = newState;
  70103. }
  70104. }
  70105. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70106. {
  70107. const Identifier i (state.getType());
  70108. if (i != startSubPathElement)
  70109. {
  70110. ValueTree newState (startSubPathElement);
  70111. Element e (newState);
  70112. e.setControlPoint (0, getEndPoint(), undoManager);
  70113. state = newState;
  70114. }
  70115. }
  70116. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70117. {
  70118. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70119. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70120. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70121. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70122. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70123. return newCp1 + (newCp2 - newCp1) * proportion;
  70124. }
  70125. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70126. {
  70127. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70128. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70129. return mid1 + (mid2 - mid1) * proportion;
  70130. }
  70131. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  70132. {
  70133. const Identifier i (state.getType());
  70134. float bestProp = 0;
  70135. if (i == cubicToElement)
  70136. {
  70137. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70138. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70139. float bestDistance = std::numeric_limits<float>::max();
  70140. for (int i = 110; --i >= 0;)
  70141. {
  70142. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70143. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70144. const float distance = centre.getDistanceFrom (targetPoint);
  70145. if (distance < bestDistance)
  70146. {
  70147. bestProp = prop;
  70148. bestDistance = distance;
  70149. }
  70150. }
  70151. }
  70152. else if (i == quadraticToElement)
  70153. {
  70154. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70155. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70156. float bestDistance = std::numeric_limits<float>::max();
  70157. for (int i = 110; --i >= 0;)
  70158. {
  70159. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70160. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70161. const float distance = centre.getDistanceFrom (targetPoint);
  70162. if (distance < bestDistance)
  70163. {
  70164. bestProp = prop;
  70165. bestDistance = distance;
  70166. }
  70167. }
  70168. }
  70169. else if (i == lineToElement)
  70170. {
  70171. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70172. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70173. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70174. }
  70175. return bestProp;
  70176. }
  70177. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  70178. {
  70179. ValueTree newTree;
  70180. const Identifier i (state.getType());
  70181. if (i == cubicToElement)
  70182. {
  70183. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70184. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70185. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70186. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70187. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70188. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70189. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70190. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70191. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70192. setControlPoint (0, mid1, undoManager);
  70193. setControlPoint (1, newCp1, undoManager);
  70194. setControlPoint (2, newCentre, undoManager);
  70195. setModeOfEndPoint (roundedMode, undoManager);
  70196. Element newElement (newTree = ValueTree (cubicToElement));
  70197. newElement.setControlPoint (0, newCp2, 0);
  70198. newElement.setControlPoint (1, mid3, 0);
  70199. newElement.setControlPoint (2, rp4, 0);
  70200. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70201. }
  70202. else if (i == quadraticToElement)
  70203. {
  70204. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70205. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70206. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70207. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70208. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70209. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70210. setControlPoint (0, mid1, undoManager);
  70211. setControlPoint (1, newCentre, undoManager);
  70212. setModeOfEndPoint (roundedMode, undoManager);
  70213. Element newElement (newTree = ValueTree (quadraticToElement));
  70214. newElement.setControlPoint (0, mid2, 0);
  70215. newElement.setControlPoint (1, rp3, 0);
  70216. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70217. }
  70218. else if (i == lineToElement)
  70219. {
  70220. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70221. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70222. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70223. setControlPoint (0, newPoint, undoManager);
  70224. Element newElement (newTree = ValueTree (lineToElement));
  70225. newElement.setControlPoint (0, rp2, 0);
  70226. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70227. }
  70228. else if (i == closeSubPathElement)
  70229. {
  70230. }
  70231. return newTree;
  70232. }
  70233. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70234. {
  70235. state.getParent().removeChild (state, undoManager);
  70236. }
  70237. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70238. {
  70239. Rectangle<float> damageRect;
  70240. ValueTreeWrapper v (tree);
  70241. setName (v.getID());
  70242. bool needsRedraw = false;
  70243. const FillType newFill (v.getMainFill (parent, imageProvider));
  70244. if (mainFill != newFill)
  70245. {
  70246. needsRedraw = true;
  70247. mainFill = newFill;
  70248. }
  70249. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70250. if (strokeFill != newStrokeFill)
  70251. {
  70252. needsRedraw = true;
  70253. strokeFill = newStrokeFill;
  70254. }
  70255. const PathStrokeType newStroke (v.getStrokeType());
  70256. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70257. Path newPath;
  70258. newRelativePath->createPath (newPath, parent);
  70259. if (! newRelativePath->containsAnyDynamicPoints())
  70260. newRelativePath = 0;
  70261. if (strokeType != newStroke || path != newPath)
  70262. {
  70263. damageRect = getBounds();
  70264. path.swapWithPath (newPath);
  70265. strokeNeedsUpdating = true;
  70266. strokeType = newStroke;
  70267. needsRedraw = true;
  70268. }
  70269. relativePath = newRelativePath;
  70270. if (needsRedraw)
  70271. damageRect = damageRect.getUnion (getBounds());
  70272. return damageRect;
  70273. }
  70274. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70275. {
  70276. ValueTree tree (valueTreeType);
  70277. ValueTreeWrapper v (tree);
  70278. v.setID (getName(), 0);
  70279. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70280. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70281. v.setStrokeType (strokeType, 0);
  70282. if (relativePath != 0)
  70283. {
  70284. relativePath->writeTo (tree, 0);
  70285. }
  70286. else
  70287. {
  70288. RelativePointPath rp (path);
  70289. rp.writeTo (tree, 0);
  70290. }
  70291. return tree;
  70292. }
  70293. END_JUCE_NAMESPACE
  70294. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70295. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70296. BEGIN_JUCE_NAMESPACE
  70297. DrawableText::DrawableText()
  70298. : colour (Colours::black),
  70299. justification (Justification::centredLeft)
  70300. {
  70301. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70302. RelativePoint (50.0f, 0.0f),
  70303. RelativePoint (0.0f, 20.0f)));
  70304. setFont (Font (15.0f), true);
  70305. }
  70306. DrawableText::DrawableText (const DrawableText& other)
  70307. : text (other.text),
  70308. font (other.font),
  70309. colour (other.colour),
  70310. justification (other.justification),
  70311. bounds (other.bounds),
  70312. fontSizeControlPoint (other.fontSizeControlPoint)
  70313. {
  70314. }
  70315. DrawableText::~DrawableText()
  70316. {
  70317. }
  70318. void DrawableText::setText (const String& newText)
  70319. {
  70320. text = newText;
  70321. }
  70322. void DrawableText::setColour (const Colour& newColour)
  70323. {
  70324. colour = newColour;
  70325. }
  70326. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70327. {
  70328. font = newFont;
  70329. if (applySizeAndScale)
  70330. {
  70331. Point<float> corners[3];
  70332. bounds.resolveThreePoints (corners, parent);
  70333. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70334. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70335. }
  70336. }
  70337. void DrawableText::setJustification (const Justification& newJustification)
  70338. {
  70339. justification = newJustification;
  70340. }
  70341. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70342. {
  70343. bounds = newBounds;
  70344. }
  70345. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70346. {
  70347. fontSizeControlPoint = newPoint;
  70348. }
  70349. void DrawableText::render (const Drawable::RenderingContext& context) const
  70350. {
  70351. Point<float> points[3];
  70352. bounds.resolveThreePoints (points, parent);
  70353. const float w = Line<float> (points[0], points[1]).getLength();
  70354. const float h = Line<float> (points[0], points[2]).getLength();
  70355. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70356. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70357. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70358. Font f (font);
  70359. f.setHeight (fontHeight);
  70360. f.setHorizontalScale (fontWidth / fontHeight);
  70361. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70362. GlyphArrangement ga;
  70363. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70364. ga.draw (context.g,
  70365. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70366. w, 0, points[1].getX(), points[1].getY(),
  70367. 0, h, points[2].getX(), points[2].getY())
  70368. .followedBy (context.transform));
  70369. }
  70370. const Rectangle<float> DrawableText::getBounds() const
  70371. {
  70372. return bounds.getBounds (parent);
  70373. }
  70374. bool DrawableText::hitTest (float x, float y) const
  70375. {
  70376. Path p;
  70377. bounds.getPath (p, parent);
  70378. return p.contains (x, y);
  70379. }
  70380. Drawable* DrawableText::createCopy() const
  70381. {
  70382. return new DrawableText (*this);
  70383. }
  70384. void DrawableText::invalidatePoints()
  70385. {
  70386. }
  70387. const Identifier DrawableText::valueTreeType ("Text");
  70388. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70389. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70390. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70391. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70392. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70393. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70394. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70395. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70396. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70397. : ValueTreeWrapperBase (state_)
  70398. {
  70399. jassert (state.hasType (valueTreeType));
  70400. }
  70401. const String DrawableText::ValueTreeWrapper::getText() const
  70402. {
  70403. return state [text].toString();
  70404. }
  70405. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70406. {
  70407. state.setProperty (text, newText, undoManager);
  70408. }
  70409. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70410. {
  70411. return state.getPropertyAsValue (text, undoManager);
  70412. }
  70413. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70414. {
  70415. return Colour::fromString (state [colour].toString());
  70416. }
  70417. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70418. {
  70419. state.setProperty (colour, newColour.toString(), undoManager);
  70420. }
  70421. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70422. {
  70423. return Justification ((int) state [justification]);
  70424. }
  70425. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70426. {
  70427. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70428. }
  70429. const Font DrawableText::ValueTreeWrapper::getFont() const
  70430. {
  70431. return Font::fromString (state [font]);
  70432. }
  70433. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70434. {
  70435. state.setProperty (font, newFont.toString(), undoManager);
  70436. }
  70437. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70438. {
  70439. return state.getPropertyAsValue (font, undoManager);
  70440. }
  70441. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70442. {
  70443. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70444. }
  70445. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70446. {
  70447. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70448. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70449. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70450. }
  70451. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70452. {
  70453. return state [fontSizeAnchor].toString();
  70454. }
  70455. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70456. {
  70457. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70458. }
  70459. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70460. {
  70461. ValueTreeWrapper v (tree);
  70462. setName (v.getID());
  70463. const RelativeParallelogram newBounds (v.getBoundingBox());
  70464. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70465. const Colour newColour (v.getColour());
  70466. const Justification newJustification (v.getJustification());
  70467. const String newText (v.getText());
  70468. const Font newFont (v.getFont());
  70469. if (text != newText || font != newFont || justification != newJustification
  70470. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70471. {
  70472. const Rectangle<float> damage (getBounds());
  70473. setBoundingBox (newBounds);
  70474. setFontSizeControlPoint (newFontPoint);
  70475. setColour (newColour);
  70476. setFont (newFont, false);
  70477. setJustification (newJustification);
  70478. setText (newText);
  70479. return damage.getUnion (getBounds());
  70480. }
  70481. return Rectangle<float>();
  70482. }
  70483. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70484. {
  70485. ValueTree tree (valueTreeType);
  70486. ValueTreeWrapper v (tree);
  70487. v.setID (getName(), 0);
  70488. v.setText (text, 0);
  70489. v.setFont (font, 0);
  70490. v.setJustification (justification, 0);
  70491. v.setColour (colour, 0);
  70492. v.setBoundingBox (bounds, 0);
  70493. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  70494. return tree;
  70495. }
  70496. END_JUCE_NAMESPACE
  70497. /*** End of inlined file: juce_DrawableText.cpp ***/
  70498. /*** Start of inlined file: juce_SVGParser.cpp ***/
  70499. BEGIN_JUCE_NAMESPACE
  70500. class SVGState
  70501. {
  70502. public:
  70503. SVGState (const XmlElement* const topLevel)
  70504. : topLevelXml (topLevel),
  70505. elementX (0), elementY (0),
  70506. width (512), height (512),
  70507. viewBoxW (0), viewBoxH (0)
  70508. {
  70509. }
  70510. ~SVGState()
  70511. {
  70512. }
  70513. Drawable* parseSVGElement (const XmlElement& xml)
  70514. {
  70515. if (! xml.hasTagName ("svg"))
  70516. return 0;
  70517. DrawableComposite* const drawable = new DrawableComposite();
  70518. drawable->setName (xml.getStringAttribute ("id"));
  70519. SVGState newState (*this);
  70520. if (xml.hasAttribute ("transform"))
  70521. newState.addTransform (xml);
  70522. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  70523. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  70524. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  70525. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  70526. if (xml.hasAttribute ("viewBox"))
  70527. {
  70528. const String viewParams (xml.getStringAttribute ("viewBox"));
  70529. int i = 0;
  70530. float vx, vy, vw, vh;
  70531. if (parseCoords (viewParams, vx, vy, i, true)
  70532. && parseCoords (viewParams, vw, vh, i, true)
  70533. && vw > 0
  70534. && vh > 0)
  70535. {
  70536. newState.viewBoxW = vw;
  70537. newState.viewBoxH = vh;
  70538. int placementFlags = 0;
  70539. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  70540. if (aspect.containsIgnoreCase ("none"))
  70541. {
  70542. placementFlags = RectanglePlacement::stretchToFit;
  70543. }
  70544. else
  70545. {
  70546. if (aspect.containsIgnoreCase ("slice"))
  70547. placementFlags |= RectanglePlacement::fillDestination;
  70548. if (aspect.containsIgnoreCase ("xMin"))
  70549. placementFlags |= RectanglePlacement::xLeft;
  70550. else if (aspect.containsIgnoreCase ("xMax"))
  70551. placementFlags |= RectanglePlacement::xRight;
  70552. else
  70553. placementFlags |= RectanglePlacement::xMid;
  70554. if (aspect.containsIgnoreCase ("yMin"))
  70555. placementFlags |= RectanglePlacement::yTop;
  70556. else if (aspect.containsIgnoreCase ("yMax"))
  70557. placementFlags |= RectanglePlacement::yBottom;
  70558. else
  70559. placementFlags |= RectanglePlacement::yMid;
  70560. }
  70561. const RectanglePlacement placement (placementFlags);
  70562. newState.transform
  70563. = placement.getTransformToFit (vx, vy, vw, vh,
  70564. 0.0f, 0.0f, newState.width, newState.height)
  70565. .followedBy (newState.transform);
  70566. }
  70567. }
  70568. else
  70569. {
  70570. if (viewBoxW == 0)
  70571. newState.viewBoxW = newState.width;
  70572. if (viewBoxH == 0)
  70573. newState.viewBoxH = newState.height;
  70574. }
  70575. newState.parseSubElements (xml, drawable);
  70576. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  70577. return drawable;
  70578. }
  70579. private:
  70580. const XmlElement* const topLevelXml;
  70581. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  70582. AffineTransform transform;
  70583. String cssStyleText;
  70584. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  70585. {
  70586. forEachXmlChildElement (xml, e)
  70587. {
  70588. Drawable* d = 0;
  70589. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  70590. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  70591. else if (e->hasTagName ("path")) d = parsePath (*e);
  70592. else if (e->hasTagName ("rect")) d = parseRect (*e);
  70593. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  70594. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  70595. else if (e->hasTagName ("line")) d = parseLine (*e);
  70596. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  70597. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  70598. else if (e->hasTagName ("text")) d = parseText (*e);
  70599. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  70600. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  70601. parentDrawable->insertDrawable (d);
  70602. }
  70603. }
  70604. DrawableComposite* parseSwitch (const XmlElement& xml)
  70605. {
  70606. const XmlElement* const group = xml.getChildByName ("g");
  70607. if (group != 0)
  70608. return parseGroupElement (*group);
  70609. return 0;
  70610. }
  70611. DrawableComposite* parseGroupElement (const XmlElement& xml)
  70612. {
  70613. DrawableComposite* const drawable = new DrawableComposite();
  70614. drawable->setName (xml.getStringAttribute ("id"));
  70615. if (xml.hasAttribute ("transform"))
  70616. {
  70617. SVGState newState (*this);
  70618. newState.addTransform (xml);
  70619. newState.parseSubElements (xml, drawable);
  70620. }
  70621. else
  70622. {
  70623. parseSubElements (xml, drawable);
  70624. }
  70625. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  70626. return drawable;
  70627. }
  70628. Drawable* parsePath (const XmlElement& xml) const
  70629. {
  70630. const String d (xml.getStringAttribute ("d").trimStart());
  70631. Path path;
  70632. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  70633. path.setUsingNonZeroWinding (false);
  70634. int index = 0;
  70635. float lastX = 0, lastY = 0;
  70636. float lastX2 = 0, lastY2 = 0;
  70637. juce_wchar lastCommandChar = 0;
  70638. bool isRelative = true;
  70639. bool carryOn = true;
  70640. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  70641. while (d[index] != 0)
  70642. {
  70643. float x, y, x2, y2, x3, y3;
  70644. if (validCommandChars.containsChar (d[index]))
  70645. {
  70646. lastCommandChar = d [index++];
  70647. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  70648. }
  70649. switch (lastCommandChar)
  70650. {
  70651. case 'M':
  70652. case 'm':
  70653. case 'L':
  70654. case 'l':
  70655. if (parseCoords (d, x, y, index, false))
  70656. {
  70657. if (isRelative)
  70658. {
  70659. x += lastX;
  70660. y += lastY;
  70661. }
  70662. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  70663. {
  70664. path.startNewSubPath (x, y);
  70665. lastCommandChar = 'l';
  70666. }
  70667. else
  70668. path.lineTo (x, y);
  70669. lastX2 = lastX;
  70670. lastY2 = lastY;
  70671. lastX = x;
  70672. lastY = y;
  70673. }
  70674. else
  70675. {
  70676. ++index;
  70677. }
  70678. break;
  70679. case 'H':
  70680. case 'h':
  70681. if (parseCoord (d, x, index, false, true))
  70682. {
  70683. if (isRelative)
  70684. x += lastX;
  70685. path.lineTo (x, lastY);
  70686. lastX2 = lastX;
  70687. lastX = x;
  70688. }
  70689. else
  70690. {
  70691. ++index;
  70692. }
  70693. break;
  70694. case 'V':
  70695. case 'v':
  70696. if (parseCoord (d, y, index, false, false))
  70697. {
  70698. if (isRelative)
  70699. y += lastY;
  70700. path.lineTo (lastX, y);
  70701. lastY2 = lastY;
  70702. lastY = y;
  70703. }
  70704. else
  70705. {
  70706. ++index;
  70707. }
  70708. break;
  70709. case 'C':
  70710. case 'c':
  70711. if (parseCoords (d, x, y, index, false)
  70712. && parseCoords (d, x2, y2, index, false)
  70713. && parseCoords (d, x3, y3, index, false))
  70714. {
  70715. if (isRelative)
  70716. {
  70717. x += lastX;
  70718. y += lastY;
  70719. x2 += lastX;
  70720. y2 += lastY;
  70721. x3 += lastX;
  70722. y3 += lastY;
  70723. }
  70724. path.cubicTo (x, y, x2, y2, x3, y3);
  70725. lastX2 = x2;
  70726. lastY2 = y2;
  70727. lastX = x3;
  70728. lastY = y3;
  70729. }
  70730. else
  70731. {
  70732. ++index;
  70733. }
  70734. break;
  70735. case 'S':
  70736. case 's':
  70737. if (parseCoords (d, x, y, index, false)
  70738. && parseCoords (d, x3, y3, index, false))
  70739. {
  70740. if (isRelative)
  70741. {
  70742. x += lastX;
  70743. y += lastY;
  70744. x3 += lastX;
  70745. y3 += lastY;
  70746. }
  70747. x2 = lastX + (lastX - lastX2);
  70748. y2 = lastY + (lastY - lastY2);
  70749. path.cubicTo (x2, y2, x, y, x3, y3);
  70750. lastX2 = x;
  70751. lastY2 = y;
  70752. lastX = x3;
  70753. lastY = y3;
  70754. }
  70755. else
  70756. {
  70757. ++index;
  70758. }
  70759. break;
  70760. case 'Q':
  70761. case 'q':
  70762. if (parseCoords (d, x, y, index, false)
  70763. && parseCoords (d, x2, y2, index, false))
  70764. {
  70765. if (isRelative)
  70766. {
  70767. x += lastX;
  70768. y += lastY;
  70769. x2 += lastX;
  70770. y2 += lastY;
  70771. }
  70772. path.quadraticTo (x, y, x2, y2);
  70773. lastX2 = x;
  70774. lastY2 = y;
  70775. lastX = x2;
  70776. lastY = y2;
  70777. }
  70778. else
  70779. {
  70780. ++index;
  70781. }
  70782. break;
  70783. case 'T':
  70784. case 't':
  70785. if (parseCoords (d, x, y, index, false))
  70786. {
  70787. if (isRelative)
  70788. {
  70789. x += lastX;
  70790. y += lastY;
  70791. }
  70792. x2 = lastX + (lastX - lastX2);
  70793. y2 = lastY + (lastY - lastY2);
  70794. path.quadraticTo (x2, y2, x, y);
  70795. lastX2 = x2;
  70796. lastY2 = y2;
  70797. lastX = x;
  70798. lastY = y;
  70799. }
  70800. else
  70801. {
  70802. ++index;
  70803. }
  70804. break;
  70805. case 'A':
  70806. case 'a':
  70807. if (parseCoords (d, x, y, index, false))
  70808. {
  70809. String num;
  70810. if (parseNextNumber (d, num, index, false))
  70811. {
  70812. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  70813. if (parseNextNumber (d, num, index, false))
  70814. {
  70815. const bool largeArc = num.getIntValue() != 0;
  70816. if (parseNextNumber (d, num, index, false))
  70817. {
  70818. const bool sweep = num.getIntValue() != 0;
  70819. if (parseCoords (d, x2, y2, index, false))
  70820. {
  70821. if (isRelative)
  70822. {
  70823. x2 += lastX;
  70824. y2 += lastY;
  70825. }
  70826. if (lastX != x2 || lastY != y2)
  70827. {
  70828. double centreX, centreY, startAngle, deltaAngle;
  70829. double rx = x, ry = y;
  70830. endpointToCentreParameters (lastX, lastY, x2, y2,
  70831. angle, largeArc, sweep,
  70832. rx, ry, centreX, centreY,
  70833. startAngle, deltaAngle);
  70834. path.addCentredArc ((float) centreX, (float) centreY,
  70835. (float) rx, (float) ry,
  70836. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  70837. false);
  70838. path.lineTo (x2, y2);
  70839. }
  70840. lastX2 = lastX;
  70841. lastY2 = lastY;
  70842. lastX = x2;
  70843. lastY = y2;
  70844. }
  70845. }
  70846. }
  70847. }
  70848. }
  70849. else
  70850. {
  70851. ++index;
  70852. }
  70853. break;
  70854. case 'Z':
  70855. case 'z':
  70856. path.closeSubPath();
  70857. while (CharacterFunctions::isWhitespace (d [index]))
  70858. ++index;
  70859. break;
  70860. default:
  70861. carryOn = false;
  70862. break;
  70863. }
  70864. if (! carryOn)
  70865. break;
  70866. }
  70867. return parseShape (xml, path);
  70868. }
  70869. Drawable* parseRect (const XmlElement& xml) const
  70870. {
  70871. Path rect;
  70872. const bool hasRX = xml.hasAttribute ("rx");
  70873. const bool hasRY = xml.hasAttribute ("ry");
  70874. if (hasRX || hasRY)
  70875. {
  70876. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70877. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70878. if (! hasRX)
  70879. rx = ry;
  70880. else if (! hasRY)
  70881. ry = rx;
  70882. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  70883. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  70884. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  70885. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  70886. rx, ry);
  70887. }
  70888. else
  70889. {
  70890. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  70891. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  70892. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  70893. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  70894. }
  70895. return parseShape (xml, rect);
  70896. }
  70897. Drawable* parseCircle (const XmlElement& xml) const
  70898. {
  70899. Path circle;
  70900. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70901. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70902. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  70903. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  70904. return parseShape (xml, circle);
  70905. }
  70906. Drawable* parseEllipse (const XmlElement& xml) const
  70907. {
  70908. Path ellipse;
  70909. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70910. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70911. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70912. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70913. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  70914. return parseShape (xml, ellipse);
  70915. }
  70916. Drawable* parseLine (const XmlElement& xml) const
  70917. {
  70918. Path line;
  70919. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  70920. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  70921. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  70922. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  70923. line.startNewSubPath (x1, y1);
  70924. line.lineTo (x2, y2);
  70925. return parseShape (xml, line);
  70926. }
  70927. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  70928. {
  70929. const String points (xml.getStringAttribute ("points"));
  70930. Path path;
  70931. int index = 0;
  70932. float x, y;
  70933. if (parseCoords (points, x, y, index, true))
  70934. {
  70935. float firstX = x;
  70936. float firstY = y;
  70937. float lastX = 0, lastY = 0;
  70938. path.startNewSubPath (x, y);
  70939. while (parseCoords (points, x, y, index, true))
  70940. {
  70941. lastX = x;
  70942. lastY = y;
  70943. path.lineTo (x, y);
  70944. }
  70945. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  70946. path.closeSubPath();
  70947. }
  70948. return parseShape (xml, path);
  70949. }
  70950. Drawable* parseShape (const XmlElement& xml, Path& path,
  70951. const bool shouldParseTransform = true) const
  70952. {
  70953. if (shouldParseTransform && xml.hasAttribute ("transform"))
  70954. {
  70955. SVGState newState (*this);
  70956. newState.addTransform (xml);
  70957. return newState.parseShape (xml, path, false);
  70958. }
  70959. DrawablePath* dp = new DrawablePath();
  70960. dp->setName (xml.getStringAttribute ("id"));
  70961. dp->setFill (Colours::transparentBlack);
  70962. path.applyTransform (transform);
  70963. dp->setPath (path);
  70964. Path::Iterator iter (path);
  70965. bool containsClosedSubPath = false;
  70966. while (iter.next())
  70967. {
  70968. if (iter.elementType == Path::Iterator::closePath)
  70969. {
  70970. containsClosedSubPath = true;
  70971. break;
  70972. }
  70973. }
  70974. dp->setFill (getPathFillType (path,
  70975. getStyleAttribute (&xml, "fill"),
  70976. getStyleAttribute (&xml, "fill-opacity"),
  70977. getStyleAttribute (&xml, "opacity"),
  70978. containsClosedSubPath ? Colours::black
  70979. : Colours::transparentBlack));
  70980. const String strokeType (getStyleAttribute (&xml, "stroke"));
  70981. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  70982. {
  70983. dp->setStrokeFill (getPathFillType (path, strokeType,
  70984. getStyleAttribute (&xml, "stroke-opacity"),
  70985. getStyleAttribute (&xml, "opacity"),
  70986. Colours::transparentBlack));
  70987. dp->setStrokeType (getStrokeFor (&xml));
  70988. }
  70989. return dp;
  70990. }
  70991. const XmlElement* findLinkedElement (const XmlElement* e) const
  70992. {
  70993. const String id (e->getStringAttribute ("xlink:href"));
  70994. if (! id.startsWithChar ('#'))
  70995. return 0;
  70996. return findElementForId (topLevelXml, id.substring (1));
  70997. }
  70998. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  70999. {
  71000. if (fillXml == 0)
  71001. return;
  71002. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71003. {
  71004. int index = 0;
  71005. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71006. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71007. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71008. double offset = e->getDoubleAttribute ("offset");
  71009. if (e->getStringAttribute ("offset").containsChar ('%'))
  71010. offset *= 0.01;
  71011. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71012. }
  71013. }
  71014. const FillType getPathFillType (const Path& path,
  71015. const String& fill,
  71016. const String& fillOpacity,
  71017. const String& overallOpacity,
  71018. const Colour& defaultColour) const
  71019. {
  71020. float opacity = 1.0f;
  71021. if (overallOpacity.isNotEmpty())
  71022. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71023. if (fillOpacity.isNotEmpty())
  71024. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71025. if (fill.startsWithIgnoreCase ("url"))
  71026. {
  71027. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71028. .upToLastOccurrenceOf (")", false, false).trim());
  71029. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71030. if (fillXml != 0
  71031. && (fillXml->hasTagName ("linearGradient")
  71032. || fillXml->hasTagName ("radialGradient")))
  71033. {
  71034. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71035. ColourGradient gradient;
  71036. addGradientStopsIn (gradient, inheritedFrom);
  71037. addGradientStopsIn (gradient, fillXml);
  71038. if (gradient.getNumColours() > 0)
  71039. {
  71040. gradient.addColour (0.0, gradient.getColour (0));
  71041. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71042. }
  71043. else
  71044. {
  71045. gradient.addColour (0.0, Colours::black);
  71046. gradient.addColour (1.0, Colours::black);
  71047. }
  71048. if (overallOpacity.isNotEmpty())
  71049. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71050. jassert (gradient.getNumColours() > 0);
  71051. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71052. float gradientWidth = viewBoxW;
  71053. float gradientHeight = viewBoxH;
  71054. float dx = 0.0f;
  71055. float dy = 0.0f;
  71056. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71057. if (! userSpace)
  71058. {
  71059. const Rectangle<float> bounds (path.getBounds());
  71060. dx = bounds.getX();
  71061. dy = bounds.getY();
  71062. gradientWidth = bounds.getWidth();
  71063. gradientHeight = bounds.getHeight();
  71064. }
  71065. if (gradient.isRadial)
  71066. {
  71067. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71068. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71069. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71070. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71071. //xxx (the fx, fy focal point isn't handled properly here..)
  71072. }
  71073. else
  71074. {
  71075. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71076. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71077. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71078. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71079. if (gradient.point1 == gradient.point2)
  71080. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71081. }
  71082. FillType type (gradient);
  71083. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71084. .followedBy (transform);
  71085. return type;
  71086. }
  71087. }
  71088. if (fill.equalsIgnoreCase ("none"))
  71089. return Colours::transparentBlack;
  71090. int i = 0;
  71091. const Colour colour (parseColour (fill, i, defaultColour));
  71092. return colour.withMultipliedAlpha (opacity);
  71093. }
  71094. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71095. {
  71096. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71097. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71098. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71099. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71100. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71101. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71102. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71103. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71104. if (join.equalsIgnoreCase ("round"))
  71105. joinStyle = PathStrokeType::curved;
  71106. else if (join.equalsIgnoreCase ("bevel"))
  71107. joinStyle = PathStrokeType::beveled;
  71108. if (cap.equalsIgnoreCase ("round"))
  71109. capStyle = PathStrokeType::rounded;
  71110. else if (cap.equalsIgnoreCase ("square"))
  71111. capStyle = PathStrokeType::square;
  71112. float ox = 0.0f, oy = 0.0f;
  71113. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71114. transform.transformPoints (ox, oy, x, y);
  71115. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71116. joinStyle, capStyle);
  71117. }
  71118. Drawable* parseText (const XmlElement& xml)
  71119. {
  71120. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71121. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71122. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71123. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71124. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71125. //xxx not done text yet!
  71126. forEachXmlChildElement (xml, e)
  71127. {
  71128. if (e->isTextElement())
  71129. {
  71130. const String text (e->getText());
  71131. Path path;
  71132. Drawable* s = parseShape (*e, path);
  71133. delete s;
  71134. }
  71135. else if (e->hasTagName ("tspan"))
  71136. {
  71137. Drawable* s = parseText (*e);
  71138. delete s;
  71139. }
  71140. }
  71141. return 0;
  71142. }
  71143. void addTransform (const XmlElement& xml)
  71144. {
  71145. transform = parseTransform (xml.getStringAttribute ("transform"))
  71146. .followedBy (transform);
  71147. }
  71148. bool parseCoord (const String& s, float& value, int& index,
  71149. const bool allowUnits, const bool isX) const
  71150. {
  71151. String number;
  71152. if (! parseNextNumber (s, number, index, allowUnits))
  71153. {
  71154. value = 0;
  71155. return false;
  71156. }
  71157. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71158. return true;
  71159. }
  71160. bool parseCoords (const String& s, float& x, float& y,
  71161. int& index, const bool allowUnits) const
  71162. {
  71163. return parseCoord (s, x, index, allowUnits, true)
  71164. && parseCoord (s, y, index, allowUnits, false);
  71165. }
  71166. float getCoordLength (const String& s, const float sizeForProportions) const
  71167. {
  71168. float n = s.getFloatValue();
  71169. const int len = s.length();
  71170. if (len > 2)
  71171. {
  71172. const float dpi = 96.0f;
  71173. const juce_wchar n1 = s [len - 2];
  71174. const juce_wchar n2 = s [len - 1];
  71175. if (n1 == 'i' && n2 == 'n')
  71176. n *= dpi;
  71177. else if (n1 == 'm' && n2 == 'm')
  71178. n *= dpi / 25.4f;
  71179. else if (n1 == 'c' && n2 == 'm')
  71180. n *= dpi / 2.54f;
  71181. else if (n1 == 'p' && n2 == 'c')
  71182. n *= 15.0f;
  71183. else if (n2 == '%')
  71184. n *= 0.01f * sizeForProportions;
  71185. }
  71186. return n;
  71187. }
  71188. void getCoordList (Array <float>& coords, const String& list,
  71189. const bool allowUnits, const bool isX) const
  71190. {
  71191. int index = 0;
  71192. float value;
  71193. while (parseCoord (list, value, index, allowUnits, isX))
  71194. coords.add (value);
  71195. }
  71196. void parseCSSStyle (const XmlElement& xml)
  71197. {
  71198. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71199. }
  71200. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71201. const String& defaultValue = String::empty) const
  71202. {
  71203. if (xml->hasAttribute (attributeName))
  71204. return xml->getStringAttribute (attributeName, defaultValue);
  71205. const String styleAtt (xml->getStringAttribute ("style"));
  71206. if (styleAtt.isNotEmpty())
  71207. {
  71208. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71209. if (value.isNotEmpty())
  71210. return value;
  71211. }
  71212. else if (xml->hasAttribute ("class"))
  71213. {
  71214. const String className ("." + xml->getStringAttribute ("class"));
  71215. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71216. if (index < 0)
  71217. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71218. if (index >= 0)
  71219. {
  71220. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71221. if (openBracket > index)
  71222. {
  71223. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71224. if (closeBracket > openBracket)
  71225. {
  71226. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71227. if (value.isNotEmpty())
  71228. return value;
  71229. }
  71230. }
  71231. }
  71232. }
  71233. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71234. if (xml != 0)
  71235. return getStyleAttribute (xml, attributeName, defaultValue);
  71236. return defaultValue;
  71237. }
  71238. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71239. {
  71240. if (xml->hasAttribute (attributeName))
  71241. return xml->getStringAttribute (attributeName);
  71242. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71243. if (xml != 0)
  71244. return getInheritedAttribute (xml, attributeName);
  71245. return String::empty;
  71246. }
  71247. static bool isIdentifierChar (const juce_wchar c)
  71248. {
  71249. return CharacterFunctions::isLetter (c) || c == '-';
  71250. }
  71251. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71252. {
  71253. int i = 0;
  71254. for (;;)
  71255. {
  71256. i = list.indexOf (i, attributeName);
  71257. if (i < 0)
  71258. break;
  71259. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71260. && ! isIdentifierChar (list [i + attributeName.length()]))
  71261. {
  71262. i = list.indexOfChar (i, ':');
  71263. if (i < 0)
  71264. break;
  71265. int end = list.indexOfChar (i, ';');
  71266. if (end < 0)
  71267. end = 0x7ffff;
  71268. return list.substring (i + 1, end).trim();
  71269. }
  71270. ++i;
  71271. }
  71272. return defaultValue;
  71273. }
  71274. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71275. {
  71276. const juce_wchar* const s = source;
  71277. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71278. ++index;
  71279. int start = index;
  71280. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71281. ++index;
  71282. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71283. ++index;
  71284. if ((s[index] == 'e' || s[index] == 'E')
  71285. && (CharacterFunctions::isDigit (s[index + 1])
  71286. || s[index + 1] == '-'
  71287. || s[index + 1] == '+'))
  71288. {
  71289. index += 2;
  71290. while (CharacterFunctions::isDigit (s[index]))
  71291. ++index;
  71292. }
  71293. if (allowUnits)
  71294. {
  71295. while (CharacterFunctions::isLetter (s[index]))
  71296. ++index;
  71297. }
  71298. if (index == start)
  71299. return false;
  71300. value = String (s + start, index - start);
  71301. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71302. ++index;
  71303. return true;
  71304. }
  71305. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71306. {
  71307. if (s [index] == '#')
  71308. {
  71309. uint32 hex [6];
  71310. zeromem (hex, sizeof (hex));
  71311. int numChars = 0;
  71312. for (int i = 6; --i >= 0;)
  71313. {
  71314. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71315. if (hexValue >= 0)
  71316. hex [numChars++] = hexValue;
  71317. else
  71318. break;
  71319. }
  71320. if (numChars <= 3)
  71321. return Colour ((uint8) (hex [0] * 0x11),
  71322. (uint8) (hex [1] * 0x11),
  71323. (uint8) (hex [2] * 0x11));
  71324. else
  71325. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71326. (uint8) ((hex [2] << 4) + hex [3]),
  71327. (uint8) ((hex [4] << 4) + hex [5]));
  71328. }
  71329. else if (s [index] == 'r'
  71330. && s [index + 1] == 'g'
  71331. && s [index + 2] == 'b')
  71332. {
  71333. const int openBracket = s.indexOfChar (index, '(');
  71334. const int closeBracket = s.indexOfChar (openBracket, ')');
  71335. if (openBracket >= 3 && closeBracket > openBracket)
  71336. {
  71337. index = closeBracket;
  71338. StringArray tokens;
  71339. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71340. tokens.trim();
  71341. tokens.removeEmptyStrings();
  71342. if (tokens[0].containsChar ('%'))
  71343. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71344. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71345. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71346. else
  71347. return Colour ((uint8) tokens[0].getIntValue(),
  71348. (uint8) tokens[1].getIntValue(),
  71349. (uint8) tokens[2].getIntValue());
  71350. }
  71351. }
  71352. return Colours::findColourForName (s, defaultColour);
  71353. }
  71354. static const AffineTransform parseTransform (String t)
  71355. {
  71356. AffineTransform result;
  71357. while (t.isNotEmpty())
  71358. {
  71359. StringArray tokens;
  71360. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71361. .upToFirstOccurrenceOf (")", false, false),
  71362. ", ", String::empty);
  71363. tokens.removeEmptyStrings (true);
  71364. float numbers [6];
  71365. for (int i = 0; i < 6; ++i)
  71366. numbers[i] = tokens[i].getFloatValue();
  71367. AffineTransform trans;
  71368. if (t.startsWithIgnoreCase ("matrix"))
  71369. {
  71370. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71371. numbers[1], numbers[3], numbers[5]);
  71372. }
  71373. else if (t.startsWithIgnoreCase ("translate"))
  71374. {
  71375. jassert (tokens.size() == 2);
  71376. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71377. }
  71378. else if (t.startsWithIgnoreCase ("scale"))
  71379. {
  71380. if (tokens.size() == 1)
  71381. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71382. else
  71383. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71384. }
  71385. else if (t.startsWithIgnoreCase ("rotate"))
  71386. {
  71387. if (tokens.size() != 3)
  71388. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71389. else
  71390. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71391. numbers[1], numbers[2]);
  71392. }
  71393. else if (t.startsWithIgnoreCase ("skewX"))
  71394. {
  71395. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71396. 0.0f, 1.0f, 0.0f);
  71397. }
  71398. else if (t.startsWithIgnoreCase ("skewY"))
  71399. {
  71400. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71401. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71402. }
  71403. result = trans.followedBy (result);
  71404. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71405. }
  71406. return result;
  71407. }
  71408. static void endpointToCentreParameters (const double x1, const double y1,
  71409. const double x2, const double y2,
  71410. const double angle,
  71411. const bool largeArc, const bool sweep,
  71412. double& rx, double& ry,
  71413. double& centreX, double& centreY,
  71414. double& startAngle, double& deltaAngle)
  71415. {
  71416. const double midX = (x1 - x2) * 0.5;
  71417. const double midY = (y1 - y2) * 0.5;
  71418. const double cosAngle = cos (angle);
  71419. const double sinAngle = sin (angle);
  71420. const double xp = cosAngle * midX + sinAngle * midY;
  71421. const double yp = cosAngle * midY - sinAngle * midX;
  71422. const double xp2 = xp * xp;
  71423. const double yp2 = yp * yp;
  71424. double rx2 = rx * rx;
  71425. double ry2 = ry * ry;
  71426. const double s = (xp2 / rx2) + (yp2 / ry2);
  71427. double c;
  71428. if (s <= 1.0)
  71429. {
  71430. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71431. / (( rx2 * yp2) + (ry2 * xp2))));
  71432. if (largeArc == sweep)
  71433. c = -c;
  71434. }
  71435. else
  71436. {
  71437. const double s2 = std::sqrt (s);
  71438. rx *= s2;
  71439. ry *= s2;
  71440. rx2 = rx * rx;
  71441. ry2 = ry * ry;
  71442. c = 0;
  71443. }
  71444. const double cpx = ((rx * yp) / ry) * c;
  71445. const double cpy = ((-ry * xp) / rx) * c;
  71446. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71447. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71448. const double ux = (xp - cpx) / rx;
  71449. const double uy = (yp - cpy) / ry;
  71450. const double vx = (-xp - cpx) / rx;
  71451. const double vy = (-yp - cpy) / ry;
  71452. const double length = juce_hypot (ux, uy);
  71453. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71454. if (uy < 0)
  71455. startAngle = -startAngle;
  71456. startAngle += double_Pi * 0.5;
  71457. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71458. / (length * juce_hypot (vx, vy))));
  71459. if ((ux * vy) - (uy * vx) < 0)
  71460. deltaAngle = -deltaAngle;
  71461. if (sweep)
  71462. {
  71463. if (deltaAngle < 0)
  71464. deltaAngle += double_Pi * 2.0;
  71465. }
  71466. else
  71467. {
  71468. if (deltaAngle > 0)
  71469. deltaAngle -= double_Pi * 2.0;
  71470. }
  71471. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71472. }
  71473. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71474. {
  71475. forEachXmlChildElement (*parent, e)
  71476. {
  71477. if (e->compareAttribute ("id", id))
  71478. return e;
  71479. const XmlElement* const found = findElementForId (e, id);
  71480. if (found != 0)
  71481. return found;
  71482. }
  71483. return 0;
  71484. }
  71485. SVGState& operator= (const SVGState&);
  71486. };
  71487. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  71488. {
  71489. SVGState state (&svgDocument);
  71490. return state.parseSVGElement (svgDocument);
  71491. }
  71492. END_JUCE_NAMESPACE
  71493. /*** End of inlined file: juce_SVGParser.cpp ***/
  71494. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  71495. BEGIN_JUCE_NAMESPACE
  71496. #if JUCE_MSVC && JUCE_DEBUG
  71497. #pragma optimize ("t", on)
  71498. #endif
  71499. DropShadowEffect::DropShadowEffect()
  71500. : offsetX (0),
  71501. offsetY (0),
  71502. radius (4),
  71503. opacity (0.6f)
  71504. {
  71505. }
  71506. DropShadowEffect::~DropShadowEffect()
  71507. {
  71508. }
  71509. void DropShadowEffect::setShadowProperties (const float newRadius,
  71510. const float newOpacity,
  71511. const int newShadowOffsetX,
  71512. const int newShadowOffsetY)
  71513. {
  71514. radius = jmax (1.1f, newRadius);
  71515. offsetX = newShadowOffsetX;
  71516. offsetY = newShadowOffsetY;
  71517. opacity = newOpacity;
  71518. }
  71519. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  71520. {
  71521. const int w = image.getWidth();
  71522. const int h = image.getHeight();
  71523. Image shadowImage (Image::SingleChannel, w, h, false);
  71524. const Image::BitmapData srcData (image, false);
  71525. const Image::BitmapData destData (shadowImage, true);
  71526. const int filter = roundToInt (63.0f / radius);
  71527. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  71528. for (int x = w; --x >= 0;)
  71529. {
  71530. int shadowAlpha = 0;
  71531. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  71532. uint8* shadowPix = destData.data + x;
  71533. for (int y = h; --y >= 0;)
  71534. {
  71535. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  71536. *shadowPix = (uint8) shadowAlpha;
  71537. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  71538. shadowPix += destData.lineStride;
  71539. }
  71540. }
  71541. for (int y = h; --y >= 0;)
  71542. {
  71543. int shadowAlpha = 0;
  71544. uint8* shadowPix = destData.getLinePointer (y);
  71545. for (int x = w; --x >= 0;)
  71546. {
  71547. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  71548. *shadowPix++ = (uint8) shadowAlpha;
  71549. }
  71550. }
  71551. g.setColour (Colours::black.withAlpha (opacity));
  71552. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  71553. g.setOpacity (1.0f);
  71554. g.drawImageAt (image, 0, 0);
  71555. }
  71556. #if JUCE_MSVC && JUCE_DEBUG
  71557. #pragma optimize ("", on) // resets optimisations to the project defaults
  71558. #endif
  71559. END_JUCE_NAMESPACE
  71560. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  71561. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  71562. BEGIN_JUCE_NAMESPACE
  71563. GlowEffect::GlowEffect()
  71564. : radius (2.0f),
  71565. colour (Colours::white)
  71566. {
  71567. }
  71568. GlowEffect::~GlowEffect()
  71569. {
  71570. }
  71571. void GlowEffect::setGlowProperties (const float newRadius,
  71572. const Colour& newColour)
  71573. {
  71574. radius = newRadius;
  71575. colour = newColour;
  71576. }
  71577. void GlowEffect::applyEffect (Image& image, Graphics& g)
  71578. {
  71579. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  71580. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  71581. blurKernel.createGaussianBlur (radius);
  71582. blurKernel.rescaleAllValues (radius);
  71583. blurKernel.applyToImage (temp, image, image.getBounds());
  71584. g.setColour (colour);
  71585. g.drawImageAt (temp, 0, 0, true);
  71586. g.setOpacity (1.0f);
  71587. g.drawImageAt (image, 0, 0, false);
  71588. }
  71589. END_JUCE_NAMESPACE
  71590. /*** End of inlined file: juce_GlowEffect.cpp ***/
  71591. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  71592. BEGIN_JUCE_NAMESPACE
  71593. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  71594. : opacity (opacity_)
  71595. {
  71596. }
  71597. ReduceOpacityEffect::~ReduceOpacityEffect()
  71598. {
  71599. }
  71600. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  71601. {
  71602. opacity = jlimit (0.0f, 1.0f, newOpacity);
  71603. }
  71604. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  71605. {
  71606. g.setOpacity (opacity);
  71607. g.drawImageAt (image, 0, 0);
  71608. }
  71609. END_JUCE_NAMESPACE
  71610. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  71611. /*** Start of inlined file: juce_Font.cpp ***/
  71612. BEGIN_JUCE_NAMESPACE
  71613. namespace FontValues
  71614. {
  71615. static float limitFontHeight (const float height) throw()
  71616. {
  71617. return jlimit (0.1f, 10000.0f, height);
  71618. }
  71619. static const float defaultFontHeight = 14.0f;
  71620. static String fallbackFont;
  71621. }
  71622. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  71623. const float kerning_, const float ascent_, const int styleFlags_,
  71624. Typeface* const typeface_) throw()
  71625. : typefaceName (typefaceName_),
  71626. height (height_),
  71627. horizontalScale (horizontalScale_),
  71628. kerning (kerning_),
  71629. ascent (ascent_),
  71630. styleFlags (styleFlags_),
  71631. typeface (typeface_)
  71632. {
  71633. }
  71634. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  71635. : typefaceName (other.typefaceName),
  71636. height (other.height),
  71637. horizontalScale (other.horizontalScale),
  71638. kerning (other.kerning),
  71639. ascent (other.ascent),
  71640. styleFlags (other.styleFlags),
  71641. typeface (other.typeface)
  71642. {
  71643. }
  71644. Font::Font() throw()
  71645. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  71646. 1.0f, 0, 0, Font::plain, 0))
  71647. {
  71648. }
  71649. Font::Font (const float fontHeight, const int styleFlags_) throw()
  71650. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  71651. 1.0f, 0, 0, styleFlags_, 0))
  71652. {
  71653. }
  71654. Font::Font (const String& typefaceName_,
  71655. const float fontHeight,
  71656. const int styleFlags_) throw()
  71657. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  71658. 1.0f, 0, 0, styleFlags_, 0))
  71659. {
  71660. }
  71661. Font::Font (const Font& other) throw()
  71662. : font (other.font)
  71663. {
  71664. }
  71665. Font& Font::operator= (const Font& other) throw()
  71666. {
  71667. font = other.font;
  71668. return *this;
  71669. }
  71670. Font::~Font() throw()
  71671. {
  71672. }
  71673. Font::Font (const Typeface::Ptr& typeface) throw()
  71674. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  71675. 1.0f, 0, 0, Font::plain, typeface))
  71676. {
  71677. }
  71678. bool Font::operator== (const Font& other) const throw()
  71679. {
  71680. return font == other.font
  71681. || (font->height == other.font->height
  71682. && font->styleFlags == other.font->styleFlags
  71683. && font->horizontalScale == other.font->horizontalScale
  71684. && font->kerning == other.font->kerning
  71685. && font->typefaceName == other.font->typefaceName);
  71686. }
  71687. bool Font::operator!= (const Font& other) const throw()
  71688. {
  71689. return ! operator== (other);
  71690. }
  71691. void Font::dupeInternalIfShared() throw()
  71692. {
  71693. if (font->getReferenceCount() > 1)
  71694. font = new SharedFontInternal (*font);
  71695. }
  71696. const String Font::getDefaultSansSerifFontName() throw()
  71697. {
  71698. static const String name ("<Sans-Serif>");
  71699. return name;
  71700. }
  71701. const String Font::getDefaultSerifFontName() throw()
  71702. {
  71703. static const String name ("<Serif>");
  71704. return name;
  71705. }
  71706. const String Font::getDefaultMonospacedFontName() throw()
  71707. {
  71708. static const String name ("<Monospaced>");
  71709. return name;
  71710. }
  71711. void Font::setTypefaceName (const String& faceName) throw()
  71712. {
  71713. if (faceName != font->typefaceName)
  71714. {
  71715. dupeInternalIfShared();
  71716. font->typefaceName = faceName;
  71717. font->typeface = 0;
  71718. font->ascent = 0;
  71719. }
  71720. }
  71721. const String Font::getFallbackFontName() throw()
  71722. {
  71723. return FontValues::fallbackFont;
  71724. }
  71725. void Font::setFallbackFontName (const String& name) throw()
  71726. {
  71727. FontValues::fallbackFont = name;
  71728. }
  71729. void Font::setHeight (float newHeight) throw()
  71730. {
  71731. newHeight = FontValues::limitFontHeight (newHeight);
  71732. if (font->height != newHeight)
  71733. {
  71734. dupeInternalIfShared();
  71735. font->height = newHeight;
  71736. }
  71737. }
  71738. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  71739. {
  71740. newHeight = FontValues::limitFontHeight (newHeight);
  71741. if (font->height != newHeight)
  71742. {
  71743. dupeInternalIfShared();
  71744. font->horizontalScale *= (font->height / newHeight);
  71745. font->height = newHeight;
  71746. }
  71747. }
  71748. void Font::setStyleFlags (const int newFlags) throw()
  71749. {
  71750. if (font->styleFlags != newFlags)
  71751. {
  71752. dupeInternalIfShared();
  71753. font->styleFlags = newFlags;
  71754. font->typeface = 0;
  71755. font->ascent = 0;
  71756. }
  71757. }
  71758. void Font::setSizeAndStyle (float newHeight,
  71759. const int newStyleFlags,
  71760. const float newHorizontalScale,
  71761. const float newKerningAmount) throw()
  71762. {
  71763. newHeight = FontValues::limitFontHeight (newHeight);
  71764. if (font->height != newHeight
  71765. || font->horizontalScale != newHorizontalScale
  71766. || font->kerning != newKerningAmount)
  71767. {
  71768. dupeInternalIfShared();
  71769. font->height = newHeight;
  71770. font->horizontalScale = newHorizontalScale;
  71771. font->kerning = newKerningAmount;
  71772. }
  71773. setStyleFlags (newStyleFlags);
  71774. }
  71775. void Font::setHorizontalScale (const float scaleFactor) throw()
  71776. {
  71777. dupeInternalIfShared();
  71778. font->horizontalScale = scaleFactor;
  71779. }
  71780. void Font::setExtraKerningFactor (const float extraKerning) throw()
  71781. {
  71782. dupeInternalIfShared();
  71783. font->kerning = extraKerning;
  71784. }
  71785. void Font::setBold (const bool shouldBeBold) throw()
  71786. {
  71787. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  71788. : (font->styleFlags & ~bold));
  71789. }
  71790. bool Font::isBold() const throw()
  71791. {
  71792. return (font->styleFlags & bold) != 0;
  71793. }
  71794. void Font::setItalic (const bool shouldBeItalic) throw()
  71795. {
  71796. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  71797. : (font->styleFlags & ~italic));
  71798. }
  71799. bool Font::isItalic() const throw()
  71800. {
  71801. return (font->styleFlags & italic) != 0;
  71802. }
  71803. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  71804. {
  71805. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  71806. : (font->styleFlags & ~underlined));
  71807. }
  71808. bool Font::isUnderlined() const throw()
  71809. {
  71810. return (font->styleFlags & underlined) != 0;
  71811. }
  71812. float Font::getAscent() const throw()
  71813. {
  71814. if (font->ascent == 0)
  71815. font->ascent = getTypeface()->getAscent();
  71816. return font->height * font->ascent;
  71817. }
  71818. float Font::getDescent() const throw()
  71819. {
  71820. return font->height - getAscent();
  71821. }
  71822. int Font::getStringWidth (const String& text) const throw()
  71823. {
  71824. return roundToInt (getStringWidthFloat (text));
  71825. }
  71826. float Font::getStringWidthFloat (const String& text) const throw()
  71827. {
  71828. float w = getTypeface()->getStringWidth (text);
  71829. if (font->kerning != 0)
  71830. w += font->kerning * text.length();
  71831. return w * font->height * font->horizontalScale;
  71832. }
  71833. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  71834. {
  71835. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  71836. const float scale = font->height * font->horizontalScale;
  71837. const int num = xOffsets.size();
  71838. if (num > 0)
  71839. {
  71840. float* const x = &(xOffsets.getReference(0));
  71841. if (font->kerning != 0)
  71842. {
  71843. for (int i = 0; i < num; ++i)
  71844. x[i] = (x[i] + i * font->kerning) * scale;
  71845. }
  71846. else
  71847. {
  71848. for (int i = 0; i < num; ++i)
  71849. x[i] *= scale;
  71850. }
  71851. }
  71852. }
  71853. void Font::findFonts (Array<Font>& destArray) throw()
  71854. {
  71855. const StringArray names (findAllTypefaceNames());
  71856. for (int i = 0; i < names.size(); ++i)
  71857. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  71858. }
  71859. const String Font::toString() const
  71860. {
  71861. String s (getTypefaceName());
  71862. if (s == getDefaultSansSerifFontName())
  71863. s = String::empty;
  71864. else
  71865. s += "; ";
  71866. s += String (getHeight(), 1);
  71867. if (isBold())
  71868. s += " bold";
  71869. if (isItalic())
  71870. s += " italic";
  71871. return s;
  71872. }
  71873. const Font Font::fromString (const String& fontDescription)
  71874. {
  71875. String name;
  71876. const int separator = fontDescription.indexOfChar (';');
  71877. if (separator > 0)
  71878. name = fontDescription.substring (0, separator).trim();
  71879. if (name.isEmpty())
  71880. name = getDefaultSansSerifFontName();
  71881. String sizeAndStyle (fontDescription.substring (separator + 1));
  71882. float height = sizeAndStyle.getFloatValue();
  71883. if (height <= 0)
  71884. height = 10.0f;
  71885. int flags = Font::plain;
  71886. if (sizeAndStyle.containsIgnoreCase ("bold"))
  71887. flags |= Font::bold;
  71888. if (sizeAndStyle.containsIgnoreCase ("italic"))
  71889. flags |= Font::italic;
  71890. return Font (name, height, flags);
  71891. }
  71892. class TypefaceCache : public DeletedAtShutdown
  71893. {
  71894. public:
  71895. TypefaceCache (int numToCache = 10) throw()
  71896. : counter (1)
  71897. {
  71898. while (--numToCache >= 0)
  71899. faces.add (new CachedFace());
  71900. }
  71901. ~TypefaceCache()
  71902. {
  71903. clearSingletonInstance();
  71904. }
  71905. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  71906. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  71907. {
  71908. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  71909. const String faceName (font.getTypefaceName());
  71910. int i;
  71911. for (i = faces.size(); --i >= 0;)
  71912. {
  71913. CachedFace* const face = faces.getUnchecked(i);
  71914. if (face->flags == flags
  71915. && face->typefaceName == faceName)
  71916. {
  71917. face->lastUsageCount = ++counter;
  71918. return face->typeFace;
  71919. }
  71920. }
  71921. int replaceIndex = 0;
  71922. int bestLastUsageCount = std::numeric_limits<int>::max();
  71923. for (i = faces.size(); --i >= 0;)
  71924. {
  71925. const int lu = faces.getUnchecked(i)->lastUsageCount;
  71926. if (bestLastUsageCount > lu)
  71927. {
  71928. bestLastUsageCount = lu;
  71929. replaceIndex = i;
  71930. }
  71931. }
  71932. CachedFace* const face = faces.getUnchecked (replaceIndex);
  71933. face->typefaceName = faceName;
  71934. face->flags = flags;
  71935. face->lastUsageCount = ++counter;
  71936. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  71937. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  71938. return face->typeFace;
  71939. }
  71940. juce_UseDebuggingNewOperator
  71941. private:
  71942. struct CachedFace
  71943. {
  71944. CachedFace() throw()
  71945. : lastUsageCount (0), flags (-1)
  71946. {
  71947. }
  71948. String typefaceName;
  71949. int lastUsageCount;
  71950. int flags;
  71951. Typeface::Ptr typeFace;
  71952. };
  71953. int counter;
  71954. OwnedArray <CachedFace> faces;
  71955. TypefaceCache (const TypefaceCache&);
  71956. TypefaceCache& operator= (const TypefaceCache&);
  71957. };
  71958. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  71959. Typeface* Font::getTypeface() const throw()
  71960. {
  71961. if (font->typeface == 0)
  71962. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  71963. return font->typeface;
  71964. }
  71965. END_JUCE_NAMESPACE
  71966. /*** End of inlined file: juce_Font.cpp ***/
  71967. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  71968. BEGIN_JUCE_NAMESPACE
  71969. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  71970. const juce_wchar character_, const int glyph_)
  71971. : x (x_),
  71972. y (y_),
  71973. w (w_),
  71974. font (font_),
  71975. character (character_),
  71976. glyph (glyph_)
  71977. {
  71978. }
  71979. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  71980. : x (other.x),
  71981. y (other.y),
  71982. w (other.w),
  71983. font (other.font),
  71984. character (other.character),
  71985. glyph (other.glyph)
  71986. {
  71987. }
  71988. void PositionedGlyph::draw (const Graphics& g) const
  71989. {
  71990. if (! isWhitespace())
  71991. {
  71992. g.getInternalContext()->setFont (font);
  71993. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  71994. }
  71995. }
  71996. void PositionedGlyph::draw (const Graphics& g,
  71997. const AffineTransform& transform) const
  71998. {
  71999. if (! isWhitespace())
  72000. {
  72001. g.getInternalContext()->setFont (font);
  72002. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72003. .followedBy (transform));
  72004. }
  72005. }
  72006. void PositionedGlyph::createPath (Path& path) const
  72007. {
  72008. if (! isWhitespace())
  72009. {
  72010. Typeface* const t = font.getTypeface();
  72011. if (t != 0)
  72012. {
  72013. Path p;
  72014. t->getOutlineForGlyph (glyph, p);
  72015. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72016. .translated (x, y));
  72017. }
  72018. }
  72019. }
  72020. bool PositionedGlyph::hitTest (float px, float py) const
  72021. {
  72022. if (getBounds().contains (px, py) && ! isWhitespace())
  72023. {
  72024. Typeface* const t = font.getTypeface();
  72025. if (t != 0)
  72026. {
  72027. Path p;
  72028. t->getOutlineForGlyph (glyph, p);
  72029. AffineTransform::translation (-x, -y)
  72030. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72031. .transformPoint (px, py);
  72032. return p.contains (px, py);
  72033. }
  72034. }
  72035. return false;
  72036. }
  72037. void PositionedGlyph::moveBy (const float deltaX,
  72038. const float deltaY)
  72039. {
  72040. x += deltaX;
  72041. y += deltaY;
  72042. }
  72043. GlyphArrangement::GlyphArrangement()
  72044. {
  72045. glyphs.ensureStorageAllocated (128);
  72046. }
  72047. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72048. {
  72049. addGlyphArrangement (other);
  72050. }
  72051. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72052. {
  72053. if (this != &other)
  72054. {
  72055. clear();
  72056. addGlyphArrangement (other);
  72057. }
  72058. return *this;
  72059. }
  72060. GlyphArrangement::~GlyphArrangement()
  72061. {
  72062. }
  72063. void GlyphArrangement::clear()
  72064. {
  72065. glyphs.clear();
  72066. }
  72067. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72068. {
  72069. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72070. return *glyphs [index];
  72071. }
  72072. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72073. {
  72074. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72075. glyphs.addCopiesOf (other.glyphs);
  72076. }
  72077. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72078. {
  72079. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72080. }
  72081. void GlyphArrangement::addLineOfText (const Font& font,
  72082. const String& text,
  72083. const float xOffset,
  72084. const float yOffset)
  72085. {
  72086. addCurtailedLineOfText (font, text,
  72087. xOffset, yOffset,
  72088. 1.0e10f, false);
  72089. }
  72090. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72091. const String& text,
  72092. float xOffset,
  72093. const float yOffset,
  72094. const float maxWidthPixels,
  72095. const bool useEllipsis)
  72096. {
  72097. if (text.isNotEmpty())
  72098. {
  72099. Array <int> newGlyphs;
  72100. Array <float> xOffsets;
  72101. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72102. const int textLen = newGlyphs.size();
  72103. const juce_wchar* const unicodeText = text;
  72104. for (int i = 0; i < textLen; ++i)
  72105. {
  72106. const float thisX = xOffsets.getUnchecked (i);
  72107. const float nextX = xOffsets.getUnchecked (i + 1);
  72108. if (nextX > maxWidthPixels + 1.0f)
  72109. {
  72110. // curtail the string if it's too wide..
  72111. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72112. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72113. break;
  72114. }
  72115. else
  72116. {
  72117. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72118. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72119. }
  72120. }
  72121. }
  72122. }
  72123. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72124. const int startIndex, int endIndex)
  72125. {
  72126. int numDeleted = 0;
  72127. if (glyphs.size() > 0)
  72128. {
  72129. Array<int> dotGlyphs;
  72130. Array<float> dotXs;
  72131. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72132. const float dx = dotXs[1];
  72133. float xOffset = 0.0f, yOffset = 0.0f;
  72134. while (endIndex > startIndex)
  72135. {
  72136. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72137. xOffset = pg->x;
  72138. yOffset = pg->y;
  72139. glyphs.remove (endIndex);
  72140. ++numDeleted;
  72141. if (xOffset + dx * 3 <= maxXPos)
  72142. break;
  72143. }
  72144. for (int i = 3; --i >= 0;)
  72145. {
  72146. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72147. font, '.', dotGlyphs.getFirst()));
  72148. --numDeleted;
  72149. xOffset += dx;
  72150. if (xOffset > maxXPos)
  72151. break;
  72152. }
  72153. }
  72154. return numDeleted;
  72155. }
  72156. void GlyphArrangement::addJustifiedText (const Font& font,
  72157. const String& text,
  72158. float x, float y,
  72159. const float maxLineWidth,
  72160. const Justification& horizontalLayout)
  72161. {
  72162. int lineStartIndex = glyphs.size();
  72163. addLineOfText (font, text, x, y);
  72164. const float originalY = y;
  72165. while (lineStartIndex < glyphs.size())
  72166. {
  72167. int i = lineStartIndex;
  72168. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72169. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72170. ++i;
  72171. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72172. int lastWordBreakIndex = -1;
  72173. while (i < glyphs.size())
  72174. {
  72175. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72176. const juce_wchar c = pg->getCharacter();
  72177. if (c == '\r' || c == '\n')
  72178. {
  72179. ++i;
  72180. if (c == '\r' && i < glyphs.size()
  72181. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72182. ++i;
  72183. break;
  72184. }
  72185. else if (pg->isWhitespace())
  72186. {
  72187. lastWordBreakIndex = i + 1;
  72188. }
  72189. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72190. {
  72191. if (lastWordBreakIndex >= 0)
  72192. i = lastWordBreakIndex;
  72193. break;
  72194. }
  72195. ++i;
  72196. }
  72197. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72198. float currentLineEndX = currentLineStartX;
  72199. for (int j = i; --j >= lineStartIndex;)
  72200. {
  72201. if (! glyphs.getUnchecked (j)->isWhitespace())
  72202. {
  72203. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72204. break;
  72205. }
  72206. }
  72207. float deltaX = 0.0f;
  72208. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72209. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72210. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72211. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72212. else if (horizontalLayout.testFlags (Justification::right))
  72213. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72214. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72215. x + deltaX - currentLineStartX, y - originalY);
  72216. lineStartIndex = i;
  72217. y += font.getHeight();
  72218. }
  72219. }
  72220. void GlyphArrangement::addFittedText (const Font& f,
  72221. const String& text,
  72222. const float x, const float y,
  72223. const float width, const float height,
  72224. const Justification& layout,
  72225. int maximumLines,
  72226. const float minimumHorizontalScale)
  72227. {
  72228. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72229. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72230. if (text.containsAnyOf ("\r\n"))
  72231. {
  72232. GlyphArrangement ga;
  72233. ga.addJustifiedText (f, text, x, y, width, layout);
  72234. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72235. float dy = y - bb.getY();
  72236. if (layout.testFlags (Justification::verticallyCentred))
  72237. dy += (height - bb.getHeight()) * 0.5f;
  72238. else if (layout.testFlags (Justification::bottom))
  72239. dy += height - bb.getHeight();
  72240. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72241. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72242. for (int i = 0; i < ga.glyphs.size(); ++i)
  72243. glyphs.add (ga.glyphs.getUnchecked (i));
  72244. ga.glyphs.clear (false);
  72245. return;
  72246. }
  72247. int startIndex = glyphs.size();
  72248. addLineOfText (f, text.trim(), x, y);
  72249. if (glyphs.size() > startIndex)
  72250. {
  72251. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72252. - glyphs.getUnchecked (startIndex)->getLeft();
  72253. if (lineWidth <= 0)
  72254. return;
  72255. if (lineWidth * minimumHorizontalScale < width)
  72256. {
  72257. if (lineWidth > width)
  72258. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72259. width / lineWidth);
  72260. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72261. x, y, width, height, layout);
  72262. }
  72263. else if (maximumLines <= 1)
  72264. {
  72265. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72266. x, y, width, height, f, layout, minimumHorizontalScale);
  72267. }
  72268. else
  72269. {
  72270. Font font (f);
  72271. String txt (text.trim());
  72272. const int length = txt.length();
  72273. const int originalStartIndex = startIndex;
  72274. int numLines = 1;
  72275. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72276. maximumLines = 1;
  72277. maximumLines = jmin (maximumLines, length);
  72278. while (numLines < maximumLines)
  72279. {
  72280. ++numLines;
  72281. const float newFontHeight = height / (float) numLines;
  72282. if (newFontHeight < font.getHeight())
  72283. {
  72284. font.setHeight (jmax (8.0f, newFontHeight));
  72285. removeRangeOfGlyphs (startIndex, -1);
  72286. addLineOfText (font, txt, x, y);
  72287. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72288. - glyphs.getUnchecked (startIndex)->getLeft();
  72289. }
  72290. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72291. break;
  72292. }
  72293. if (numLines < 1)
  72294. numLines = 1;
  72295. float lineY = y;
  72296. float widthPerLine = lineWidth / numLines;
  72297. int lastLineStartIndex = 0;
  72298. for (int line = 0; line < numLines; ++line)
  72299. {
  72300. int i = startIndex;
  72301. lastLineStartIndex = i;
  72302. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72303. if (line == numLines - 1)
  72304. {
  72305. widthPerLine = width;
  72306. i = glyphs.size();
  72307. }
  72308. else
  72309. {
  72310. while (i < glyphs.size())
  72311. {
  72312. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72313. if (lineWidth > widthPerLine)
  72314. {
  72315. // got to a point where the line's too long, so skip forward to find a
  72316. // good place to break it..
  72317. const int searchStartIndex = i;
  72318. while (i < glyphs.size())
  72319. {
  72320. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72321. {
  72322. if (glyphs.getUnchecked (i)->isWhitespace()
  72323. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72324. {
  72325. ++i;
  72326. break;
  72327. }
  72328. }
  72329. else
  72330. {
  72331. // can't find a suitable break, so try looking backwards..
  72332. i = searchStartIndex;
  72333. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72334. {
  72335. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72336. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72337. {
  72338. i -= back - 1;
  72339. break;
  72340. }
  72341. }
  72342. break;
  72343. }
  72344. ++i;
  72345. }
  72346. break;
  72347. }
  72348. ++i;
  72349. }
  72350. int wsStart = i;
  72351. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72352. --wsStart;
  72353. int wsEnd = i;
  72354. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72355. ++wsEnd;
  72356. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72357. i = jmax (wsStart, startIndex + 1);
  72358. }
  72359. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72360. x, lineY, width, font.getHeight(), font,
  72361. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72362. minimumHorizontalScale);
  72363. startIndex = i;
  72364. lineY += font.getHeight();
  72365. if (startIndex >= glyphs.size())
  72366. break;
  72367. }
  72368. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72369. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72370. }
  72371. }
  72372. }
  72373. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72374. const float dx, const float dy)
  72375. {
  72376. jassert (startIndex >= 0);
  72377. if (dx != 0.0f || dy != 0.0f)
  72378. {
  72379. if (num < 0 || startIndex + num > glyphs.size())
  72380. num = glyphs.size() - startIndex;
  72381. while (--num >= 0)
  72382. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72383. }
  72384. }
  72385. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72386. const Justification& justification, float minimumHorizontalScale)
  72387. {
  72388. int numDeleted = 0;
  72389. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72390. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72391. if (lineWidth > w)
  72392. {
  72393. if (minimumHorizontalScale < 1.0f)
  72394. {
  72395. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72396. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72397. }
  72398. if (lineWidth > w)
  72399. {
  72400. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72401. numGlyphs -= numDeleted;
  72402. }
  72403. }
  72404. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72405. return numDeleted;
  72406. }
  72407. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72408. const float horizontalScaleFactor)
  72409. {
  72410. jassert (startIndex >= 0);
  72411. if (num < 0 || startIndex + num > glyphs.size())
  72412. num = glyphs.size() - startIndex;
  72413. if (num > 0)
  72414. {
  72415. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72416. while (--num >= 0)
  72417. {
  72418. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72419. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72420. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72421. pg->w *= horizontalScaleFactor;
  72422. }
  72423. }
  72424. }
  72425. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72426. {
  72427. jassert (startIndex >= 0);
  72428. if (num < 0 || startIndex + num > glyphs.size())
  72429. num = glyphs.size() - startIndex;
  72430. Rectangle<float> result;
  72431. while (--num >= 0)
  72432. {
  72433. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72434. if (includeWhitespace || ! pg->isWhitespace())
  72435. result = result.getUnion (pg->getBounds());
  72436. }
  72437. return result;
  72438. }
  72439. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72440. const float x, const float y, const float width, const float height,
  72441. const Justification& justification)
  72442. {
  72443. jassert (num >= 0 && startIndex >= 0);
  72444. if (glyphs.size() > 0 && num > 0)
  72445. {
  72446. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72447. | Justification::horizontallyCentred)));
  72448. float deltaX = 0.0f;
  72449. if (justification.testFlags (Justification::horizontallyJustified))
  72450. deltaX = x - bb.getX();
  72451. else if (justification.testFlags (Justification::horizontallyCentred))
  72452. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72453. else if (justification.testFlags (Justification::right))
  72454. deltaX = (x + width) - bb.getRight();
  72455. else
  72456. deltaX = x - bb.getX();
  72457. float deltaY = 0.0f;
  72458. if (justification.testFlags (Justification::top))
  72459. deltaY = y - bb.getY();
  72460. else if (justification.testFlags (Justification::bottom))
  72461. deltaY = (y + height) - bb.getBottom();
  72462. else
  72463. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72464. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72465. if (justification.testFlags (Justification::horizontallyJustified))
  72466. {
  72467. int lineStart = 0;
  72468. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72469. int i;
  72470. for (i = 0; i < num; ++i)
  72471. {
  72472. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72473. if (glyphY != baseY)
  72474. {
  72475. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72476. lineStart = i;
  72477. baseY = glyphY;
  72478. }
  72479. }
  72480. if (i > lineStart)
  72481. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72482. }
  72483. }
  72484. }
  72485. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72486. {
  72487. if (start + num < glyphs.size()
  72488. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  72489. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  72490. {
  72491. int numSpaces = 0;
  72492. int spacesAtEnd = 0;
  72493. for (int i = 0; i < num; ++i)
  72494. {
  72495. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72496. {
  72497. ++spacesAtEnd;
  72498. ++numSpaces;
  72499. }
  72500. else
  72501. {
  72502. spacesAtEnd = 0;
  72503. }
  72504. }
  72505. numSpaces -= spacesAtEnd;
  72506. if (numSpaces > 0)
  72507. {
  72508. const float startX = glyphs.getUnchecked (start)->getLeft();
  72509. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  72510. const float extraPaddingBetweenWords
  72511. = (targetWidth - (endX - startX)) / (float) numSpaces;
  72512. float deltaX = 0.0f;
  72513. for (int i = 0; i < num; ++i)
  72514. {
  72515. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  72516. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72517. deltaX += extraPaddingBetweenWords;
  72518. }
  72519. }
  72520. }
  72521. }
  72522. void GlyphArrangement::draw (const Graphics& g) const
  72523. {
  72524. for (int i = 0; i < glyphs.size(); ++i)
  72525. {
  72526. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72527. if (pg->font.isUnderlined())
  72528. {
  72529. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72530. float nextX = pg->x + pg->w;
  72531. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72532. nextX = glyphs.getUnchecked (i + 1)->x;
  72533. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  72534. nextX - pg->x, lineThickness);
  72535. }
  72536. pg->draw (g);
  72537. }
  72538. }
  72539. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  72540. {
  72541. for (int i = 0; i < glyphs.size(); ++i)
  72542. {
  72543. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72544. if (pg->font.isUnderlined())
  72545. {
  72546. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72547. float nextX = pg->x + pg->w;
  72548. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72549. nextX = glyphs.getUnchecked (i + 1)->x;
  72550. Path p;
  72551. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  72552. nextX, pg->y + lineThickness * 2.0f),
  72553. lineThickness);
  72554. g.fillPath (p, transform);
  72555. }
  72556. pg->draw (g, transform);
  72557. }
  72558. }
  72559. void GlyphArrangement::createPath (Path& path) const
  72560. {
  72561. for (int i = 0; i < glyphs.size(); ++i)
  72562. glyphs.getUnchecked (i)->createPath (path);
  72563. }
  72564. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  72565. {
  72566. for (int i = 0; i < glyphs.size(); ++i)
  72567. if (glyphs.getUnchecked (i)->hitTest (x, y))
  72568. return i;
  72569. return -1;
  72570. }
  72571. END_JUCE_NAMESPACE
  72572. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  72573. /*** Start of inlined file: juce_TextLayout.cpp ***/
  72574. BEGIN_JUCE_NAMESPACE
  72575. class TextLayout::Token
  72576. {
  72577. public:
  72578. String text;
  72579. Font font;
  72580. int x, y, w, h;
  72581. int line, lineHeight;
  72582. bool isWhitespace, isNewLine;
  72583. Token (const String& t,
  72584. const Font& f,
  72585. const bool isWhitespace_)
  72586. : text (t),
  72587. font (f),
  72588. x(0),
  72589. y(0),
  72590. isWhitespace (isWhitespace_)
  72591. {
  72592. w = font.getStringWidth (t);
  72593. h = roundToInt (f.getHeight());
  72594. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  72595. }
  72596. Token (const Token& other)
  72597. : text (other.text),
  72598. font (other.font),
  72599. x (other.x),
  72600. y (other.y),
  72601. w (other.w),
  72602. h (other.h),
  72603. line (other.line),
  72604. lineHeight (other.lineHeight),
  72605. isWhitespace (other.isWhitespace),
  72606. isNewLine (other.isNewLine)
  72607. {
  72608. }
  72609. ~Token()
  72610. {
  72611. }
  72612. void draw (Graphics& g,
  72613. const int xOffset,
  72614. const int yOffset)
  72615. {
  72616. if (! isWhitespace)
  72617. {
  72618. g.setFont (font);
  72619. g.drawSingleLineText (text.trimEnd(),
  72620. xOffset + x,
  72621. yOffset + y + (lineHeight - h)
  72622. + roundToInt (font.getAscent()));
  72623. }
  72624. }
  72625. juce_UseDebuggingNewOperator
  72626. };
  72627. TextLayout::TextLayout()
  72628. : totalLines (0)
  72629. {
  72630. tokens.ensureStorageAllocated (64);
  72631. }
  72632. TextLayout::TextLayout (const String& text, const Font& font)
  72633. : totalLines (0)
  72634. {
  72635. tokens.ensureStorageAllocated (64);
  72636. appendText (text, font);
  72637. }
  72638. TextLayout::TextLayout (const TextLayout& other)
  72639. : totalLines (0)
  72640. {
  72641. *this = other;
  72642. }
  72643. TextLayout& TextLayout::operator= (const TextLayout& other)
  72644. {
  72645. if (this != &other)
  72646. {
  72647. clear();
  72648. totalLines = other.totalLines;
  72649. tokens.addCopiesOf (other.tokens);
  72650. }
  72651. return *this;
  72652. }
  72653. TextLayout::~TextLayout()
  72654. {
  72655. clear();
  72656. }
  72657. void TextLayout::clear()
  72658. {
  72659. tokens.clear();
  72660. totalLines = 0;
  72661. }
  72662. void TextLayout::appendText (const String& text, const Font& font)
  72663. {
  72664. const juce_wchar* t = text;
  72665. String currentString;
  72666. int lastCharType = 0;
  72667. for (;;)
  72668. {
  72669. const juce_wchar c = *t++;
  72670. if (c == 0)
  72671. break;
  72672. int charType;
  72673. if (c == '\r' || c == '\n')
  72674. {
  72675. charType = 0;
  72676. }
  72677. else if (CharacterFunctions::isWhitespace (c))
  72678. {
  72679. charType = 2;
  72680. }
  72681. else
  72682. {
  72683. charType = 1;
  72684. }
  72685. if (charType == 0 || charType != lastCharType)
  72686. {
  72687. if (currentString.isNotEmpty())
  72688. {
  72689. tokens.add (new Token (currentString, font,
  72690. lastCharType == 2 || lastCharType == 0));
  72691. }
  72692. currentString = String::charToString (c);
  72693. if (c == '\r' && *t == '\n')
  72694. currentString += *t++;
  72695. }
  72696. else
  72697. {
  72698. currentString += c;
  72699. }
  72700. lastCharType = charType;
  72701. }
  72702. if (currentString.isNotEmpty())
  72703. tokens.add (new Token (currentString, font, lastCharType == 2));
  72704. }
  72705. void TextLayout::setText (const String& text, const Font& font)
  72706. {
  72707. clear();
  72708. appendText (text, font);
  72709. }
  72710. void TextLayout::layout (int maxWidth,
  72711. const Justification& justification,
  72712. const bool attemptToBalanceLineLengths)
  72713. {
  72714. if (attemptToBalanceLineLengths)
  72715. {
  72716. const int originalW = maxWidth;
  72717. int bestWidth = maxWidth;
  72718. float bestLineProportion = 0.0f;
  72719. while (maxWidth > originalW / 2)
  72720. {
  72721. layout (maxWidth, justification, false);
  72722. if (getNumLines() <= 1)
  72723. return;
  72724. const int lastLineW = getLineWidth (getNumLines() - 1);
  72725. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  72726. const float prop = lastLineW / (float) lastButOneLineW;
  72727. if (prop > 0.9f)
  72728. return;
  72729. if (prop > bestLineProportion)
  72730. {
  72731. bestLineProportion = prop;
  72732. bestWidth = maxWidth;
  72733. }
  72734. maxWidth -= 10;
  72735. }
  72736. layout (bestWidth, justification, false);
  72737. }
  72738. else
  72739. {
  72740. int x = 0;
  72741. int y = 0;
  72742. int h = 0;
  72743. totalLines = 0;
  72744. int i;
  72745. for (i = 0; i < tokens.size(); ++i)
  72746. {
  72747. Token* const t = tokens.getUnchecked(i);
  72748. t->x = x;
  72749. t->y = y;
  72750. t->line = totalLines;
  72751. x += t->w;
  72752. h = jmax (h, t->h);
  72753. const Token* nextTok = tokens [i + 1];
  72754. if (nextTok == 0)
  72755. break;
  72756. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  72757. {
  72758. // finished a line, so go back and update the heights of the things on it
  72759. for (int j = i; j >= 0; --j)
  72760. {
  72761. Token* const tok = tokens.getUnchecked(j);
  72762. if (tok->line == totalLines)
  72763. tok->lineHeight = h;
  72764. else
  72765. break;
  72766. }
  72767. x = 0;
  72768. y += h;
  72769. h = 0;
  72770. ++totalLines;
  72771. }
  72772. }
  72773. // finished a line, so go back and update the heights of the things on it
  72774. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  72775. {
  72776. Token* const t = tokens.getUnchecked(j);
  72777. if (t->line == totalLines)
  72778. t->lineHeight = h;
  72779. else
  72780. break;
  72781. }
  72782. ++totalLines;
  72783. if (! justification.testFlags (Justification::left))
  72784. {
  72785. int totalW = getWidth();
  72786. for (i = totalLines; --i >= 0;)
  72787. {
  72788. const int lineW = getLineWidth (i);
  72789. int dx = 0;
  72790. if (justification.testFlags (Justification::horizontallyCentred))
  72791. dx = (totalW - lineW) / 2;
  72792. else if (justification.testFlags (Justification::right))
  72793. dx = totalW - lineW;
  72794. for (int j = tokens.size(); --j >= 0;)
  72795. {
  72796. Token* const t = tokens.getUnchecked(j);
  72797. if (t->line == i)
  72798. t->x += dx;
  72799. }
  72800. }
  72801. }
  72802. }
  72803. }
  72804. int TextLayout::getLineWidth (const int lineNumber) const
  72805. {
  72806. int maxW = 0;
  72807. for (int i = tokens.size(); --i >= 0;)
  72808. {
  72809. const Token* const t = tokens.getUnchecked(i);
  72810. if (t->line == lineNumber && ! t->isWhitespace)
  72811. maxW = jmax (maxW, t->x + t->w);
  72812. }
  72813. return maxW;
  72814. }
  72815. int TextLayout::getWidth() const
  72816. {
  72817. int maxW = 0;
  72818. for (int i = tokens.size(); --i >= 0;)
  72819. {
  72820. const Token* const t = tokens.getUnchecked(i);
  72821. if (! t->isWhitespace)
  72822. maxW = jmax (maxW, t->x + t->w);
  72823. }
  72824. return maxW;
  72825. }
  72826. int TextLayout::getHeight() const
  72827. {
  72828. int maxH = 0;
  72829. for (int i = tokens.size(); --i >= 0;)
  72830. {
  72831. const Token* const t = tokens.getUnchecked(i);
  72832. if (! t->isWhitespace)
  72833. maxH = jmax (maxH, t->y + t->h);
  72834. }
  72835. return maxH;
  72836. }
  72837. void TextLayout::draw (Graphics& g,
  72838. const int xOffset,
  72839. const int yOffset) const
  72840. {
  72841. for (int i = tokens.size(); --i >= 0;)
  72842. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  72843. }
  72844. void TextLayout::drawWithin (Graphics& g,
  72845. int x, int y, int w, int h,
  72846. const Justification& justification) const
  72847. {
  72848. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  72849. x, y, w, h);
  72850. draw (g, x, y);
  72851. }
  72852. END_JUCE_NAMESPACE
  72853. /*** End of inlined file: juce_TextLayout.cpp ***/
  72854. /*** Start of inlined file: juce_Typeface.cpp ***/
  72855. BEGIN_JUCE_NAMESPACE
  72856. Typeface::Typeface (const String& name_) throw()
  72857. : name (name_)
  72858. {
  72859. }
  72860. Typeface::~Typeface()
  72861. {
  72862. }
  72863. class CustomTypeface::GlyphInfo
  72864. {
  72865. public:
  72866. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  72867. : character (character_), path (path_), width (width_)
  72868. {
  72869. }
  72870. ~GlyphInfo() throw()
  72871. {
  72872. }
  72873. struct KerningPair
  72874. {
  72875. juce_wchar character2;
  72876. float kerningAmount;
  72877. };
  72878. void addKerningPair (const juce_wchar subsequentCharacter,
  72879. const float extraKerningAmount) throw()
  72880. {
  72881. KerningPair kp;
  72882. kp.character2 = subsequentCharacter;
  72883. kp.kerningAmount = extraKerningAmount;
  72884. kerningPairs.add (kp);
  72885. }
  72886. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  72887. {
  72888. if (subsequentCharacter != 0)
  72889. {
  72890. for (int i = kerningPairs.size(); --i >= 0;)
  72891. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  72892. return width + kerningPairs.getReference(i).kerningAmount;
  72893. }
  72894. return width;
  72895. }
  72896. const juce_wchar character;
  72897. const Path path;
  72898. float width;
  72899. Array <KerningPair> kerningPairs;
  72900. juce_UseDebuggingNewOperator
  72901. private:
  72902. GlyphInfo (const GlyphInfo&);
  72903. GlyphInfo& operator= (const GlyphInfo&);
  72904. };
  72905. CustomTypeface::CustomTypeface()
  72906. : Typeface (String::empty)
  72907. {
  72908. clear();
  72909. }
  72910. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  72911. : Typeface (String::empty)
  72912. {
  72913. clear();
  72914. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  72915. BufferedInputStream in (&gzin, 32768, false);
  72916. name = in.readString();
  72917. isBold = in.readBool();
  72918. isItalic = in.readBool();
  72919. ascent = in.readFloat();
  72920. defaultCharacter = (juce_wchar) in.readShort();
  72921. int i, numChars = in.readInt();
  72922. for (i = 0; i < numChars; ++i)
  72923. {
  72924. const juce_wchar c = (juce_wchar) in.readShort();
  72925. const float width = in.readFloat();
  72926. Path p;
  72927. p.loadPathFromStream (in);
  72928. addGlyph (c, p, width);
  72929. }
  72930. const int numKerningPairs = in.readInt();
  72931. for (i = 0; i < numKerningPairs; ++i)
  72932. {
  72933. const juce_wchar char1 = (juce_wchar) in.readShort();
  72934. const juce_wchar char2 = (juce_wchar) in.readShort();
  72935. addKerningPair (char1, char2, in.readFloat());
  72936. }
  72937. }
  72938. CustomTypeface::~CustomTypeface()
  72939. {
  72940. }
  72941. void CustomTypeface::clear()
  72942. {
  72943. defaultCharacter = 0;
  72944. ascent = 1.0f;
  72945. isBold = isItalic = false;
  72946. zeromem (lookupTable, sizeof (lookupTable));
  72947. glyphs.clear();
  72948. }
  72949. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  72950. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  72951. {
  72952. name = name_;
  72953. defaultCharacter = defaultCharacter_;
  72954. ascent = ascent_;
  72955. isBold = isBold_;
  72956. isItalic = isItalic_;
  72957. }
  72958. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  72959. {
  72960. // Check that you're not trying to add the same character twice..
  72961. jassert (findGlyph (character, false) == 0);
  72962. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  72963. lookupTable [character] = (short) glyphs.size();
  72964. glyphs.add (new GlyphInfo (character, path, width));
  72965. }
  72966. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  72967. {
  72968. if (extraAmount != 0)
  72969. {
  72970. GlyphInfo* const g = findGlyph (char1, true);
  72971. jassert (g != 0); // can only add kerning pairs for characters that exist!
  72972. if (g != 0)
  72973. g->addKerningPair (char2, extraAmount);
  72974. }
  72975. }
  72976. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  72977. {
  72978. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  72979. return glyphs [(int) lookupTable [(int) character]];
  72980. for (int i = 0; i < glyphs.size(); ++i)
  72981. {
  72982. GlyphInfo* const g = glyphs.getUnchecked(i);
  72983. if (g->character == character)
  72984. return g;
  72985. }
  72986. if (loadIfNeeded && loadGlyphIfPossible (character))
  72987. return findGlyph (character, false);
  72988. return 0;
  72989. }
  72990. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  72991. {
  72992. GlyphInfo* glyph = findGlyph (character, true);
  72993. if (glyph == 0)
  72994. {
  72995. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  72996. glyph = findGlyph (L' ', true);
  72997. if (glyph == 0)
  72998. {
  72999. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73000. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73001. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73002. {
  73003. //xxx
  73004. }
  73005. if (glyph == 0)
  73006. glyph = findGlyph (defaultCharacter, true);
  73007. }
  73008. }
  73009. return glyph;
  73010. }
  73011. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73012. {
  73013. return false;
  73014. }
  73015. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73016. {
  73017. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73018. for (int i = 0; i < numCharacters; ++i)
  73019. {
  73020. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73021. Array <int> glyphIndexes;
  73022. Array <float> offsets;
  73023. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73024. const int glyphIndex = glyphIndexes.getFirst();
  73025. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73026. {
  73027. const float glyphWidth = offsets[1];
  73028. Path p;
  73029. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73030. addGlyph (c, p, glyphWidth);
  73031. for (int j = glyphs.size() - 1; --j >= 0;)
  73032. {
  73033. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73034. glyphIndexes.clearQuick();
  73035. offsets.clearQuick();
  73036. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73037. if (offsets.size() > 1)
  73038. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73039. }
  73040. }
  73041. }
  73042. }
  73043. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73044. {
  73045. GZIPCompressorOutputStream out (&outputStream);
  73046. out.writeString (name);
  73047. out.writeBool (isBold);
  73048. out.writeBool (isItalic);
  73049. out.writeFloat (ascent);
  73050. out.writeShort ((short) (unsigned short) defaultCharacter);
  73051. out.writeInt (glyphs.size());
  73052. int i, numKerningPairs = 0;
  73053. for (i = 0; i < glyphs.size(); ++i)
  73054. {
  73055. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73056. out.writeShort ((short) (unsigned short) g->character);
  73057. out.writeFloat (g->width);
  73058. g->path.writePathToStream (out);
  73059. numKerningPairs += g->kerningPairs.size();
  73060. }
  73061. out.writeInt (numKerningPairs);
  73062. for (i = 0; i < glyphs.size(); ++i)
  73063. {
  73064. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73065. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73066. {
  73067. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73068. out.writeShort ((short) (unsigned short) g->character);
  73069. out.writeShort ((short) (unsigned short) p.character2);
  73070. out.writeFloat (p.kerningAmount);
  73071. }
  73072. }
  73073. return true;
  73074. }
  73075. float CustomTypeface::getAscent() const
  73076. {
  73077. return ascent;
  73078. }
  73079. float CustomTypeface::getDescent() const
  73080. {
  73081. return 1.0f - ascent;
  73082. }
  73083. float CustomTypeface::getStringWidth (const String& text)
  73084. {
  73085. float x = 0;
  73086. const juce_wchar* t = text;
  73087. while (*t != 0)
  73088. {
  73089. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73090. if (glyph != 0)
  73091. x += glyph->getHorizontalSpacing (*t);
  73092. }
  73093. return x;
  73094. }
  73095. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73096. {
  73097. xOffsets.add (0);
  73098. float x = 0;
  73099. const juce_wchar* t = text;
  73100. while (*t != 0)
  73101. {
  73102. const juce_wchar c = *t++;
  73103. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73104. if (glyph != 0)
  73105. {
  73106. x += glyph->getHorizontalSpacing (*t);
  73107. resultGlyphs.add ((int) glyph->character);
  73108. xOffsets.add (x);
  73109. }
  73110. }
  73111. }
  73112. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73113. {
  73114. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73115. if (glyph != 0)
  73116. {
  73117. path = glyph->path;
  73118. return true;
  73119. }
  73120. return false;
  73121. }
  73122. END_JUCE_NAMESPACE
  73123. /*** End of inlined file: juce_Typeface.cpp ***/
  73124. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73125. BEGIN_JUCE_NAMESPACE
  73126. AffineTransform::AffineTransform() throw()
  73127. : mat00 (1.0f),
  73128. mat01 (0),
  73129. mat02 (0),
  73130. mat10 (0),
  73131. mat11 (1.0f),
  73132. mat12 (0)
  73133. {
  73134. }
  73135. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73136. : mat00 (other.mat00),
  73137. mat01 (other.mat01),
  73138. mat02 (other.mat02),
  73139. mat10 (other.mat10),
  73140. mat11 (other.mat11),
  73141. mat12 (other.mat12)
  73142. {
  73143. }
  73144. AffineTransform::AffineTransform (const float mat00_,
  73145. const float mat01_,
  73146. const float mat02_,
  73147. const float mat10_,
  73148. const float mat11_,
  73149. const float mat12_) throw()
  73150. : mat00 (mat00_),
  73151. mat01 (mat01_),
  73152. mat02 (mat02_),
  73153. mat10 (mat10_),
  73154. mat11 (mat11_),
  73155. mat12 (mat12_)
  73156. {
  73157. }
  73158. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73159. {
  73160. mat00 = other.mat00;
  73161. mat01 = other.mat01;
  73162. mat02 = other.mat02;
  73163. mat10 = other.mat10;
  73164. mat11 = other.mat11;
  73165. mat12 = other.mat12;
  73166. return *this;
  73167. }
  73168. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73169. {
  73170. return mat00 == other.mat00
  73171. && mat01 == other.mat01
  73172. && mat02 == other.mat02
  73173. && mat10 == other.mat10
  73174. && mat11 == other.mat11
  73175. && mat12 == other.mat12;
  73176. }
  73177. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73178. {
  73179. return ! operator== (other);
  73180. }
  73181. bool AffineTransform::isIdentity() const throw()
  73182. {
  73183. return (mat01 == 0)
  73184. && (mat02 == 0)
  73185. && (mat10 == 0)
  73186. && (mat12 == 0)
  73187. && (mat00 == 1.0f)
  73188. && (mat11 == 1.0f);
  73189. }
  73190. const AffineTransform AffineTransform::identity;
  73191. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73192. {
  73193. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73194. other.mat00 * mat01 + other.mat01 * mat11,
  73195. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73196. other.mat10 * mat00 + other.mat11 * mat10,
  73197. other.mat10 * mat01 + other.mat11 * mat11,
  73198. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73199. }
  73200. const AffineTransform AffineTransform::followedBy (const float omat00,
  73201. const float omat01,
  73202. const float omat02,
  73203. const float omat10,
  73204. const float omat11,
  73205. const float omat12) const throw()
  73206. {
  73207. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73208. omat00 * mat01 + omat01 * mat11,
  73209. omat00 * mat02 + omat01 * mat12 + omat02,
  73210. omat10 * mat00 + omat11 * mat10,
  73211. omat10 * mat01 + omat11 * mat11,
  73212. omat10 * mat02 + omat11 * mat12 + omat12);
  73213. }
  73214. const AffineTransform AffineTransform::translated (const float dx,
  73215. const float dy) const throw()
  73216. {
  73217. return AffineTransform (mat00, mat01, mat02 + dx,
  73218. mat10, mat11, mat12 + dy);
  73219. }
  73220. const AffineTransform AffineTransform::translation (const float dx,
  73221. const float dy) throw()
  73222. {
  73223. return AffineTransform (1.0f, 0, dx,
  73224. 0, 1.0f, dy);
  73225. }
  73226. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73227. {
  73228. const float cosRad = std::cos (rad);
  73229. const float sinRad = std::sin (rad);
  73230. return followedBy (cosRad, -sinRad, 0,
  73231. sinRad, cosRad, 0);
  73232. }
  73233. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73234. {
  73235. const float cosRad = std::cos (rad);
  73236. const float sinRad = std::sin (rad);
  73237. return AffineTransform (cosRad, -sinRad, 0,
  73238. sinRad, cosRad, 0);
  73239. }
  73240. const AffineTransform AffineTransform::rotated (const float angle,
  73241. const float pivotX,
  73242. const float pivotY) const throw()
  73243. {
  73244. return translated (-pivotX, -pivotY)
  73245. .rotated (angle)
  73246. .translated (pivotX, pivotY);
  73247. }
  73248. const AffineTransform AffineTransform::rotation (const float angle,
  73249. const float pivotX,
  73250. const float pivotY) throw()
  73251. {
  73252. return translation (-pivotX, -pivotY)
  73253. .rotated (angle)
  73254. .translated (pivotX, pivotY);
  73255. }
  73256. const AffineTransform AffineTransform::scaled (const float factorX,
  73257. const float factorY) const throw()
  73258. {
  73259. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73260. factorY * mat10, factorY * mat11, factorY * mat12);
  73261. }
  73262. const AffineTransform AffineTransform::scale (const float factorX,
  73263. const float factorY) throw()
  73264. {
  73265. return AffineTransform (factorX, 0, 0,
  73266. 0, factorY, 0);
  73267. }
  73268. const AffineTransform AffineTransform::sheared (const float shearX,
  73269. const float shearY) const throw()
  73270. {
  73271. return followedBy (1.0f, shearX, 0,
  73272. shearY, 1.0f, 0);
  73273. }
  73274. const AffineTransform AffineTransform::inverted() const throw()
  73275. {
  73276. double determinant = (mat00 * mat11 - mat10 * mat01);
  73277. if (determinant != 0.0)
  73278. {
  73279. determinant = 1.0 / determinant;
  73280. const float dst00 = (float) (mat11 * determinant);
  73281. const float dst10 = (float) (-mat10 * determinant);
  73282. const float dst01 = (float) (-mat01 * determinant);
  73283. const float dst11 = (float) (mat00 * determinant);
  73284. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73285. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73286. }
  73287. else
  73288. {
  73289. // singularity..
  73290. return *this;
  73291. }
  73292. }
  73293. bool AffineTransform::isSingularity() const throw()
  73294. {
  73295. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73296. }
  73297. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73298. const float x10, const float y10,
  73299. const float x01, const float y01) throw()
  73300. {
  73301. return AffineTransform (x10 - x00, x01 - x00, x00,
  73302. y10 - y00, y01 - y00, y00);
  73303. }
  73304. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73305. const float sx2, const float sy2, const float tx2, const float ty2,
  73306. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73307. {
  73308. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73309. .inverted()
  73310. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73311. }
  73312. bool AffineTransform::isOnlyTranslation() const throw()
  73313. {
  73314. return (mat01 == 0)
  73315. && (mat10 == 0)
  73316. && (mat00 == 1.0f)
  73317. && (mat11 == 1.0f);
  73318. }
  73319. END_JUCE_NAMESPACE
  73320. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73321. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73322. BEGIN_JUCE_NAMESPACE
  73323. BorderSize::BorderSize() throw()
  73324. : top (0),
  73325. left (0),
  73326. bottom (0),
  73327. right (0)
  73328. {
  73329. }
  73330. BorderSize::BorderSize (const BorderSize& other) throw()
  73331. : top (other.top),
  73332. left (other.left),
  73333. bottom (other.bottom),
  73334. right (other.right)
  73335. {
  73336. }
  73337. BorderSize::BorderSize (const int topGap,
  73338. const int leftGap,
  73339. const int bottomGap,
  73340. const int rightGap) throw()
  73341. : top (topGap),
  73342. left (leftGap),
  73343. bottom (bottomGap),
  73344. right (rightGap)
  73345. {
  73346. }
  73347. BorderSize::BorderSize (const int allGaps) throw()
  73348. : top (allGaps),
  73349. left (allGaps),
  73350. bottom (allGaps),
  73351. right (allGaps)
  73352. {
  73353. }
  73354. BorderSize::~BorderSize() throw()
  73355. {
  73356. }
  73357. void BorderSize::setTop (const int newTopGap) throw()
  73358. {
  73359. top = newTopGap;
  73360. }
  73361. void BorderSize::setLeft (const int newLeftGap) throw()
  73362. {
  73363. left = newLeftGap;
  73364. }
  73365. void BorderSize::setBottom (const int newBottomGap) throw()
  73366. {
  73367. bottom = newBottomGap;
  73368. }
  73369. void BorderSize::setRight (const int newRightGap) throw()
  73370. {
  73371. right = newRightGap;
  73372. }
  73373. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73374. {
  73375. return Rectangle<int> (r.getX() + left,
  73376. r.getY() + top,
  73377. r.getWidth() - (left + right),
  73378. r.getHeight() - (top + bottom));
  73379. }
  73380. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73381. {
  73382. r.setBounds (r.getX() + left,
  73383. r.getY() + top,
  73384. r.getWidth() - (left + right),
  73385. r.getHeight() - (top + bottom));
  73386. }
  73387. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73388. {
  73389. return Rectangle<int> (r.getX() - left,
  73390. r.getY() - top,
  73391. r.getWidth() + (left + right),
  73392. r.getHeight() + (top + bottom));
  73393. }
  73394. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73395. {
  73396. r.setBounds (r.getX() - left,
  73397. r.getY() - top,
  73398. r.getWidth() + (left + right),
  73399. r.getHeight() + (top + bottom));
  73400. }
  73401. bool BorderSize::operator== (const BorderSize& other) const throw()
  73402. {
  73403. return top == other.top
  73404. && left == other.left
  73405. && bottom == other.bottom
  73406. && right == other.right;
  73407. }
  73408. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73409. {
  73410. return ! operator== (other);
  73411. }
  73412. END_JUCE_NAMESPACE
  73413. /*** End of inlined file: juce_BorderSize.cpp ***/
  73414. /*** Start of inlined file: juce_Path.cpp ***/
  73415. BEGIN_JUCE_NAMESPACE
  73416. // tests that some co-ords aren't NaNs
  73417. #define CHECK_COORDS_ARE_VALID(x, y) \
  73418. jassert (x == x && y == y);
  73419. namespace PathHelpers
  73420. {
  73421. static const float ellipseAngularIncrement = 0.05f;
  73422. static const String nextToken (const juce_wchar*& t)
  73423. {
  73424. while (CharacterFunctions::isWhitespace (*t))
  73425. ++t;
  73426. const juce_wchar* const start = t;
  73427. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73428. ++t;
  73429. return String (start, (int) (t - start));
  73430. }
  73431. }
  73432. const float Path::lineMarker = 100001.0f;
  73433. const float Path::moveMarker = 100002.0f;
  73434. const float Path::quadMarker = 100003.0f;
  73435. const float Path::cubicMarker = 100004.0f;
  73436. const float Path::closeSubPathMarker = 100005.0f;
  73437. Path::Path()
  73438. : numElements (0),
  73439. pathXMin (0),
  73440. pathXMax (0),
  73441. pathYMin (0),
  73442. pathYMax (0),
  73443. useNonZeroWinding (true)
  73444. {
  73445. }
  73446. Path::~Path()
  73447. {
  73448. }
  73449. Path::Path (const Path& other)
  73450. : numElements (other.numElements),
  73451. pathXMin (other.pathXMin),
  73452. pathXMax (other.pathXMax),
  73453. pathYMin (other.pathYMin),
  73454. pathYMax (other.pathYMax),
  73455. useNonZeroWinding (other.useNonZeroWinding)
  73456. {
  73457. if (numElements > 0)
  73458. {
  73459. data.setAllocatedSize ((int) numElements);
  73460. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73461. }
  73462. }
  73463. Path& Path::operator= (const Path& other)
  73464. {
  73465. if (this != &other)
  73466. {
  73467. data.ensureAllocatedSize ((int) other.numElements);
  73468. numElements = other.numElements;
  73469. pathXMin = other.pathXMin;
  73470. pathXMax = other.pathXMax;
  73471. pathYMin = other.pathYMin;
  73472. pathYMax = other.pathYMax;
  73473. useNonZeroWinding = other.useNonZeroWinding;
  73474. if (numElements > 0)
  73475. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73476. }
  73477. return *this;
  73478. }
  73479. bool Path::operator== (const Path& other) const throw()
  73480. {
  73481. return ! operator!= (other);
  73482. }
  73483. bool Path::operator!= (const Path& other) const throw()
  73484. {
  73485. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  73486. return true;
  73487. for (size_t i = 0; i < numElements; ++i)
  73488. if (data.elements[i] != other.data.elements[i])
  73489. return true;
  73490. return false;
  73491. }
  73492. void Path::clear() throw()
  73493. {
  73494. numElements = 0;
  73495. pathXMin = 0;
  73496. pathYMin = 0;
  73497. pathYMax = 0;
  73498. pathXMax = 0;
  73499. }
  73500. void Path::swapWithPath (Path& other) throw()
  73501. {
  73502. data.swapWith (other.data);
  73503. swapVariables <size_t> (numElements, other.numElements);
  73504. swapVariables <float> (pathXMin, other.pathXMin);
  73505. swapVariables <float> (pathXMax, other.pathXMax);
  73506. swapVariables <float> (pathYMin, other.pathYMin);
  73507. swapVariables <float> (pathYMax, other.pathYMax);
  73508. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  73509. }
  73510. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  73511. {
  73512. useNonZeroWinding = isNonZero;
  73513. }
  73514. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  73515. const bool preserveProportions) throw()
  73516. {
  73517. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  73518. }
  73519. bool Path::isEmpty() const throw()
  73520. {
  73521. size_t i = 0;
  73522. while (i < numElements)
  73523. {
  73524. const float type = data.elements [i++];
  73525. if (type == moveMarker)
  73526. {
  73527. i += 2;
  73528. }
  73529. else if (type == lineMarker
  73530. || type == quadMarker
  73531. || type == cubicMarker)
  73532. {
  73533. return false;
  73534. }
  73535. }
  73536. return true;
  73537. }
  73538. const Rectangle<float> Path::getBounds() const throw()
  73539. {
  73540. return Rectangle<float> (pathXMin, pathYMin,
  73541. pathXMax - pathXMin,
  73542. pathYMax - pathYMin);
  73543. }
  73544. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  73545. {
  73546. return getBounds().transformed (transform);
  73547. }
  73548. void Path::startNewSubPath (const float x, const float y)
  73549. {
  73550. CHECK_COORDS_ARE_VALID (x, y);
  73551. if (numElements == 0)
  73552. {
  73553. pathXMin = pathXMax = x;
  73554. pathYMin = pathYMax = y;
  73555. }
  73556. else
  73557. {
  73558. pathXMin = jmin (pathXMin, x);
  73559. pathXMax = jmax (pathXMax, x);
  73560. pathYMin = jmin (pathYMin, y);
  73561. pathYMax = jmax (pathYMax, y);
  73562. }
  73563. data.ensureAllocatedSize ((int) numElements + 3);
  73564. data.elements [numElements++] = moveMarker;
  73565. data.elements [numElements++] = x;
  73566. data.elements [numElements++] = y;
  73567. }
  73568. void Path::startNewSubPath (const Point<float>& start)
  73569. {
  73570. startNewSubPath (start.getX(), start.getY());
  73571. }
  73572. void Path::lineTo (const float x, const float y)
  73573. {
  73574. CHECK_COORDS_ARE_VALID (x, y);
  73575. if (numElements == 0)
  73576. startNewSubPath (0, 0);
  73577. data.ensureAllocatedSize ((int) numElements + 3);
  73578. data.elements [numElements++] = lineMarker;
  73579. data.elements [numElements++] = x;
  73580. data.elements [numElements++] = y;
  73581. pathXMin = jmin (pathXMin, x);
  73582. pathXMax = jmax (pathXMax, x);
  73583. pathYMin = jmin (pathYMin, y);
  73584. pathYMax = jmax (pathYMax, y);
  73585. }
  73586. void Path::lineTo (const Point<float>& end)
  73587. {
  73588. lineTo (end.getX(), end.getY());
  73589. }
  73590. void Path::quadraticTo (const float x1, const float y1,
  73591. const float x2, const float y2)
  73592. {
  73593. CHECK_COORDS_ARE_VALID (x1, y1);
  73594. CHECK_COORDS_ARE_VALID (x2, y2);
  73595. if (numElements == 0)
  73596. startNewSubPath (0, 0);
  73597. data.ensureAllocatedSize ((int) numElements + 5);
  73598. data.elements [numElements++] = quadMarker;
  73599. data.elements [numElements++] = x1;
  73600. data.elements [numElements++] = y1;
  73601. data.elements [numElements++] = x2;
  73602. data.elements [numElements++] = y2;
  73603. pathXMin = jmin (pathXMin, x1, x2);
  73604. pathXMax = jmax (pathXMax, x1, x2);
  73605. pathYMin = jmin (pathYMin, y1, y2);
  73606. pathYMax = jmax (pathYMax, y1, y2);
  73607. }
  73608. void Path::quadraticTo (const Point<float>& controlPoint,
  73609. const Point<float>& endPoint)
  73610. {
  73611. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  73612. endPoint.getX(), endPoint.getY());
  73613. }
  73614. void Path::cubicTo (const float x1, const float y1,
  73615. const float x2, const float y2,
  73616. const float x3, const float y3)
  73617. {
  73618. CHECK_COORDS_ARE_VALID (x1, y1);
  73619. CHECK_COORDS_ARE_VALID (x2, y2);
  73620. CHECK_COORDS_ARE_VALID (x3, y3);
  73621. if (numElements == 0)
  73622. startNewSubPath (0, 0);
  73623. data.ensureAllocatedSize ((int) numElements + 7);
  73624. data.elements [numElements++] = cubicMarker;
  73625. data.elements [numElements++] = x1;
  73626. data.elements [numElements++] = y1;
  73627. data.elements [numElements++] = x2;
  73628. data.elements [numElements++] = y2;
  73629. data.elements [numElements++] = x3;
  73630. data.elements [numElements++] = y3;
  73631. pathXMin = jmin (pathXMin, x1, x2, x3);
  73632. pathXMax = jmax (pathXMax, x1, x2, x3);
  73633. pathYMin = jmin (pathYMin, y1, y2, y3);
  73634. pathYMax = jmax (pathYMax, y1, y2, y3);
  73635. }
  73636. void Path::cubicTo (const Point<float>& controlPoint1,
  73637. const Point<float>& controlPoint2,
  73638. const Point<float>& endPoint)
  73639. {
  73640. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  73641. controlPoint2.getX(), controlPoint2.getY(),
  73642. endPoint.getX(), endPoint.getY());
  73643. }
  73644. void Path::closeSubPath()
  73645. {
  73646. if (numElements > 0
  73647. && data.elements [numElements - 1] != closeSubPathMarker)
  73648. {
  73649. data.ensureAllocatedSize ((int) numElements + 1);
  73650. data.elements [numElements++] = closeSubPathMarker;
  73651. }
  73652. }
  73653. const Point<float> Path::getCurrentPosition() const
  73654. {
  73655. size_t i = numElements - 1;
  73656. if (i > 0 && data.elements[i] == closeSubPathMarker)
  73657. {
  73658. while (i >= 0)
  73659. {
  73660. if (data.elements[i] == moveMarker)
  73661. {
  73662. i += 2;
  73663. break;
  73664. }
  73665. --i;
  73666. }
  73667. }
  73668. if (i > 0)
  73669. return Point<float> (data.elements [i - 1], data.elements [i]);
  73670. return Point<float>();
  73671. }
  73672. void Path::addRectangle (const float x, const float y,
  73673. const float w, const float h)
  73674. {
  73675. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  73676. if (w < 0)
  73677. swapVariables (x1, x2);
  73678. if (h < 0)
  73679. swapVariables (y1, y2);
  73680. data.ensureAllocatedSize ((int) numElements + 13);
  73681. if (numElements == 0)
  73682. {
  73683. pathXMin = x1;
  73684. pathXMax = x2;
  73685. pathYMin = y1;
  73686. pathYMax = y2;
  73687. }
  73688. else
  73689. {
  73690. pathXMin = jmin (pathXMin, x1);
  73691. pathXMax = jmax (pathXMax, x2);
  73692. pathYMin = jmin (pathYMin, y1);
  73693. pathYMax = jmax (pathYMax, y2);
  73694. }
  73695. data.elements [numElements++] = moveMarker;
  73696. data.elements [numElements++] = x1;
  73697. data.elements [numElements++] = y2;
  73698. data.elements [numElements++] = lineMarker;
  73699. data.elements [numElements++] = x1;
  73700. data.elements [numElements++] = y1;
  73701. data.elements [numElements++] = lineMarker;
  73702. data.elements [numElements++] = x2;
  73703. data.elements [numElements++] = y1;
  73704. data.elements [numElements++] = lineMarker;
  73705. data.elements [numElements++] = x2;
  73706. data.elements [numElements++] = y2;
  73707. data.elements [numElements++] = closeSubPathMarker;
  73708. }
  73709. void Path::addRectangle (const Rectangle<int>& rectangle)
  73710. {
  73711. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  73712. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  73713. }
  73714. void Path::addRoundedRectangle (const float x, const float y,
  73715. const float w, const float h,
  73716. float csx,
  73717. float csy)
  73718. {
  73719. csx = jmin (csx, w * 0.5f);
  73720. csy = jmin (csy, h * 0.5f);
  73721. const float cs45x = csx * 0.45f;
  73722. const float cs45y = csy * 0.45f;
  73723. const float x2 = x + w;
  73724. const float y2 = y + h;
  73725. startNewSubPath (x + csx, y);
  73726. lineTo (x2 - csx, y);
  73727. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  73728. lineTo (x2, y2 - csy);
  73729. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  73730. lineTo (x + csx, y2);
  73731. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  73732. lineTo (x, y + csy);
  73733. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  73734. closeSubPath();
  73735. }
  73736. void Path::addRoundedRectangle (const float x, const float y,
  73737. const float w, const float h,
  73738. float cs)
  73739. {
  73740. addRoundedRectangle (x, y, w, h, cs, cs);
  73741. }
  73742. void Path::addTriangle (const float x1, const float y1,
  73743. const float x2, const float y2,
  73744. const float x3, const float y3)
  73745. {
  73746. startNewSubPath (x1, y1);
  73747. lineTo (x2, y2);
  73748. lineTo (x3, y3);
  73749. closeSubPath();
  73750. }
  73751. void Path::addQuadrilateral (const float x1, const float y1,
  73752. const float x2, const float y2,
  73753. const float x3, const float y3,
  73754. const float x4, const float y4)
  73755. {
  73756. startNewSubPath (x1, y1);
  73757. lineTo (x2, y2);
  73758. lineTo (x3, y3);
  73759. lineTo (x4, y4);
  73760. closeSubPath();
  73761. }
  73762. void Path::addEllipse (const float x, const float y,
  73763. const float w, const float h)
  73764. {
  73765. const float hw = w * 0.5f;
  73766. const float hw55 = hw * 0.55f;
  73767. const float hh = h * 0.5f;
  73768. const float hh45 = hh * 0.55f;
  73769. const float cx = x + hw;
  73770. const float cy = y + hh;
  73771. startNewSubPath (cx, cy - hh);
  73772. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  73773. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  73774. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  73775. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  73776. closeSubPath();
  73777. }
  73778. void Path::addArc (const float x, const float y,
  73779. const float w, const float h,
  73780. const float fromRadians,
  73781. const float toRadians,
  73782. const bool startAsNewSubPath)
  73783. {
  73784. const float radiusX = w / 2.0f;
  73785. const float radiusY = h / 2.0f;
  73786. addCentredArc (x + radiusX,
  73787. y + radiusY,
  73788. radiusX, radiusY,
  73789. 0.0f,
  73790. fromRadians, toRadians,
  73791. startAsNewSubPath);
  73792. }
  73793. void Path::addCentredArc (const float centreX, const float centreY,
  73794. const float radiusX, const float radiusY,
  73795. const float rotationOfEllipse,
  73796. const float fromRadians,
  73797. const float toRadians,
  73798. const bool startAsNewSubPath)
  73799. {
  73800. if (radiusX > 0.0f && radiusY > 0.0f)
  73801. {
  73802. const Point<float> centre (centreX, centreY);
  73803. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  73804. float angle = fromRadians;
  73805. if (startAsNewSubPath)
  73806. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73807. if (fromRadians < toRadians)
  73808. {
  73809. if (startAsNewSubPath)
  73810. angle += PathHelpers::ellipseAngularIncrement;
  73811. while (angle < toRadians)
  73812. {
  73813. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73814. angle += PathHelpers::ellipseAngularIncrement;
  73815. }
  73816. }
  73817. else
  73818. {
  73819. if (startAsNewSubPath)
  73820. angle -= PathHelpers::ellipseAngularIncrement;
  73821. while (angle > toRadians)
  73822. {
  73823. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73824. angle -= PathHelpers::ellipseAngularIncrement;
  73825. }
  73826. }
  73827. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  73828. }
  73829. }
  73830. void Path::addPieSegment (const float x, const float y,
  73831. const float width, const float height,
  73832. const float fromRadians,
  73833. const float toRadians,
  73834. const float innerCircleProportionalSize)
  73835. {
  73836. float radiusX = width * 0.5f;
  73837. float radiusY = height * 0.5f;
  73838. const Point<float> centre (x + radiusX, y + radiusY);
  73839. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  73840. addArc (x, y, width, height, fromRadians, toRadians);
  73841. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  73842. {
  73843. closeSubPath();
  73844. if (innerCircleProportionalSize > 0)
  73845. {
  73846. radiusX *= innerCircleProportionalSize;
  73847. radiusY *= innerCircleProportionalSize;
  73848. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  73849. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  73850. }
  73851. }
  73852. else
  73853. {
  73854. if (innerCircleProportionalSize > 0)
  73855. {
  73856. radiusX *= innerCircleProportionalSize;
  73857. radiusY *= innerCircleProportionalSize;
  73858. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  73859. }
  73860. else
  73861. {
  73862. lineTo (centre);
  73863. }
  73864. }
  73865. closeSubPath();
  73866. }
  73867. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  73868. {
  73869. const Line<float> reversed (line.reversed());
  73870. lineThickness *= 0.5f;
  73871. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  73872. lineTo (line.getPointAlongLine (0, -lineThickness));
  73873. lineTo (reversed.getPointAlongLine (0, lineThickness));
  73874. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  73875. closeSubPath();
  73876. }
  73877. void Path::addArrow (const Line<float>& line, float lineThickness,
  73878. float arrowheadWidth, float arrowheadLength)
  73879. {
  73880. const Line<float> reversed (line.reversed());
  73881. lineThickness *= 0.5f;
  73882. arrowheadWidth *= 0.5f;
  73883. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  73884. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  73885. lineTo (line.getPointAlongLine (0, -lineThickness));
  73886. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  73887. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  73888. lineTo (line.getEnd());
  73889. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  73890. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  73891. closeSubPath();
  73892. }
  73893. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  73894. const float radius, const float startAngle)
  73895. {
  73896. jassert (numberOfSides > 1); // this would be silly.
  73897. if (numberOfSides > 1)
  73898. {
  73899. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  73900. for (int i = 0; i < numberOfSides; ++i)
  73901. {
  73902. const float angle = startAngle + i * angleBetweenPoints;
  73903. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  73904. if (i == 0)
  73905. startNewSubPath (p);
  73906. else
  73907. lineTo (p);
  73908. }
  73909. closeSubPath();
  73910. }
  73911. }
  73912. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  73913. const float innerRadius, const float outerRadius, const float startAngle)
  73914. {
  73915. jassert (numberOfPoints > 1); // this would be silly.
  73916. if (numberOfPoints > 1)
  73917. {
  73918. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  73919. for (int i = 0; i < numberOfPoints; ++i)
  73920. {
  73921. const float angle = startAngle + i * angleBetweenPoints;
  73922. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  73923. if (i == 0)
  73924. startNewSubPath (p);
  73925. else
  73926. lineTo (p);
  73927. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  73928. }
  73929. closeSubPath();
  73930. }
  73931. }
  73932. void Path::addBubble (float x, float y,
  73933. float w, float h,
  73934. float cs,
  73935. float tipX,
  73936. float tipY,
  73937. int whichSide,
  73938. float arrowPos,
  73939. float arrowWidth)
  73940. {
  73941. if (w > 1.0f && h > 1.0f)
  73942. {
  73943. cs = jmin (cs, w * 0.5f, h * 0.5f);
  73944. const float cs2 = 2.0f * cs;
  73945. startNewSubPath (x + cs, y);
  73946. if (whichSide == 0)
  73947. {
  73948. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73949. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73950. lineTo (arrowX1, y);
  73951. lineTo (tipX, tipY);
  73952. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  73953. }
  73954. lineTo (x + w - cs, y);
  73955. if (cs > 0.0f)
  73956. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  73957. if (whichSide == 3)
  73958. {
  73959. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73960. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73961. lineTo (x + w, arrowY1);
  73962. lineTo (tipX, tipY);
  73963. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  73964. }
  73965. lineTo (x + w, y + h - cs);
  73966. if (cs > 0.0f)
  73967. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  73968. if (whichSide == 2)
  73969. {
  73970. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73971. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73972. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  73973. lineTo (tipX, tipY);
  73974. lineTo (arrowX1, y + h);
  73975. }
  73976. lineTo (x + cs, y + h);
  73977. if (cs > 0.0f)
  73978. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  73979. if (whichSide == 1)
  73980. {
  73981. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73982. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73983. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  73984. lineTo (tipX, tipY);
  73985. lineTo (x, arrowY1);
  73986. }
  73987. lineTo (x, y + cs);
  73988. if (cs > 0.0f)
  73989. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  73990. closeSubPath();
  73991. }
  73992. }
  73993. void Path::addPath (const Path& other)
  73994. {
  73995. size_t i = 0;
  73996. while (i < other.numElements)
  73997. {
  73998. const float type = other.data.elements [i++];
  73999. if (type == moveMarker)
  74000. {
  74001. startNewSubPath (other.data.elements [i],
  74002. other.data.elements [i + 1]);
  74003. i += 2;
  74004. }
  74005. else if (type == lineMarker)
  74006. {
  74007. lineTo (other.data.elements [i],
  74008. other.data.elements [i + 1]);
  74009. i += 2;
  74010. }
  74011. else if (type == quadMarker)
  74012. {
  74013. quadraticTo (other.data.elements [i],
  74014. other.data.elements [i + 1],
  74015. other.data.elements [i + 2],
  74016. other.data.elements [i + 3]);
  74017. i += 4;
  74018. }
  74019. else if (type == cubicMarker)
  74020. {
  74021. cubicTo (other.data.elements [i],
  74022. other.data.elements [i + 1],
  74023. other.data.elements [i + 2],
  74024. other.data.elements [i + 3],
  74025. other.data.elements [i + 4],
  74026. other.data.elements [i + 5]);
  74027. i += 6;
  74028. }
  74029. else if (type == closeSubPathMarker)
  74030. {
  74031. closeSubPath();
  74032. }
  74033. else
  74034. {
  74035. // something's gone wrong with the element list!
  74036. jassertfalse;
  74037. }
  74038. }
  74039. }
  74040. void Path::addPath (const Path& other,
  74041. const AffineTransform& transformToApply)
  74042. {
  74043. size_t i = 0;
  74044. while (i < other.numElements)
  74045. {
  74046. const float type = other.data.elements [i++];
  74047. if (type == closeSubPathMarker)
  74048. {
  74049. closeSubPath();
  74050. }
  74051. else
  74052. {
  74053. float x = other.data.elements [i++];
  74054. float y = other.data.elements [i++];
  74055. transformToApply.transformPoint (x, y);
  74056. if (type == moveMarker)
  74057. {
  74058. startNewSubPath (x, y);
  74059. }
  74060. else if (type == lineMarker)
  74061. {
  74062. lineTo (x, y);
  74063. }
  74064. else if (type == quadMarker)
  74065. {
  74066. float x2 = other.data.elements [i++];
  74067. float y2 = other.data.elements [i++];
  74068. transformToApply.transformPoint (x2, y2);
  74069. quadraticTo (x, y, x2, y2);
  74070. }
  74071. else if (type == cubicMarker)
  74072. {
  74073. float x2 = other.data.elements [i++];
  74074. float y2 = other.data.elements [i++];
  74075. float x3 = other.data.elements [i++];
  74076. float y3 = other.data.elements [i++];
  74077. transformToApply.transformPoints (x2, y2, x3, y3);
  74078. cubicTo (x, y, x2, y2, x3, y3);
  74079. }
  74080. else
  74081. {
  74082. // something's gone wrong with the element list!
  74083. jassertfalse;
  74084. }
  74085. }
  74086. }
  74087. }
  74088. void Path::applyTransform (const AffineTransform& transform) throw()
  74089. {
  74090. size_t i = 0;
  74091. pathYMin = pathXMin = 0;
  74092. pathYMax = pathXMax = 0;
  74093. bool setMaxMin = false;
  74094. while (i < numElements)
  74095. {
  74096. const float type = data.elements [i++];
  74097. if (type == moveMarker)
  74098. {
  74099. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74100. if (setMaxMin)
  74101. {
  74102. pathXMin = jmin (pathXMin, data.elements [i]);
  74103. pathXMax = jmax (pathXMax, data.elements [i]);
  74104. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74105. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74106. }
  74107. else
  74108. {
  74109. pathXMin = pathXMax = data.elements [i];
  74110. pathYMin = pathYMax = data.elements [i + 1];
  74111. setMaxMin = true;
  74112. }
  74113. i += 2;
  74114. }
  74115. else if (type == lineMarker)
  74116. {
  74117. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74118. pathXMin = jmin (pathXMin, data.elements [i]);
  74119. pathXMax = jmax (pathXMax, data.elements [i]);
  74120. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74121. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74122. i += 2;
  74123. }
  74124. else if (type == quadMarker)
  74125. {
  74126. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74127. data.elements [i + 2], data.elements [i + 3]);
  74128. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74129. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74130. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74131. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74132. i += 4;
  74133. }
  74134. else if (type == cubicMarker)
  74135. {
  74136. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74137. data.elements [i + 2], data.elements [i + 3],
  74138. data.elements [i + 4], data.elements [i + 5]);
  74139. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74140. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74141. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74142. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74143. i += 6;
  74144. }
  74145. }
  74146. }
  74147. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74148. const float w, const float h,
  74149. const bool preserveProportions,
  74150. const Justification& justification) const
  74151. {
  74152. Rectangle<float> bounds (getBounds());
  74153. if (preserveProportions)
  74154. {
  74155. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74156. return AffineTransform::identity;
  74157. float newW, newH;
  74158. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74159. if (srcRatio > h / w)
  74160. {
  74161. newW = h / srcRatio;
  74162. newH = h;
  74163. }
  74164. else
  74165. {
  74166. newW = w;
  74167. newH = w * srcRatio;
  74168. }
  74169. float newXCentre = x;
  74170. float newYCentre = y;
  74171. if (justification.testFlags (Justification::left))
  74172. newXCentre += newW * 0.5f;
  74173. else if (justification.testFlags (Justification::right))
  74174. newXCentre += w - newW * 0.5f;
  74175. else
  74176. newXCentre += w * 0.5f;
  74177. if (justification.testFlags (Justification::top))
  74178. newYCentre += newH * 0.5f;
  74179. else if (justification.testFlags (Justification::bottom))
  74180. newYCentre += h - newH * 0.5f;
  74181. else
  74182. newYCentre += h * 0.5f;
  74183. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74184. bounds.getHeight() * -0.5f - bounds.getY())
  74185. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74186. .translated (newXCentre, newYCentre);
  74187. }
  74188. else
  74189. {
  74190. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74191. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74192. .translated (x, y);
  74193. }
  74194. }
  74195. bool Path::contains (const float x, const float y, const float tolerence) const
  74196. {
  74197. if (x <= pathXMin || x >= pathXMax
  74198. || y <= pathYMin || y >= pathYMax)
  74199. return false;
  74200. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74201. int positiveCrossings = 0;
  74202. int negativeCrossings = 0;
  74203. while (i.next())
  74204. {
  74205. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74206. {
  74207. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74208. if (intersectX <= x)
  74209. {
  74210. if (i.y1 < i.y2)
  74211. ++positiveCrossings;
  74212. else
  74213. ++negativeCrossings;
  74214. }
  74215. }
  74216. }
  74217. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74218. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74219. }
  74220. bool Path::contains (const Point<float>& point, const float tolerence) const
  74221. {
  74222. return contains (point.getX(), point.getY(), tolerence);
  74223. }
  74224. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74225. {
  74226. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74227. Point<float> intersection;
  74228. while (i.next())
  74229. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74230. return true;
  74231. return false;
  74232. }
  74233. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74234. {
  74235. Line<float> result (line);
  74236. const bool startInside = contains (line.getStart());
  74237. const bool endInside = contains (line.getEnd());
  74238. if (startInside == endInside)
  74239. {
  74240. if (keepSectionOutsidePath == startInside)
  74241. result = Line<float>();
  74242. }
  74243. else
  74244. {
  74245. PathFlatteningIterator i (*this, AffineTransform::identity);
  74246. Point<float> intersection;
  74247. while (i.next())
  74248. {
  74249. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74250. {
  74251. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74252. result.setStart (intersection);
  74253. else
  74254. result.setEnd (intersection);
  74255. }
  74256. }
  74257. }
  74258. return result;
  74259. }
  74260. float Path::getLength (const AffineTransform& transform) const
  74261. {
  74262. float length = 0;
  74263. PathFlatteningIterator i (*this, transform);
  74264. while (i.next())
  74265. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74266. return length;
  74267. }
  74268. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74269. {
  74270. PathFlatteningIterator i (*this, transform);
  74271. while (i.next())
  74272. {
  74273. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74274. const float lineLength = line.getLength();
  74275. if (distanceFromStart <= lineLength)
  74276. return line.getPointAlongLine (distanceFromStart);
  74277. distanceFromStart -= lineLength;
  74278. }
  74279. return Point<float> (i.x2, i.y2);
  74280. }
  74281. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74282. const AffineTransform& transform) const
  74283. {
  74284. PathFlatteningIterator i (*this, transform);
  74285. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74286. float length = 0;
  74287. Point<float> pointOnLine;
  74288. while (i.next())
  74289. {
  74290. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74291. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74292. if (distance < bestDistance)
  74293. {
  74294. bestDistance = distance;
  74295. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74296. pointOnPath = pointOnLine;
  74297. }
  74298. length += line.getLength();
  74299. }
  74300. return bestPosition;
  74301. }
  74302. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74303. {
  74304. if (cornerRadius <= 0.01f)
  74305. return *this;
  74306. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74307. size_t n = 0;
  74308. bool lastWasLine = false, firstWasLine = false;
  74309. Path p;
  74310. while (n < numElements)
  74311. {
  74312. const float type = data.elements [n++];
  74313. if (type == moveMarker)
  74314. {
  74315. indexOfPathStart = p.numElements;
  74316. indexOfPathStartThis = n - 1;
  74317. const float x = data.elements [n++];
  74318. const float y = data.elements [n++];
  74319. p.startNewSubPath (x, y);
  74320. lastWasLine = false;
  74321. firstWasLine = (data.elements [n] == lineMarker);
  74322. }
  74323. else if (type == lineMarker || type == closeSubPathMarker)
  74324. {
  74325. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74326. if (type == lineMarker)
  74327. {
  74328. endX = data.elements [n++];
  74329. endY = data.elements [n++];
  74330. if (n > 8)
  74331. {
  74332. startX = data.elements [n - 8];
  74333. startY = data.elements [n - 7];
  74334. joinX = data.elements [n - 5];
  74335. joinY = data.elements [n - 4];
  74336. }
  74337. }
  74338. else
  74339. {
  74340. endX = data.elements [indexOfPathStartThis + 1];
  74341. endY = data.elements [indexOfPathStartThis + 2];
  74342. if (n > 6)
  74343. {
  74344. startX = data.elements [n - 6];
  74345. startY = data.elements [n - 5];
  74346. joinX = data.elements [n - 3];
  74347. joinY = data.elements [n - 2];
  74348. }
  74349. }
  74350. if (lastWasLine)
  74351. {
  74352. const double len1 = juce_hypot (startX - joinX,
  74353. startY - joinY);
  74354. if (len1 > 0)
  74355. {
  74356. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74357. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74358. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74359. }
  74360. const double len2 = juce_hypot (endX - joinX,
  74361. endY - joinY);
  74362. if (len2 > 0)
  74363. {
  74364. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74365. p.quadraticTo (joinX, joinY,
  74366. (float) (joinX + (endX - joinX) * propNeeded),
  74367. (float) (joinY + (endY - joinY) * propNeeded));
  74368. }
  74369. p.lineTo (endX, endY);
  74370. }
  74371. else if (type == lineMarker)
  74372. {
  74373. p.lineTo (endX, endY);
  74374. lastWasLine = true;
  74375. }
  74376. if (type == closeSubPathMarker)
  74377. {
  74378. if (firstWasLine)
  74379. {
  74380. startX = data.elements [n - 3];
  74381. startY = data.elements [n - 2];
  74382. joinX = endX;
  74383. joinY = endY;
  74384. endX = data.elements [indexOfPathStartThis + 4];
  74385. endY = data.elements [indexOfPathStartThis + 5];
  74386. const double len1 = juce_hypot (startX - joinX,
  74387. startY - joinY);
  74388. if (len1 > 0)
  74389. {
  74390. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74391. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74392. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74393. }
  74394. const double len2 = juce_hypot (endX - joinX,
  74395. endY - joinY);
  74396. if (len2 > 0)
  74397. {
  74398. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74399. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74400. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74401. p.quadraticTo (joinX, joinY, endX, endY);
  74402. p.data.elements [indexOfPathStart + 1] = endX;
  74403. p.data.elements [indexOfPathStart + 2] = endY;
  74404. }
  74405. }
  74406. p.closeSubPath();
  74407. }
  74408. }
  74409. else if (type == quadMarker)
  74410. {
  74411. lastWasLine = false;
  74412. const float x1 = data.elements [n++];
  74413. const float y1 = data.elements [n++];
  74414. const float x2 = data.elements [n++];
  74415. const float y2 = data.elements [n++];
  74416. p.quadraticTo (x1, y1, x2, y2);
  74417. }
  74418. else if (type == cubicMarker)
  74419. {
  74420. lastWasLine = false;
  74421. const float x1 = data.elements [n++];
  74422. const float y1 = data.elements [n++];
  74423. const float x2 = data.elements [n++];
  74424. const float y2 = data.elements [n++];
  74425. const float x3 = data.elements [n++];
  74426. const float y3 = data.elements [n++];
  74427. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74428. }
  74429. }
  74430. return p;
  74431. }
  74432. void Path::loadPathFromStream (InputStream& source)
  74433. {
  74434. while (! source.isExhausted())
  74435. {
  74436. switch (source.readByte())
  74437. {
  74438. case 'm':
  74439. {
  74440. const float x = source.readFloat();
  74441. const float y = source.readFloat();
  74442. startNewSubPath (x, y);
  74443. break;
  74444. }
  74445. case 'l':
  74446. {
  74447. const float x = source.readFloat();
  74448. const float y = source.readFloat();
  74449. lineTo (x, y);
  74450. break;
  74451. }
  74452. case 'q':
  74453. {
  74454. const float x1 = source.readFloat();
  74455. const float y1 = source.readFloat();
  74456. const float x2 = source.readFloat();
  74457. const float y2 = source.readFloat();
  74458. quadraticTo (x1, y1, x2, y2);
  74459. break;
  74460. }
  74461. case 'b':
  74462. {
  74463. const float x1 = source.readFloat();
  74464. const float y1 = source.readFloat();
  74465. const float x2 = source.readFloat();
  74466. const float y2 = source.readFloat();
  74467. const float x3 = source.readFloat();
  74468. const float y3 = source.readFloat();
  74469. cubicTo (x1, y1, x2, y2, x3, y3);
  74470. break;
  74471. }
  74472. case 'c':
  74473. closeSubPath();
  74474. break;
  74475. case 'n':
  74476. useNonZeroWinding = true;
  74477. break;
  74478. case 'z':
  74479. useNonZeroWinding = false;
  74480. break;
  74481. case 'e':
  74482. return; // end of path marker
  74483. default:
  74484. jassertfalse; // illegal char in the stream
  74485. break;
  74486. }
  74487. }
  74488. }
  74489. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  74490. {
  74491. MemoryInputStream in (pathData, numberOfBytes, false);
  74492. loadPathFromStream (in);
  74493. }
  74494. void Path::writePathToStream (OutputStream& dest) const
  74495. {
  74496. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  74497. size_t i = 0;
  74498. while (i < numElements)
  74499. {
  74500. const float type = data.elements [i++];
  74501. if (type == moveMarker)
  74502. {
  74503. dest.writeByte ('m');
  74504. dest.writeFloat (data.elements [i++]);
  74505. dest.writeFloat (data.elements [i++]);
  74506. }
  74507. else if (type == lineMarker)
  74508. {
  74509. dest.writeByte ('l');
  74510. dest.writeFloat (data.elements [i++]);
  74511. dest.writeFloat (data.elements [i++]);
  74512. }
  74513. else if (type == quadMarker)
  74514. {
  74515. dest.writeByte ('q');
  74516. dest.writeFloat (data.elements [i++]);
  74517. dest.writeFloat (data.elements [i++]);
  74518. dest.writeFloat (data.elements [i++]);
  74519. dest.writeFloat (data.elements [i++]);
  74520. }
  74521. else if (type == cubicMarker)
  74522. {
  74523. dest.writeByte ('b');
  74524. dest.writeFloat (data.elements [i++]);
  74525. dest.writeFloat (data.elements [i++]);
  74526. dest.writeFloat (data.elements [i++]);
  74527. dest.writeFloat (data.elements [i++]);
  74528. dest.writeFloat (data.elements [i++]);
  74529. dest.writeFloat (data.elements [i++]);
  74530. }
  74531. else if (type == closeSubPathMarker)
  74532. {
  74533. dest.writeByte ('c');
  74534. }
  74535. }
  74536. dest.writeByte ('e'); // marks the end-of-path
  74537. }
  74538. const String Path::toString() const
  74539. {
  74540. MemoryOutputStream s (2048);
  74541. if (! useNonZeroWinding)
  74542. s << 'a';
  74543. size_t i = 0;
  74544. float lastMarker = 0.0f;
  74545. while (i < numElements)
  74546. {
  74547. const float marker = data.elements [i++];
  74548. char markerChar = 0;
  74549. int numCoords = 0;
  74550. if (marker == moveMarker)
  74551. {
  74552. markerChar = 'm';
  74553. numCoords = 2;
  74554. }
  74555. else if (marker == lineMarker)
  74556. {
  74557. markerChar = 'l';
  74558. numCoords = 2;
  74559. }
  74560. else if (marker == quadMarker)
  74561. {
  74562. markerChar = 'q';
  74563. numCoords = 4;
  74564. }
  74565. else if (marker == cubicMarker)
  74566. {
  74567. markerChar = 'c';
  74568. numCoords = 6;
  74569. }
  74570. else
  74571. {
  74572. jassert (marker == closeSubPathMarker);
  74573. markerChar = 'z';
  74574. }
  74575. if (marker != lastMarker)
  74576. {
  74577. if (s.getDataSize() != 0)
  74578. s << ' ';
  74579. s << markerChar;
  74580. lastMarker = marker;
  74581. }
  74582. while (--numCoords >= 0 && i < numElements)
  74583. {
  74584. String coord (data.elements [i++], 3);
  74585. while (coord.endsWithChar ('0') && coord != "0")
  74586. coord = coord.dropLastCharacters (1);
  74587. if (coord.endsWithChar ('.'))
  74588. coord = coord.dropLastCharacters (1);
  74589. if (s.getDataSize() != 0)
  74590. s << ' ';
  74591. s << coord;
  74592. }
  74593. }
  74594. return s.toUTF8();
  74595. }
  74596. void Path::restoreFromString (const String& stringVersion)
  74597. {
  74598. clear();
  74599. setUsingNonZeroWinding (true);
  74600. const juce_wchar* t = stringVersion;
  74601. juce_wchar marker = 'm';
  74602. int numValues = 2;
  74603. float values [6];
  74604. for (;;)
  74605. {
  74606. const String token (PathHelpers::nextToken (t));
  74607. const juce_wchar firstChar = token[0];
  74608. int startNum = 0;
  74609. if (firstChar == 0)
  74610. break;
  74611. if (firstChar == 'm' || firstChar == 'l')
  74612. {
  74613. marker = firstChar;
  74614. numValues = 2;
  74615. }
  74616. else if (firstChar == 'q')
  74617. {
  74618. marker = firstChar;
  74619. numValues = 4;
  74620. }
  74621. else if (firstChar == 'c')
  74622. {
  74623. marker = firstChar;
  74624. numValues = 6;
  74625. }
  74626. else if (firstChar == 'z')
  74627. {
  74628. marker = firstChar;
  74629. numValues = 0;
  74630. }
  74631. else if (firstChar == 'a')
  74632. {
  74633. setUsingNonZeroWinding (false);
  74634. continue;
  74635. }
  74636. else
  74637. {
  74638. ++startNum;
  74639. values [0] = token.getFloatValue();
  74640. }
  74641. for (int i = startNum; i < numValues; ++i)
  74642. values [i] = PathHelpers::nextToken (t).getFloatValue();
  74643. switch (marker)
  74644. {
  74645. case 'm':
  74646. startNewSubPath (values[0], values[1]);
  74647. break;
  74648. case 'l':
  74649. lineTo (values[0], values[1]);
  74650. break;
  74651. case 'q':
  74652. quadraticTo (values[0], values[1],
  74653. values[2], values[3]);
  74654. break;
  74655. case 'c':
  74656. cubicTo (values[0], values[1],
  74657. values[2], values[3],
  74658. values[4], values[5]);
  74659. break;
  74660. case 'z':
  74661. closeSubPath();
  74662. break;
  74663. default:
  74664. jassertfalse; // illegal string format?
  74665. break;
  74666. }
  74667. }
  74668. }
  74669. Path::Iterator::Iterator (const Path& path_)
  74670. : path (path_),
  74671. index (0)
  74672. {
  74673. }
  74674. Path::Iterator::~Iterator()
  74675. {
  74676. }
  74677. bool Path::Iterator::next()
  74678. {
  74679. const float* const elements = path.data.elements;
  74680. if (index < path.numElements)
  74681. {
  74682. const float type = elements [index++];
  74683. if (type == moveMarker)
  74684. {
  74685. elementType = startNewSubPath;
  74686. x1 = elements [index++];
  74687. y1 = elements [index++];
  74688. }
  74689. else if (type == lineMarker)
  74690. {
  74691. elementType = lineTo;
  74692. x1 = elements [index++];
  74693. y1 = elements [index++];
  74694. }
  74695. else if (type == quadMarker)
  74696. {
  74697. elementType = quadraticTo;
  74698. x1 = elements [index++];
  74699. y1 = elements [index++];
  74700. x2 = elements [index++];
  74701. y2 = elements [index++];
  74702. }
  74703. else if (type == cubicMarker)
  74704. {
  74705. elementType = cubicTo;
  74706. x1 = elements [index++];
  74707. y1 = elements [index++];
  74708. x2 = elements [index++];
  74709. y2 = elements [index++];
  74710. x3 = elements [index++];
  74711. y3 = elements [index++];
  74712. }
  74713. else if (type == closeSubPathMarker)
  74714. {
  74715. elementType = closePath;
  74716. }
  74717. return true;
  74718. }
  74719. return false;
  74720. }
  74721. END_JUCE_NAMESPACE
  74722. /*** End of inlined file: juce_Path.cpp ***/
  74723. /*** Start of inlined file: juce_PathIterator.cpp ***/
  74724. BEGIN_JUCE_NAMESPACE
  74725. #if JUCE_MSVC && JUCE_DEBUG
  74726. #pragma optimize ("t", on)
  74727. #endif
  74728. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  74729. const AffineTransform& transform_,
  74730. float tolerence_)
  74731. : x2 (0),
  74732. y2 (0),
  74733. closesSubPath (false),
  74734. subPathIndex (-1),
  74735. path (path_),
  74736. transform (transform_),
  74737. points (path_.data.elements),
  74738. tolerence (tolerence_ * tolerence_),
  74739. subPathCloseX (0),
  74740. subPathCloseY (0),
  74741. isIdentityTransform (transform_.isIdentity()),
  74742. stackBase (32),
  74743. index (0),
  74744. stackSize (32)
  74745. {
  74746. stackPos = stackBase;
  74747. }
  74748. PathFlatteningIterator::~PathFlatteningIterator()
  74749. {
  74750. }
  74751. bool PathFlatteningIterator::next()
  74752. {
  74753. x1 = x2;
  74754. y1 = y2;
  74755. float x3 = 0;
  74756. float y3 = 0;
  74757. float x4 = 0;
  74758. float y4 = 0;
  74759. float type;
  74760. for (;;)
  74761. {
  74762. if (stackPos == stackBase)
  74763. {
  74764. if (index >= path.numElements)
  74765. {
  74766. return false;
  74767. }
  74768. else
  74769. {
  74770. type = points [index++];
  74771. if (type != Path::closeSubPathMarker)
  74772. {
  74773. x2 = points [index++];
  74774. y2 = points [index++];
  74775. if (type == Path::quadMarker)
  74776. {
  74777. x3 = points [index++];
  74778. y3 = points [index++];
  74779. if (! isIdentityTransform)
  74780. transform.transformPoints (x2, y2, x3, y3);
  74781. }
  74782. else if (type == Path::cubicMarker)
  74783. {
  74784. x3 = points [index++];
  74785. y3 = points [index++];
  74786. x4 = points [index++];
  74787. y4 = points [index++];
  74788. if (! isIdentityTransform)
  74789. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  74790. }
  74791. else
  74792. {
  74793. if (! isIdentityTransform)
  74794. transform.transformPoint (x2, y2);
  74795. }
  74796. }
  74797. }
  74798. }
  74799. else
  74800. {
  74801. type = *--stackPos;
  74802. if (type != Path::closeSubPathMarker)
  74803. {
  74804. x2 = *--stackPos;
  74805. y2 = *--stackPos;
  74806. if (type == Path::quadMarker)
  74807. {
  74808. x3 = *--stackPos;
  74809. y3 = *--stackPos;
  74810. }
  74811. else if (type == Path::cubicMarker)
  74812. {
  74813. x3 = *--stackPos;
  74814. y3 = *--stackPos;
  74815. x4 = *--stackPos;
  74816. y4 = *--stackPos;
  74817. }
  74818. }
  74819. }
  74820. if (type == Path::lineMarker)
  74821. {
  74822. ++subPathIndex;
  74823. closesSubPath = (stackPos == stackBase)
  74824. && (index < path.numElements)
  74825. && (points [index] == Path::closeSubPathMarker)
  74826. && x2 == subPathCloseX
  74827. && y2 == subPathCloseY;
  74828. return true;
  74829. }
  74830. else if (type == Path::quadMarker)
  74831. {
  74832. const size_t offset = (size_t) (stackPos - stackBase);
  74833. if (offset >= stackSize - 10)
  74834. {
  74835. stackSize <<= 1;
  74836. stackBase.realloc (stackSize);
  74837. stackPos = stackBase + offset;
  74838. }
  74839. const float dx1 = x1 - x2;
  74840. const float dy1 = y1 - y2;
  74841. const float dx2 = x2 - x3;
  74842. const float dy2 = y2 - y3;
  74843. const float m1x = (x1 + x2) * 0.5f;
  74844. const float m1y = (y1 + y2) * 0.5f;
  74845. const float m2x = (x2 + x3) * 0.5f;
  74846. const float m2y = (y2 + y3) * 0.5f;
  74847. const float m3x = (m1x + m2x) * 0.5f;
  74848. const float m3y = (m1y + m2y) * 0.5f;
  74849. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  74850. {
  74851. *stackPos++ = y3;
  74852. *stackPos++ = x3;
  74853. *stackPos++ = m2y;
  74854. *stackPos++ = m2x;
  74855. *stackPos++ = Path::quadMarker;
  74856. *stackPos++ = m3y;
  74857. *stackPos++ = m3x;
  74858. *stackPos++ = m1y;
  74859. *stackPos++ = m1x;
  74860. *stackPos++ = Path::quadMarker;
  74861. }
  74862. else
  74863. {
  74864. *stackPos++ = y3;
  74865. *stackPos++ = x3;
  74866. *stackPos++ = Path::lineMarker;
  74867. *stackPos++ = m3y;
  74868. *stackPos++ = m3x;
  74869. *stackPos++ = Path::lineMarker;
  74870. }
  74871. jassert (stackPos < stackBase + stackSize);
  74872. }
  74873. else if (type == Path::cubicMarker)
  74874. {
  74875. const size_t offset = (size_t) (stackPos - stackBase);
  74876. if (offset >= stackSize - 16)
  74877. {
  74878. stackSize <<= 1;
  74879. stackBase.realloc (stackSize);
  74880. stackPos = stackBase + offset;
  74881. }
  74882. const float dx1 = x1 - x2;
  74883. const float dy1 = y1 - y2;
  74884. const float dx2 = x2 - x3;
  74885. const float dy2 = y2 - y3;
  74886. const float dx3 = x3 - x4;
  74887. const float dy3 = y3 - y4;
  74888. const float m1x = (x1 + x2) * 0.5f;
  74889. const float m1y = (y1 + y2) * 0.5f;
  74890. const float m2x = (x3 + x2) * 0.5f;
  74891. const float m2y = (y3 + y2) * 0.5f;
  74892. const float m3x = (x3 + x4) * 0.5f;
  74893. const float m3y = (y3 + y4) * 0.5f;
  74894. const float m4x = (m1x + m2x) * 0.5f;
  74895. const float m4y = (m1y + m2y) * 0.5f;
  74896. const float m5x = (m3x + m2x) * 0.5f;
  74897. const float m5y = (m3y + m2y) * 0.5f;
  74898. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  74899. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  74900. {
  74901. *stackPos++ = y4;
  74902. *stackPos++ = x4;
  74903. *stackPos++ = m3y;
  74904. *stackPos++ = m3x;
  74905. *stackPos++ = m5y;
  74906. *stackPos++ = m5x;
  74907. *stackPos++ = Path::cubicMarker;
  74908. *stackPos++ = (m4y + m5y) * 0.5f;
  74909. *stackPos++ = (m4x + m5x) * 0.5f;
  74910. *stackPos++ = m4y;
  74911. *stackPos++ = m4x;
  74912. *stackPos++ = m1y;
  74913. *stackPos++ = m1x;
  74914. *stackPos++ = Path::cubicMarker;
  74915. }
  74916. else
  74917. {
  74918. *stackPos++ = y4;
  74919. *stackPos++ = x4;
  74920. *stackPos++ = Path::lineMarker;
  74921. *stackPos++ = m5y;
  74922. *stackPos++ = m5x;
  74923. *stackPos++ = Path::lineMarker;
  74924. *stackPos++ = m4y;
  74925. *stackPos++ = m4x;
  74926. *stackPos++ = Path::lineMarker;
  74927. }
  74928. }
  74929. else if (type == Path::closeSubPathMarker)
  74930. {
  74931. if (x2 != subPathCloseX || y2 != subPathCloseY)
  74932. {
  74933. x1 = x2;
  74934. y1 = y2;
  74935. x2 = subPathCloseX;
  74936. y2 = subPathCloseY;
  74937. closesSubPath = true;
  74938. return true;
  74939. }
  74940. }
  74941. else
  74942. {
  74943. jassert (type == Path::moveMarker);
  74944. subPathIndex = -1;
  74945. subPathCloseX = x1 = x2;
  74946. subPathCloseY = y1 = y2;
  74947. }
  74948. }
  74949. }
  74950. #if JUCE_MSVC && JUCE_DEBUG
  74951. #pragma optimize ("", on) // resets optimisations to the project defaults
  74952. #endif
  74953. END_JUCE_NAMESPACE
  74954. /*** End of inlined file: juce_PathIterator.cpp ***/
  74955. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  74956. BEGIN_JUCE_NAMESPACE
  74957. PathStrokeType::PathStrokeType (const float strokeThickness,
  74958. const JointStyle jointStyle_,
  74959. const EndCapStyle endStyle_) throw()
  74960. : thickness (strokeThickness),
  74961. jointStyle (jointStyle_),
  74962. endStyle (endStyle_)
  74963. {
  74964. }
  74965. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  74966. : thickness (other.thickness),
  74967. jointStyle (other.jointStyle),
  74968. endStyle (other.endStyle)
  74969. {
  74970. }
  74971. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  74972. {
  74973. thickness = other.thickness;
  74974. jointStyle = other.jointStyle;
  74975. endStyle = other.endStyle;
  74976. return *this;
  74977. }
  74978. PathStrokeType::~PathStrokeType() throw()
  74979. {
  74980. }
  74981. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  74982. {
  74983. return thickness == other.thickness
  74984. && jointStyle == other.jointStyle
  74985. && endStyle == other.endStyle;
  74986. }
  74987. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  74988. {
  74989. return ! operator== (other);
  74990. }
  74991. namespace PathStrokeHelpers
  74992. {
  74993. static bool lineIntersection (const float x1, const float y1,
  74994. const float x2, const float y2,
  74995. const float x3, const float y3,
  74996. const float x4, const float y4,
  74997. float& intersectionX,
  74998. float& intersectionY,
  74999. float& distanceBeyondLine1EndSquared) throw()
  75000. {
  75001. if (x2 != x3 || y2 != y3)
  75002. {
  75003. const float dx1 = x2 - x1;
  75004. const float dy1 = y2 - y1;
  75005. const float dx2 = x4 - x3;
  75006. const float dy2 = y4 - y3;
  75007. const float divisor = dx1 * dy2 - dx2 * dy1;
  75008. if (divisor == 0)
  75009. {
  75010. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75011. {
  75012. if (dy1 == 0 && dy2 != 0)
  75013. {
  75014. const float along = (y1 - y3) / dy2;
  75015. intersectionX = x3 + along * dx2;
  75016. intersectionY = y1;
  75017. distanceBeyondLine1EndSquared = intersectionX - x2;
  75018. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75019. if ((x2 > x1) == (intersectionX < x2))
  75020. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75021. return along >= 0 && along <= 1.0f;
  75022. }
  75023. else if (dy2 == 0 && dy1 != 0)
  75024. {
  75025. const float along = (y3 - y1) / dy1;
  75026. intersectionX = x1 + along * dx1;
  75027. intersectionY = y3;
  75028. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75029. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75030. if (along < 1.0f)
  75031. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75032. return along >= 0 && along <= 1.0f;
  75033. }
  75034. else if (dx1 == 0 && dx2 != 0)
  75035. {
  75036. const float along = (x1 - x3) / dx2;
  75037. intersectionX = x1;
  75038. intersectionY = y3 + along * dy2;
  75039. distanceBeyondLine1EndSquared = intersectionY - y2;
  75040. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75041. if ((y2 > y1) == (intersectionY < y2))
  75042. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75043. return along >= 0 && along <= 1.0f;
  75044. }
  75045. else if (dx2 == 0 && dx1 != 0)
  75046. {
  75047. const float along = (x3 - x1) / dx1;
  75048. intersectionX = x3;
  75049. intersectionY = y1 + along * dy1;
  75050. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75051. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75052. if (along < 1.0f)
  75053. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75054. return along >= 0 && along <= 1.0f;
  75055. }
  75056. }
  75057. intersectionX = 0.5f * (x2 + x3);
  75058. intersectionY = 0.5f * (y2 + y3);
  75059. distanceBeyondLine1EndSquared = 0.0f;
  75060. return false;
  75061. }
  75062. else
  75063. {
  75064. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75065. intersectionX = x1 + along1 * dx1;
  75066. intersectionY = y1 + along1 * dy1;
  75067. if (along1 >= 0 && along1 <= 1.0f)
  75068. {
  75069. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75070. if (along2 >= 0 && along2 <= divisor)
  75071. {
  75072. distanceBeyondLine1EndSquared = 0.0f;
  75073. return true;
  75074. }
  75075. }
  75076. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75077. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75078. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75079. if (along1 < 1.0f)
  75080. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75081. return false;
  75082. }
  75083. }
  75084. intersectionX = x2;
  75085. intersectionY = y2;
  75086. distanceBeyondLine1EndSquared = 0.0f;
  75087. return true;
  75088. }
  75089. static void addEdgeAndJoint (Path& destPath,
  75090. const PathStrokeType::JointStyle style,
  75091. const float maxMiterExtensionSquared, const float width,
  75092. const float x1, const float y1,
  75093. const float x2, const float y2,
  75094. const float x3, const float y3,
  75095. const float x4, const float y4,
  75096. const float midX, const float midY)
  75097. {
  75098. if (style == PathStrokeType::beveled
  75099. || (x3 == x4 && y3 == y4)
  75100. || (x1 == x2 && y1 == y2))
  75101. {
  75102. destPath.lineTo (x2, y2);
  75103. destPath.lineTo (x3, y3);
  75104. }
  75105. else
  75106. {
  75107. float jx, jy, distanceBeyondLine1EndSquared;
  75108. // if they intersect, use this point..
  75109. if (lineIntersection (x1, y1, x2, y2,
  75110. x3, y3, x4, y4,
  75111. jx, jy, distanceBeyondLine1EndSquared))
  75112. {
  75113. destPath.lineTo (jx, jy);
  75114. }
  75115. else
  75116. {
  75117. if (style == PathStrokeType::mitered)
  75118. {
  75119. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75120. && distanceBeyondLine1EndSquared > 0.0f)
  75121. {
  75122. destPath.lineTo (jx, jy);
  75123. }
  75124. else
  75125. {
  75126. // the end sticks out too far, so just use a blunt joint
  75127. destPath.lineTo (x2, y2);
  75128. destPath.lineTo (x3, y3);
  75129. }
  75130. }
  75131. else
  75132. {
  75133. // curved joints
  75134. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75135. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75136. const float angleIncrement = 0.1f;
  75137. destPath.lineTo (x2, y2);
  75138. if (std::abs (angle1 - angle2) > angleIncrement)
  75139. {
  75140. if (angle2 > angle1 + float_Pi
  75141. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75142. {
  75143. if (angle2 > angle1)
  75144. angle2 -= float_Pi * 2.0f;
  75145. jassert (angle1 <= angle2 + float_Pi);
  75146. angle1 -= angleIncrement;
  75147. while (angle1 > angle2)
  75148. {
  75149. destPath.lineTo (midX + width * std::sin (angle1),
  75150. midY + width * std::cos (angle1));
  75151. angle1 -= angleIncrement;
  75152. }
  75153. }
  75154. else
  75155. {
  75156. if (angle1 > angle2)
  75157. angle1 -= float_Pi * 2.0f;
  75158. jassert (angle1 >= angle2 - float_Pi);
  75159. angle1 += angleIncrement;
  75160. while (angle1 < angle2)
  75161. {
  75162. destPath.lineTo (midX + width * std::sin (angle1),
  75163. midY + width * std::cos (angle1));
  75164. angle1 += angleIncrement;
  75165. }
  75166. }
  75167. }
  75168. destPath.lineTo (x3, y3);
  75169. }
  75170. }
  75171. }
  75172. }
  75173. static void addLineEnd (Path& destPath,
  75174. const PathStrokeType::EndCapStyle style,
  75175. const float x1, const float y1,
  75176. const float x2, const float y2,
  75177. const float width)
  75178. {
  75179. if (style == PathStrokeType::butt)
  75180. {
  75181. destPath.lineTo (x2, y2);
  75182. }
  75183. else
  75184. {
  75185. float offx1, offy1, offx2, offy2;
  75186. float dx = x2 - x1;
  75187. float dy = y2 - y1;
  75188. const float len = juce_hypotf (dx, dy);
  75189. if (len == 0)
  75190. {
  75191. offx1 = offx2 = x1;
  75192. offy1 = offy2 = y1;
  75193. }
  75194. else
  75195. {
  75196. const float offset = width / len;
  75197. dx *= offset;
  75198. dy *= offset;
  75199. offx1 = x1 + dy;
  75200. offy1 = y1 - dx;
  75201. offx2 = x2 + dy;
  75202. offy2 = y2 - dx;
  75203. }
  75204. if (style == PathStrokeType::square)
  75205. {
  75206. // sqaure ends
  75207. destPath.lineTo (offx1, offy1);
  75208. destPath.lineTo (offx2, offy2);
  75209. destPath.lineTo (x2, y2);
  75210. }
  75211. else
  75212. {
  75213. // rounded ends
  75214. const float midx = (offx1 + offx2) * 0.5f;
  75215. const float midy = (offy1 + offy2) * 0.5f;
  75216. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75217. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75218. midx, midy);
  75219. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75220. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75221. x2, y2);
  75222. }
  75223. }
  75224. }
  75225. struct Arrowhead
  75226. {
  75227. float startWidth, startLength;
  75228. float endWidth, endLength;
  75229. };
  75230. static void addArrowhead (Path& destPath,
  75231. const float x1, const float y1,
  75232. const float x2, const float y2,
  75233. const float tipX, const float tipY,
  75234. const float width,
  75235. const float arrowheadWidth)
  75236. {
  75237. Line<float> line (x1, y1, x2, y2);
  75238. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75239. destPath.lineTo (tipX, tipY);
  75240. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75241. destPath.lineTo (x2, y2);
  75242. }
  75243. struct LineSection
  75244. {
  75245. float x1, y1, x2, y2; // original line
  75246. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75247. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75248. };
  75249. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75250. {
  75251. while (amountAtEnd > 0 && subPath.size() > 0)
  75252. {
  75253. LineSection& l = subPath.getReference (subPath.size() - 1);
  75254. float dx = l.rx2 - l.rx1;
  75255. float dy = l.ry2 - l.ry1;
  75256. const float len = juce_hypotf (dx, dy);
  75257. if (len <= amountAtEnd && subPath.size() > 1)
  75258. {
  75259. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75260. prev.x2 = l.x2;
  75261. prev.y2 = l.y2;
  75262. subPath.removeLast();
  75263. amountAtEnd -= len;
  75264. }
  75265. else
  75266. {
  75267. const float prop = jmin (0.9999f, amountAtEnd / len);
  75268. dx *= prop;
  75269. dy *= prop;
  75270. l.rx1 += dx;
  75271. l.ry1 += dy;
  75272. l.lx2 += dx;
  75273. l.ly2 += dy;
  75274. break;
  75275. }
  75276. }
  75277. while (amountAtStart > 0 && subPath.size() > 0)
  75278. {
  75279. LineSection& l = subPath.getReference (0);
  75280. float dx = l.rx2 - l.rx1;
  75281. float dy = l.ry2 - l.ry1;
  75282. const float len = juce_hypotf (dx, dy);
  75283. if (len <= amountAtStart && subPath.size() > 1)
  75284. {
  75285. LineSection& next = subPath.getReference (1);
  75286. next.x1 = l.x1;
  75287. next.y1 = l.y1;
  75288. subPath.remove (0);
  75289. amountAtStart -= len;
  75290. }
  75291. else
  75292. {
  75293. const float prop = jmin (0.9999f, amountAtStart / len);
  75294. dx *= prop;
  75295. dy *= prop;
  75296. l.rx2 -= dx;
  75297. l.ry2 -= dy;
  75298. l.lx1 -= dx;
  75299. l.ly1 -= dy;
  75300. break;
  75301. }
  75302. }
  75303. }
  75304. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75305. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75306. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75307. const Arrowhead* const arrowhead)
  75308. {
  75309. jassert (subPath.size() > 0);
  75310. if (arrowhead != 0)
  75311. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75312. const LineSection& firstLine = subPath.getReference (0);
  75313. float lastX1 = firstLine.lx1;
  75314. float lastY1 = firstLine.ly1;
  75315. float lastX2 = firstLine.lx2;
  75316. float lastY2 = firstLine.ly2;
  75317. if (isClosed)
  75318. {
  75319. destPath.startNewSubPath (lastX1, lastY1);
  75320. }
  75321. else
  75322. {
  75323. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75324. if (arrowhead != 0)
  75325. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75326. width, arrowhead->startWidth);
  75327. else
  75328. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75329. }
  75330. int i;
  75331. for (i = 1; i < subPath.size(); ++i)
  75332. {
  75333. const LineSection& l = subPath.getReference (i);
  75334. addEdgeAndJoint (destPath, jointStyle,
  75335. maxMiterExtensionSquared, width,
  75336. lastX1, lastY1, lastX2, lastY2,
  75337. l.lx1, l.ly1, l.lx2, l.ly2,
  75338. l.x1, l.y1);
  75339. lastX1 = l.lx1;
  75340. lastY1 = l.ly1;
  75341. lastX2 = l.lx2;
  75342. lastY2 = l.ly2;
  75343. }
  75344. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75345. if (isClosed)
  75346. {
  75347. const LineSection& l = subPath.getReference (0);
  75348. addEdgeAndJoint (destPath, jointStyle,
  75349. maxMiterExtensionSquared, width,
  75350. lastX1, lastY1, lastX2, lastY2,
  75351. l.lx1, l.ly1, l.lx2, l.ly2,
  75352. l.x1, l.y1);
  75353. destPath.closeSubPath();
  75354. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75355. }
  75356. else
  75357. {
  75358. destPath.lineTo (lastX2, lastY2);
  75359. if (arrowhead != 0)
  75360. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75361. width, arrowhead->endWidth);
  75362. else
  75363. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75364. }
  75365. lastX1 = lastLine.rx1;
  75366. lastY1 = lastLine.ry1;
  75367. lastX2 = lastLine.rx2;
  75368. lastY2 = lastLine.ry2;
  75369. for (i = subPath.size() - 1; --i >= 0;)
  75370. {
  75371. const LineSection& l = subPath.getReference (i);
  75372. addEdgeAndJoint (destPath, jointStyle,
  75373. maxMiterExtensionSquared, width,
  75374. lastX1, lastY1, lastX2, lastY2,
  75375. l.rx1, l.ry1, l.rx2, l.ry2,
  75376. l.x2, l.y2);
  75377. lastX1 = l.rx1;
  75378. lastY1 = l.ry1;
  75379. lastX2 = l.rx2;
  75380. lastY2 = l.ry2;
  75381. }
  75382. if (isClosed)
  75383. {
  75384. addEdgeAndJoint (destPath, jointStyle,
  75385. maxMiterExtensionSquared, width,
  75386. lastX1, lastY1, lastX2, lastY2,
  75387. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75388. lastLine.x2, lastLine.y2);
  75389. }
  75390. else
  75391. {
  75392. // do the last line
  75393. destPath.lineTo (lastX2, lastY2);
  75394. }
  75395. destPath.closeSubPath();
  75396. }
  75397. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75398. const PathStrokeType::EndCapStyle endStyle,
  75399. Path& destPath, const Path& source,
  75400. const AffineTransform& transform,
  75401. const float extraAccuracy, const Arrowhead* const arrowhead)
  75402. {
  75403. if (thickness <= 0)
  75404. {
  75405. destPath.clear();
  75406. return;
  75407. }
  75408. const Path* sourcePath = &source;
  75409. Path temp;
  75410. if (sourcePath == &destPath)
  75411. {
  75412. destPath.swapWithPath (temp);
  75413. sourcePath = &temp;
  75414. }
  75415. else
  75416. {
  75417. destPath.clear();
  75418. }
  75419. destPath.setUsingNonZeroWinding (true);
  75420. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75421. const float width = 0.5f * thickness;
  75422. // Iterate the path, creating a list of the
  75423. // left/right-hand lines along either side of it...
  75424. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75425. Array <LineSection> subPath;
  75426. subPath.ensureStorageAllocated (512);
  75427. LineSection l;
  75428. l.x1 = 0;
  75429. l.y1 = 0;
  75430. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75431. while (it.next())
  75432. {
  75433. if (it.subPathIndex == 0)
  75434. {
  75435. if (subPath.size() > 0)
  75436. {
  75437. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75438. subPath.clearQuick();
  75439. }
  75440. l.x1 = it.x1;
  75441. l.y1 = it.y1;
  75442. }
  75443. l.x2 = it.x2;
  75444. l.y2 = it.y2;
  75445. float dx = l.x2 - l.x1;
  75446. float dy = l.y2 - l.y1;
  75447. const float hypotSquared = dx*dx + dy*dy;
  75448. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75449. {
  75450. const float len = std::sqrt (hypotSquared);
  75451. if (len == 0)
  75452. {
  75453. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75454. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75455. }
  75456. else
  75457. {
  75458. const float offset = width / len;
  75459. dx *= offset;
  75460. dy *= offset;
  75461. l.rx2 = l.x1 - dy;
  75462. l.ry2 = l.y1 + dx;
  75463. l.lx1 = l.x1 + dy;
  75464. l.ly1 = l.y1 - dx;
  75465. l.lx2 = l.x2 + dy;
  75466. l.ly2 = l.y2 - dx;
  75467. l.rx1 = l.x2 - dy;
  75468. l.ry1 = l.y2 + dx;
  75469. }
  75470. subPath.add (l);
  75471. if (it.closesSubPath)
  75472. {
  75473. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75474. subPath.clearQuick();
  75475. }
  75476. else
  75477. {
  75478. l.x1 = it.x2;
  75479. l.y1 = it.y2;
  75480. }
  75481. }
  75482. }
  75483. if (subPath.size() > 0)
  75484. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75485. }
  75486. }
  75487. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  75488. const AffineTransform& transform, const float extraAccuracy) const
  75489. {
  75490. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  75491. transform, extraAccuracy, 0);
  75492. }
  75493. void PathStrokeType::createDashedStroke (Path& destPath,
  75494. const Path& sourcePath,
  75495. const float* dashLengths,
  75496. int numDashLengths,
  75497. const AffineTransform& transform,
  75498. const float extraAccuracy) const
  75499. {
  75500. if (thickness <= 0)
  75501. return;
  75502. // this should really be an even number..
  75503. jassert ((numDashLengths & 1) == 0);
  75504. Path newDestPath;
  75505. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  75506. bool first = true;
  75507. int dashNum = 0;
  75508. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  75509. float dx = 0.0f, dy = 0.0f;
  75510. for (;;)
  75511. {
  75512. const bool isSolid = ((dashNum & 1) == 0);
  75513. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  75514. jassert (dashLen > 0); // must be a positive increment!
  75515. if (dashLen <= 0)
  75516. break;
  75517. pos += dashLen;
  75518. while (pos > lineEndPos)
  75519. {
  75520. if (! it.next())
  75521. {
  75522. if (isSolid && ! first)
  75523. newDestPath.lineTo (it.x2, it.y2);
  75524. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  75525. return;
  75526. }
  75527. if (isSolid && ! first)
  75528. newDestPath.lineTo (it.x1, it.y1);
  75529. else
  75530. newDestPath.startNewSubPath (it.x1, it.y1);
  75531. dx = it.x2 - it.x1;
  75532. dy = it.y2 - it.y1;
  75533. lineLen = juce_hypotf (dx, dy);
  75534. lineEndPos += lineLen;
  75535. first = it.closesSubPath;
  75536. }
  75537. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  75538. if (isSolid)
  75539. newDestPath.lineTo (it.x1 + dx * alpha,
  75540. it.y1 + dy * alpha);
  75541. else
  75542. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  75543. it.y1 + dy * alpha);
  75544. }
  75545. }
  75546. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  75547. const Path& sourcePath,
  75548. const float arrowheadStartWidth, const float arrowheadStartLength,
  75549. const float arrowheadEndWidth, const float arrowheadEndLength,
  75550. const AffineTransform& transform,
  75551. const float extraAccuracy) const
  75552. {
  75553. PathStrokeHelpers::Arrowhead head;
  75554. head.startWidth = arrowheadStartWidth;
  75555. head.startLength = arrowheadStartLength;
  75556. head.endWidth = arrowheadEndWidth;
  75557. head.endLength = arrowheadEndLength;
  75558. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  75559. destPath, sourcePath, transform, extraAccuracy, &head);
  75560. }
  75561. END_JUCE_NAMESPACE
  75562. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  75563. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  75564. BEGIN_JUCE_NAMESPACE
  75565. PositionedRectangle::PositionedRectangle() throw()
  75566. : x (0.0),
  75567. y (0.0),
  75568. w (0.0),
  75569. h (0.0),
  75570. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  75571. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  75572. wMode (absoluteSize),
  75573. hMode (absoluteSize)
  75574. {
  75575. }
  75576. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  75577. : x (other.x),
  75578. y (other.y),
  75579. w (other.w),
  75580. h (other.h),
  75581. xMode (other.xMode),
  75582. yMode (other.yMode),
  75583. wMode (other.wMode),
  75584. hMode (other.hMode)
  75585. {
  75586. }
  75587. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  75588. {
  75589. x = other.x;
  75590. y = other.y;
  75591. w = other.w;
  75592. h = other.h;
  75593. xMode = other.xMode;
  75594. yMode = other.yMode;
  75595. wMode = other.wMode;
  75596. hMode = other.hMode;
  75597. return *this;
  75598. }
  75599. PositionedRectangle::~PositionedRectangle() throw()
  75600. {
  75601. }
  75602. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  75603. {
  75604. return x == other.x
  75605. && y == other.y
  75606. && w == other.w
  75607. && h == other.h
  75608. && xMode == other.xMode
  75609. && yMode == other.yMode
  75610. && wMode == other.wMode
  75611. && hMode == other.hMode;
  75612. }
  75613. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  75614. {
  75615. return ! operator== (other);
  75616. }
  75617. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  75618. {
  75619. StringArray tokens;
  75620. tokens.addTokens (stringVersion, false);
  75621. decodePosString (tokens [0], xMode, x);
  75622. decodePosString (tokens [1], yMode, y);
  75623. decodeSizeString (tokens [2], wMode, w);
  75624. decodeSizeString (tokens [3], hMode, h);
  75625. }
  75626. const String PositionedRectangle::toString() const throw()
  75627. {
  75628. String s;
  75629. s.preallocateStorage (12);
  75630. addPosDescription (s, xMode, x);
  75631. s << ' ';
  75632. addPosDescription (s, yMode, y);
  75633. s << ' ';
  75634. addSizeDescription (s, wMode, w);
  75635. s << ' ';
  75636. addSizeDescription (s, hMode, h);
  75637. return s;
  75638. }
  75639. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  75640. {
  75641. jassert (! target.isEmpty());
  75642. double x_, y_, w_, h_;
  75643. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  75644. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  75645. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  75646. roundToInt (w_), roundToInt (h_));
  75647. }
  75648. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  75649. double& x_, double& y_,
  75650. double& w_, double& h_) const throw()
  75651. {
  75652. jassert (! target.isEmpty());
  75653. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  75654. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  75655. }
  75656. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  75657. {
  75658. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  75659. }
  75660. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  75661. const Rectangle<int>& target) throw()
  75662. {
  75663. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  75664. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  75665. }
  75666. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  75667. const double newW, const double newH,
  75668. const Rectangle<int>& target) throw()
  75669. {
  75670. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  75671. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  75672. }
  75673. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  75674. {
  75675. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  75676. updateFrom (comp.getBounds(), Rectangle<int>());
  75677. else
  75678. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  75679. }
  75680. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  75681. {
  75682. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  75683. }
  75684. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  75685. {
  75686. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  75687. | absoluteFromParentBottomRight
  75688. | absoluteFromParentCentre
  75689. | proportionOfParentSize));
  75690. }
  75691. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  75692. {
  75693. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  75694. }
  75695. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  75696. {
  75697. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  75698. | absoluteFromParentBottomRight
  75699. | absoluteFromParentCentre
  75700. | proportionOfParentSize));
  75701. }
  75702. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  75703. {
  75704. return (SizeMode) wMode;
  75705. }
  75706. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  75707. {
  75708. return (SizeMode) hMode;
  75709. }
  75710. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  75711. const PositionMode xMode_,
  75712. const AnchorPoint yAnchor,
  75713. const PositionMode yMode_,
  75714. const SizeMode widthMode,
  75715. const SizeMode heightMode,
  75716. const Rectangle<int>& target) throw()
  75717. {
  75718. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  75719. {
  75720. double tx, tw;
  75721. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  75722. xMode = (uint8) (xAnchor | xMode_);
  75723. wMode = (uint8) widthMode;
  75724. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  75725. }
  75726. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  75727. {
  75728. double ty, th;
  75729. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  75730. yMode = (uint8) (yAnchor | yMode_);
  75731. hMode = (uint8) heightMode;
  75732. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  75733. }
  75734. }
  75735. bool PositionedRectangle::isPositionAbsolute() const throw()
  75736. {
  75737. return xMode == absoluteFromParentTopLeft
  75738. && yMode == absoluteFromParentTopLeft
  75739. && wMode == absoluteSize
  75740. && hMode == absoluteSize;
  75741. }
  75742. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  75743. {
  75744. if ((mode & proportionOfParentSize) != 0)
  75745. {
  75746. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  75747. }
  75748. else
  75749. {
  75750. s << (roundToInt (value * 100.0) / 100.0);
  75751. if ((mode & absoluteFromParentBottomRight) != 0)
  75752. s << 'R';
  75753. else if ((mode & absoluteFromParentCentre) != 0)
  75754. s << 'C';
  75755. }
  75756. if ((mode & anchorAtRightOrBottom) != 0)
  75757. s << 'r';
  75758. else if ((mode & anchorAtCentre) != 0)
  75759. s << 'c';
  75760. }
  75761. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  75762. {
  75763. if (mode == proportionalSize)
  75764. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  75765. else if (mode == parentSizeMinusAbsolute)
  75766. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  75767. else
  75768. s << (roundToInt (value * 100.0) / 100.0);
  75769. }
  75770. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  75771. {
  75772. if (s.containsChar ('r'))
  75773. mode = anchorAtRightOrBottom;
  75774. else if (s.containsChar ('c'))
  75775. mode = anchorAtCentre;
  75776. else
  75777. mode = anchorAtLeftOrTop;
  75778. if (s.containsChar ('%'))
  75779. {
  75780. mode |= proportionOfParentSize;
  75781. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  75782. }
  75783. else
  75784. {
  75785. if (s.containsChar ('R'))
  75786. mode |= absoluteFromParentBottomRight;
  75787. else if (s.containsChar ('C'))
  75788. mode |= absoluteFromParentCentre;
  75789. else
  75790. mode |= absoluteFromParentTopLeft;
  75791. value = s.removeCharacters ("rcRC").getDoubleValue();
  75792. }
  75793. }
  75794. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  75795. {
  75796. if (s.containsChar ('%'))
  75797. {
  75798. mode = proportionalSize;
  75799. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  75800. }
  75801. else if (s.containsChar ('M'))
  75802. {
  75803. mode = parentSizeMinusAbsolute;
  75804. value = s.getDoubleValue();
  75805. }
  75806. else
  75807. {
  75808. mode = absoluteSize;
  75809. value = s.getDoubleValue();
  75810. }
  75811. }
  75812. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  75813. const double x_, const double w_,
  75814. const uint8 xMode_, const uint8 wMode_,
  75815. const int parentPos,
  75816. const int parentSize) const throw()
  75817. {
  75818. if (wMode_ == proportionalSize)
  75819. wOut = roundToInt (w_ * parentSize);
  75820. else if (wMode_ == parentSizeMinusAbsolute)
  75821. wOut = jmax (0, parentSize - roundToInt (w_));
  75822. else
  75823. wOut = roundToInt (w_);
  75824. if ((xMode_ & proportionOfParentSize) != 0)
  75825. xOut = parentPos + x_ * parentSize;
  75826. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  75827. xOut = (parentPos + parentSize) - x_;
  75828. else if ((xMode_ & absoluteFromParentCentre) != 0)
  75829. xOut = x_ + (parentPos + parentSize / 2);
  75830. else
  75831. xOut = x_ + parentPos;
  75832. if ((xMode_ & anchorAtRightOrBottom) != 0)
  75833. xOut -= wOut;
  75834. else if ((xMode_ & anchorAtCentre) != 0)
  75835. xOut -= wOut / 2;
  75836. }
  75837. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  75838. double x_, const double w_,
  75839. const uint8 xMode_, const uint8 wMode_,
  75840. const int parentPos,
  75841. const int parentSize) const throw()
  75842. {
  75843. if (wMode_ == proportionalSize)
  75844. {
  75845. if (parentSize > 0)
  75846. wOut = w_ / parentSize;
  75847. }
  75848. else if (wMode_ == parentSizeMinusAbsolute)
  75849. wOut = parentSize - w_;
  75850. else
  75851. wOut = w_;
  75852. if ((xMode_ & anchorAtRightOrBottom) != 0)
  75853. x_ += w_;
  75854. else if ((xMode_ & anchorAtCentre) != 0)
  75855. x_ += w_ / 2;
  75856. if ((xMode_ & proportionOfParentSize) != 0)
  75857. {
  75858. if (parentSize > 0)
  75859. xOut = (x_ - parentPos) / parentSize;
  75860. }
  75861. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  75862. xOut = (parentPos + parentSize) - x_;
  75863. else if ((xMode_ & absoluteFromParentCentre) != 0)
  75864. xOut = x_ - (parentPos + parentSize / 2);
  75865. else
  75866. xOut = x_ - parentPos;
  75867. }
  75868. END_JUCE_NAMESPACE
  75869. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  75870. /*** Start of inlined file: juce_RectangleList.cpp ***/
  75871. BEGIN_JUCE_NAMESPACE
  75872. RectangleList::RectangleList() throw()
  75873. {
  75874. }
  75875. RectangleList::RectangleList (const Rectangle<int>& rect)
  75876. {
  75877. if (! rect.isEmpty())
  75878. rects.add (rect);
  75879. }
  75880. RectangleList::RectangleList (const RectangleList& other)
  75881. : rects (other.rects)
  75882. {
  75883. }
  75884. RectangleList& RectangleList::operator= (const RectangleList& other)
  75885. {
  75886. rects = other.rects;
  75887. return *this;
  75888. }
  75889. RectangleList::~RectangleList()
  75890. {
  75891. }
  75892. void RectangleList::clear()
  75893. {
  75894. rects.clearQuick();
  75895. }
  75896. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  75897. {
  75898. if (((unsigned int) index) < (unsigned int) rects.size())
  75899. return rects.getReference (index);
  75900. return Rectangle<int>();
  75901. }
  75902. bool RectangleList::isEmpty() const throw()
  75903. {
  75904. return rects.size() == 0;
  75905. }
  75906. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  75907. : current (0),
  75908. owner (list),
  75909. index (list.rects.size())
  75910. {
  75911. }
  75912. RectangleList::Iterator::~Iterator()
  75913. {
  75914. }
  75915. bool RectangleList::Iterator::next() throw()
  75916. {
  75917. if (--index >= 0)
  75918. {
  75919. current = & (owner.rects.getReference (index));
  75920. return true;
  75921. }
  75922. return false;
  75923. }
  75924. void RectangleList::add (const Rectangle<int>& rect)
  75925. {
  75926. if (! rect.isEmpty())
  75927. {
  75928. if (rects.size() == 0)
  75929. {
  75930. rects.add (rect);
  75931. }
  75932. else
  75933. {
  75934. bool anyOverlaps = false;
  75935. int i;
  75936. for (i = rects.size(); --i >= 0;)
  75937. {
  75938. Rectangle<int>& ourRect = rects.getReference (i);
  75939. if (rect.intersects (ourRect))
  75940. {
  75941. if (rect.contains (ourRect))
  75942. rects.remove (i);
  75943. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  75944. anyOverlaps = true;
  75945. }
  75946. }
  75947. if (anyOverlaps && rects.size() > 0)
  75948. {
  75949. RectangleList r (rect);
  75950. for (i = rects.size(); --i >= 0;)
  75951. {
  75952. const Rectangle<int>& ourRect = rects.getReference (i);
  75953. if (rect.intersects (ourRect))
  75954. {
  75955. r.subtract (ourRect);
  75956. if (r.rects.size() == 0)
  75957. return;
  75958. }
  75959. }
  75960. for (i = r.getNumRectangles(); --i >= 0;)
  75961. rects.add (r.rects.getReference (i));
  75962. }
  75963. else
  75964. {
  75965. rects.add (rect);
  75966. }
  75967. }
  75968. }
  75969. }
  75970. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  75971. {
  75972. if (! rect.isEmpty())
  75973. rects.add (rect);
  75974. }
  75975. void RectangleList::add (const int x, const int y, const int w, const int h)
  75976. {
  75977. if (rects.size() == 0)
  75978. {
  75979. if (w > 0 && h > 0)
  75980. rects.add (Rectangle<int> (x, y, w, h));
  75981. }
  75982. else
  75983. {
  75984. add (Rectangle<int> (x, y, w, h));
  75985. }
  75986. }
  75987. void RectangleList::add (const RectangleList& other)
  75988. {
  75989. for (int i = 0; i < other.rects.size(); ++i)
  75990. add (other.rects.getReference (i));
  75991. }
  75992. void RectangleList::subtract (const Rectangle<int>& rect)
  75993. {
  75994. const int originalNumRects = rects.size();
  75995. if (originalNumRects > 0)
  75996. {
  75997. const int x1 = rect.x;
  75998. const int y1 = rect.y;
  75999. const int x2 = x1 + rect.w;
  76000. const int y2 = y1 + rect.h;
  76001. for (int i = getNumRectangles(); --i >= 0;)
  76002. {
  76003. Rectangle<int>& r = rects.getReference (i);
  76004. const int rx1 = r.x;
  76005. const int ry1 = r.y;
  76006. const int rx2 = rx1 + r.w;
  76007. const int ry2 = ry1 + r.h;
  76008. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76009. {
  76010. if (x1 > rx1 && x1 < rx2)
  76011. {
  76012. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76013. {
  76014. r.w = x1 - rx1;
  76015. }
  76016. else
  76017. {
  76018. r.x = x1;
  76019. r.w = rx2 - x1;
  76020. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76021. i += 2;
  76022. }
  76023. }
  76024. else if (x2 > rx1 && x2 < rx2)
  76025. {
  76026. r.x = x2;
  76027. r.w = rx2 - x2;
  76028. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76029. {
  76030. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76031. i += 2;
  76032. }
  76033. }
  76034. else if (y1 > ry1 && y1 < ry2)
  76035. {
  76036. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76037. {
  76038. r.h = y1 - ry1;
  76039. }
  76040. else
  76041. {
  76042. r.y = y1;
  76043. r.h = ry2 - y1;
  76044. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76045. i += 2;
  76046. }
  76047. }
  76048. else if (y2 > ry1 && y2 < ry2)
  76049. {
  76050. r.y = y2;
  76051. r.h = ry2 - y2;
  76052. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76053. {
  76054. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76055. i += 2;
  76056. }
  76057. }
  76058. else
  76059. {
  76060. rects.remove (i);
  76061. }
  76062. }
  76063. }
  76064. }
  76065. }
  76066. bool RectangleList::subtract (const RectangleList& otherList)
  76067. {
  76068. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76069. subtract (otherList.rects.getReference (i));
  76070. return rects.size() > 0;
  76071. }
  76072. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76073. {
  76074. bool notEmpty = false;
  76075. if (rect.isEmpty())
  76076. {
  76077. clear();
  76078. }
  76079. else
  76080. {
  76081. for (int i = rects.size(); --i >= 0;)
  76082. {
  76083. Rectangle<int>& r = rects.getReference (i);
  76084. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76085. rects.remove (i);
  76086. else
  76087. notEmpty = true;
  76088. }
  76089. }
  76090. return notEmpty;
  76091. }
  76092. bool RectangleList::clipTo (const RectangleList& other)
  76093. {
  76094. if (rects.size() == 0)
  76095. return false;
  76096. RectangleList result;
  76097. for (int j = 0; j < rects.size(); ++j)
  76098. {
  76099. const Rectangle<int>& rect = rects.getReference (j);
  76100. for (int i = other.rects.size(); --i >= 0;)
  76101. {
  76102. Rectangle<int> r (other.rects.getReference (i));
  76103. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76104. result.rects.add (r);
  76105. }
  76106. }
  76107. swapWith (result);
  76108. return ! isEmpty();
  76109. }
  76110. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76111. {
  76112. destRegion.clear();
  76113. if (! rect.isEmpty())
  76114. {
  76115. for (int i = rects.size(); --i >= 0;)
  76116. {
  76117. Rectangle<int> r (rects.getReference (i));
  76118. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76119. destRegion.rects.add (r);
  76120. }
  76121. }
  76122. return destRegion.rects.size() > 0;
  76123. }
  76124. void RectangleList::swapWith (RectangleList& otherList) throw()
  76125. {
  76126. rects.swapWithArray (otherList.rects);
  76127. }
  76128. void RectangleList::consolidate()
  76129. {
  76130. int i;
  76131. for (i = 0; i < getNumRectangles() - 1; ++i)
  76132. {
  76133. Rectangle<int>& r = rects.getReference (i);
  76134. const int rx1 = r.x;
  76135. const int ry1 = r.y;
  76136. const int rx2 = rx1 + r.w;
  76137. const int ry2 = ry1 + r.h;
  76138. for (int j = rects.size(); --j > i;)
  76139. {
  76140. Rectangle<int>& r2 = rects.getReference (j);
  76141. const int jrx1 = r2.x;
  76142. const int jry1 = r2.y;
  76143. const int jrx2 = jrx1 + r2.w;
  76144. const int jry2 = jry1 + r2.h;
  76145. // if the vertical edges of any blocks are touching and their horizontals don't
  76146. // line up, split them horizontally..
  76147. if (jrx1 == rx2 || jrx2 == rx1)
  76148. {
  76149. if (jry1 > ry1 && jry1 < ry2)
  76150. {
  76151. r.h = jry1 - ry1;
  76152. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76153. i = -1;
  76154. break;
  76155. }
  76156. if (jry2 > ry1 && jry2 < ry2)
  76157. {
  76158. r.h = jry2 - ry1;
  76159. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76160. i = -1;
  76161. break;
  76162. }
  76163. else if (ry1 > jry1 && ry1 < jry2)
  76164. {
  76165. r2.h = ry1 - jry1;
  76166. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76167. i = -1;
  76168. break;
  76169. }
  76170. else if (ry2 > jry1 && ry2 < jry2)
  76171. {
  76172. r2.h = ry2 - jry1;
  76173. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76174. i = -1;
  76175. break;
  76176. }
  76177. }
  76178. }
  76179. }
  76180. for (i = 0; i < rects.size() - 1; ++i)
  76181. {
  76182. Rectangle<int>& r = rects.getReference (i);
  76183. for (int j = rects.size(); --j > i;)
  76184. {
  76185. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76186. {
  76187. rects.remove (j);
  76188. i = -1;
  76189. break;
  76190. }
  76191. }
  76192. }
  76193. }
  76194. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76195. {
  76196. for (int i = getNumRectangles(); --i >= 0;)
  76197. if (rects.getReference (i).contains (x, y))
  76198. return true;
  76199. return false;
  76200. }
  76201. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76202. {
  76203. if (rects.size() > 1)
  76204. {
  76205. RectangleList r (rectangleToCheck);
  76206. for (int i = rects.size(); --i >= 0;)
  76207. {
  76208. r.subtract (rects.getReference (i));
  76209. if (r.rects.size() == 0)
  76210. return true;
  76211. }
  76212. }
  76213. else if (rects.size() > 0)
  76214. {
  76215. return rects.getReference (0).contains (rectangleToCheck);
  76216. }
  76217. return false;
  76218. }
  76219. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76220. {
  76221. for (int i = rects.size(); --i >= 0;)
  76222. if (rects.getReference (i).intersects (rectangleToCheck))
  76223. return true;
  76224. return false;
  76225. }
  76226. bool RectangleList::intersects (const RectangleList& other) const throw()
  76227. {
  76228. for (int i = rects.size(); --i >= 0;)
  76229. if (other.intersectsRectangle (rects.getReference (i)))
  76230. return true;
  76231. return false;
  76232. }
  76233. const Rectangle<int> RectangleList::getBounds() const throw()
  76234. {
  76235. if (rects.size() <= 1)
  76236. {
  76237. if (rects.size() == 0)
  76238. return Rectangle<int>();
  76239. else
  76240. return rects.getReference (0);
  76241. }
  76242. else
  76243. {
  76244. const Rectangle<int>& r = rects.getReference (0);
  76245. int minX = r.x;
  76246. int minY = r.y;
  76247. int maxX = minX + r.w;
  76248. int maxY = minY + r.h;
  76249. for (int i = rects.size(); --i > 0;)
  76250. {
  76251. const Rectangle<int>& r2 = rects.getReference (i);
  76252. minX = jmin (minX, r2.x);
  76253. minY = jmin (minY, r2.y);
  76254. maxX = jmax (maxX, r2.getRight());
  76255. maxY = jmax (maxY, r2.getBottom());
  76256. }
  76257. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76258. }
  76259. }
  76260. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76261. {
  76262. for (int i = rects.size(); --i >= 0;)
  76263. {
  76264. Rectangle<int>& r = rects.getReference (i);
  76265. r.x += dx;
  76266. r.y += dy;
  76267. }
  76268. }
  76269. const Path RectangleList::toPath() const
  76270. {
  76271. Path p;
  76272. for (int i = rects.size(); --i >= 0;)
  76273. {
  76274. const Rectangle<int>& r = rects.getReference (i);
  76275. p.addRectangle ((float) r.x,
  76276. (float) r.y,
  76277. (float) r.w,
  76278. (float) r.h);
  76279. }
  76280. return p;
  76281. }
  76282. END_JUCE_NAMESPACE
  76283. /*** End of inlined file: juce_RectangleList.cpp ***/
  76284. /*** Start of inlined file: juce_Image.cpp ***/
  76285. BEGIN_JUCE_NAMESPACE
  76286. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76287. : format (format_), width (width_), height (height_)
  76288. {
  76289. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76290. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76291. }
  76292. Image::SharedImage::~SharedImage()
  76293. {
  76294. }
  76295. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76296. {
  76297. return imageData + lineStride * y + pixelStride * x;
  76298. }
  76299. class SoftwareSharedImage : public Image::SharedImage
  76300. {
  76301. public:
  76302. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76303. : Image::SharedImage (format_, width_, height_)
  76304. {
  76305. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76306. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76307. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76308. imageData = imageDataAllocated;
  76309. }
  76310. ~SoftwareSharedImage()
  76311. {
  76312. }
  76313. Image::ImageType getType() const
  76314. {
  76315. return Image::SoftwareImage;
  76316. }
  76317. LowLevelGraphicsContext* createLowLevelContext()
  76318. {
  76319. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76320. }
  76321. SharedImage* clone()
  76322. {
  76323. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76324. memcpy (s->imageData, imageData, lineStride * height);
  76325. return s;
  76326. }
  76327. private:
  76328. HeapBlock<uint8> imageDataAllocated;
  76329. };
  76330. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76331. {
  76332. return new SoftwareSharedImage (format, width, height, clearImage);
  76333. }
  76334. class SubsectionSharedImage : public Image::SharedImage
  76335. {
  76336. public:
  76337. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76338. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76339. image (image_), area (area_)
  76340. {
  76341. pixelStride = image_->getPixelStride();
  76342. lineStride = image_->getLineStride();
  76343. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76344. }
  76345. ~SubsectionSharedImage() {}
  76346. Image::ImageType getType() const
  76347. {
  76348. return Image::SoftwareImage;
  76349. }
  76350. LowLevelGraphicsContext* createLowLevelContext()
  76351. {
  76352. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76353. g->clipToRectangle (area);
  76354. g->setOrigin (area.getX(), area.getY());
  76355. return g;
  76356. }
  76357. SharedImage* clone()
  76358. {
  76359. return new SubsectionSharedImage (image->clone(), area);
  76360. }
  76361. private:
  76362. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76363. const Rectangle<int> area;
  76364. SubsectionSharedImage (const SubsectionSharedImage&);
  76365. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76366. };
  76367. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76368. {
  76369. if (area.contains (getBounds()))
  76370. return *this;
  76371. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76372. if (validArea.isEmpty())
  76373. return Image::null;
  76374. return Image (new SubsectionSharedImage (image, validArea));
  76375. }
  76376. Image::Image()
  76377. {
  76378. }
  76379. Image::Image (SharedImage* const instance)
  76380. : image (instance)
  76381. {
  76382. }
  76383. Image::Image (const PixelFormat format,
  76384. const int width, const int height,
  76385. const bool clearImage, const ImageType type)
  76386. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76387. : new SoftwareSharedImage (format, width, height, clearImage))
  76388. {
  76389. }
  76390. Image::Image (const Image& other)
  76391. : image (other.image)
  76392. {
  76393. }
  76394. Image& Image::operator= (const Image& other)
  76395. {
  76396. image = other.image;
  76397. return *this;
  76398. }
  76399. Image::~Image()
  76400. {
  76401. }
  76402. const Image Image::null;
  76403. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76404. {
  76405. return image == 0 ? 0 : image->createLowLevelContext();
  76406. }
  76407. void Image::duplicateIfShared()
  76408. {
  76409. if (image != 0 && image->getReferenceCount() > 1)
  76410. image = image->clone();
  76411. }
  76412. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76413. {
  76414. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76415. return *this;
  76416. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76417. Graphics g (newImage);
  76418. g.setImageResamplingQuality (quality);
  76419. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76420. return newImage;
  76421. }
  76422. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76423. {
  76424. if (image == 0 || newFormat == image->format)
  76425. return *this;
  76426. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76427. if (newFormat == SingleChannel)
  76428. {
  76429. if (! hasAlphaChannel())
  76430. {
  76431. newImage.clear (getBounds(), Colours::black);
  76432. }
  76433. else
  76434. {
  76435. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76436. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76437. for (int y = 0; y < image->height; ++y)
  76438. {
  76439. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76440. uint8* dst = destData.getLinePointer (y);
  76441. for (int x = image->width; --x >= 0;)
  76442. {
  76443. *dst++ = src->getAlpha();
  76444. ++src;
  76445. }
  76446. }
  76447. }
  76448. }
  76449. else
  76450. {
  76451. if (hasAlphaChannel())
  76452. newImage.clear (getBounds());
  76453. Graphics g (newImage);
  76454. g.drawImageAt (*this, 0, 0);
  76455. }
  76456. return newImage;
  76457. }
  76458. const var Image::getTag() const
  76459. {
  76460. return image == 0 ? var::null : image->userTag;
  76461. }
  76462. void Image::setTag (const var& newTag)
  76463. {
  76464. if (image != 0)
  76465. image->userTag = newTag;
  76466. }
  76467. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76468. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76469. pixelFormat (image.getFormat()),
  76470. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76471. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76472. width (w),
  76473. height (h)
  76474. {
  76475. jassert (data != 0);
  76476. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76477. }
  76478. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76479. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76480. pixelFormat (image.getFormat()),
  76481. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76482. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76483. width (w),
  76484. height (h)
  76485. {
  76486. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76487. }
  76488. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76489. : data (image.image == 0 ? 0 : image.image->imageData),
  76490. pixelFormat (image.getFormat()),
  76491. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76492. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76493. width (image.getWidth()),
  76494. height (image.getHeight())
  76495. {
  76496. }
  76497. Image::BitmapData::~BitmapData()
  76498. {
  76499. }
  76500. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76501. {
  76502. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76503. const uint8* const pixel = getPixelPointer (x, y);
  76504. switch (pixelFormat)
  76505. {
  76506. case Image::ARGB:
  76507. {
  76508. PixelARGB p (*(const PixelARGB*) pixel);
  76509. p.unpremultiply();
  76510. return Colour (p.getARGB());
  76511. }
  76512. case Image::RGB:
  76513. return Colour (((const PixelRGB*) pixel)->getARGB());
  76514. case Image::SingleChannel:
  76515. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76516. default:
  76517. jassertfalse;
  76518. break;
  76519. }
  76520. return Colour();
  76521. }
  76522. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76523. {
  76524. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76525. uint8* const pixel = getPixelPointer (x, y);
  76526. const PixelARGB col (colour.getPixelARGB());
  76527. switch (pixelFormat)
  76528. {
  76529. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76530. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76531. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76532. default: jassertfalse; break;
  76533. }
  76534. }
  76535. void Image::setPixelData (int x, int y, int w, int h,
  76536. const uint8* const sourcePixelData, const int sourceLineStride)
  76537. {
  76538. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76539. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76540. {
  76541. const BitmapData dest (*this, x, y, w, h, true);
  76542. for (int i = 0; i < h; ++i)
  76543. {
  76544. memcpy (dest.getLinePointer(i),
  76545. sourcePixelData + sourceLineStride * i,
  76546. w * dest.pixelStride);
  76547. }
  76548. }
  76549. }
  76550. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76551. {
  76552. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76553. if (! clipped.isEmpty())
  76554. {
  76555. const PixelARGB col (colourToClearTo.getPixelARGB());
  76556. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76557. uint8* dest = destData.data;
  76558. int dh = clipped.getHeight();
  76559. while (--dh >= 0)
  76560. {
  76561. uint8* line = dest;
  76562. dest += destData.lineStride;
  76563. if (isARGB())
  76564. {
  76565. for (int x = clipped.getWidth(); --x >= 0;)
  76566. {
  76567. ((PixelARGB*) line)->set (col);
  76568. line += destData.pixelStride;
  76569. }
  76570. }
  76571. else if (isRGB())
  76572. {
  76573. for (int x = clipped.getWidth(); --x >= 0;)
  76574. {
  76575. ((PixelRGB*) line)->set (col);
  76576. line += destData.pixelStride;
  76577. }
  76578. }
  76579. else
  76580. {
  76581. for (int x = clipped.getWidth(); --x >= 0;)
  76582. {
  76583. *line = col.getAlpha();
  76584. line += destData.pixelStride;
  76585. }
  76586. }
  76587. }
  76588. }
  76589. }
  76590. const Colour Image::getPixelAt (const int x, const int y) const
  76591. {
  76592. if (((unsigned int) x) < (unsigned int) getWidth()
  76593. && ((unsigned int) y) < (unsigned int) getHeight())
  76594. {
  76595. const BitmapData srcData (*this, x, y, 1, 1);
  76596. return srcData.getPixelColour (0, 0);
  76597. }
  76598. return Colour();
  76599. }
  76600. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76601. {
  76602. if (((unsigned int) x) < (unsigned int) getWidth()
  76603. && ((unsigned int) y) < (unsigned int) getHeight())
  76604. {
  76605. const BitmapData destData (*this, x, y, 1, 1, true);
  76606. destData.setPixelColour (0, 0, colour);
  76607. }
  76608. }
  76609. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76610. {
  76611. if (((unsigned int) x) < (unsigned int) getWidth()
  76612. && ((unsigned int) y) < (unsigned int) getHeight()
  76613. && hasAlphaChannel())
  76614. {
  76615. const BitmapData destData (*this, x, y, 1, 1, true);
  76616. if (isARGB())
  76617. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76618. else
  76619. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76620. }
  76621. }
  76622. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76623. {
  76624. if (hasAlphaChannel())
  76625. {
  76626. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76627. if (isARGB())
  76628. {
  76629. for (int y = 0; y < destData.height; ++y)
  76630. {
  76631. uint8* p = destData.getLinePointer (y);
  76632. for (int x = 0; x < destData.width; ++x)
  76633. {
  76634. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76635. p += destData.pixelStride;
  76636. }
  76637. }
  76638. }
  76639. else
  76640. {
  76641. for (int y = 0; y < destData.height; ++y)
  76642. {
  76643. uint8* p = destData.getLinePointer (y);
  76644. for (int x = 0; x < destData.width; ++x)
  76645. {
  76646. *p = (uint8) (*p * amountToMultiplyBy);
  76647. p += destData.pixelStride;
  76648. }
  76649. }
  76650. }
  76651. }
  76652. else
  76653. {
  76654. jassertfalse; // can't do this without an alpha-channel!
  76655. }
  76656. }
  76657. void Image::desaturate()
  76658. {
  76659. if (isARGB() || isRGB())
  76660. {
  76661. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76662. if (isARGB())
  76663. {
  76664. for (int y = 0; y < destData.height; ++y)
  76665. {
  76666. uint8* p = destData.getLinePointer (y);
  76667. for (int x = 0; x < destData.width; ++x)
  76668. {
  76669. ((PixelARGB*) p)->desaturate();
  76670. p += destData.pixelStride;
  76671. }
  76672. }
  76673. }
  76674. else
  76675. {
  76676. for (int y = 0; y < destData.height; ++y)
  76677. {
  76678. uint8* p = destData.getLinePointer (y);
  76679. for (int x = 0; x < destData.width; ++x)
  76680. {
  76681. ((PixelRGB*) p)->desaturate();
  76682. p += destData.pixelStride;
  76683. }
  76684. }
  76685. }
  76686. }
  76687. }
  76688. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76689. {
  76690. if (hasAlphaChannel())
  76691. {
  76692. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76693. SparseSet<int> pixelsOnRow;
  76694. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76695. for (int y = 0; y < srcData.height; ++y)
  76696. {
  76697. pixelsOnRow.clear();
  76698. const uint8* lineData = srcData.getLinePointer (y);
  76699. if (isARGB())
  76700. {
  76701. for (int x = 0; x < srcData.width; ++x)
  76702. {
  76703. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76704. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76705. lineData += srcData.pixelStride;
  76706. }
  76707. }
  76708. else
  76709. {
  76710. for (int x = 0; x < srcData.width; ++x)
  76711. {
  76712. if (*lineData >= threshold)
  76713. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76714. lineData += srcData.pixelStride;
  76715. }
  76716. }
  76717. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76718. {
  76719. const Range<int> range (pixelsOnRow.getRange (i));
  76720. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76721. }
  76722. result.consolidate();
  76723. }
  76724. }
  76725. else
  76726. {
  76727. result.add (0, 0, getWidth(), getHeight());
  76728. }
  76729. }
  76730. void Image::moveImageSection (int dx, int dy,
  76731. int sx, int sy,
  76732. int w, int h)
  76733. {
  76734. if (dx < 0)
  76735. {
  76736. w += dx;
  76737. sx -= dx;
  76738. dx = 0;
  76739. }
  76740. if (dy < 0)
  76741. {
  76742. h += dy;
  76743. sy -= dy;
  76744. dy = 0;
  76745. }
  76746. if (sx < 0)
  76747. {
  76748. w += sx;
  76749. dx -= sx;
  76750. sx = 0;
  76751. }
  76752. if (sy < 0)
  76753. {
  76754. h += sy;
  76755. dy -= sy;
  76756. sy = 0;
  76757. }
  76758. const int minX = jmin (dx, sx);
  76759. const int minY = jmin (dy, sy);
  76760. w = jmin (w, getWidth() - jmax (sx, dx));
  76761. h = jmin (h, getHeight() - jmax (sy, dy));
  76762. if (w > 0 && h > 0)
  76763. {
  76764. const int maxX = jmax (dx, sx) + w;
  76765. const int maxY = jmax (dy, sy) + h;
  76766. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76767. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76768. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76769. const int lineSize = destData.pixelStride * w;
  76770. if (dy > sy)
  76771. {
  76772. while (--h >= 0)
  76773. {
  76774. const int offset = h * destData.lineStride;
  76775. memmove (dst + offset, src + offset, lineSize);
  76776. }
  76777. }
  76778. else if (dst != src)
  76779. {
  76780. while (--h >= 0)
  76781. {
  76782. memmove (dst, src, lineSize);
  76783. dst += destData.lineStride;
  76784. src += destData.lineStride;
  76785. }
  76786. }
  76787. }
  76788. }
  76789. END_JUCE_NAMESPACE
  76790. /*** End of inlined file: juce_Image.cpp ***/
  76791. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76792. BEGIN_JUCE_NAMESPACE
  76793. class ImageCache::Pimpl : public Timer,
  76794. public DeletedAtShutdown
  76795. {
  76796. public:
  76797. Pimpl()
  76798. : cacheTimeout (5000)
  76799. {
  76800. }
  76801. ~Pimpl()
  76802. {
  76803. clearSingletonInstance();
  76804. }
  76805. const Image getFromHashCode (const int64 hashCode)
  76806. {
  76807. const ScopedLock sl (lock);
  76808. for (int i = images.size(); --i >= 0;)
  76809. {
  76810. Item* const item = images.getUnchecked(i);
  76811. if (item->hashCode == hashCode)
  76812. return item->image;
  76813. }
  76814. return Image::null;
  76815. }
  76816. void addImageToCache (const Image& image, const int64 hashCode)
  76817. {
  76818. if (image.isValid())
  76819. {
  76820. if (! isTimerRunning())
  76821. startTimer (2000);
  76822. Item* const item = new Item();
  76823. item->hashCode = hashCode;
  76824. item->image = image;
  76825. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76826. const ScopedLock sl (lock);
  76827. images.add (item);
  76828. }
  76829. }
  76830. void timerCallback()
  76831. {
  76832. const uint32 now = Time::getApproximateMillisecondCounter();
  76833. const ScopedLock sl (lock);
  76834. for (int i = images.size(); --i >= 0;)
  76835. {
  76836. Item* const item = images.getUnchecked(i);
  76837. if (item->image.getReferenceCount() <= 1)
  76838. {
  76839. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76840. images.remove (i);
  76841. }
  76842. else
  76843. {
  76844. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76845. }
  76846. }
  76847. if (images.size() == 0)
  76848. stopTimer();
  76849. }
  76850. struct Item
  76851. {
  76852. Image image;
  76853. int64 hashCode;
  76854. uint32 lastUseTime;
  76855. };
  76856. int cacheTimeout;
  76857. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76858. private:
  76859. OwnedArray<Item> images;
  76860. CriticalSection lock;
  76861. Pimpl (const Pimpl&);
  76862. Pimpl& operator= (const Pimpl&);
  76863. };
  76864. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76865. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76866. {
  76867. if (Pimpl::getInstanceWithoutCreating() != 0)
  76868. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76869. return Image::null;
  76870. }
  76871. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76872. {
  76873. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76874. }
  76875. const Image ImageCache::getFromFile (const File& file)
  76876. {
  76877. const int64 hashCode = file.hashCode64();
  76878. Image image (getFromHashCode (hashCode));
  76879. if (image.isNull())
  76880. {
  76881. image = ImageFileFormat::loadFrom (file);
  76882. addImageToCache (image, hashCode);
  76883. }
  76884. return image;
  76885. }
  76886. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76887. {
  76888. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76889. Image image (getFromHashCode (hashCode));
  76890. if (image.isNull())
  76891. {
  76892. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76893. addImageToCache (image, hashCode);
  76894. }
  76895. return image;
  76896. }
  76897. void ImageCache::setCacheTimeout (const int millisecs)
  76898. {
  76899. Pimpl::getInstance()->cacheTimeout = millisecs;
  76900. }
  76901. END_JUCE_NAMESPACE
  76902. /*** End of inlined file: juce_ImageCache.cpp ***/
  76903. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76904. BEGIN_JUCE_NAMESPACE
  76905. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76906. : values (size_ * size_),
  76907. size (size_)
  76908. {
  76909. clear();
  76910. }
  76911. ImageConvolutionKernel::~ImageConvolutionKernel()
  76912. {
  76913. }
  76914. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76915. {
  76916. if (((unsigned int) x) < (unsigned int) size
  76917. && ((unsigned int) y) < (unsigned int) size)
  76918. {
  76919. return values [x + y * size];
  76920. }
  76921. else
  76922. {
  76923. jassertfalse;
  76924. return 0;
  76925. }
  76926. }
  76927. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76928. {
  76929. if (((unsigned int) x) < (unsigned int) size
  76930. && ((unsigned int) y) < (unsigned int) size)
  76931. {
  76932. values [x + y * size] = value;
  76933. }
  76934. else
  76935. {
  76936. jassertfalse;
  76937. }
  76938. }
  76939. void ImageConvolutionKernel::clear()
  76940. {
  76941. for (int i = size * size; --i >= 0;)
  76942. values[i] = 0;
  76943. }
  76944. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76945. {
  76946. double currentTotal = 0.0;
  76947. for (int i = size * size; --i >= 0;)
  76948. currentTotal += values[i];
  76949. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76950. }
  76951. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76952. {
  76953. for (int i = size * size; --i >= 0;)
  76954. values[i] *= multiplier;
  76955. }
  76956. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76957. {
  76958. const double radiusFactor = -1.0 / (radius * radius * 2);
  76959. const int centre = size >> 1;
  76960. for (int y = size; --y >= 0;)
  76961. {
  76962. for (int x = size; --x >= 0;)
  76963. {
  76964. const int cx = x - centre;
  76965. const int cy = y - centre;
  76966. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76967. }
  76968. }
  76969. setOverallSum (1.0f);
  76970. }
  76971. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76972. const Image& sourceImage,
  76973. const Rectangle<int>& destinationArea) const
  76974. {
  76975. if (sourceImage == destImage)
  76976. {
  76977. destImage.duplicateIfShared();
  76978. }
  76979. else
  76980. {
  76981. if (sourceImage.getWidth() != destImage.getWidth()
  76982. || sourceImage.getHeight() != destImage.getHeight()
  76983. || sourceImage.getFormat() != destImage.getFormat())
  76984. {
  76985. jassertfalse;
  76986. return;
  76987. }
  76988. }
  76989. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76990. if (area.isEmpty())
  76991. return;
  76992. const int right = area.getRight();
  76993. const int bottom = area.getBottom();
  76994. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76995. uint8* line = destData.data;
  76996. const Image::BitmapData srcData (sourceImage, false);
  76997. if (destData.pixelStride == 4)
  76998. {
  76999. for (int y = area.getY(); y < bottom; ++y)
  77000. {
  77001. uint8* dest = line;
  77002. line += destData.lineStride;
  77003. for (int x = area.getX(); x < right; ++x)
  77004. {
  77005. float c1 = 0;
  77006. float c2 = 0;
  77007. float c3 = 0;
  77008. float c4 = 0;
  77009. for (int yy = 0; yy < size; ++yy)
  77010. {
  77011. const int sy = y + yy - (size >> 1);
  77012. if (sy >= srcData.height)
  77013. break;
  77014. if (sy >= 0)
  77015. {
  77016. int sx = x - (size >> 1);
  77017. const uint8* src = srcData.getPixelPointer (sx, sy);
  77018. for (int xx = 0; xx < size; ++xx)
  77019. {
  77020. if (sx >= srcData.width)
  77021. break;
  77022. if (sx >= 0)
  77023. {
  77024. const float kernelMult = values [xx + yy * size];
  77025. c1 += kernelMult * *src++;
  77026. c2 += kernelMult * *src++;
  77027. c3 += kernelMult * *src++;
  77028. c4 += kernelMult * *src++;
  77029. }
  77030. else
  77031. {
  77032. src += 4;
  77033. }
  77034. ++sx;
  77035. }
  77036. }
  77037. }
  77038. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77039. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77040. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77041. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77042. }
  77043. }
  77044. }
  77045. else if (destData.pixelStride == 3)
  77046. {
  77047. for (int y = area.getY(); y < bottom; ++y)
  77048. {
  77049. uint8* dest = line;
  77050. line += destData.lineStride;
  77051. for (int x = area.getX(); x < right; ++x)
  77052. {
  77053. float c1 = 0;
  77054. float c2 = 0;
  77055. float c3 = 0;
  77056. for (int yy = 0; yy < size; ++yy)
  77057. {
  77058. const int sy = y + yy - (size >> 1);
  77059. if (sy >= srcData.height)
  77060. break;
  77061. if (sy >= 0)
  77062. {
  77063. int sx = x - (size >> 1);
  77064. const uint8* src = srcData.getPixelPointer (sx, sy);
  77065. for (int xx = 0; xx < size; ++xx)
  77066. {
  77067. if (sx >= srcData.width)
  77068. break;
  77069. if (sx >= 0)
  77070. {
  77071. const float kernelMult = values [xx + yy * size];
  77072. c1 += kernelMult * *src++;
  77073. c2 += kernelMult * *src++;
  77074. c3 += kernelMult * *src++;
  77075. }
  77076. else
  77077. {
  77078. src += 3;
  77079. }
  77080. ++sx;
  77081. }
  77082. }
  77083. }
  77084. *dest++ = (uint8) roundToInt (c1);
  77085. *dest++ = (uint8) roundToInt (c2);
  77086. *dest++ = (uint8) roundToInt (c3);
  77087. }
  77088. }
  77089. }
  77090. }
  77091. END_JUCE_NAMESPACE
  77092. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77093. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77094. BEGIN_JUCE_NAMESPACE
  77095. /*** Start of inlined file: juce_GIFLoader.h ***/
  77096. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  77097. #define __JUCE_GIFLOADER_JUCEHEADER__
  77098. #ifndef DOXYGEN
  77099. /**
  77100. Used internally by ImageFileFormat - don't use this class directly in your
  77101. application.
  77102. @see ImageFileFormat
  77103. */
  77104. class GIFLoader
  77105. {
  77106. public:
  77107. GIFLoader (InputStream& in);
  77108. ~GIFLoader();
  77109. const Image& getImage() const { return image; }
  77110. private:
  77111. Image image;
  77112. InputStream& input;
  77113. uint8 buffer [300];
  77114. uint8 palette [256][4];
  77115. bool dataBlockIsZero, fresh, finished;
  77116. int currentBit, lastBit, lastByteIndex;
  77117. int codeSize, setCodeSize;
  77118. int maxCode, maxCodeSize;
  77119. int firstcode, oldcode;
  77120. int clearCode, end_code;
  77121. enum { maxGifCode = 1 << 12 };
  77122. int table [2] [maxGifCode];
  77123. int stack [2 * maxGifCode];
  77124. int *sp;
  77125. bool getSizeFromHeader (int& width, int& height);
  77126. bool readPalette (const int numCols);
  77127. int readDataBlock (unsigned char* dest);
  77128. int processExtension (int type, int& transparent);
  77129. int readLZWByte (bool initialise, int input_code_size);
  77130. int getCode (int code_size, bool initialise);
  77131. bool readImage (int interlace, int transparent);
  77132. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77133. GIFLoader (const GIFLoader&);
  77134. GIFLoader& operator= (const GIFLoader&);
  77135. };
  77136. #endif // DOXYGEN
  77137. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  77138. /*** End of inlined file: juce_GIFLoader.h ***/
  77139. class GIFImageFormat : public ImageFileFormat
  77140. {
  77141. public:
  77142. GIFImageFormat() {}
  77143. ~GIFImageFormat() {}
  77144. const String getFormatName()
  77145. {
  77146. return "GIF";
  77147. }
  77148. bool canUnderstand (InputStream& in)
  77149. {
  77150. const int bytesNeeded = 4;
  77151. char header [bytesNeeded];
  77152. return (in.read (header, bytesNeeded) == bytesNeeded)
  77153. && header[0] == 'G'
  77154. && header[1] == 'I'
  77155. && header[2] == 'F';
  77156. }
  77157. const Image decodeImage (InputStream& in)
  77158. {
  77159. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77160. return loader->getImage();
  77161. }
  77162. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77163. {
  77164. return false;
  77165. }
  77166. };
  77167. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77168. {
  77169. static PNGImageFormat png;
  77170. static JPEGImageFormat jpg;
  77171. static GIFImageFormat gif;
  77172. ImageFileFormat* formats[4];
  77173. int numFormats = 0;
  77174. formats [numFormats++] = &png;
  77175. formats [numFormats++] = &jpg;
  77176. formats [numFormats++] = &gif;
  77177. const int64 streamPos = input.getPosition();
  77178. for (int i = 0; i < numFormats; ++i)
  77179. {
  77180. const bool found = formats[i]->canUnderstand (input);
  77181. input.setPosition (streamPos);
  77182. if (found)
  77183. return formats[i];
  77184. }
  77185. return 0;
  77186. }
  77187. const Image ImageFileFormat::loadFrom (InputStream& input)
  77188. {
  77189. ImageFileFormat* const format = findImageFormatForStream (input);
  77190. if (format != 0)
  77191. return format->decodeImage (input);
  77192. return Image::null;
  77193. }
  77194. const Image ImageFileFormat::loadFrom (const File& file)
  77195. {
  77196. InputStream* const in = file.createInputStream();
  77197. if (in != 0)
  77198. {
  77199. BufferedInputStream b (in, 8192, true);
  77200. return loadFrom (b);
  77201. }
  77202. return Image::null;
  77203. }
  77204. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77205. {
  77206. if (rawData != 0 && numBytes > 4)
  77207. {
  77208. MemoryInputStream stream (rawData, numBytes, false);
  77209. return loadFrom (stream);
  77210. }
  77211. return Image::null;
  77212. }
  77213. END_JUCE_NAMESPACE
  77214. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77215. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77216. BEGIN_JUCE_NAMESPACE
  77217. GIFLoader::GIFLoader (InputStream& in)
  77218. : input (in),
  77219. dataBlockIsZero (false),
  77220. fresh (false),
  77221. finished (false)
  77222. {
  77223. currentBit = lastBit = lastByteIndex = 0;
  77224. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77225. firstcode = oldcode = 0;
  77226. clearCode = end_code = 0;
  77227. int imageWidth, imageHeight;
  77228. int transparent = -1;
  77229. if (! getSizeFromHeader (imageWidth, imageHeight))
  77230. return;
  77231. if ((imageWidth <= 0) || (imageHeight <= 0))
  77232. return;
  77233. unsigned char buf [16];
  77234. if (in.read (buf, 3) != 3)
  77235. return;
  77236. int numColours = 2 << (buf[0] & 7);
  77237. if ((buf[0] & 0x80) != 0)
  77238. readPalette (numColours);
  77239. for (;;)
  77240. {
  77241. if (input.read (buf, 1) != 1)
  77242. break;
  77243. if (buf[0] == ';')
  77244. break;
  77245. if (buf[0] == '!')
  77246. {
  77247. if (input.read (buf, 1) != 1)
  77248. break;
  77249. if (processExtension (buf[0], transparent) < 0)
  77250. break;
  77251. continue;
  77252. }
  77253. if (buf[0] != ',')
  77254. continue;
  77255. if (input.read (buf, 9) != 9)
  77256. break;
  77257. imageWidth = makeWord (buf[4], buf[5]);
  77258. imageHeight = makeWord (buf[6], buf[7]);
  77259. numColours = 2 << (buf[8] & 7);
  77260. if ((buf[8] & 0x80) != 0)
  77261. if (! readPalette (numColours))
  77262. break;
  77263. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77264. imageWidth, imageHeight, (transparent >= 0));
  77265. readImage ((buf[8] & 0x40) != 0, transparent);
  77266. break;
  77267. }
  77268. }
  77269. GIFLoader::~GIFLoader()
  77270. {
  77271. }
  77272. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  77273. {
  77274. char b[8];
  77275. if (input.read (b, 6) == 6)
  77276. {
  77277. if ((strncmp ("GIF87a", b, 6) == 0)
  77278. || (strncmp ("GIF89a", b, 6) == 0))
  77279. {
  77280. if (input.read (b, 4) == 4)
  77281. {
  77282. w = makeWord (b[0], b[1]);
  77283. h = makeWord (b[2], b[3]);
  77284. return true;
  77285. }
  77286. }
  77287. }
  77288. return false;
  77289. }
  77290. bool GIFLoader::readPalette (const int numCols)
  77291. {
  77292. unsigned char rgb[4];
  77293. for (int i = 0; i < numCols; ++i)
  77294. {
  77295. input.read (rgb, 3);
  77296. palette [i][0] = rgb[0];
  77297. palette [i][1] = rgb[1];
  77298. palette [i][2] = rgb[2];
  77299. palette [i][3] = 0xff;
  77300. }
  77301. return true;
  77302. }
  77303. int GIFLoader::readDataBlock (unsigned char* const dest)
  77304. {
  77305. unsigned char n;
  77306. if (input.read (&n, 1) == 1)
  77307. {
  77308. dataBlockIsZero = (n == 0);
  77309. if (dataBlockIsZero || (input.read (dest, n) == n))
  77310. return n;
  77311. }
  77312. return -1;
  77313. }
  77314. int GIFLoader::processExtension (const int type, int& transparent)
  77315. {
  77316. unsigned char b [300];
  77317. int n = 0;
  77318. if (type == 0xf9)
  77319. {
  77320. n = readDataBlock (b);
  77321. if (n < 0)
  77322. return 1;
  77323. if ((b[0] & 0x1) != 0)
  77324. transparent = b[3];
  77325. }
  77326. do
  77327. {
  77328. n = readDataBlock (b);
  77329. }
  77330. while (n > 0);
  77331. return n;
  77332. }
  77333. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  77334. {
  77335. if (initialise)
  77336. {
  77337. currentBit = 0;
  77338. lastBit = 0;
  77339. finished = false;
  77340. return 0;
  77341. }
  77342. if ((currentBit + codeSize_) >= lastBit)
  77343. {
  77344. if (finished)
  77345. return -1;
  77346. buffer[0] = buffer [lastByteIndex - 2];
  77347. buffer[1] = buffer [lastByteIndex - 1];
  77348. const int n = readDataBlock (&buffer[2]);
  77349. if (n == 0)
  77350. finished = true;
  77351. lastByteIndex = 2 + n;
  77352. currentBit = (currentBit - lastBit) + 16;
  77353. lastBit = (2 + n) * 8 ;
  77354. }
  77355. int result = 0;
  77356. int i = currentBit;
  77357. for (int j = 0; j < codeSize_; ++j)
  77358. {
  77359. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77360. ++i;
  77361. }
  77362. currentBit += codeSize_;
  77363. return result;
  77364. }
  77365. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77366. {
  77367. int code, incode, i;
  77368. if (initialise)
  77369. {
  77370. setCodeSize = inputCodeSize;
  77371. codeSize = setCodeSize + 1;
  77372. clearCode = 1 << setCodeSize;
  77373. end_code = clearCode + 1;
  77374. maxCodeSize = 2 * clearCode;
  77375. maxCode = clearCode + 2;
  77376. getCode (0, true);
  77377. fresh = true;
  77378. for (i = 0; i < clearCode; ++i)
  77379. {
  77380. table[0][i] = 0;
  77381. table[1][i] = i;
  77382. }
  77383. for (; i < maxGifCode; ++i)
  77384. {
  77385. table[0][i] = 0;
  77386. table[1][i] = 0;
  77387. }
  77388. sp = stack;
  77389. return 0;
  77390. }
  77391. else if (fresh)
  77392. {
  77393. fresh = false;
  77394. do
  77395. {
  77396. firstcode = oldcode
  77397. = getCode (codeSize, false);
  77398. }
  77399. while (firstcode == clearCode);
  77400. return firstcode;
  77401. }
  77402. if (sp > stack)
  77403. return *--sp;
  77404. while ((code = getCode (codeSize, false)) >= 0)
  77405. {
  77406. if (code == clearCode)
  77407. {
  77408. for (i = 0; i < clearCode; ++i)
  77409. {
  77410. table[0][i] = 0;
  77411. table[1][i] = i;
  77412. }
  77413. for (; i < maxGifCode; ++i)
  77414. {
  77415. table[0][i] = 0;
  77416. table[1][i] = 0;
  77417. }
  77418. codeSize = setCodeSize + 1;
  77419. maxCodeSize = 2 * clearCode;
  77420. maxCode = clearCode + 2;
  77421. sp = stack;
  77422. firstcode = oldcode = getCode (codeSize, false);
  77423. return firstcode;
  77424. }
  77425. else if (code == end_code)
  77426. {
  77427. if (dataBlockIsZero)
  77428. return -2;
  77429. unsigned char buf [260];
  77430. int n;
  77431. while ((n = readDataBlock (buf)) > 0)
  77432. {}
  77433. if (n != 0)
  77434. return -2;
  77435. }
  77436. incode = code;
  77437. if (code >= maxCode)
  77438. {
  77439. *sp++ = firstcode;
  77440. code = oldcode;
  77441. }
  77442. while (code >= clearCode)
  77443. {
  77444. *sp++ = table[1][code];
  77445. if (code == table[0][code])
  77446. return -2;
  77447. code = table[0][code];
  77448. }
  77449. *sp++ = firstcode = table[1][code];
  77450. if ((code = maxCode) < maxGifCode)
  77451. {
  77452. table[0][code] = oldcode;
  77453. table[1][code] = firstcode;
  77454. ++maxCode;
  77455. if ((maxCode >= maxCodeSize)
  77456. && (maxCodeSize < maxGifCode))
  77457. {
  77458. maxCodeSize <<= 1;
  77459. ++codeSize;
  77460. }
  77461. }
  77462. oldcode = incode;
  77463. if (sp > stack)
  77464. return *--sp;
  77465. }
  77466. return code;
  77467. }
  77468. bool GIFLoader::readImage (const int interlace, const int transparent)
  77469. {
  77470. unsigned char c;
  77471. if (input.read (&c, 1) != 1
  77472. || readLZWByte (true, c) < 0)
  77473. return false;
  77474. if (transparent >= 0)
  77475. {
  77476. palette [transparent][0] = 0;
  77477. palette [transparent][1] = 0;
  77478. palette [transparent][2] = 0;
  77479. palette [transparent][3] = 0;
  77480. }
  77481. int index;
  77482. int xpos = 0, ypos = 0, pass = 0;
  77483. const Image::BitmapData destData (image, true);
  77484. uint8* p = destData.data;
  77485. const bool hasAlpha = image.hasAlphaChannel();
  77486. while ((index = readLZWByte (false, c)) >= 0)
  77487. {
  77488. const uint8* const paletteEntry = palette [index];
  77489. if (hasAlpha)
  77490. {
  77491. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77492. paletteEntry[0],
  77493. paletteEntry[1],
  77494. paletteEntry[2]);
  77495. ((PixelARGB*) p)->premultiply();
  77496. }
  77497. else
  77498. {
  77499. ((PixelRGB*) p)->setARGB (0,
  77500. paletteEntry[0],
  77501. paletteEntry[1],
  77502. paletteEntry[2]);
  77503. }
  77504. p += destData.pixelStride;
  77505. ++xpos;
  77506. if (xpos == destData.width)
  77507. {
  77508. xpos = 0;
  77509. if (interlace)
  77510. {
  77511. switch (pass)
  77512. {
  77513. case 0:
  77514. case 1: ypos += 8; break;
  77515. case 2: ypos += 4; break;
  77516. case 3: ypos += 2; break;
  77517. }
  77518. while (ypos >= destData.height)
  77519. {
  77520. ++pass;
  77521. switch (pass)
  77522. {
  77523. case 1: ypos = 4; break;
  77524. case 2: ypos = 2; break;
  77525. case 3: ypos = 1; break;
  77526. default: return true;
  77527. }
  77528. }
  77529. }
  77530. else
  77531. {
  77532. ++ypos;
  77533. }
  77534. p = destData.getPixelPointer (xpos, ypos);
  77535. }
  77536. if (ypos >= destData.height)
  77537. break;
  77538. }
  77539. return true;
  77540. }
  77541. END_JUCE_NAMESPACE
  77542. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77543. #endif
  77544. //==============================================================================
  77545. // some files include lots of library code, so leave them to the end to avoid cluttering
  77546. // up the build for the clean files.
  77547. #if JUCE_BUILD_CORE
  77548. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77549. namespace zlibNamespace
  77550. {
  77551. #if JUCE_INCLUDE_ZLIB_CODE
  77552. #undef OS_CODE
  77553. #undef fdopen
  77554. /*** Start of inlined file: zlib.h ***/
  77555. #ifndef ZLIB_H
  77556. #define ZLIB_H
  77557. /*** Start of inlined file: zconf.h ***/
  77558. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77559. #ifndef ZCONF_H
  77560. #define ZCONF_H
  77561. // *** Just a few hacks here to make it compile nicely with Juce..
  77562. #define Z_PREFIX 1
  77563. #undef __MACTYPES__
  77564. #ifdef _MSC_VER
  77565. #pragma warning (disable : 4131 4127 4244 4267)
  77566. #endif
  77567. /*
  77568. * If you *really* need a unique prefix for all types and library functions,
  77569. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77570. */
  77571. #ifdef Z_PREFIX
  77572. # define deflateInit_ z_deflateInit_
  77573. # define deflate z_deflate
  77574. # define deflateEnd z_deflateEnd
  77575. # define inflateInit_ z_inflateInit_
  77576. # define inflate z_inflate
  77577. # define inflateEnd z_inflateEnd
  77578. # define inflatePrime z_inflatePrime
  77579. # define inflateGetHeader z_inflateGetHeader
  77580. # define adler32_combine z_adler32_combine
  77581. # define crc32_combine z_crc32_combine
  77582. # define deflateInit2_ z_deflateInit2_
  77583. # define deflateSetDictionary z_deflateSetDictionary
  77584. # define deflateCopy z_deflateCopy
  77585. # define deflateReset z_deflateReset
  77586. # define deflateParams z_deflateParams
  77587. # define deflateBound z_deflateBound
  77588. # define deflatePrime z_deflatePrime
  77589. # define inflateInit2_ z_inflateInit2_
  77590. # define inflateSetDictionary z_inflateSetDictionary
  77591. # define inflateSync z_inflateSync
  77592. # define inflateSyncPoint z_inflateSyncPoint
  77593. # define inflateCopy z_inflateCopy
  77594. # define inflateReset z_inflateReset
  77595. # define inflateBack z_inflateBack
  77596. # define inflateBackEnd z_inflateBackEnd
  77597. # define compress z_compress
  77598. # define compress2 z_compress2
  77599. # define compressBound z_compressBound
  77600. # define uncompress z_uncompress
  77601. # define adler32 z_adler32
  77602. # define crc32 z_crc32
  77603. # define get_crc_table z_get_crc_table
  77604. # define zError z_zError
  77605. # define alloc_func z_alloc_func
  77606. # define free_func z_free_func
  77607. # define in_func z_in_func
  77608. # define out_func z_out_func
  77609. # define Byte z_Byte
  77610. # define uInt z_uInt
  77611. # define uLong z_uLong
  77612. # define Bytef z_Bytef
  77613. # define charf z_charf
  77614. # define intf z_intf
  77615. # define uIntf z_uIntf
  77616. # define uLongf z_uLongf
  77617. # define voidpf z_voidpf
  77618. # define voidp z_voidp
  77619. #endif
  77620. #if defined(__MSDOS__) && !defined(MSDOS)
  77621. # define MSDOS
  77622. #endif
  77623. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77624. # define OS2
  77625. #endif
  77626. #if defined(_WINDOWS) && !defined(WINDOWS)
  77627. # define WINDOWS
  77628. #endif
  77629. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77630. # ifndef WIN32
  77631. # define WIN32
  77632. # endif
  77633. #endif
  77634. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77635. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77636. # ifndef SYS16BIT
  77637. # define SYS16BIT
  77638. # endif
  77639. # endif
  77640. #endif
  77641. /*
  77642. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77643. * than 64k bytes at a time (needed on systems with 16-bit int).
  77644. */
  77645. #ifdef SYS16BIT
  77646. # define MAXSEG_64K
  77647. #endif
  77648. #ifdef MSDOS
  77649. # define UNALIGNED_OK
  77650. #endif
  77651. #ifdef __STDC_VERSION__
  77652. # ifndef STDC
  77653. # define STDC
  77654. # endif
  77655. # if __STDC_VERSION__ >= 199901L
  77656. # ifndef STDC99
  77657. # define STDC99
  77658. # endif
  77659. # endif
  77660. #endif
  77661. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77662. # define STDC
  77663. #endif
  77664. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77665. # define STDC
  77666. #endif
  77667. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77668. # define STDC
  77669. #endif
  77670. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77671. # define STDC
  77672. #endif
  77673. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77674. # define STDC
  77675. #endif
  77676. #ifndef STDC
  77677. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77678. # define const /* note: need a more gentle solution here */
  77679. # endif
  77680. #endif
  77681. /* Some Mac compilers merge all .h files incorrectly: */
  77682. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77683. # define NO_DUMMY_DECL
  77684. #endif
  77685. /* Maximum value for memLevel in deflateInit2 */
  77686. #ifndef MAX_MEM_LEVEL
  77687. # ifdef MAXSEG_64K
  77688. # define MAX_MEM_LEVEL 8
  77689. # else
  77690. # define MAX_MEM_LEVEL 9
  77691. # endif
  77692. #endif
  77693. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77694. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77695. * created by gzip. (Files created by minigzip can still be extracted by
  77696. * gzip.)
  77697. */
  77698. #ifndef MAX_WBITS
  77699. # define MAX_WBITS 15 /* 32K LZ77 window */
  77700. #endif
  77701. /* The memory requirements for deflate are (in bytes):
  77702. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77703. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77704. plus a few kilobytes for small objects. For example, if you want to reduce
  77705. the default memory requirements from 256K to 128K, compile with
  77706. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77707. Of course this will generally degrade compression (there's no free lunch).
  77708. The memory requirements for inflate are (in bytes) 1 << windowBits
  77709. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77710. for small objects.
  77711. */
  77712. /* Type declarations */
  77713. #ifndef OF /* function prototypes */
  77714. # ifdef STDC
  77715. # define OF(args) args
  77716. # else
  77717. # define OF(args) ()
  77718. # endif
  77719. #endif
  77720. /* The following definitions for FAR are needed only for MSDOS mixed
  77721. * model programming (small or medium model with some far allocations).
  77722. * This was tested only with MSC; for other MSDOS compilers you may have
  77723. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77724. * just define FAR to be empty.
  77725. */
  77726. #ifdef SYS16BIT
  77727. # if defined(M_I86SM) || defined(M_I86MM)
  77728. /* MSC small or medium model */
  77729. # define SMALL_MEDIUM
  77730. # ifdef _MSC_VER
  77731. # define FAR _far
  77732. # else
  77733. # define FAR far
  77734. # endif
  77735. # endif
  77736. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77737. /* Turbo C small or medium model */
  77738. # define SMALL_MEDIUM
  77739. # ifdef __BORLANDC__
  77740. # define FAR _far
  77741. # else
  77742. # define FAR far
  77743. # endif
  77744. # endif
  77745. #endif
  77746. #if defined(WINDOWS) || defined(WIN32)
  77747. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77748. * This is not mandatory, but it offers a little performance increase.
  77749. */
  77750. # ifdef ZLIB_DLL
  77751. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77752. # ifdef ZLIB_INTERNAL
  77753. # define ZEXTERN extern __declspec(dllexport)
  77754. # else
  77755. # define ZEXTERN extern __declspec(dllimport)
  77756. # endif
  77757. # endif
  77758. # endif /* ZLIB_DLL */
  77759. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77760. * define ZLIB_WINAPI.
  77761. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77762. */
  77763. # ifdef ZLIB_WINAPI
  77764. # ifdef FAR
  77765. # undef FAR
  77766. # endif
  77767. # include <windows.h>
  77768. /* No need for _export, use ZLIB.DEF instead. */
  77769. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77770. # define ZEXPORT WINAPI
  77771. # ifdef WIN32
  77772. # define ZEXPORTVA WINAPIV
  77773. # else
  77774. # define ZEXPORTVA FAR CDECL
  77775. # endif
  77776. # endif
  77777. #endif
  77778. #if defined (__BEOS__)
  77779. # ifdef ZLIB_DLL
  77780. # ifdef ZLIB_INTERNAL
  77781. # define ZEXPORT __declspec(dllexport)
  77782. # define ZEXPORTVA __declspec(dllexport)
  77783. # else
  77784. # define ZEXPORT __declspec(dllimport)
  77785. # define ZEXPORTVA __declspec(dllimport)
  77786. # endif
  77787. # endif
  77788. #endif
  77789. #ifndef ZEXTERN
  77790. # define ZEXTERN extern
  77791. #endif
  77792. #ifndef ZEXPORT
  77793. # define ZEXPORT
  77794. #endif
  77795. #ifndef ZEXPORTVA
  77796. # define ZEXPORTVA
  77797. #endif
  77798. #ifndef FAR
  77799. # define FAR
  77800. #endif
  77801. #if !defined(__MACTYPES__)
  77802. typedef unsigned char Byte; /* 8 bits */
  77803. #endif
  77804. typedef unsigned int uInt; /* 16 bits or more */
  77805. typedef unsigned long uLong; /* 32 bits or more */
  77806. #ifdef SMALL_MEDIUM
  77807. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77808. # define Bytef Byte FAR
  77809. #else
  77810. typedef Byte FAR Bytef;
  77811. #endif
  77812. typedef char FAR charf;
  77813. typedef int FAR intf;
  77814. typedef uInt FAR uIntf;
  77815. typedef uLong FAR uLongf;
  77816. #ifdef STDC
  77817. typedef void const *voidpc;
  77818. typedef void FAR *voidpf;
  77819. typedef void *voidp;
  77820. #else
  77821. typedef Byte const *voidpc;
  77822. typedef Byte FAR *voidpf;
  77823. typedef Byte *voidp;
  77824. #endif
  77825. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77826. # include <sys/types.h> /* for off_t */
  77827. # include <unistd.h> /* for SEEK_* and off_t */
  77828. # ifdef VMS
  77829. # include <unixio.h> /* for off_t */
  77830. # endif
  77831. # define z_off_t off_t
  77832. #endif
  77833. #ifndef SEEK_SET
  77834. # define SEEK_SET 0 /* Seek from beginning of file. */
  77835. # define SEEK_CUR 1 /* Seek from current position. */
  77836. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77837. #endif
  77838. #ifndef z_off_t
  77839. # define z_off_t long
  77840. #endif
  77841. #if defined(__OS400__)
  77842. # define NO_vsnprintf
  77843. #endif
  77844. #if defined(__MVS__)
  77845. # define NO_vsnprintf
  77846. # ifdef FAR
  77847. # undef FAR
  77848. # endif
  77849. #endif
  77850. /* MVS linker does not support external names larger than 8 bytes */
  77851. #if defined(__MVS__)
  77852. # pragma map(deflateInit_,"DEIN")
  77853. # pragma map(deflateInit2_,"DEIN2")
  77854. # pragma map(deflateEnd,"DEEND")
  77855. # pragma map(deflateBound,"DEBND")
  77856. # pragma map(inflateInit_,"ININ")
  77857. # pragma map(inflateInit2_,"ININ2")
  77858. # pragma map(inflateEnd,"INEND")
  77859. # pragma map(inflateSync,"INSY")
  77860. # pragma map(inflateSetDictionary,"INSEDI")
  77861. # pragma map(compressBound,"CMBND")
  77862. # pragma map(inflate_table,"INTABL")
  77863. # pragma map(inflate_fast,"INFA")
  77864. # pragma map(inflate_copyright,"INCOPY")
  77865. #endif
  77866. #endif /* ZCONF_H */
  77867. /*** End of inlined file: zconf.h ***/
  77868. #ifdef __cplusplus
  77869. //extern "C" {
  77870. #endif
  77871. #define ZLIB_VERSION "1.2.3"
  77872. #define ZLIB_VERNUM 0x1230
  77873. /*
  77874. The 'zlib' compression library provides in-memory compression and
  77875. decompression functions, including integrity checks of the uncompressed
  77876. data. This version of the library supports only one compression method
  77877. (deflation) but other algorithms will be added later and will have the same
  77878. stream interface.
  77879. Compression can be done in a single step if the buffers are large
  77880. enough (for example if an input file is mmap'ed), or can be done by
  77881. repeated calls of the compression function. In the latter case, the
  77882. application must provide more input and/or consume the output
  77883. (providing more output space) before each call.
  77884. The compressed data format used by default by the in-memory functions is
  77885. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77886. around a deflate stream, which is itself documented in RFC 1951.
  77887. The library also supports reading and writing files in gzip (.gz) format
  77888. with an interface similar to that of stdio using the functions that start
  77889. with "gz". The gzip format is different from the zlib format. gzip is a
  77890. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77891. This library can optionally read and write gzip streams in memory as well.
  77892. The zlib format was designed to be compact and fast for use in memory
  77893. and on communications channels. The gzip format was designed for single-
  77894. file compression on file systems, has a larger header than zlib to maintain
  77895. directory information, and uses a different, slower check method than zlib.
  77896. The library does not install any signal handler. The decoder checks
  77897. the consistency of the compressed data, so the library should never
  77898. crash even in case of corrupted input.
  77899. */
  77900. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77901. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77902. struct internal_state;
  77903. typedef struct z_stream_s {
  77904. Bytef *next_in; /* next input byte */
  77905. uInt avail_in; /* number of bytes available at next_in */
  77906. uLong total_in; /* total nb of input bytes read so far */
  77907. Bytef *next_out; /* next output byte should be put there */
  77908. uInt avail_out; /* remaining free space at next_out */
  77909. uLong total_out; /* total nb of bytes output so far */
  77910. char *msg; /* last error message, NULL if no error */
  77911. struct internal_state FAR *state; /* not visible by applications */
  77912. alloc_func zalloc; /* used to allocate the internal state */
  77913. free_func zfree; /* used to free the internal state */
  77914. voidpf opaque; /* private data object passed to zalloc and zfree */
  77915. int data_type; /* best guess about the data type: binary or text */
  77916. uLong adler; /* adler32 value of the uncompressed data */
  77917. uLong reserved; /* reserved for future use */
  77918. } z_stream;
  77919. typedef z_stream FAR *z_streamp;
  77920. /*
  77921. gzip header information passed to and from zlib routines. See RFC 1952
  77922. for more details on the meanings of these fields.
  77923. */
  77924. typedef struct gz_header_s {
  77925. int text; /* true if compressed data believed to be text */
  77926. uLong time; /* modification time */
  77927. int xflags; /* extra flags (not used when writing a gzip file) */
  77928. int os; /* operating system */
  77929. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77930. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77931. uInt extra_max; /* space at extra (only when reading header) */
  77932. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77933. uInt name_max; /* space at name (only when reading header) */
  77934. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77935. uInt comm_max; /* space at comment (only when reading header) */
  77936. int hcrc; /* true if there was or will be a header crc */
  77937. int done; /* true when done reading gzip header (not used
  77938. when writing a gzip file) */
  77939. } gz_header;
  77940. typedef gz_header FAR *gz_headerp;
  77941. /*
  77942. The application must update next_in and avail_in when avail_in has
  77943. dropped to zero. It must update next_out and avail_out when avail_out
  77944. has dropped to zero. The application must initialize zalloc, zfree and
  77945. opaque before calling the init function. All other fields are set by the
  77946. compression library and must not be updated by the application.
  77947. The opaque value provided by the application will be passed as the first
  77948. parameter for calls of zalloc and zfree. This can be useful for custom
  77949. memory management. The compression library attaches no meaning to the
  77950. opaque value.
  77951. zalloc must return Z_NULL if there is not enough memory for the object.
  77952. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77953. thread safe.
  77954. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77955. exactly 65536 bytes, but will not be required to allocate more than this
  77956. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77957. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77958. have their offset normalized to zero. The default allocation function
  77959. provided by this library ensures this (see zutil.c). To reduce memory
  77960. requirements and avoid any allocation of 64K objects, at the expense of
  77961. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77962. The fields total_in and total_out can be used for statistics or
  77963. progress reports. After compression, total_in holds the total size of
  77964. the uncompressed data and may be saved for use in the decompressor
  77965. (particularly if the decompressor wants to decompress everything in
  77966. a single step).
  77967. */
  77968. /* constants */
  77969. #define Z_NO_FLUSH 0
  77970. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77971. #define Z_SYNC_FLUSH 2
  77972. #define Z_FULL_FLUSH 3
  77973. #define Z_FINISH 4
  77974. #define Z_BLOCK 5
  77975. /* Allowed flush values; see deflate() and inflate() below for details */
  77976. #define Z_OK 0
  77977. #define Z_STREAM_END 1
  77978. #define Z_NEED_DICT 2
  77979. #define Z_ERRNO (-1)
  77980. #define Z_STREAM_ERROR (-2)
  77981. #define Z_DATA_ERROR (-3)
  77982. #define Z_MEM_ERROR (-4)
  77983. #define Z_BUF_ERROR (-5)
  77984. #define Z_VERSION_ERROR (-6)
  77985. /* Return codes for the compression/decompression functions. Negative
  77986. * values are errors, positive values are used for special but normal events.
  77987. */
  77988. #define Z_NO_COMPRESSION 0
  77989. #define Z_BEST_SPEED 1
  77990. #define Z_BEST_COMPRESSION 9
  77991. #define Z_DEFAULT_COMPRESSION (-1)
  77992. /* compression levels */
  77993. #define Z_FILTERED 1
  77994. #define Z_HUFFMAN_ONLY 2
  77995. #define Z_RLE 3
  77996. #define Z_FIXED 4
  77997. #define Z_DEFAULT_STRATEGY 0
  77998. /* compression strategy; see deflateInit2() below for details */
  77999. #define Z_BINARY 0
  78000. #define Z_TEXT 1
  78001. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78002. #define Z_UNKNOWN 2
  78003. /* Possible values of the data_type field (though see inflate()) */
  78004. #define Z_DEFLATED 8
  78005. /* The deflate compression method (the only one supported in this version) */
  78006. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78007. #define zlib_version zlibVersion()
  78008. /* for compatibility with versions < 1.0.2 */
  78009. /* basic functions */
  78010. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78011. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78012. If the first character differs, the library code actually used is
  78013. not compatible with the zlib.h header file used by the application.
  78014. This check is automatically made by deflateInit and inflateInit.
  78015. */
  78016. /*
  78017. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78018. Initializes the internal stream state for compression. The fields
  78019. zalloc, zfree and opaque must be initialized before by the caller.
  78020. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78021. use default allocation functions.
  78022. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78023. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78024. all (the input data is simply copied a block at a time).
  78025. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78026. compression (currently equivalent to level 6).
  78027. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78028. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78029. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78030. with the version assumed by the caller (ZLIB_VERSION).
  78031. msg is set to null if there is no error message. deflateInit does not
  78032. perform any compression: this will be done by deflate().
  78033. */
  78034. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78035. /*
  78036. deflate compresses as much data as possible, and stops when the input
  78037. buffer becomes empty or the output buffer becomes full. It may introduce some
  78038. output latency (reading input without producing any output) except when
  78039. forced to flush.
  78040. The detailed semantics are as follows. deflate performs one or both of the
  78041. following actions:
  78042. - Compress more input starting at next_in and update next_in and avail_in
  78043. accordingly. If not all input can be processed (because there is not
  78044. enough room in the output buffer), next_in and avail_in are updated and
  78045. processing will resume at this point for the next call of deflate().
  78046. - Provide more output starting at next_out and update next_out and avail_out
  78047. accordingly. This action is forced if the parameter flush is non zero.
  78048. Forcing flush frequently degrades the compression ratio, so this parameter
  78049. should be set only when necessary (in interactive applications).
  78050. Some output may be provided even if flush is not set.
  78051. Before the call of deflate(), the application should ensure that at least
  78052. one of the actions is possible, by providing more input and/or consuming
  78053. more output, and updating avail_in or avail_out accordingly; avail_out
  78054. should never be zero before the call. The application can consume the
  78055. compressed output when it wants, for example when the output buffer is full
  78056. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78057. and with zero avail_out, it must be called again after making room in the
  78058. output buffer because there might be more output pending.
  78059. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78060. decide how much data to accumualte before producing output, in order to
  78061. maximize compression.
  78062. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78063. flushed to the output buffer and the output is aligned on a byte boundary, so
  78064. that the decompressor can get all input data available so far. (In particular
  78065. avail_in is zero after the call if enough output space has been provided
  78066. before the call.) Flushing may degrade compression for some compression
  78067. algorithms and so it should be used only when necessary.
  78068. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78069. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78070. restart from this point if previous compressed data has been damaged or if
  78071. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78072. compression.
  78073. If deflate returns with avail_out == 0, this function must be called again
  78074. with the same value of the flush parameter and more output space (updated
  78075. avail_out), until the flush is complete (deflate returns with non-zero
  78076. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78077. avail_out is greater than six to avoid repeated flush markers due to
  78078. avail_out == 0 on return.
  78079. If the parameter flush is set to Z_FINISH, pending input is processed,
  78080. pending output is flushed and deflate returns with Z_STREAM_END if there
  78081. was enough output space; if deflate returns with Z_OK, this function must be
  78082. called again with Z_FINISH and more output space (updated avail_out) but no
  78083. more input data, until it returns with Z_STREAM_END or an error. After
  78084. deflate has returned Z_STREAM_END, the only possible operations on the
  78085. stream are deflateReset or deflateEnd.
  78086. Z_FINISH can be used immediately after deflateInit if all the compression
  78087. is to be done in a single step. In this case, avail_out must be at least
  78088. the value returned by deflateBound (see below). If deflate does not return
  78089. Z_STREAM_END, then it must be called again as described above.
  78090. deflate() sets strm->adler to the adler32 checksum of all input read
  78091. so far (that is, total_in bytes).
  78092. deflate() may update strm->data_type if it can make a good guess about
  78093. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78094. binary. This field is only for information purposes and does not affect
  78095. the compression algorithm in any manner.
  78096. deflate() returns Z_OK if some progress has been made (more input
  78097. processed or more output produced), Z_STREAM_END if all input has been
  78098. consumed and all output has been produced (only when flush is set to
  78099. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78100. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78101. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78102. fatal, and deflate() can be called again with more input and more output
  78103. space to continue compressing.
  78104. */
  78105. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78106. /*
  78107. All dynamically allocated data structures for this stream are freed.
  78108. This function discards any unprocessed input and does not flush any
  78109. pending output.
  78110. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78111. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78112. prematurely (some input or output was discarded). In the error case,
  78113. msg may be set but then points to a static string (which must not be
  78114. deallocated).
  78115. */
  78116. /*
  78117. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78118. Initializes the internal stream state for decompression. The fields
  78119. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78120. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78121. value depends on the compression method), inflateInit determines the
  78122. compression method from the zlib header and allocates all data structures
  78123. accordingly; otherwise the allocation will be deferred to the first call of
  78124. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78125. use default allocation functions.
  78126. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78127. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78128. version assumed by the caller. msg is set to null if there is no error
  78129. message. inflateInit does not perform any decompression apart from reading
  78130. the zlib header if present: this will be done by inflate(). (So next_in and
  78131. avail_in may be modified, but next_out and avail_out are unchanged.)
  78132. */
  78133. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78134. /*
  78135. inflate decompresses as much data as possible, and stops when the input
  78136. buffer becomes empty or the output buffer becomes full. It may introduce
  78137. some output latency (reading input without producing any output) except when
  78138. forced to flush.
  78139. The detailed semantics are as follows. inflate performs one or both of the
  78140. following actions:
  78141. - Decompress more input starting at next_in and update next_in and avail_in
  78142. accordingly. If not all input can be processed (because there is not
  78143. enough room in the output buffer), next_in is updated and processing
  78144. will resume at this point for the next call of inflate().
  78145. - Provide more output starting at next_out and update next_out and avail_out
  78146. accordingly. inflate() provides as much output as possible, until there
  78147. is no more input data or no more space in the output buffer (see below
  78148. about the flush parameter).
  78149. Before the call of inflate(), the application should ensure that at least
  78150. one of the actions is possible, by providing more input and/or consuming
  78151. more output, and updating the next_* and avail_* values accordingly.
  78152. The application can consume the uncompressed output when it wants, for
  78153. example when the output buffer is full (avail_out == 0), or after each
  78154. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78155. must be called again after making room in the output buffer because there
  78156. might be more output pending.
  78157. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78158. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78159. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78160. if and when it gets to the next deflate block boundary. When decoding the
  78161. zlib or gzip format, this will cause inflate() to return immediately after
  78162. the header and before the first block. When doing a raw inflate, inflate()
  78163. will go ahead and process the first block, and will return when it gets to
  78164. the end of that block, or when it runs out of data.
  78165. The Z_BLOCK option assists in appending to or combining deflate streams.
  78166. Also to assist in this, on return inflate() will set strm->data_type to the
  78167. number of unused bits in the last byte taken from strm->next_in, plus 64
  78168. if inflate() is currently decoding the last block in the deflate stream,
  78169. plus 128 if inflate() returned immediately after decoding an end-of-block
  78170. code or decoding the complete header up to just before the first byte of the
  78171. deflate stream. The end-of-block will not be indicated until all of the
  78172. uncompressed data from that block has been written to strm->next_out. The
  78173. number of unused bits may in general be greater than seven, except when
  78174. bit 7 of data_type is set, in which case the number of unused bits will be
  78175. less than eight.
  78176. inflate() should normally be called until it returns Z_STREAM_END or an
  78177. error. However if all decompression is to be performed in a single step
  78178. (a single call of inflate), the parameter flush should be set to
  78179. Z_FINISH. In this case all pending input is processed and all pending
  78180. output is flushed; avail_out must be large enough to hold all the
  78181. uncompressed data. (The size of the uncompressed data may have been saved
  78182. by the compressor for this purpose.) The next operation on this stream must
  78183. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78184. is never required, but can be used to inform inflate that a faster approach
  78185. may be used for the single inflate() call.
  78186. In this implementation, inflate() always flushes as much output as
  78187. possible to the output buffer, and always uses the faster approach on the
  78188. first call. So the only effect of the flush parameter in this implementation
  78189. is on the return value of inflate(), as noted below, or when it returns early
  78190. because Z_BLOCK is used.
  78191. If a preset dictionary is needed after this call (see inflateSetDictionary
  78192. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78193. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78194. strm->adler to the adler32 checksum of all output produced so far (that is,
  78195. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78196. below. At the end of the stream, inflate() checks that its computed adler32
  78197. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78198. only if the checksum is correct.
  78199. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78200. deflate data. The header type is detected automatically. Any information
  78201. contained in the gzip header is not retained, so applications that need that
  78202. information should instead use raw inflate, see inflateInit2() below, or
  78203. inflateBack() and perform their own processing of the gzip header and
  78204. trailer.
  78205. inflate() returns Z_OK if some progress has been made (more input processed
  78206. or more output produced), Z_STREAM_END if the end of the compressed data has
  78207. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78208. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78209. corrupted (input stream not conforming to the zlib format or incorrect check
  78210. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78211. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78212. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78213. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78214. inflate() can be called again with more input and more output space to
  78215. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78216. call inflateSync() to look for a good compression block if a partial recovery
  78217. of the data is desired.
  78218. */
  78219. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78220. /*
  78221. All dynamically allocated data structures for this stream are freed.
  78222. This function discards any unprocessed input and does not flush any
  78223. pending output.
  78224. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78225. was inconsistent. In the error case, msg may be set but then points to a
  78226. static string (which must not be deallocated).
  78227. */
  78228. /* Advanced functions */
  78229. /*
  78230. The following functions are needed only in some special applications.
  78231. */
  78232. /*
  78233. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78234. int level,
  78235. int method,
  78236. int windowBits,
  78237. int memLevel,
  78238. int strategy));
  78239. This is another version of deflateInit with more compression options. The
  78240. fields next_in, zalloc, zfree and opaque must be initialized before by
  78241. the caller.
  78242. The method parameter is the compression method. It must be Z_DEFLATED in
  78243. this version of the library.
  78244. The windowBits parameter is the base two logarithm of the window size
  78245. (the size of the history buffer). It should be in the range 8..15 for this
  78246. version of the library. Larger values of this parameter result in better
  78247. compression at the expense of memory usage. The default value is 15 if
  78248. deflateInit is used instead.
  78249. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78250. determines the window size. deflate() will then generate raw deflate data
  78251. with no zlib header or trailer, and will not compute an adler32 check value.
  78252. windowBits can also be greater than 15 for optional gzip encoding. Add
  78253. 16 to windowBits to write a simple gzip header and trailer around the
  78254. compressed data instead of a zlib wrapper. The gzip header will have no
  78255. file name, no extra data, no comment, no modification time (set to zero),
  78256. no header crc, and the operating system will be set to 255 (unknown). If a
  78257. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78258. The memLevel parameter specifies how much memory should be allocated
  78259. for the internal compression state. memLevel=1 uses minimum memory but
  78260. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78261. for optimal speed. The default value is 8. See zconf.h for total memory
  78262. usage as a function of windowBits and memLevel.
  78263. The strategy parameter is used to tune the compression algorithm. Use the
  78264. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78265. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78266. string match), or Z_RLE to limit match distances to one (run-length
  78267. encoding). Filtered data consists mostly of small values with a somewhat
  78268. random distribution. In this case, the compression algorithm is tuned to
  78269. compress them better. The effect of Z_FILTERED is to force more Huffman
  78270. coding and less string matching; it is somewhat intermediate between
  78271. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78272. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78273. parameter only affects the compression ratio but not the correctness of the
  78274. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78275. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78276. applications.
  78277. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78278. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78279. method). msg is set to null if there is no error message. deflateInit2 does
  78280. not perform any compression: this will be done by deflate().
  78281. */
  78282. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78283. const Bytef *dictionary,
  78284. uInt dictLength));
  78285. /*
  78286. Initializes the compression dictionary from the given byte sequence
  78287. without producing any compressed output. This function must be called
  78288. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78289. call of deflate. The compressor and decompressor must use exactly the same
  78290. dictionary (see inflateSetDictionary).
  78291. The dictionary should consist of strings (byte sequences) that are likely
  78292. to be encountered later in the data to be compressed, with the most commonly
  78293. used strings preferably put towards the end of the dictionary. Using a
  78294. dictionary is most useful when the data to be compressed is short and can be
  78295. predicted with good accuracy; the data can then be compressed better than
  78296. with the default empty dictionary.
  78297. Depending on the size of the compression data structures selected by
  78298. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78299. discarded, for example if the dictionary is larger than the window size in
  78300. deflate or deflate2. Thus the strings most likely to be useful should be
  78301. put at the end of the dictionary, not at the front. In addition, the
  78302. current implementation of deflate will use at most the window size minus
  78303. 262 bytes of the provided dictionary.
  78304. Upon return of this function, strm->adler is set to the adler32 value
  78305. of the dictionary; the decompressor may later use this value to determine
  78306. which dictionary has been used by the compressor. (The adler32 value
  78307. applies to the whole dictionary even if only a subset of the dictionary is
  78308. actually used by the compressor.) If a raw deflate was requested, then the
  78309. adler32 value is not computed and strm->adler is not set.
  78310. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78311. parameter is invalid (such as NULL dictionary) or the stream state is
  78312. inconsistent (for example if deflate has already been called for this stream
  78313. or if the compression method is bsort). deflateSetDictionary does not
  78314. perform any compression: this will be done by deflate().
  78315. */
  78316. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78317. z_streamp source));
  78318. /*
  78319. Sets the destination stream as a complete copy of the source stream.
  78320. This function can be useful when several compression strategies will be
  78321. tried, for example when there are several ways of pre-processing the input
  78322. data with a filter. The streams that will be discarded should then be freed
  78323. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78324. compression state which can be quite large, so this strategy is slow and
  78325. can consume lots of memory.
  78326. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78327. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78328. (such as zalloc being NULL). msg is left unchanged in both source and
  78329. destination.
  78330. */
  78331. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78332. /*
  78333. This function is equivalent to deflateEnd followed by deflateInit,
  78334. but does not free and reallocate all the internal compression state.
  78335. The stream will keep the same compression level and any other attributes
  78336. that may have been set by deflateInit2.
  78337. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78338. stream state was inconsistent (such as zalloc or state being NULL).
  78339. */
  78340. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78341. int level,
  78342. int strategy));
  78343. /*
  78344. Dynamically update the compression level and compression strategy. The
  78345. interpretation of level and strategy is as in deflateInit2. This can be
  78346. used to switch between compression and straight copy of the input data, or
  78347. to switch to a different kind of input data requiring a different
  78348. strategy. If the compression level is changed, the input available so far
  78349. is compressed with the old level (and may be flushed); the new level will
  78350. take effect only at the next call of deflate().
  78351. Before the call of deflateParams, the stream state must be set as for
  78352. a call of deflate(), since the currently available input may have to
  78353. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78354. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78355. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78356. if strm->avail_out was zero.
  78357. */
  78358. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78359. int good_length,
  78360. int max_lazy,
  78361. int nice_length,
  78362. int max_chain));
  78363. /*
  78364. Fine tune deflate's internal compression parameters. This should only be
  78365. used by someone who understands the algorithm used by zlib's deflate for
  78366. searching for the best matching string, and even then only by the most
  78367. fanatic optimizer trying to squeeze out the last compressed bit for their
  78368. specific input data. Read the deflate.c source code for the meaning of the
  78369. max_lazy, good_length, nice_length, and max_chain parameters.
  78370. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78371. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78372. */
  78373. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78374. uLong sourceLen));
  78375. /*
  78376. deflateBound() returns an upper bound on the compressed size after
  78377. deflation of sourceLen bytes. It must be called after deflateInit()
  78378. or deflateInit2(). This would be used to allocate an output buffer
  78379. for deflation in a single pass, and so would be called before deflate().
  78380. */
  78381. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78382. int bits,
  78383. int value));
  78384. /*
  78385. deflatePrime() inserts bits in the deflate output stream. The intent
  78386. is that this function is used to start off the deflate output with the
  78387. bits leftover from a previous deflate stream when appending to it. As such,
  78388. this function can only be used for raw deflate, and must be used before the
  78389. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78390. less than or equal to 16, and that many of the least significant bits of
  78391. value will be inserted in the output.
  78392. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78393. stream state was inconsistent.
  78394. */
  78395. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78396. gz_headerp head));
  78397. /*
  78398. deflateSetHeader() provides gzip header information for when a gzip
  78399. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78400. after deflateInit2() or deflateReset() and before the first call of
  78401. deflate(). The text, time, os, extra field, name, and comment information
  78402. in the provided gz_header structure are written to the gzip header (xflag is
  78403. ignored -- the extra flags are set according to the compression level). The
  78404. caller must assure that, if not Z_NULL, name and comment are terminated with
  78405. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78406. available there. If hcrc is true, a gzip header crc is included. Note that
  78407. the current versions of the command-line version of gzip (up through version
  78408. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78409. gzip file" and give up.
  78410. If deflateSetHeader is not used, the default gzip header has text false,
  78411. the time set to zero, and os set to 255, with no extra, name, or comment
  78412. fields. The gzip header is returned to the default state by deflateReset().
  78413. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78414. stream state was inconsistent.
  78415. */
  78416. /*
  78417. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78418. int windowBits));
  78419. This is another version of inflateInit with an extra parameter. The
  78420. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78421. before by the caller.
  78422. The windowBits parameter is the base two logarithm of the maximum window
  78423. size (the size of the history buffer). It should be in the range 8..15 for
  78424. this version of the library. The default value is 15 if inflateInit is used
  78425. instead. windowBits must be greater than or equal to the windowBits value
  78426. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78427. deflateInit2() was not used. If a compressed stream with a larger window
  78428. size is given as input, inflate() will return with the error code
  78429. Z_DATA_ERROR instead of trying to allocate a larger window.
  78430. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78431. determines the window size. inflate() will then process raw deflate data,
  78432. not looking for a zlib or gzip header, not generating a check value, and not
  78433. looking for any check values for comparison at the end of the stream. This
  78434. is for use with other formats that use the deflate compressed data format
  78435. such as zip. Those formats provide their own check values. If a custom
  78436. format is developed using the raw deflate format for compressed data, it is
  78437. recommended that a check value such as an adler32 or a crc32 be applied to
  78438. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78439. most applications, the zlib format should be used as is. Note that comments
  78440. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78441. windowBits can also be greater than 15 for optional gzip decoding. Add
  78442. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78443. detection, or add 16 to decode only the gzip format (the zlib format will
  78444. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78445. a crc32 instead of an adler32.
  78446. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78447. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78448. is set to null if there is no error message. inflateInit2 does not perform
  78449. any decompression apart from reading the zlib header if present: this will
  78450. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78451. and avail_out are unchanged.)
  78452. */
  78453. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78454. const Bytef *dictionary,
  78455. uInt dictLength));
  78456. /*
  78457. Initializes the decompression dictionary from the given uncompressed byte
  78458. sequence. This function must be called immediately after a call of inflate,
  78459. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78460. can be determined from the adler32 value returned by that call of inflate.
  78461. The compressor and decompressor must use exactly the same dictionary (see
  78462. deflateSetDictionary). For raw inflate, this function can be called
  78463. immediately after inflateInit2() or inflateReset() and before any call of
  78464. inflate() to set the dictionary. The application must insure that the
  78465. dictionary that was used for compression is provided.
  78466. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78467. parameter is invalid (such as NULL dictionary) or the stream state is
  78468. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78469. expected one (incorrect adler32 value). inflateSetDictionary does not
  78470. perform any decompression: this will be done by subsequent calls of
  78471. inflate().
  78472. */
  78473. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78474. /*
  78475. Skips invalid compressed data until a full flush point (see above the
  78476. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78477. available input is skipped. No output is provided.
  78478. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78479. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78480. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78481. case, the application may save the current current value of total_in which
  78482. indicates where valid compressed data was found. In the error case, the
  78483. application may repeatedly call inflateSync, providing more input each time,
  78484. until success or end of the input data.
  78485. */
  78486. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78487. z_streamp source));
  78488. /*
  78489. Sets the destination stream as a complete copy of the source stream.
  78490. This function can be useful when randomly accessing a large stream. The
  78491. first pass through the stream can periodically record the inflate state,
  78492. allowing restarting inflate at those points when randomly accessing the
  78493. stream.
  78494. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78495. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78496. (such as zalloc being NULL). msg is left unchanged in both source and
  78497. destination.
  78498. */
  78499. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78500. /*
  78501. This function is equivalent to inflateEnd followed by inflateInit,
  78502. but does not free and reallocate all the internal decompression state.
  78503. The stream will keep attributes that may have been set by inflateInit2.
  78504. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78505. stream state was inconsistent (such as zalloc or state being NULL).
  78506. */
  78507. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78508. int bits,
  78509. int value));
  78510. /*
  78511. This function inserts bits in the inflate input stream. The intent is
  78512. that this function is used to start inflating at a bit position in the
  78513. middle of a byte. The provided bits will be used before any bytes are used
  78514. from next_in. This function should only be used with raw inflate, and
  78515. should be used before the first inflate() call after inflateInit2() or
  78516. inflateReset(). bits must be less than or equal to 16, and that many of the
  78517. least significant bits of value will be inserted in the input.
  78518. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78519. stream state was inconsistent.
  78520. */
  78521. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78522. gz_headerp head));
  78523. /*
  78524. inflateGetHeader() requests that gzip header information be stored in the
  78525. provided gz_header structure. inflateGetHeader() may be called after
  78526. inflateInit2() or inflateReset(), and before the first call of inflate().
  78527. As inflate() processes the gzip stream, head->done is zero until the header
  78528. is completed, at which time head->done is set to one. If a zlib stream is
  78529. being decoded, then head->done is set to -1 to indicate that there will be
  78530. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78531. force inflate() to return immediately after header processing is complete
  78532. and before any actual data is decompressed.
  78533. The text, time, xflags, and os fields are filled in with the gzip header
  78534. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78535. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78536. contains the maximum number of bytes to write to extra. Once done is true,
  78537. extra_len contains the actual extra field length, and extra contains the
  78538. extra field, or that field truncated if extra_max is less than extra_len.
  78539. If name is not Z_NULL, then up to name_max characters are written there,
  78540. terminated with a zero unless the length is greater than name_max. If
  78541. comment is not Z_NULL, then up to comm_max characters are written there,
  78542. terminated with a zero unless the length is greater than comm_max. When
  78543. any of extra, name, or comment are not Z_NULL and the respective field is
  78544. not present in the header, then that field is set to Z_NULL to signal its
  78545. absence. This allows the use of deflateSetHeader() with the returned
  78546. structure to duplicate the header. However if those fields are set to
  78547. allocated memory, then the application will need to save those pointers
  78548. elsewhere so that they can be eventually freed.
  78549. If inflateGetHeader is not used, then the header information is simply
  78550. discarded. The header is always checked for validity, including the header
  78551. CRC if present. inflateReset() will reset the process to discard the header
  78552. information. The application would need to call inflateGetHeader() again to
  78553. retrieve the header from the next gzip stream.
  78554. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78555. stream state was inconsistent.
  78556. */
  78557. /*
  78558. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78559. unsigned char FAR *window));
  78560. Initialize the internal stream state for decompression using inflateBack()
  78561. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78562. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78563. derived memory allocation routines are used. windowBits is the base two
  78564. logarithm of the window size, in the range 8..15. window is a caller
  78565. supplied buffer of that size. Except for special applications where it is
  78566. assured that deflate was used with small window sizes, windowBits must be 15
  78567. and a 32K byte window must be supplied to be able to decompress general
  78568. deflate streams.
  78569. See inflateBack() for the usage of these routines.
  78570. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78571. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78572. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78573. match the version of the header file.
  78574. */
  78575. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78576. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78577. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78578. in_func in, void FAR *in_desc,
  78579. out_func out, void FAR *out_desc));
  78580. /*
  78581. inflateBack() does a raw inflate with a single call using a call-back
  78582. interface for input and output. This is more efficient than inflate() for
  78583. file i/o applications in that it avoids copying between the output and the
  78584. sliding window by simply making the window itself the output buffer. This
  78585. function trusts the application to not change the output buffer passed by
  78586. the output function, at least until inflateBack() returns.
  78587. inflateBackInit() must be called first to allocate the internal state
  78588. and to initialize the state with the user-provided window buffer.
  78589. inflateBack() may then be used multiple times to inflate a complete, raw
  78590. deflate stream with each call. inflateBackEnd() is then called to free
  78591. the allocated state.
  78592. A raw deflate stream is one with no zlib or gzip header or trailer.
  78593. This routine would normally be used in a utility that reads zip or gzip
  78594. files and writes out uncompressed files. The utility would decode the
  78595. header and process the trailer on its own, hence this routine expects
  78596. only the raw deflate stream to decompress. This is different from the
  78597. normal behavior of inflate(), which expects either a zlib or gzip header and
  78598. trailer around the deflate stream.
  78599. inflateBack() uses two subroutines supplied by the caller that are then
  78600. called by inflateBack() for input and output. inflateBack() calls those
  78601. routines until it reads a complete deflate stream and writes out all of the
  78602. uncompressed data, or until it encounters an error. The function's
  78603. parameters and return types are defined above in the in_func and out_func
  78604. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78605. number of bytes of provided input, and a pointer to that input in buf. If
  78606. there is no input available, in() must return zero--buf is ignored in that
  78607. case--and inflateBack() will return a buffer error. inflateBack() will call
  78608. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78609. should return zero on success, or non-zero on failure. If out() returns
  78610. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78611. are permitted to change the contents of the window provided to
  78612. inflateBackInit(), which is also the buffer that out() uses to write from.
  78613. The length written by out() will be at most the window size. Any non-zero
  78614. amount of input may be provided by in().
  78615. For convenience, inflateBack() can be provided input on the first call by
  78616. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78617. in() will be called. Therefore strm->next_in must be initialized before
  78618. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78619. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78620. must also be initialized, and then if strm->avail_in is not zero, input will
  78621. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78622. The in_desc and out_desc parameters of inflateBack() is passed as the
  78623. first parameter of in() and out() respectively when they are called. These
  78624. descriptors can be optionally used to pass any information that the caller-
  78625. supplied in() and out() functions need to do their job.
  78626. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78627. pass back any unused input that was provided by the last in() call. The
  78628. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78629. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78630. error in the deflate stream (in which case strm->msg is set to indicate the
  78631. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78632. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78633. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78634. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78635. out() returning non-zero. (in() will always be called before out(), so
  78636. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78637. that inflateBack() cannot return Z_OK.
  78638. */
  78639. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78640. /*
  78641. All memory allocated by inflateBackInit() is freed.
  78642. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78643. state was inconsistent.
  78644. */
  78645. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78646. /* Return flags indicating compile-time options.
  78647. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78648. 1.0: size of uInt
  78649. 3.2: size of uLong
  78650. 5.4: size of voidpf (pointer)
  78651. 7.6: size of z_off_t
  78652. Compiler, assembler, and debug options:
  78653. 8: DEBUG
  78654. 9: ASMV or ASMINF -- use ASM code
  78655. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78656. 11: 0 (reserved)
  78657. One-time table building (smaller code, but not thread-safe if true):
  78658. 12: BUILDFIXED -- build static block decoding tables when needed
  78659. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78660. 14,15: 0 (reserved)
  78661. Library content (indicates missing functionality):
  78662. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78663. deflate code when not needed)
  78664. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78665. and decode gzip streams (to avoid linking crc code)
  78666. 18-19: 0 (reserved)
  78667. Operation variations (changes in library functionality):
  78668. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78669. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78670. 22,23: 0 (reserved)
  78671. The sprintf variant used by gzprintf (zero is best):
  78672. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78673. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78674. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78675. Remainder:
  78676. 27-31: 0 (reserved)
  78677. */
  78678. /* utility functions */
  78679. /*
  78680. The following utility functions are implemented on top of the
  78681. basic stream-oriented functions. To simplify the interface, some
  78682. default options are assumed (compression level and memory usage,
  78683. standard memory allocation functions). The source code of these
  78684. utility functions can easily be modified if you need special options.
  78685. */
  78686. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78687. const Bytef *source, uLong sourceLen));
  78688. /*
  78689. Compresses the source buffer into the destination buffer. sourceLen is
  78690. the byte length of the source buffer. Upon entry, destLen is the total
  78691. size of the destination buffer, which must be at least the value returned
  78692. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78693. compressed buffer.
  78694. This function can be used to compress a whole file at once if the
  78695. input file is mmap'ed.
  78696. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78697. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78698. buffer.
  78699. */
  78700. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78701. const Bytef *source, uLong sourceLen,
  78702. int level));
  78703. /*
  78704. Compresses the source buffer into the destination buffer. The level
  78705. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78706. length of the source buffer. Upon entry, destLen is the total size of the
  78707. destination buffer, which must be at least the value returned by
  78708. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78709. compressed buffer.
  78710. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78711. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78712. Z_STREAM_ERROR if the level parameter is invalid.
  78713. */
  78714. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78715. /*
  78716. compressBound() returns an upper bound on the compressed size after
  78717. compress() or compress2() on sourceLen bytes. It would be used before
  78718. a compress() or compress2() call to allocate the destination buffer.
  78719. */
  78720. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78721. const Bytef *source, uLong sourceLen));
  78722. /*
  78723. Decompresses the source buffer into the destination buffer. sourceLen is
  78724. the byte length of the source buffer. Upon entry, destLen is the total
  78725. size of the destination buffer, which must be large enough to hold the
  78726. entire uncompressed data. (The size of the uncompressed data must have
  78727. been saved previously by the compressor and transmitted to the decompressor
  78728. by some mechanism outside the scope of this compression library.)
  78729. Upon exit, destLen is the actual size of the compressed buffer.
  78730. This function can be used to decompress a whole file at once if the
  78731. input file is mmap'ed.
  78732. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78733. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78734. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78735. */
  78736. typedef voidp gzFile;
  78737. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78738. /*
  78739. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78740. is as in fopen ("rb" or "wb") but can also include a compression level
  78741. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78742. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78743. as in "wb1R". (See the description of deflateInit2 for more information
  78744. about the strategy parameter.)
  78745. gzopen can be used to read a file which is not in gzip format; in this
  78746. case gzread will directly read from the file without decompression.
  78747. gzopen returns NULL if the file could not be opened or if there was
  78748. insufficient memory to allocate the (de)compression state; errno
  78749. can be checked to distinguish the two cases (if errno is zero, the
  78750. zlib error is Z_MEM_ERROR). */
  78751. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78752. /*
  78753. gzdopen() associates a gzFile with the file descriptor fd. File
  78754. descriptors are obtained from calls like open, dup, creat, pipe or
  78755. fileno (in the file has been previously opened with fopen).
  78756. The mode parameter is as in gzopen.
  78757. The next call of gzclose on the returned gzFile will also close the
  78758. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78759. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78760. gzdopen returns NULL if there was insufficient memory to allocate
  78761. the (de)compression state.
  78762. */
  78763. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78764. /*
  78765. Dynamically update the compression level or strategy. See the description
  78766. of deflateInit2 for the meaning of these parameters.
  78767. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78768. opened for writing.
  78769. */
  78770. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78771. /*
  78772. Reads the given number of uncompressed bytes from the compressed file.
  78773. If the input file was not in gzip format, gzread copies the given number
  78774. of bytes into the buffer.
  78775. gzread returns the number of uncompressed bytes actually read (0 for
  78776. end of file, -1 for error). */
  78777. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78778. voidpc buf, unsigned len));
  78779. /*
  78780. Writes the given number of uncompressed bytes into the compressed file.
  78781. gzwrite returns the number of uncompressed bytes actually written
  78782. (0 in case of error).
  78783. */
  78784. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78785. /*
  78786. Converts, formats, and writes the args to the compressed file under
  78787. control of the format string, as in fprintf. gzprintf returns the number of
  78788. uncompressed bytes actually written (0 in case of error). The number of
  78789. uncompressed bytes written is limited to 4095. The caller should assure that
  78790. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78791. return an error (0) with nothing written. In this case, there may also be a
  78792. buffer overflow with unpredictable consequences, which is possible only if
  78793. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78794. because the secure snprintf() or vsnprintf() functions were not available.
  78795. */
  78796. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78797. /*
  78798. Writes the given null-terminated string to the compressed file, excluding
  78799. the terminating null character.
  78800. gzputs returns the number of characters written, or -1 in case of error.
  78801. */
  78802. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78803. /*
  78804. Reads bytes from the compressed file until len-1 characters are read, or
  78805. a newline character is read and transferred to buf, or an end-of-file
  78806. condition is encountered. The string is then terminated with a null
  78807. character.
  78808. gzgets returns buf, or Z_NULL in case of error.
  78809. */
  78810. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78811. /*
  78812. Writes c, converted to an unsigned char, into the compressed file.
  78813. gzputc returns the value that was written, or -1 in case of error.
  78814. */
  78815. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78816. /*
  78817. Reads one byte from the compressed file. gzgetc returns this byte
  78818. or -1 in case of end of file or error.
  78819. */
  78820. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78821. /*
  78822. Push one character back onto the stream to be read again later.
  78823. Only one character of push-back is allowed. gzungetc() returns the
  78824. character pushed, or -1 on failure. gzungetc() will fail if a
  78825. character has been pushed but not read yet, or if c is -1. The pushed
  78826. character will be discarded if the stream is repositioned with gzseek()
  78827. or gzrewind().
  78828. */
  78829. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78830. /*
  78831. Flushes all pending output into the compressed file. The parameter
  78832. flush is as in the deflate() function. The return value is the zlib
  78833. error number (see function gzerror below). gzflush returns Z_OK if
  78834. the flush parameter is Z_FINISH and all output could be flushed.
  78835. gzflush should be called only when strictly necessary because it can
  78836. degrade compression.
  78837. */
  78838. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78839. z_off_t offset, int whence));
  78840. /*
  78841. Sets the starting position for the next gzread or gzwrite on the
  78842. given compressed file. The offset represents a number of bytes in the
  78843. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78844. the value SEEK_END is not supported.
  78845. If the file is opened for reading, this function is emulated but can be
  78846. extremely slow. If the file is opened for writing, only forward seeks are
  78847. supported; gzseek then compresses a sequence of zeroes up to the new
  78848. starting position.
  78849. gzseek returns the resulting offset location as measured in bytes from
  78850. the beginning of the uncompressed stream, or -1 in case of error, in
  78851. particular if the file is opened for writing and the new starting position
  78852. would be before the current position.
  78853. */
  78854. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78855. /*
  78856. Rewinds the given file. This function is supported only for reading.
  78857. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78858. */
  78859. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78860. /*
  78861. Returns the starting position for the next gzread or gzwrite on the
  78862. given compressed file. This position represents a number of bytes in the
  78863. uncompressed data stream.
  78864. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78865. */
  78866. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78867. /*
  78868. Returns 1 when EOF has previously been detected reading the given
  78869. input stream, otherwise zero.
  78870. */
  78871. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78872. /*
  78873. Returns 1 if file is being read directly without decompression, otherwise
  78874. zero.
  78875. */
  78876. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78877. /*
  78878. Flushes all pending output if necessary, closes the compressed file
  78879. and deallocates all the (de)compression state. The return value is the zlib
  78880. error number (see function gzerror below).
  78881. */
  78882. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78883. /*
  78884. Returns the error message for the last error which occurred on the
  78885. given compressed file. errnum is set to zlib error number. If an
  78886. error occurred in the file system and not in the compression library,
  78887. errnum is set to Z_ERRNO and the application may consult errno
  78888. to get the exact error code.
  78889. */
  78890. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78891. /*
  78892. Clears the error and end-of-file flags for file. This is analogous to the
  78893. clearerr() function in stdio. This is useful for continuing to read a gzip
  78894. file that is being written concurrently.
  78895. */
  78896. /* checksum functions */
  78897. /*
  78898. These functions are not related to compression but are exported
  78899. anyway because they might be useful in applications using the
  78900. compression library.
  78901. */
  78902. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78903. /*
  78904. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78905. return the updated checksum. If buf is NULL, this function returns
  78906. the required initial value for the checksum.
  78907. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78908. much faster. Usage example:
  78909. uLong adler = adler32(0L, Z_NULL, 0);
  78910. while (read_buffer(buffer, length) != EOF) {
  78911. adler = adler32(adler, buffer, length);
  78912. }
  78913. if (adler != original_adler) error();
  78914. */
  78915. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78916. z_off_t len2));
  78917. /*
  78918. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78919. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78920. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78921. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78922. */
  78923. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78924. /*
  78925. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78926. updated CRC-32. If buf is NULL, this function returns the required initial
  78927. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78928. performed within this function so it shouldn't be done by the application.
  78929. Usage example:
  78930. uLong crc = crc32(0L, Z_NULL, 0);
  78931. while (read_buffer(buffer, length) != EOF) {
  78932. crc = crc32(crc, buffer, length);
  78933. }
  78934. if (crc != original_crc) error();
  78935. */
  78936. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78937. /*
  78938. Combine two CRC-32 check values into one. For two sequences of bytes,
  78939. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78940. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78941. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78942. len2.
  78943. */
  78944. /* various hacks, don't look :) */
  78945. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78946. * and the compiler's view of z_stream:
  78947. */
  78948. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78949. const char *version, int stream_size));
  78950. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78951. const char *version, int stream_size));
  78952. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78953. int windowBits, int memLevel,
  78954. int strategy, const char *version,
  78955. int stream_size));
  78956. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78957. const char *version, int stream_size));
  78958. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78959. unsigned char FAR *window,
  78960. const char *version,
  78961. int stream_size));
  78962. #define deflateInit(strm, level) \
  78963. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78964. #define inflateInit(strm) \
  78965. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78966. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78967. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78968. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78969. #define inflateInit2(strm, windowBits) \
  78970. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78971. #define inflateBackInit(strm, windowBits, window) \
  78972. inflateBackInit_((strm), (windowBits), (window), \
  78973. ZLIB_VERSION, sizeof(z_stream))
  78974. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78975. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78976. #endif
  78977. ZEXTERN const char * ZEXPORT zError OF((int));
  78978. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78979. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78980. #ifdef __cplusplus
  78981. //}
  78982. #endif
  78983. #endif /* ZLIB_H */
  78984. /*** End of inlined file: zlib.h ***/
  78985. #undef OS_CODE
  78986. #else
  78987. #include <zlib.h>
  78988. #endif
  78989. }
  78990. BEGIN_JUCE_NAMESPACE
  78991. // internal helper object that holds the zlib structures so they don't have to be
  78992. // included publicly.
  78993. class GZIPCompressorHelper
  78994. {
  78995. public:
  78996. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78997. : data (0),
  78998. dataSize (0),
  78999. compLevel (compressionLevel),
  79000. strategy (0),
  79001. setParams (true),
  79002. streamIsValid (false),
  79003. finished (false),
  79004. shouldFinish (false)
  79005. {
  79006. using namespace zlibNamespace;
  79007. zerostruct (stream);
  79008. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79009. nowrap ? -MAX_WBITS : MAX_WBITS,
  79010. 8, strategy) == Z_OK);
  79011. }
  79012. ~GZIPCompressorHelper()
  79013. {
  79014. using namespace zlibNamespace;
  79015. if (streamIsValid)
  79016. deflateEnd (&stream);
  79017. }
  79018. bool needsInput() const throw()
  79019. {
  79020. return dataSize <= 0;
  79021. }
  79022. void setInput (const uint8* const newData, const int size) throw()
  79023. {
  79024. data = newData;
  79025. dataSize = size;
  79026. }
  79027. int doNextBlock (uint8* const dest, const int destSize) throw()
  79028. {
  79029. using namespace zlibNamespace;
  79030. if (streamIsValid)
  79031. {
  79032. stream.next_in = const_cast <uint8*> (data);
  79033. stream.next_out = dest;
  79034. stream.avail_in = dataSize;
  79035. stream.avail_out = destSize;
  79036. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79037. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79038. setParams = false;
  79039. switch (result)
  79040. {
  79041. case Z_STREAM_END:
  79042. finished = true;
  79043. // Deliberate fall-through..
  79044. case Z_OK:
  79045. data += dataSize - stream.avail_in;
  79046. dataSize = stream.avail_in;
  79047. return destSize - stream.avail_out;
  79048. default:
  79049. break;
  79050. }
  79051. }
  79052. return 0;
  79053. }
  79054. private:
  79055. zlibNamespace::z_stream stream;
  79056. const uint8* data;
  79057. int dataSize, compLevel, strategy;
  79058. bool setParams, streamIsValid;
  79059. public:
  79060. bool finished, shouldFinish;
  79061. };
  79062. const int gzipCompBufferSize = 32768;
  79063. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79064. int compressionLevel,
  79065. const bool deleteDestStream,
  79066. const bool noWrap)
  79067. : destStream (destStream_),
  79068. streamToDelete (deleteDestStream ? destStream_ : 0),
  79069. buffer (gzipCompBufferSize)
  79070. {
  79071. if (compressionLevel < 1 || compressionLevel > 9)
  79072. compressionLevel = -1;
  79073. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79074. }
  79075. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79076. {
  79077. flush();
  79078. }
  79079. void GZIPCompressorOutputStream::flush()
  79080. {
  79081. if (! helper->finished)
  79082. {
  79083. helper->shouldFinish = true;
  79084. while (! helper->finished)
  79085. doNextBlock();
  79086. }
  79087. destStream->flush();
  79088. }
  79089. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79090. {
  79091. if (! helper->finished)
  79092. {
  79093. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79094. while (! helper->needsInput())
  79095. {
  79096. if (! doNextBlock())
  79097. return false;
  79098. }
  79099. }
  79100. return true;
  79101. }
  79102. bool GZIPCompressorOutputStream::doNextBlock()
  79103. {
  79104. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79105. if (len > 0)
  79106. return destStream->write (buffer, len);
  79107. else
  79108. return true;
  79109. }
  79110. int64 GZIPCompressorOutputStream::getPosition()
  79111. {
  79112. return destStream->getPosition();
  79113. }
  79114. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79115. {
  79116. jassertfalse; // can't do it!
  79117. return false;
  79118. }
  79119. END_JUCE_NAMESPACE
  79120. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79121. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79122. #if JUCE_MSVC
  79123. #pragma warning (push)
  79124. #pragma warning (disable: 4309 4305)
  79125. #endif
  79126. namespace zlibNamespace
  79127. {
  79128. #if JUCE_INCLUDE_ZLIB_CODE
  79129. #undef OS_CODE
  79130. #undef fdopen
  79131. #define ZLIB_INTERNAL
  79132. #define NO_DUMMY_DECL
  79133. /*** Start of inlined file: adler32.c ***/
  79134. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79135. #define ZLIB_INTERNAL
  79136. #define BASE 65521UL /* largest prime smaller than 65536 */
  79137. #define NMAX 5552
  79138. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79139. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79140. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79141. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79142. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79143. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79144. /* use NO_DIVIDE if your processor does not do division in hardware */
  79145. #ifdef NO_DIVIDE
  79146. # define MOD(a) \
  79147. do { \
  79148. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79149. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79150. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79151. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79152. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79153. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79154. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79155. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79156. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79157. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79158. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79159. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79160. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79161. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79162. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79163. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79164. if (a >= BASE) a -= BASE; \
  79165. } while (0)
  79166. # define MOD4(a) \
  79167. do { \
  79168. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79169. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79170. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79171. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79172. if (a >= BASE) a -= BASE; \
  79173. } while (0)
  79174. #else
  79175. # define MOD(a) a %= BASE
  79176. # define MOD4(a) a %= BASE
  79177. #endif
  79178. /* ========================================================================= */
  79179. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79180. {
  79181. unsigned long sum2;
  79182. unsigned n;
  79183. /* split Adler-32 into component sums */
  79184. sum2 = (adler >> 16) & 0xffff;
  79185. adler &= 0xffff;
  79186. /* in case user likes doing a byte at a time, keep it fast */
  79187. if (len == 1) {
  79188. adler += buf[0];
  79189. if (adler >= BASE)
  79190. adler -= BASE;
  79191. sum2 += adler;
  79192. if (sum2 >= BASE)
  79193. sum2 -= BASE;
  79194. return adler | (sum2 << 16);
  79195. }
  79196. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79197. if (buf == Z_NULL)
  79198. return 1L;
  79199. /* in case short lengths are provided, keep it somewhat fast */
  79200. if (len < 16) {
  79201. while (len--) {
  79202. adler += *buf++;
  79203. sum2 += adler;
  79204. }
  79205. if (adler >= BASE)
  79206. adler -= BASE;
  79207. MOD4(sum2); /* only added so many BASE's */
  79208. return adler | (sum2 << 16);
  79209. }
  79210. /* do length NMAX blocks -- requires just one modulo operation */
  79211. while (len >= NMAX) {
  79212. len -= NMAX;
  79213. n = NMAX / 16; /* NMAX is divisible by 16 */
  79214. do {
  79215. DO16(buf); /* 16 sums unrolled */
  79216. buf += 16;
  79217. } while (--n);
  79218. MOD(adler);
  79219. MOD(sum2);
  79220. }
  79221. /* do remaining bytes (less than NMAX, still just one modulo) */
  79222. if (len) { /* avoid modulos if none remaining */
  79223. while (len >= 16) {
  79224. len -= 16;
  79225. DO16(buf);
  79226. buf += 16;
  79227. }
  79228. while (len--) {
  79229. adler += *buf++;
  79230. sum2 += adler;
  79231. }
  79232. MOD(adler);
  79233. MOD(sum2);
  79234. }
  79235. /* return recombined sums */
  79236. return adler | (sum2 << 16);
  79237. }
  79238. /* ========================================================================= */
  79239. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79240. {
  79241. unsigned long sum1;
  79242. unsigned long sum2;
  79243. unsigned rem;
  79244. /* the derivation of this formula is left as an exercise for the reader */
  79245. rem = (unsigned)(len2 % BASE);
  79246. sum1 = adler1 & 0xffff;
  79247. sum2 = rem * sum1;
  79248. MOD(sum2);
  79249. sum1 += (adler2 & 0xffff) + BASE - 1;
  79250. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79251. if (sum1 > BASE) sum1 -= BASE;
  79252. if (sum1 > BASE) sum1 -= BASE;
  79253. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79254. if (sum2 > BASE) sum2 -= BASE;
  79255. return sum1 | (sum2 << 16);
  79256. }
  79257. /*** End of inlined file: adler32.c ***/
  79258. /*** Start of inlined file: compress.c ***/
  79259. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79260. #define ZLIB_INTERNAL
  79261. /* ===========================================================================
  79262. Compresses the source buffer into the destination buffer. The level
  79263. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79264. length of the source buffer. Upon entry, destLen is the total size of the
  79265. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79266. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79267. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79268. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79269. Z_STREAM_ERROR if the level parameter is invalid.
  79270. */
  79271. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79272. uLong sourceLen, int level)
  79273. {
  79274. z_stream stream;
  79275. int err;
  79276. stream.next_in = (Bytef*)source;
  79277. stream.avail_in = (uInt)sourceLen;
  79278. #ifdef MAXSEG_64K
  79279. /* Check for source > 64K on 16-bit machine: */
  79280. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79281. #endif
  79282. stream.next_out = dest;
  79283. stream.avail_out = (uInt)*destLen;
  79284. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79285. stream.zalloc = (alloc_func)0;
  79286. stream.zfree = (free_func)0;
  79287. stream.opaque = (voidpf)0;
  79288. err = deflateInit(&stream, level);
  79289. if (err != Z_OK) return err;
  79290. err = deflate(&stream, Z_FINISH);
  79291. if (err != Z_STREAM_END) {
  79292. deflateEnd(&stream);
  79293. return err == Z_OK ? Z_BUF_ERROR : err;
  79294. }
  79295. *destLen = stream.total_out;
  79296. err = deflateEnd(&stream);
  79297. return err;
  79298. }
  79299. /* ===========================================================================
  79300. */
  79301. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79302. {
  79303. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79304. }
  79305. /* ===========================================================================
  79306. If the default memLevel or windowBits for deflateInit() is changed, then
  79307. this function needs to be updated.
  79308. */
  79309. uLong ZEXPORT compressBound (uLong sourceLen)
  79310. {
  79311. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79312. }
  79313. /*** End of inlined file: compress.c ***/
  79314. #undef DO1
  79315. #undef DO8
  79316. /*** Start of inlined file: crc32.c ***/
  79317. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79318. /*
  79319. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79320. protection on the static variables used to control the first-use generation
  79321. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79322. first call get_crc_table() to initialize the tables before allowing more than
  79323. one thread to use crc32().
  79324. */
  79325. #ifdef MAKECRCH
  79326. # include <stdio.h>
  79327. # ifndef DYNAMIC_CRC_TABLE
  79328. # define DYNAMIC_CRC_TABLE
  79329. # endif /* !DYNAMIC_CRC_TABLE */
  79330. #endif /* MAKECRCH */
  79331. /*** Start of inlined file: zutil.h ***/
  79332. /* WARNING: this file should *not* be used by applications. It is
  79333. part of the implementation of the compression library and is
  79334. subject to change. Applications should only use zlib.h.
  79335. */
  79336. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79337. #ifndef ZUTIL_H
  79338. #define ZUTIL_H
  79339. #define ZLIB_INTERNAL
  79340. #ifdef STDC
  79341. # ifndef _WIN32_WCE
  79342. # include <stddef.h>
  79343. # endif
  79344. # include <string.h>
  79345. # include <stdlib.h>
  79346. #endif
  79347. #ifdef NO_ERRNO_H
  79348. # ifdef _WIN32_WCE
  79349. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79350. * errno. We define it as a global variable to simplify porting.
  79351. * Its value is always 0 and should not be used. We rename it to
  79352. * avoid conflict with other libraries that use the same workaround.
  79353. */
  79354. # define errno z_errno
  79355. # endif
  79356. extern int errno;
  79357. #else
  79358. # ifndef _WIN32_WCE
  79359. # include <errno.h>
  79360. # endif
  79361. #endif
  79362. #ifndef local
  79363. # define local static
  79364. #endif
  79365. /* compile with -Dlocal if your debugger can't find static symbols */
  79366. typedef unsigned char uch;
  79367. typedef uch FAR uchf;
  79368. typedef unsigned short ush;
  79369. typedef ush FAR ushf;
  79370. typedef unsigned long ulg;
  79371. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79372. /* (size given to avoid silly warnings with Visual C++) */
  79373. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79374. #define ERR_RETURN(strm,err) \
  79375. return (strm->msg = (char*)ERR_MSG(err), (err))
  79376. /* To be used only when the state is known to be valid */
  79377. /* common constants */
  79378. #ifndef DEF_WBITS
  79379. # define DEF_WBITS MAX_WBITS
  79380. #endif
  79381. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79382. #if MAX_MEM_LEVEL >= 8
  79383. # define DEF_MEM_LEVEL 8
  79384. #else
  79385. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79386. #endif
  79387. /* default memLevel */
  79388. #define STORED_BLOCK 0
  79389. #define STATIC_TREES 1
  79390. #define DYN_TREES 2
  79391. /* The three kinds of block type */
  79392. #define MIN_MATCH 3
  79393. #define MAX_MATCH 258
  79394. /* The minimum and maximum match lengths */
  79395. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79396. /* target dependencies */
  79397. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79398. # define OS_CODE 0x00
  79399. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79400. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79401. /* Allow compilation with ANSI keywords only enabled */
  79402. void _Cdecl farfree( void *block );
  79403. void *_Cdecl farmalloc( unsigned long nbytes );
  79404. # else
  79405. # include <alloc.h>
  79406. # endif
  79407. # else /* MSC or DJGPP */
  79408. # include <malloc.h>
  79409. # endif
  79410. #endif
  79411. #ifdef AMIGA
  79412. # define OS_CODE 0x01
  79413. #endif
  79414. #if defined(VAXC) || defined(VMS)
  79415. # define OS_CODE 0x02
  79416. # define F_OPEN(name, mode) \
  79417. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79418. #endif
  79419. #if defined(ATARI) || defined(atarist)
  79420. # define OS_CODE 0x05
  79421. #endif
  79422. #ifdef OS2
  79423. # define OS_CODE 0x06
  79424. # ifdef M_I86
  79425. #include <malloc.h>
  79426. # endif
  79427. #endif
  79428. #if defined(MACOS) || TARGET_OS_MAC
  79429. # define OS_CODE 0x07
  79430. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79431. # include <unix.h> /* for fdopen */
  79432. # else
  79433. # ifndef fdopen
  79434. # define fdopen(fd,mode) NULL /* No fdopen() */
  79435. # endif
  79436. # endif
  79437. #endif
  79438. #ifdef TOPS20
  79439. # define OS_CODE 0x0a
  79440. #endif
  79441. #ifdef WIN32
  79442. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79443. # define OS_CODE 0x0b
  79444. # endif
  79445. #endif
  79446. #ifdef __50SERIES /* Prime/PRIMOS */
  79447. # define OS_CODE 0x0f
  79448. #endif
  79449. #if defined(_BEOS_) || defined(RISCOS)
  79450. # define fdopen(fd,mode) NULL /* No fdopen() */
  79451. #endif
  79452. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79453. # if defined(_WIN32_WCE)
  79454. # define fdopen(fd,mode) NULL /* No fdopen() */
  79455. # ifndef _PTRDIFF_T_DEFINED
  79456. typedef int ptrdiff_t;
  79457. # define _PTRDIFF_T_DEFINED
  79458. # endif
  79459. # else
  79460. # define fdopen(fd,type) _fdopen(fd,type)
  79461. # endif
  79462. #endif
  79463. /* common defaults */
  79464. #ifndef OS_CODE
  79465. # define OS_CODE 0x03 /* assume Unix */
  79466. #endif
  79467. #ifndef F_OPEN
  79468. # define F_OPEN(name, mode) fopen((name), (mode))
  79469. #endif
  79470. /* functions */
  79471. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79472. # ifndef HAVE_VSNPRINTF
  79473. # define HAVE_VSNPRINTF
  79474. # endif
  79475. #endif
  79476. #if defined(__CYGWIN__)
  79477. # ifndef HAVE_VSNPRINTF
  79478. # define HAVE_VSNPRINTF
  79479. # endif
  79480. #endif
  79481. #ifndef HAVE_VSNPRINTF
  79482. # ifdef MSDOS
  79483. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79484. but for now we just assume it doesn't. */
  79485. # define NO_vsnprintf
  79486. # endif
  79487. # ifdef __TURBOC__
  79488. # define NO_vsnprintf
  79489. # endif
  79490. # ifdef WIN32
  79491. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79492. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79493. # define vsnprintf _vsnprintf
  79494. # endif
  79495. # endif
  79496. # ifdef __SASC
  79497. # define NO_vsnprintf
  79498. # endif
  79499. #endif
  79500. #ifdef VMS
  79501. # define NO_vsnprintf
  79502. #endif
  79503. #if defined(pyr)
  79504. # define NO_MEMCPY
  79505. #endif
  79506. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79507. /* Use our own functions for small and medium model with MSC <= 5.0.
  79508. * You may have to use the same strategy for Borland C (untested).
  79509. * The __SC__ check is for Symantec.
  79510. */
  79511. # define NO_MEMCPY
  79512. #endif
  79513. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79514. # define HAVE_MEMCPY
  79515. #endif
  79516. #ifdef HAVE_MEMCPY
  79517. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79518. # define zmemcpy _fmemcpy
  79519. # define zmemcmp _fmemcmp
  79520. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79521. # else
  79522. # define zmemcpy memcpy
  79523. # define zmemcmp memcmp
  79524. # define zmemzero(dest, len) memset(dest, 0, len)
  79525. # endif
  79526. #else
  79527. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79528. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79529. extern void zmemzero OF((Bytef* dest, uInt len));
  79530. #endif
  79531. /* Diagnostic functions */
  79532. #ifdef DEBUG
  79533. # include <stdio.h>
  79534. extern int z_verbose;
  79535. extern void z_error OF((const char *m));
  79536. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79537. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79538. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79539. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79540. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79541. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79542. #else
  79543. # define Assert(cond,msg)
  79544. # define Trace(x)
  79545. # define Tracev(x)
  79546. # define Tracevv(x)
  79547. # define Tracec(c,x)
  79548. # define Tracecv(c,x)
  79549. #endif
  79550. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79551. void zcfree OF((voidpf opaque, voidpf ptr));
  79552. #define ZALLOC(strm, items, size) \
  79553. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79554. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79555. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79556. #endif /* ZUTIL_H */
  79557. /*** End of inlined file: zutil.h ***/
  79558. /* for STDC and FAR definitions */
  79559. #define local static
  79560. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79561. #ifndef NOBYFOUR
  79562. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79563. # include <limits.h>
  79564. # define BYFOUR
  79565. # if (UINT_MAX == 0xffffffffUL)
  79566. typedef unsigned int u4;
  79567. # else
  79568. # if (ULONG_MAX == 0xffffffffUL)
  79569. typedef unsigned long u4;
  79570. # else
  79571. # if (USHRT_MAX == 0xffffffffUL)
  79572. typedef unsigned short u4;
  79573. # else
  79574. # undef BYFOUR /* can't find a four-byte integer type! */
  79575. # endif
  79576. # endif
  79577. # endif
  79578. # endif /* STDC */
  79579. #endif /* !NOBYFOUR */
  79580. /* Definitions for doing the crc four data bytes at a time. */
  79581. #ifdef BYFOUR
  79582. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79583. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79584. local unsigned long crc32_little OF((unsigned long,
  79585. const unsigned char FAR *, unsigned));
  79586. local unsigned long crc32_big OF((unsigned long,
  79587. const unsigned char FAR *, unsigned));
  79588. # define TBLS 8
  79589. #else
  79590. # define TBLS 1
  79591. #endif /* BYFOUR */
  79592. /* Local functions for crc concatenation */
  79593. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79594. unsigned long vec));
  79595. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79596. #ifdef DYNAMIC_CRC_TABLE
  79597. local volatile int crc_table_empty = 1;
  79598. local unsigned long FAR crc_table[TBLS][256];
  79599. local void make_crc_table OF((void));
  79600. #ifdef MAKECRCH
  79601. local void write_table OF((FILE *, const unsigned long FAR *));
  79602. #endif /* MAKECRCH */
  79603. /*
  79604. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79605. 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.
  79606. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79607. with the lowest powers in the most significant bit. Then adding polynomials
  79608. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79609. one. If we call the above polynomial p, and represent a byte as the
  79610. polynomial q, also with the lowest power in the most significant bit (so the
  79611. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79612. where a mod b means the remainder after dividing a by b.
  79613. This calculation is done using the shift-register method of multiplying and
  79614. taking the remainder. The register is initialized to zero, and for each
  79615. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79616. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79617. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79618. out is a one). We start with the highest power (least significant bit) of
  79619. q and repeat for all eight bits of q.
  79620. The first table is simply the CRC of all possible eight bit values. This is
  79621. all the information needed to generate CRCs on data a byte at a time for all
  79622. combinations of CRC register values and incoming bytes. The remaining tables
  79623. allow for word-at-a-time CRC calculation for both big-endian and little-
  79624. endian machines, where a word is four bytes.
  79625. */
  79626. local void make_crc_table()
  79627. {
  79628. unsigned long c;
  79629. int n, k;
  79630. unsigned long poly; /* polynomial exclusive-or pattern */
  79631. /* terms of polynomial defining this crc (except x^32): */
  79632. static volatile int first = 1; /* flag to limit concurrent making */
  79633. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79634. /* See if another task is already doing this (not thread-safe, but better
  79635. than nothing -- significantly reduces duration of vulnerability in
  79636. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79637. if (first) {
  79638. first = 0;
  79639. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79640. poly = 0UL;
  79641. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79642. poly |= 1UL << (31 - p[n]);
  79643. /* generate a crc for every 8-bit value */
  79644. for (n = 0; n < 256; n++) {
  79645. c = (unsigned long)n;
  79646. for (k = 0; k < 8; k++)
  79647. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79648. crc_table[0][n] = c;
  79649. }
  79650. #ifdef BYFOUR
  79651. /* generate crc for each value followed by one, two, and three zeros,
  79652. and then the byte reversal of those as well as the first table */
  79653. for (n = 0; n < 256; n++) {
  79654. c = crc_table[0][n];
  79655. crc_table[4][n] = REV(c);
  79656. for (k = 1; k < 4; k++) {
  79657. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79658. crc_table[k][n] = c;
  79659. crc_table[k + 4][n] = REV(c);
  79660. }
  79661. }
  79662. #endif /* BYFOUR */
  79663. crc_table_empty = 0;
  79664. }
  79665. else { /* not first */
  79666. /* wait for the other guy to finish (not efficient, but rare) */
  79667. while (crc_table_empty)
  79668. ;
  79669. }
  79670. #ifdef MAKECRCH
  79671. /* write out CRC tables to crc32.h */
  79672. {
  79673. FILE *out;
  79674. out = fopen("crc32.h", "w");
  79675. if (out == NULL) return;
  79676. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79677. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79678. fprintf(out, "local const unsigned long FAR ");
  79679. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79680. write_table(out, crc_table[0]);
  79681. # ifdef BYFOUR
  79682. fprintf(out, "#ifdef BYFOUR\n");
  79683. for (k = 1; k < 8; k++) {
  79684. fprintf(out, " },\n {\n");
  79685. write_table(out, crc_table[k]);
  79686. }
  79687. fprintf(out, "#endif\n");
  79688. # endif /* BYFOUR */
  79689. fprintf(out, " }\n};\n");
  79690. fclose(out);
  79691. }
  79692. #endif /* MAKECRCH */
  79693. }
  79694. #ifdef MAKECRCH
  79695. local void write_table(out, table)
  79696. FILE *out;
  79697. const unsigned long FAR *table;
  79698. {
  79699. int n;
  79700. for (n = 0; n < 256; n++)
  79701. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79702. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79703. }
  79704. #endif /* MAKECRCH */
  79705. #else /* !DYNAMIC_CRC_TABLE */
  79706. /* ========================================================================
  79707. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79708. */
  79709. /*** Start of inlined file: crc32.h ***/
  79710. local const unsigned long FAR crc_table[TBLS][256] =
  79711. {
  79712. {
  79713. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79714. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79715. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79716. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79717. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79718. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79719. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79720. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79721. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79722. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79723. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79724. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79725. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79726. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79727. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79728. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79729. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79730. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79731. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79732. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79733. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79734. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79735. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79736. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79737. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79738. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79739. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79740. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79741. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79742. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79743. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79744. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79745. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79746. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79747. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79748. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79749. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79750. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79751. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79752. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79753. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79754. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79755. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79756. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79757. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79758. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79759. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79760. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79761. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79762. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79763. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79764. 0x2d02ef8dUL
  79765. #ifdef BYFOUR
  79766. },
  79767. {
  79768. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79769. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79770. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79771. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79772. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79773. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79774. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79775. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79776. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79777. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79778. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79779. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79780. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79781. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79782. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79783. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79784. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79785. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79786. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79787. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79788. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79789. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79790. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79791. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79792. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79793. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79794. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79795. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79796. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79797. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79798. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79799. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79800. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79801. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79802. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79803. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79804. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79805. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79806. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79807. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79808. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79809. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79810. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79811. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79812. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79813. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79814. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79815. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79816. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79817. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79818. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79819. 0x9324fd72UL
  79820. },
  79821. {
  79822. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79823. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79824. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79825. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79826. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79827. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79828. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79829. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79830. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79831. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79832. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79833. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79834. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79835. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79836. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79837. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79838. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79839. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79840. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79841. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79842. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79843. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79844. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79845. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79846. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79847. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79848. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79849. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79850. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79851. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79852. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79853. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79854. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79855. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79856. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79857. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79858. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79859. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79860. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79861. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79862. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79863. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79864. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79865. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79866. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79867. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79868. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79869. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79870. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79871. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79872. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79873. 0xbe9834edUL
  79874. },
  79875. {
  79876. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79877. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79878. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79879. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79880. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79881. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79882. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79883. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79884. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79885. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79886. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79887. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79888. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79889. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79890. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79891. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79892. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79893. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79894. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79895. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79896. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79897. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79898. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79899. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79900. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79901. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79902. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79903. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79904. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79905. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79906. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79907. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79908. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79909. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79910. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79911. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79912. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79913. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79914. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79915. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79916. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79917. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79918. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79919. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79920. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79921. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79922. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79923. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79924. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79925. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79926. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79927. 0xde0506f1UL
  79928. },
  79929. {
  79930. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79931. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79932. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79933. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79934. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79935. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79936. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79937. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79938. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79939. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79940. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79941. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79942. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79943. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79944. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79945. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79946. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79947. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79948. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79949. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79950. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79951. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79952. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79953. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79954. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79955. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79956. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79957. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79958. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79959. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79960. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79961. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79962. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79963. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79964. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79965. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79966. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79967. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79968. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79969. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79970. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79971. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79972. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79973. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79974. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79975. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79976. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79977. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79978. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79979. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79980. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79981. 0x8def022dUL
  79982. },
  79983. {
  79984. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79985. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79986. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79987. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79988. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79989. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79990. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79991. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79992. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79993. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79994. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79995. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79996. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79997. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79998. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79999. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80000. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80001. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80002. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80003. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80004. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80005. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80006. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80007. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80008. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80009. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80010. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80011. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80012. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80013. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80014. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80015. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80016. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80017. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80018. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80019. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80020. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80021. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80022. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80023. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80024. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80025. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80026. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80027. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80028. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80029. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80030. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80031. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80032. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80033. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80034. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80035. 0x72fd2493UL
  80036. },
  80037. {
  80038. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80039. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80040. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80041. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80042. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80043. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80044. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80045. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80046. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80047. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80048. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80049. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80050. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80051. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80052. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80053. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80054. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80055. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80056. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80057. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80058. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80059. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80060. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80061. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80062. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80063. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80064. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80065. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80066. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80067. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80068. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80069. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80070. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80071. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80072. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80073. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80074. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80075. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80076. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80077. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80078. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80079. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80080. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80081. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80082. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80083. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80084. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80085. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80086. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80087. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80088. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80089. 0xed3498beUL
  80090. },
  80091. {
  80092. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80093. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80094. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80095. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80096. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80097. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80098. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80099. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80100. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80101. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80102. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80103. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80104. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80105. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80106. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80107. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80108. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80109. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80110. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80111. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80112. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80113. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80114. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80115. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80116. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80117. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80118. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80119. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80120. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80121. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80122. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80123. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80124. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80125. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80126. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80127. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80128. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80129. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80130. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80131. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80132. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80133. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80134. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80135. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80136. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80137. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80138. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80139. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80140. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80141. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80142. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80143. 0xf10605deUL
  80144. #endif
  80145. }
  80146. };
  80147. /*** End of inlined file: crc32.h ***/
  80148. #endif /* DYNAMIC_CRC_TABLE */
  80149. /* =========================================================================
  80150. * This function can be used by asm versions of crc32()
  80151. */
  80152. const unsigned long FAR * ZEXPORT get_crc_table()
  80153. {
  80154. #ifdef DYNAMIC_CRC_TABLE
  80155. if (crc_table_empty)
  80156. make_crc_table();
  80157. #endif /* DYNAMIC_CRC_TABLE */
  80158. return (const unsigned long FAR *)crc_table;
  80159. }
  80160. /* ========================================================================= */
  80161. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80162. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80163. /* ========================================================================= */
  80164. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80165. {
  80166. if (buf == Z_NULL) return 0UL;
  80167. #ifdef DYNAMIC_CRC_TABLE
  80168. if (crc_table_empty)
  80169. make_crc_table();
  80170. #endif /* DYNAMIC_CRC_TABLE */
  80171. #ifdef BYFOUR
  80172. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80173. u4 endian;
  80174. endian = 1;
  80175. if (*((unsigned char *)(&endian)))
  80176. return crc32_little(crc, buf, len);
  80177. else
  80178. return crc32_big(crc, buf, len);
  80179. }
  80180. #endif /* BYFOUR */
  80181. crc = crc ^ 0xffffffffUL;
  80182. while (len >= 8) {
  80183. DO8;
  80184. len -= 8;
  80185. }
  80186. if (len) do {
  80187. DO1;
  80188. } while (--len);
  80189. return crc ^ 0xffffffffUL;
  80190. }
  80191. #ifdef BYFOUR
  80192. /* ========================================================================= */
  80193. #define DOLIT4 c ^= *buf4++; \
  80194. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80195. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80196. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80197. /* ========================================================================= */
  80198. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80199. {
  80200. register u4 c;
  80201. register const u4 FAR *buf4;
  80202. c = (u4)crc;
  80203. c = ~c;
  80204. while (len && ((ptrdiff_t)buf & 3)) {
  80205. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80206. len--;
  80207. }
  80208. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80209. while (len >= 32) {
  80210. DOLIT32;
  80211. len -= 32;
  80212. }
  80213. while (len >= 4) {
  80214. DOLIT4;
  80215. len -= 4;
  80216. }
  80217. buf = (const unsigned char FAR *)buf4;
  80218. if (len) do {
  80219. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80220. } while (--len);
  80221. c = ~c;
  80222. return (unsigned long)c;
  80223. }
  80224. /* ========================================================================= */
  80225. #define DOBIG4 c ^= *++buf4; \
  80226. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80227. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80228. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80229. /* ========================================================================= */
  80230. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80231. {
  80232. register u4 c;
  80233. register const u4 FAR *buf4;
  80234. c = REV((u4)crc);
  80235. c = ~c;
  80236. while (len && ((ptrdiff_t)buf & 3)) {
  80237. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80238. len--;
  80239. }
  80240. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80241. buf4--;
  80242. while (len >= 32) {
  80243. DOBIG32;
  80244. len -= 32;
  80245. }
  80246. while (len >= 4) {
  80247. DOBIG4;
  80248. len -= 4;
  80249. }
  80250. buf4++;
  80251. buf = (const unsigned char FAR *)buf4;
  80252. if (len) do {
  80253. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80254. } while (--len);
  80255. c = ~c;
  80256. return (unsigned long)(REV(c));
  80257. }
  80258. #endif /* BYFOUR */
  80259. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80260. /* ========================================================================= */
  80261. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80262. {
  80263. unsigned long sum;
  80264. sum = 0;
  80265. while (vec) {
  80266. if (vec & 1)
  80267. sum ^= *mat;
  80268. vec >>= 1;
  80269. mat++;
  80270. }
  80271. return sum;
  80272. }
  80273. /* ========================================================================= */
  80274. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80275. {
  80276. int n;
  80277. for (n = 0; n < GF2_DIM; n++)
  80278. square[n] = gf2_matrix_times(mat, mat[n]);
  80279. }
  80280. /* ========================================================================= */
  80281. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80282. {
  80283. int n;
  80284. unsigned long row;
  80285. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80286. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80287. /* degenerate case */
  80288. if (len2 == 0)
  80289. return crc1;
  80290. /* put operator for one zero bit in odd */
  80291. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80292. row = 1;
  80293. for (n = 1; n < GF2_DIM; n++) {
  80294. odd[n] = row;
  80295. row <<= 1;
  80296. }
  80297. /* put operator for two zero bits in even */
  80298. gf2_matrix_square(even, odd);
  80299. /* put operator for four zero bits in odd */
  80300. gf2_matrix_square(odd, even);
  80301. /* apply len2 zeros to crc1 (first square will put the operator for one
  80302. zero byte, eight zero bits, in even) */
  80303. do {
  80304. /* apply zeros operator for this bit of len2 */
  80305. gf2_matrix_square(even, odd);
  80306. if (len2 & 1)
  80307. crc1 = gf2_matrix_times(even, crc1);
  80308. len2 >>= 1;
  80309. /* if no more bits set, then done */
  80310. if (len2 == 0)
  80311. break;
  80312. /* another iteration of the loop with odd and even swapped */
  80313. gf2_matrix_square(odd, even);
  80314. if (len2 & 1)
  80315. crc1 = gf2_matrix_times(odd, crc1);
  80316. len2 >>= 1;
  80317. /* if no more bits set, then done */
  80318. } while (len2 != 0);
  80319. /* return combined crc */
  80320. crc1 ^= crc2;
  80321. return crc1;
  80322. }
  80323. /*** End of inlined file: crc32.c ***/
  80324. /*** Start of inlined file: deflate.c ***/
  80325. /*
  80326. * ALGORITHM
  80327. *
  80328. * The "deflation" process depends on being able to identify portions
  80329. * of the input text which are identical to earlier input (within a
  80330. * sliding window trailing behind the input currently being processed).
  80331. *
  80332. * The most straightforward technique turns out to be the fastest for
  80333. * most input files: try all possible matches and select the longest.
  80334. * The key feature of this algorithm is that insertions into the string
  80335. * dictionary are very simple and thus fast, and deletions are avoided
  80336. * completely. Insertions are performed at each input character, whereas
  80337. * string matches are performed only when the previous match ends. So it
  80338. * is preferable to spend more time in matches to allow very fast string
  80339. * insertions and avoid deletions. The matching algorithm for small
  80340. * strings is inspired from that of Rabin & Karp. A brute force approach
  80341. * is used to find longer strings when a small match has been found.
  80342. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80343. * (by Leonid Broukhis).
  80344. * A previous version of this file used a more sophisticated algorithm
  80345. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80346. * time, but has a larger average cost, uses more memory and is patented.
  80347. * However the F&G algorithm may be faster for some highly redundant
  80348. * files if the parameter max_chain_length (described below) is too large.
  80349. *
  80350. * ACKNOWLEDGEMENTS
  80351. *
  80352. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80353. * I found it in 'freeze' written by Leonid Broukhis.
  80354. * Thanks to many people for bug reports and testing.
  80355. *
  80356. * REFERENCES
  80357. *
  80358. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80359. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80360. *
  80361. * A description of the Rabin and Karp algorithm is given in the book
  80362. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80363. *
  80364. * Fiala,E.R., and Greene,D.H.
  80365. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80366. *
  80367. */
  80368. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80369. /*** Start of inlined file: deflate.h ***/
  80370. /* WARNING: this file should *not* be used by applications. It is
  80371. part of the implementation of the compression library and is
  80372. subject to change. Applications should only use zlib.h.
  80373. */
  80374. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80375. #ifndef DEFLATE_H
  80376. #define DEFLATE_H
  80377. /* define NO_GZIP when compiling if you want to disable gzip header and
  80378. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80379. the crc code when it is not needed. For shared libraries, gzip encoding
  80380. should be left enabled. */
  80381. #ifndef NO_GZIP
  80382. # define GZIP
  80383. #endif
  80384. #define NO_DUMMY_DECL
  80385. /* ===========================================================================
  80386. * Internal compression state.
  80387. */
  80388. #define LENGTH_CODES 29
  80389. /* number of length codes, not counting the special END_BLOCK code */
  80390. #define LITERALS 256
  80391. /* number of literal bytes 0..255 */
  80392. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80393. /* number of Literal or Length codes, including the END_BLOCK code */
  80394. #define D_CODES 30
  80395. /* number of distance codes */
  80396. #define BL_CODES 19
  80397. /* number of codes used to transfer the bit lengths */
  80398. #define HEAP_SIZE (2*L_CODES+1)
  80399. /* maximum heap size */
  80400. #define MAX_BITS 15
  80401. /* All codes must not exceed MAX_BITS bits */
  80402. #define INIT_STATE 42
  80403. #define EXTRA_STATE 69
  80404. #define NAME_STATE 73
  80405. #define COMMENT_STATE 91
  80406. #define HCRC_STATE 103
  80407. #define BUSY_STATE 113
  80408. #define FINISH_STATE 666
  80409. /* Stream status */
  80410. /* Data structure describing a single value and its code string. */
  80411. typedef struct ct_data_s {
  80412. union {
  80413. ush freq; /* frequency count */
  80414. ush code; /* bit string */
  80415. } fc;
  80416. union {
  80417. ush dad; /* father node in Huffman tree */
  80418. ush len; /* length of bit string */
  80419. } dl;
  80420. } FAR ct_data;
  80421. #define Freq fc.freq
  80422. #define Code fc.code
  80423. #define Dad dl.dad
  80424. #define Len dl.len
  80425. typedef struct static_tree_desc_s static_tree_desc;
  80426. typedef struct tree_desc_s {
  80427. ct_data *dyn_tree; /* the dynamic tree */
  80428. int max_code; /* largest code with non zero frequency */
  80429. static_tree_desc *stat_desc; /* the corresponding static tree */
  80430. } FAR tree_desc;
  80431. typedef ush Pos;
  80432. typedef Pos FAR Posf;
  80433. typedef unsigned IPos;
  80434. /* A Pos is an index in the character window. We use short instead of int to
  80435. * save space in the various tables. IPos is used only for parameter passing.
  80436. */
  80437. typedef struct internal_state {
  80438. z_streamp strm; /* pointer back to this zlib stream */
  80439. int status; /* as the name implies */
  80440. Bytef *pending_buf; /* output still pending */
  80441. ulg pending_buf_size; /* size of pending_buf */
  80442. Bytef *pending_out; /* next pending byte to output to the stream */
  80443. uInt pending; /* nb of bytes in the pending buffer */
  80444. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80445. gz_headerp gzhead; /* gzip header information to write */
  80446. uInt gzindex; /* where in extra, name, or comment */
  80447. Byte method; /* STORED (for zip only) or DEFLATED */
  80448. int last_flush; /* value of flush param for previous deflate call */
  80449. /* used by deflate.c: */
  80450. uInt w_size; /* LZ77 window size (32K by default) */
  80451. uInt w_bits; /* log2(w_size) (8..16) */
  80452. uInt w_mask; /* w_size - 1 */
  80453. Bytef *window;
  80454. /* Sliding window. Input bytes are read into the second half of the window,
  80455. * and move to the first half later to keep a dictionary of at least wSize
  80456. * bytes. With this organization, matches are limited to a distance of
  80457. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80458. * performed with a length multiple of the block size. Also, it limits
  80459. * the window size to 64K, which is quite useful on MSDOS.
  80460. * To do: use the user input buffer as sliding window.
  80461. */
  80462. ulg window_size;
  80463. /* Actual size of window: 2*wSize, except when the user input buffer
  80464. * is directly used as sliding window.
  80465. */
  80466. Posf *prev;
  80467. /* Link to older string with same hash index. To limit the size of this
  80468. * array to 64K, this link is maintained only for the last 32K strings.
  80469. * An index in this array is thus a window index modulo 32K.
  80470. */
  80471. Posf *head; /* Heads of the hash chains or NIL. */
  80472. uInt ins_h; /* hash index of string to be inserted */
  80473. uInt hash_size; /* number of elements in hash table */
  80474. uInt hash_bits; /* log2(hash_size) */
  80475. uInt hash_mask; /* hash_size-1 */
  80476. uInt hash_shift;
  80477. /* Number of bits by which ins_h must be shifted at each input
  80478. * step. It must be such that after MIN_MATCH steps, the oldest
  80479. * byte no longer takes part in the hash key, that is:
  80480. * hash_shift * MIN_MATCH >= hash_bits
  80481. */
  80482. long block_start;
  80483. /* Window position at the beginning of the current output block. Gets
  80484. * negative when the window is moved backwards.
  80485. */
  80486. uInt match_length; /* length of best match */
  80487. IPos prev_match; /* previous match */
  80488. int match_available; /* set if previous match exists */
  80489. uInt strstart; /* start of string to insert */
  80490. uInt match_start; /* start of matching string */
  80491. uInt lookahead; /* number of valid bytes ahead in window */
  80492. uInt prev_length;
  80493. /* Length of the best match at previous step. Matches not greater than this
  80494. * are discarded. This is used in the lazy match evaluation.
  80495. */
  80496. uInt max_chain_length;
  80497. /* To speed up deflation, hash chains are never searched beyond this
  80498. * length. A higher limit improves compression ratio but degrades the
  80499. * speed.
  80500. */
  80501. uInt max_lazy_match;
  80502. /* Attempt to find a better match only when the current match is strictly
  80503. * smaller than this value. This mechanism is used only for compression
  80504. * levels >= 4.
  80505. */
  80506. # define max_insert_length max_lazy_match
  80507. /* Insert new strings in the hash table only if the match length is not
  80508. * greater than this length. This saves time but degrades compression.
  80509. * max_insert_length is used only for compression levels <= 3.
  80510. */
  80511. int level; /* compression level (1..9) */
  80512. int strategy; /* favor or force Huffman coding*/
  80513. uInt good_match;
  80514. /* Use a faster search when the previous match is longer than this */
  80515. int nice_match; /* Stop searching when current match exceeds this */
  80516. /* used by trees.c: */
  80517. /* Didn't use ct_data typedef below to supress compiler warning */
  80518. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80519. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80520. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80521. struct tree_desc_s l_desc; /* desc. for literal tree */
  80522. struct tree_desc_s d_desc; /* desc. for distance tree */
  80523. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80524. ush bl_count[MAX_BITS+1];
  80525. /* number of codes at each bit length for an optimal tree */
  80526. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80527. int heap_len; /* number of elements in the heap */
  80528. int heap_max; /* element of largest frequency */
  80529. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80530. * The same heap array is used to build all trees.
  80531. */
  80532. uch depth[2*L_CODES+1];
  80533. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80534. */
  80535. uchf *l_buf; /* buffer for literals or lengths */
  80536. uInt lit_bufsize;
  80537. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80538. * limiting lit_bufsize to 64K:
  80539. * - frequencies can be kept in 16 bit counters
  80540. * - if compression is not successful for the first block, all input
  80541. * data is still in the window so we can still emit a stored block even
  80542. * when input comes from standard input. (This can also be done for
  80543. * all blocks if lit_bufsize is not greater than 32K.)
  80544. * - if compression is not successful for a file smaller than 64K, we can
  80545. * even emit a stored file instead of a stored block (saving 5 bytes).
  80546. * This is applicable only for zip (not gzip or zlib).
  80547. * - creating new Huffman trees less frequently may not provide fast
  80548. * adaptation to changes in the input data statistics. (Take for
  80549. * example a binary file with poorly compressible code followed by
  80550. * a highly compressible string table.) Smaller buffer sizes give
  80551. * fast adaptation but have of course the overhead of transmitting
  80552. * trees more frequently.
  80553. * - I can't count above 4
  80554. */
  80555. uInt last_lit; /* running index in l_buf */
  80556. ushf *d_buf;
  80557. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80558. * the same number of elements. To use different lengths, an extra flag
  80559. * array would be necessary.
  80560. */
  80561. ulg opt_len; /* bit length of current block with optimal trees */
  80562. ulg static_len; /* bit length of current block with static trees */
  80563. uInt matches; /* number of string matches in current block */
  80564. int last_eob_len; /* bit length of EOB code for last block */
  80565. #ifdef DEBUG
  80566. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80567. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80568. #endif
  80569. ush bi_buf;
  80570. /* Output buffer. bits are inserted starting at the bottom (least
  80571. * significant bits).
  80572. */
  80573. int bi_valid;
  80574. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80575. * are always zero.
  80576. */
  80577. } FAR deflate_state;
  80578. /* Output a byte on the stream.
  80579. * IN assertion: there is enough room in pending_buf.
  80580. */
  80581. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80582. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80583. /* Minimum amount of lookahead, except at the end of the input file.
  80584. * See deflate.c for comments about the MIN_MATCH+1.
  80585. */
  80586. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80587. /* In order to simplify the code, particularly on 16 bit machines, match
  80588. * distances are limited to MAX_DIST instead of WSIZE.
  80589. */
  80590. /* in trees.c */
  80591. void _tr_init OF((deflate_state *s));
  80592. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80593. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80594. int eof));
  80595. void _tr_align OF((deflate_state *s));
  80596. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80597. int eof));
  80598. #define d_code(dist) \
  80599. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80600. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80601. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80602. * used.
  80603. */
  80604. #ifndef DEBUG
  80605. /* Inline versions of _tr_tally for speed: */
  80606. #if defined(GEN_TREES_H) || !defined(STDC)
  80607. extern uch _length_code[];
  80608. extern uch _dist_code[];
  80609. #else
  80610. extern const uch _length_code[];
  80611. extern const uch _dist_code[];
  80612. #endif
  80613. # define _tr_tally_lit(s, c, flush) \
  80614. { uch cc = (c); \
  80615. s->d_buf[s->last_lit] = 0; \
  80616. s->l_buf[s->last_lit++] = cc; \
  80617. s->dyn_ltree[cc].Freq++; \
  80618. flush = (s->last_lit == s->lit_bufsize-1); \
  80619. }
  80620. # define _tr_tally_dist(s, distance, length, flush) \
  80621. { uch len = (length); \
  80622. ush dist = (distance); \
  80623. s->d_buf[s->last_lit] = dist; \
  80624. s->l_buf[s->last_lit++] = len; \
  80625. dist--; \
  80626. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80627. s->dyn_dtree[d_code(dist)].Freq++; \
  80628. flush = (s->last_lit == s->lit_bufsize-1); \
  80629. }
  80630. #else
  80631. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80632. # define _tr_tally_dist(s, distance, length, flush) \
  80633. flush = _tr_tally(s, distance, length)
  80634. #endif
  80635. #endif /* DEFLATE_H */
  80636. /*** End of inlined file: deflate.h ***/
  80637. const char deflate_copyright[] =
  80638. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80639. /*
  80640. If you use the zlib library in a product, an acknowledgment is welcome
  80641. in the documentation of your product. If for some reason you cannot
  80642. include such an acknowledgment, I would appreciate that you keep this
  80643. copyright string in the executable of your product.
  80644. */
  80645. /* ===========================================================================
  80646. * Function prototypes.
  80647. */
  80648. typedef enum {
  80649. need_more, /* block not completed, need more input or more output */
  80650. block_done, /* block flush performed */
  80651. finish_started, /* finish started, need only more output at next deflate */
  80652. finish_done /* finish done, accept no more input or output */
  80653. } block_state;
  80654. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80655. /* Compression function. Returns the block state after the call. */
  80656. local void fill_window OF((deflate_state *s));
  80657. local block_state deflate_stored OF((deflate_state *s, int flush));
  80658. local block_state deflate_fast OF((deflate_state *s, int flush));
  80659. #ifndef FASTEST
  80660. local block_state deflate_slow OF((deflate_state *s, int flush));
  80661. #endif
  80662. local void lm_init OF((deflate_state *s));
  80663. local void putShortMSB OF((deflate_state *s, uInt b));
  80664. local void flush_pending OF((z_streamp strm));
  80665. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80666. #ifndef FASTEST
  80667. #ifdef ASMV
  80668. void match_init OF((void)); /* asm code initialization */
  80669. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80670. #else
  80671. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80672. #endif
  80673. #endif
  80674. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80675. #ifdef DEBUG
  80676. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80677. int length));
  80678. #endif
  80679. /* ===========================================================================
  80680. * Local data
  80681. */
  80682. #define NIL 0
  80683. /* Tail of hash chains */
  80684. #ifndef TOO_FAR
  80685. # define TOO_FAR 4096
  80686. #endif
  80687. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80688. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80689. /* Minimum amount of lookahead, except at the end of the input file.
  80690. * See deflate.c for comments about the MIN_MATCH+1.
  80691. */
  80692. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80693. * the desired pack level (0..9). The values given below have been tuned to
  80694. * exclude worst case performance for pathological files. Better values may be
  80695. * found for specific files.
  80696. */
  80697. typedef struct config_s {
  80698. ush good_length; /* reduce lazy search above this match length */
  80699. ush max_lazy; /* do not perform lazy search above this match length */
  80700. ush nice_length; /* quit search above this match length */
  80701. ush max_chain;
  80702. compress_func func;
  80703. } config;
  80704. #ifdef FASTEST
  80705. local const config configuration_table[2] = {
  80706. /* good lazy nice chain */
  80707. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80708. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80709. #else
  80710. local const config configuration_table[10] = {
  80711. /* good lazy nice chain */
  80712. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80713. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80714. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80715. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80716. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80717. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80718. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80719. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80720. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80721. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80722. #endif
  80723. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80724. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80725. * meaning.
  80726. */
  80727. #define EQUAL 0
  80728. /* result of memcmp for equal strings */
  80729. #ifndef NO_DUMMY_DECL
  80730. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80731. #endif
  80732. /* ===========================================================================
  80733. * Update a hash value with the given input byte
  80734. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80735. * input characters, so that a running hash key can be computed from the
  80736. * previous key instead of complete recalculation each time.
  80737. */
  80738. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80739. /* ===========================================================================
  80740. * Insert string str in the dictionary and set match_head to the previous head
  80741. * of the hash chain (the most recent string with same hash key). Return
  80742. * the previous length of the hash chain.
  80743. * If this file is compiled with -DFASTEST, the compression level is forced
  80744. * to 1, and no hash chains are maintained.
  80745. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80746. * input characters and the first MIN_MATCH bytes of str are valid
  80747. * (except for the last MIN_MATCH-1 bytes of the input file).
  80748. */
  80749. #ifdef FASTEST
  80750. #define INSERT_STRING(s, str, match_head) \
  80751. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80752. match_head = s->head[s->ins_h], \
  80753. s->head[s->ins_h] = (Pos)(str))
  80754. #else
  80755. #define INSERT_STRING(s, str, match_head) \
  80756. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80757. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80758. s->head[s->ins_h] = (Pos)(str))
  80759. #endif
  80760. /* ===========================================================================
  80761. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80762. * prev[] will be initialized on the fly.
  80763. */
  80764. #define CLEAR_HASH(s) \
  80765. s->head[s->hash_size-1] = NIL; \
  80766. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80767. /* ========================================================================= */
  80768. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80769. {
  80770. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80771. Z_DEFAULT_STRATEGY, version, stream_size);
  80772. /* To do: ignore strm->next_in if we use it as window */
  80773. }
  80774. /* ========================================================================= */
  80775. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80776. {
  80777. deflate_state *s;
  80778. int wrap = 1;
  80779. static const char my_version[] = ZLIB_VERSION;
  80780. ushf *overlay;
  80781. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80782. * output size for (length,distance) codes is <= 24 bits.
  80783. */
  80784. if (version == Z_NULL || version[0] != my_version[0] ||
  80785. stream_size != sizeof(z_stream)) {
  80786. return Z_VERSION_ERROR;
  80787. }
  80788. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80789. strm->msg = Z_NULL;
  80790. if (strm->zalloc == (alloc_func)0) {
  80791. strm->zalloc = zcalloc;
  80792. strm->opaque = (voidpf)0;
  80793. }
  80794. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80795. #ifdef FASTEST
  80796. if (level != 0) level = 1;
  80797. #else
  80798. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80799. #endif
  80800. if (windowBits < 0) { /* suppress zlib wrapper */
  80801. wrap = 0;
  80802. windowBits = -windowBits;
  80803. }
  80804. #ifdef GZIP
  80805. else if (windowBits > 15) {
  80806. wrap = 2; /* write gzip wrapper instead */
  80807. windowBits -= 16;
  80808. }
  80809. #endif
  80810. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80811. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80812. strategy < 0 || strategy > Z_FIXED) {
  80813. return Z_STREAM_ERROR;
  80814. }
  80815. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80816. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80817. if (s == Z_NULL) return Z_MEM_ERROR;
  80818. strm->state = (struct internal_state FAR *)s;
  80819. s->strm = strm;
  80820. s->wrap = wrap;
  80821. s->gzhead = Z_NULL;
  80822. s->w_bits = windowBits;
  80823. s->w_size = 1 << s->w_bits;
  80824. s->w_mask = s->w_size - 1;
  80825. s->hash_bits = memLevel + 7;
  80826. s->hash_size = 1 << s->hash_bits;
  80827. s->hash_mask = s->hash_size - 1;
  80828. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80829. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80830. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80831. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80832. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80833. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80834. s->pending_buf = (uchf *) overlay;
  80835. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80836. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80837. s->pending_buf == Z_NULL) {
  80838. s->status = FINISH_STATE;
  80839. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80840. deflateEnd (strm);
  80841. return Z_MEM_ERROR;
  80842. }
  80843. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80844. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80845. s->level = level;
  80846. s->strategy = strategy;
  80847. s->method = (Byte)method;
  80848. return deflateReset(strm);
  80849. }
  80850. /* ========================================================================= */
  80851. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80852. {
  80853. deflate_state *s;
  80854. uInt length = dictLength;
  80855. uInt n;
  80856. IPos hash_head = 0;
  80857. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80858. strm->state->wrap == 2 ||
  80859. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80860. return Z_STREAM_ERROR;
  80861. s = strm->state;
  80862. if (s->wrap)
  80863. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80864. if (length < MIN_MATCH) return Z_OK;
  80865. if (length > MAX_DIST(s)) {
  80866. length = MAX_DIST(s);
  80867. dictionary += dictLength - length; /* use the tail of the dictionary */
  80868. }
  80869. zmemcpy(s->window, dictionary, length);
  80870. s->strstart = length;
  80871. s->block_start = (long)length;
  80872. /* Insert all strings in the hash table (except for the last two bytes).
  80873. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80874. * call of fill_window.
  80875. */
  80876. s->ins_h = s->window[0];
  80877. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80878. for (n = 0; n <= length - MIN_MATCH; n++) {
  80879. INSERT_STRING(s, n, hash_head);
  80880. }
  80881. if (hash_head) hash_head = 0; /* to make compiler happy */
  80882. return Z_OK;
  80883. }
  80884. /* ========================================================================= */
  80885. int ZEXPORT deflateReset (z_streamp strm)
  80886. {
  80887. deflate_state *s;
  80888. if (strm == Z_NULL || strm->state == Z_NULL ||
  80889. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80890. return Z_STREAM_ERROR;
  80891. }
  80892. strm->total_in = strm->total_out = 0;
  80893. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80894. strm->data_type = Z_UNKNOWN;
  80895. s = (deflate_state *)strm->state;
  80896. s->pending = 0;
  80897. s->pending_out = s->pending_buf;
  80898. if (s->wrap < 0) {
  80899. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80900. }
  80901. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80902. strm->adler =
  80903. #ifdef GZIP
  80904. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80905. #endif
  80906. adler32(0L, Z_NULL, 0);
  80907. s->last_flush = Z_NO_FLUSH;
  80908. _tr_init(s);
  80909. lm_init(s);
  80910. return Z_OK;
  80911. }
  80912. /* ========================================================================= */
  80913. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80914. {
  80915. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80916. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80917. strm->state->gzhead = head;
  80918. return Z_OK;
  80919. }
  80920. /* ========================================================================= */
  80921. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80922. {
  80923. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80924. strm->state->bi_valid = bits;
  80925. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80926. return Z_OK;
  80927. }
  80928. /* ========================================================================= */
  80929. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80930. {
  80931. deflate_state *s;
  80932. compress_func func;
  80933. int err = Z_OK;
  80934. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80935. s = strm->state;
  80936. #ifdef FASTEST
  80937. if (level != 0) level = 1;
  80938. #else
  80939. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80940. #endif
  80941. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80942. return Z_STREAM_ERROR;
  80943. }
  80944. func = configuration_table[s->level].func;
  80945. if (func != configuration_table[level].func && strm->total_in != 0) {
  80946. /* Flush the last buffer: */
  80947. err = deflate(strm, Z_PARTIAL_FLUSH);
  80948. }
  80949. if (s->level != level) {
  80950. s->level = level;
  80951. s->max_lazy_match = configuration_table[level].max_lazy;
  80952. s->good_match = configuration_table[level].good_length;
  80953. s->nice_match = configuration_table[level].nice_length;
  80954. s->max_chain_length = configuration_table[level].max_chain;
  80955. }
  80956. s->strategy = strategy;
  80957. return err;
  80958. }
  80959. /* ========================================================================= */
  80960. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80961. {
  80962. deflate_state *s;
  80963. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80964. s = strm->state;
  80965. s->good_match = good_length;
  80966. s->max_lazy_match = max_lazy;
  80967. s->nice_match = nice_length;
  80968. s->max_chain_length = max_chain;
  80969. return Z_OK;
  80970. }
  80971. /* =========================================================================
  80972. * For the default windowBits of 15 and memLevel of 8, this function returns
  80973. * a close to exact, as well as small, upper bound on the compressed size.
  80974. * They are coded as constants here for a reason--if the #define's are
  80975. * changed, then this function needs to be changed as well. The return
  80976. * value for 15 and 8 only works for those exact settings.
  80977. *
  80978. * For any setting other than those defaults for windowBits and memLevel,
  80979. * the value returned is a conservative worst case for the maximum expansion
  80980. * resulting from using fixed blocks instead of stored blocks, which deflate
  80981. * can emit on compressed data for some combinations of the parameters.
  80982. *
  80983. * This function could be more sophisticated to provide closer upper bounds
  80984. * for every combination of windowBits and memLevel, as well as wrap.
  80985. * But even the conservative upper bound of about 14% expansion does not
  80986. * seem onerous for output buffer allocation.
  80987. */
  80988. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80989. {
  80990. deflate_state *s;
  80991. uLong destLen;
  80992. /* conservative upper bound */
  80993. destLen = sourceLen +
  80994. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80995. /* if can't get parameters, return conservative bound */
  80996. if (strm == Z_NULL || strm->state == Z_NULL)
  80997. return destLen;
  80998. /* if not default parameters, return conservative bound */
  80999. s = strm->state;
  81000. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81001. return destLen;
  81002. /* default settings: return tight bound for that case */
  81003. return compressBound(sourceLen);
  81004. }
  81005. /* =========================================================================
  81006. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81007. * IN assertion: the stream state is correct and there is enough room in
  81008. * pending_buf.
  81009. */
  81010. local void putShortMSB (deflate_state *s, uInt b)
  81011. {
  81012. put_byte(s, (Byte)(b >> 8));
  81013. put_byte(s, (Byte)(b & 0xff));
  81014. }
  81015. /* =========================================================================
  81016. * Flush as much pending output as possible. All deflate() output goes
  81017. * through this function so some applications may wish to modify it
  81018. * to avoid allocating a large strm->next_out buffer and copying into it.
  81019. * (See also read_buf()).
  81020. */
  81021. local void flush_pending (z_streamp strm)
  81022. {
  81023. unsigned len = strm->state->pending;
  81024. if (len > strm->avail_out) len = strm->avail_out;
  81025. if (len == 0) return;
  81026. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81027. strm->next_out += len;
  81028. strm->state->pending_out += len;
  81029. strm->total_out += len;
  81030. strm->avail_out -= len;
  81031. strm->state->pending -= len;
  81032. if (strm->state->pending == 0) {
  81033. strm->state->pending_out = strm->state->pending_buf;
  81034. }
  81035. }
  81036. /* ========================================================================= */
  81037. int ZEXPORT deflate (z_streamp strm, int flush)
  81038. {
  81039. int old_flush; /* value of flush param for previous deflate call */
  81040. deflate_state *s;
  81041. if (strm == Z_NULL || strm->state == Z_NULL ||
  81042. flush > Z_FINISH || flush < 0) {
  81043. return Z_STREAM_ERROR;
  81044. }
  81045. s = strm->state;
  81046. if (strm->next_out == Z_NULL ||
  81047. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81048. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81049. ERR_RETURN(strm, Z_STREAM_ERROR);
  81050. }
  81051. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81052. s->strm = strm; /* just in case */
  81053. old_flush = s->last_flush;
  81054. s->last_flush = flush;
  81055. /* Write the header */
  81056. if (s->status == INIT_STATE) {
  81057. #ifdef GZIP
  81058. if (s->wrap == 2) {
  81059. strm->adler = crc32(0L, Z_NULL, 0);
  81060. put_byte(s, 31);
  81061. put_byte(s, 139);
  81062. put_byte(s, 8);
  81063. if (s->gzhead == NULL) {
  81064. put_byte(s, 0);
  81065. put_byte(s, 0);
  81066. put_byte(s, 0);
  81067. put_byte(s, 0);
  81068. put_byte(s, 0);
  81069. put_byte(s, s->level == 9 ? 2 :
  81070. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81071. 4 : 0));
  81072. put_byte(s, OS_CODE);
  81073. s->status = BUSY_STATE;
  81074. }
  81075. else {
  81076. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81077. (s->gzhead->hcrc ? 2 : 0) +
  81078. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81079. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81080. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81081. );
  81082. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81083. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81084. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81085. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81086. put_byte(s, s->level == 9 ? 2 :
  81087. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81088. 4 : 0));
  81089. put_byte(s, s->gzhead->os & 0xff);
  81090. if (s->gzhead->extra != NULL) {
  81091. put_byte(s, s->gzhead->extra_len & 0xff);
  81092. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81093. }
  81094. if (s->gzhead->hcrc)
  81095. strm->adler = crc32(strm->adler, s->pending_buf,
  81096. s->pending);
  81097. s->gzindex = 0;
  81098. s->status = EXTRA_STATE;
  81099. }
  81100. }
  81101. else
  81102. #endif
  81103. {
  81104. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81105. uInt level_flags;
  81106. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81107. level_flags = 0;
  81108. else if (s->level < 6)
  81109. level_flags = 1;
  81110. else if (s->level == 6)
  81111. level_flags = 2;
  81112. else
  81113. level_flags = 3;
  81114. header |= (level_flags << 6);
  81115. if (s->strstart != 0) header |= PRESET_DICT;
  81116. header += 31 - (header % 31);
  81117. s->status = BUSY_STATE;
  81118. putShortMSB(s, header);
  81119. /* Save the adler32 of the preset dictionary: */
  81120. if (s->strstart != 0) {
  81121. putShortMSB(s, (uInt)(strm->adler >> 16));
  81122. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81123. }
  81124. strm->adler = adler32(0L, Z_NULL, 0);
  81125. }
  81126. }
  81127. #ifdef GZIP
  81128. if (s->status == EXTRA_STATE) {
  81129. if (s->gzhead->extra != NULL) {
  81130. uInt beg = s->pending; /* start of bytes to update crc */
  81131. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81132. if (s->pending == s->pending_buf_size) {
  81133. if (s->gzhead->hcrc && s->pending > beg)
  81134. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81135. s->pending - beg);
  81136. flush_pending(strm);
  81137. beg = s->pending;
  81138. if (s->pending == s->pending_buf_size)
  81139. break;
  81140. }
  81141. put_byte(s, s->gzhead->extra[s->gzindex]);
  81142. s->gzindex++;
  81143. }
  81144. if (s->gzhead->hcrc && s->pending > beg)
  81145. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81146. s->pending - beg);
  81147. if (s->gzindex == s->gzhead->extra_len) {
  81148. s->gzindex = 0;
  81149. s->status = NAME_STATE;
  81150. }
  81151. }
  81152. else
  81153. s->status = NAME_STATE;
  81154. }
  81155. if (s->status == NAME_STATE) {
  81156. if (s->gzhead->name != NULL) {
  81157. uInt beg = s->pending; /* start of bytes to update crc */
  81158. int val;
  81159. do {
  81160. if (s->pending == s->pending_buf_size) {
  81161. if (s->gzhead->hcrc && s->pending > beg)
  81162. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81163. s->pending - beg);
  81164. flush_pending(strm);
  81165. beg = s->pending;
  81166. if (s->pending == s->pending_buf_size) {
  81167. val = 1;
  81168. break;
  81169. }
  81170. }
  81171. val = s->gzhead->name[s->gzindex++];
  81172. put_byte(s, val);
  81173. } while (val != 0);
  81174. if (s->gzhead->hcrc && s->pending > beg)
  81175. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81176. s->pending - beg);
  81177. if (val == 0) {
  81178. s->gzindex = 0;
  81179. s->status = COMMENT_STATE;
  81180. }
  81181. }
  81182. else
  81183. s->status = COMMENT_STATE;
  81184. }
  81185. if (s->status == COMMENT_STATE) {
  81186. if (s->gzhead->comment != NULL) {
  81187. uInt beg = s->pending; /* start of bytes to update crc */
  81188. int val;
  81189. do {
  81190. if (s->pending == s->pending_buf_size) {
  81191. if (s->gzhead->hcrc && s->pending > beg)
  81192. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81193. s->pending - beg);
  81194. flush_pending(strm);
  81195. beg = s->pending;
  81196. if (s->pending == s->pending_buf_size) {
  81197. val = 1;
  81198. break;
  81199. }
  81200. }
  81201. val = s->gzhead->comment[s->gzindex++];
  81202. put_byte(s, val);
  81203. } while (val != 0);
  81204. if (s->gzhead->hcrc && s->pending > beg)
  81205. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81206. s->pending - beg);
  81207. if (val == 0)
  81208. s->status = HCRC_STATE;
  81209. }
  81210. else
  81211. s->status = HCRC_STATE;
  81212. }
  81213. if (s->status == HCRC_STATE) {
  81214. if (s->gzhead->hcrc) {
  81215. if (s->pending + 2 > s->pending_buf_size)
  81216. flush_pending(strm);
  81217. if (s->pending + 2 <= s->pending_buf_size) {
  81218. put_byte(s, (Byte)(strm->adler & 0xff));
  81219. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81220. strm->adler = crc32(0L, Z_NULL, 0);
  81221. s->status = BUSY_STATE;
  81222. }
  81223. }
  81224. else
  81225. s->status = BUSY_STATE;
  81226. }
  81227. #endif
  81228. /* Flush as much pending output as possible */
  81229. if (s->pending != 0) {
  81230. flush_pending(strm);
  81231. if (strm->avail_out == 0) {
  81232. /* Since avail_out is 0, deflate will be called again with
  81233. * more output space, but possibly with both pending and
  81234. * avail_in equal to zero. There won't be anything to do,
  81235. * but this is not an error situation so make sure we
  81236. * return OK instead of BUF_ERROR at next call of deflate:
  81237. */
  81238. s->last_flush = -1;
  81239. return Z_OK;
  81240. }
  81241. /* Make sure there is something to do and avoid duplicate consecutive
  81242. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81243. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81244. */
  81245. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81246. flush != Z_FINISH) {
  81247. ERR_RETURN(strm, Z_BUF_ERROR);
  81248. }
  81249. /* User must not provide more input after the first FINISH: */
  81250. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81251. ERR_RETURN(strm, Z_BUF_ERROR);
  81252. }
  81253. /* Start a new block or continue the current one.
  81254. */
  81255. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81256. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81257. block_state bstate;
  81258. bstate = (*(configuration_table[s->level].func))(s, flush);
  81259. if (bstate == finish_started || bstate == finish_done) {
  81260. s->status = FINISH_STATE;
  81261. }
  81262. if (bstate == need_more || bstate == finish_started) {
  81263. if (strm->avail_out == 0) {
  81264. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81265. }
  81266. return Z_OK;
  81267. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81268. * of deflate should use the same flush parameter to make sure
  81269. * that the flush is complete. So we don't have to output an
  81270. * empty block here, this will be done at next call. This also
  81271. * ensures that for a very small output buffer, we emit at most
  81272. * one empty block.
  81273. */
  81274. }
  81275. if (bstate == block_done) {
  81276. if (flush == Z_PARTIAL_FLUSH) {
  81277. _tr_align(s);
  81278. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81279. _tr_stored_block(s, (char*)0, 0L, 0);
  81280. /* For a full flush, this empty block will be recognized
  81281. * as a special marker by inflate_sync().
  81282. */
  81283. if (flush == Z_FULL_FLUSH) {
  81284. CLEAR_HASH(s); /* forget history */
  81285. }
  81286. }
  81287. flush_pending(strm);
  81288. if (strm->avail_out == 0) {
  81289. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81290. return Z_OK;
  81291. }
  81292. }
  81293. }
  81294. Assert(strm->avail_out > 0, "bug2");
  81295. if (flush != Z_FINISH) return Z_OK;
  81296. if (s->wrap <= 0) return Z_STREAM_END;
  81297. /* Write the trailer */
  81298. #ifdef GZIP
  81299. if (s->wrap == 2) {
  81300. put_byte(s, (Byte)(strm->adler & 0xff));
  81301. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81302. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81303. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81304. put_byte(s, (Byte)(strm->total_in & 0xff));
  81305. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81306. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81307. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81308. }
  81309. else
  81310. #endif
  81311. {
  81312. putShortMSB(s, (uInt)(strm->adler >> 16));
  81313. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81314. }
  81315. flush_pending(strm);
  81316. /* If avail_out is zero, the application will call deflate again
  81317. * to flush the rest.
  81318. */
  81319. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81320. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81321. }
  81322. /* ========================================================================= */
  81323. int ZEXPORT deflateEnd (z_streamp strm)
  81324. {
  81325. int status;
  81326. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81327. status = strm->state->status;
  81328. if (status != INIT_STATE &&
  81329. status != EXTRA_STATE &&
  81330. status != NAME_STATE &&
  81331. status != COMMENT_STATE &&
  81332. status != HCRC_STATE &&
  81333. status != BUSY_STATE &&
  81334. status != FINISH_STATE) {
  81335. return Z_STREAM_ERROR;
  81336. }
  81337. /* Deallocate in reverse order of allocations: */
  81338. TRY_FREE(strm, strm->state->pending_buf);
  81339. TRY_FREE(strm, strm->state->head);
  81340. TRY_FREE(strm, strm->state->prev);
  81341. TRY_FREE(strm, strm->state->window);
  81342. ZFREE(strm, strm->state);
  81343. strm->state = Z_NULL;
  81344. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81345. }
  81346. /* =========================================================================
  81347. * Copy the source state to the destination state.
  81348. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81349. * doesn't have enough memory anyway to duplicate compression states).
  81350. */
  81351. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81352. {
  81353. #ifdef MAXSEG_64K
  81354. return Z_STREAM_ERROR;
  81355. #else
  81356. deflate_state *ds;
  81357. deflate_state *ss;
  81358. ushf *overlay;
  81359. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81360. return Z_STREAM_ERROR;
  81361. }
  81362. ss = source->state;
  81363. zmemcpy(dest, source, sizeof(z_stream));
  81364. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81365. if (ds == Z_NULL) return Z_MEM_ERROR;
  81366. dest->state = (struct internal_state FAR *) ds;
  81367. zmemcpy(ds, ss, sizeof(deflate_state));
  81368. ds->strm = dest;
  81369. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81370. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81371. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81372. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81373. ds->pending_buf = (uchf *) overlay;
  81374. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81375. ds->pending_buf == Z_NULL) {
  81376. deflateEnd (dest);
  81377. return Z_MEM_ERROR;
  81378. }
  81379. /* following zmemcpy do not work for 16-bit MSDOS */
  81380. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81381. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81382. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81383. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81384. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81385. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81386. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81387. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81388. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81389. ds->bl_desc.dyn_tree = ds->bl_tree;
  81390. return Z_OK;
  81391. #endif /* MAXSEG_64K */
  81392. }
  81393. /* ===========================================================================
  81394. * Read a new buffer from the current input stream, update the adler32
  81395. * and total number of bytes read. All deflate() input goes through
  81396. * this function so some applications may wish to modify it to avoid
  81397. * allocating a large strm->next_in buffer and copying from it.
  81398. * (See also flush_pending()).
  81399. */
  81400. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81401. {
  81402. unsigned len = strm->avail_in;
  81403. if (len > size) len = size;
  81404. if (len == 0) return 0;
  81405. strm->avail_in -= len;
  81406. if (strm->state->wrap == 1) {
  81407. strm->adler = adler32(strm->adler, strm->next_in, len);
  81408. }
  81409. #ifdef GZIP
  81410. else if (strm->state->wrap == 2) {
  81411. strm->adler = crc32(strm->adler, strm->next_in, len);
  81412. }
  81413. #endif
  81414. zmemcpy(buf, strm->next_in, len);
  81415. strm->next_in += len;
  81416. strm->total_in += len;
  81417. return (int)len;
  81418. }
  81419. /* ===========================================================================
  81420. * Initialize the "longest match" routines for a new zlib stream
  81421. */
  81422. local void lm_init (deflate_state *s)
  81423. {
  81424. s->window_size = (ulg)2L*s->w_size;
  81425. CLEAR_HASH(s);
  81426. /* Set the default configuration parameters:
  81427. */
  81428. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81429. s->good_match = configuration_table[s->level].good_length;
  81430. s->nice_match = configuration_table[s->level].nice_length;
  81431. s->max_chain_length = configuration_table[s->level].max_chain;
  81432. s->strstart = 0;
  81433. s->block_start = 0L;
  81434. s->lookahead = 0;
  81435. s->match_length = s->prev_length = MIN_MATCH-1;
  81436. s->match_available = 0;
  81437. s->ins_h = 0;
  81438. #ifndef FASTEST
  81439. #ifdef ASMV
  81440. match_init(); /* initialize the asm code */
  81441. #endif
  81442. #endif
  81443. }
  81444. #ifndef FASTEST
  81445. /* ===========================================================================
  81446. * Set match_start to the longest match starting at the given string and
  81447. * return its length. Matches shorter or equal to prev_length are discarded,
  81448. * in which case the result is equal to prev_length and match_start is
  81449. * garbage.
  81450. * IN assertions: cur_match is the head of the hash chain for the current
  81451. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81452. * OUT assertion: the match length is not greater than s->lookahead.
  81453. */
  81454. #ifndef ASMV
  81455. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81456. * match.S. The code will be functionally equivalent.
  81457. */
  81458. local uInt longest_match(deflate_state *s, IPos cur_match)
  81459. {
  81460. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81461. register Bytef *scan = s->window + s->strstart; /* current string */
  81462. register Bytef *match; /* matched string */
  81463. register int len; /* length of current match */
  81464. int best_len = s->prev_length; /* best match length so far */
  81465. int nice_match = s->nice_match; /* stop if match long enough */
  81466. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81467. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81468. /* Stop when cur_match becomes <= limit. To simplify the code,
  81469. * we prevent matches with the string of window index 0.
  81470. */
  81471. Posf *prev = s->prev;
  81472. uInt wmask = s->w_mask;
  81473. #ifdef UNALIGNED_OK
  81474. /* Compare two bytes at a time. Note: this is not always beneficial.
  81475. * Try with and without -DUNALIGNED_OK to check.
  81476. */
  81477. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81478. register ush scan_start = *(ushf*)scan;
  81479. register ush scan_end = *(ushf*)(scan+best_len-1);
  81480. #else
  81481. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81482. register Byte scan_end1 = scan[best_len-1];
  81483. register Byte scan_end = scan[best_len];
  81484. #endif
  81485. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81486. * It is easy to get rid of this optimization if necessary.
  81487. */
  81488. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81489. /* Do not waste too much time if we already have a good match: */
  81490. if (s->prev_length >= s->good_match) {
  81491. chain_length >>= 2;
  81492. }
  81493. /* Do not look for matches beyond the end of the input. This is necessary
  81494. * to make deflate deterministic.
  81495. */
  81496. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81497. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81498. do {
  81499. Assert(cur_match < s->strstart, "no future");
  81500. match = s->window + cur_match;
  81501. /* Skip to next match if the match length cannot increase
  81502. * or if the match length is less than 2. Note that the checks below
  81503. * for insufficient lookahead only occur occasionally for performance
  81504. * reasons. Therefore uninitialized memory will be accessed, and
  81505. * conditional jumps will be made that depend on those values.
  81506. * However the length of the match is limited to the lookahead, so
  81507. * the output of deflate is not affected by the uninitialized values.
  81508. */
  81509. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81510. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81511. * UNALIGNED_OK if your compiler uses a different size.
  81512. */
  81513. if (*(ushf*)(match+best_len-1) != scan_end ||
  81514. *(ushf*)match != scan_start) continue;
  81515. /* It is not necessary to compare scan[2] and match[2] since they are
  81516. * always equal when the other bytes match, given that the hash keys
  81517. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81518. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81519. * lookahead only every 4th comparison; the 128th check will be made
  81520. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81521. * necessary to put more guard bytes at the end of the window, or
  81522. * to check more often for insufficient lookahead.
  81523. */
  81524. Assert(scan[2] == match[2], "scan[2]?");
  81525. scan++, match++;
  81526. do {
  81527. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81528. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81529. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81530. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81531. scan < strend);
  81532. /* The funny "do {}" generates better code on most compilers */
  81533. /* Here, scan <= window+strstart+257 */
  81534. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81535. if (*scan == *match) scan++;
  81536. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81537. scan = strend - (MAX_MATCH-1);
  81538. #else /* UNALIGNED_OK */
  81539. if (match[best_len] != scan_end ||
  81540. match[best_len-1] != scan_end1 ||
  81541. *match != *scan ||
  81542. *++match != scan[1]) continue;
  81543. /* The check at best_len-1 can be removed because it will be made
  81544. * again later. (This heuristic is not always a win.)
  81545. * It is not necessary to compare scan[2] and match[2] since they
  81546. * are always equal when the other bytes match, given that
  81547. * the hash keys are equal and that HASH_BITS >= 8.
  81548. */
  81549. scan += 2, match++;
  81550. Assert(*scan == *match, "match[2]?");
  81551. /* We check for insufficient lookahead only every 8th comparison;
  81552. * the 256th check will be made at strstart+258.
  81553. */
  81554. do {
  81555. } while (*++scan == *++match && *++scan == *++match &&
  81556. *++scan == *++match && *++scan == *++match &&
  81557. *++scan == *++match && *++scan == *++match &&
  81558. *++scan == *++match && *++scan == *++match &&
  81559. scan < strend);
  81560. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81561. len = MAX_MATCH - (int)(strend - scan);
  81562. scan = strend - MAX_MATCH;
  81563. #endif /* UNALIGNED_OK */
  81564. if (len > best_len) {
  81565. s->match_start = cur_match;
  81566. best_len = len;
  81567. if (len >= nice_match) break;
  81568. #ifdef UNALIGNED_OK
  81569. scan_end = *(ushf*)(scan+best_len-1);
  81570. #else
  81571. scan_end1 = scan[best_len-1];
  81572. scan_end = scan[best_len];
  81573. #endif
  81574. }
  81575. } while ((cur_match = prev[cur_match & wmask]) > limit
  81576. && --chain_length != 0);
  81577. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81578. return s->lookahead;
  81579. }
  81580. #endif /* ASMV */
  81581. #endif /* FASTEST */
  81582. /* ---------------------------------------------------------------------------
  81583. * Optimized version for level == 1 or strategy == Z_RLE only
  81584. */
  81585. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81586. {
  81587. register Bytef *scan = s->window + s->strstart; /* current string */
  81588. register Bytef *match; /* matched string */
  81589. register int len; /* length of current match */
  81590. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81591. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81592. * It is easy to get rid of this optimization if necessary.
  81593. */
  81594. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81595. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81596. Assert(cur_match < s->strstart, "no future");
  81597. match = s->window + cur_match;
  81598. /* Return failure if the match length is less than 2:
  81599. */
  81600. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81601. /* The check at best_len-1 can be removed because it will be made
  81602. * again later. (This heuristic is not always a win.)
  81603. * It is not necessary to compare scan[2] and match[2] since they
  81604. * are always equal when the other bytes match, given that
  81605. * the hash keys are equal and that HASH_BITS >= 8.
  81606. */
  81607. scan += 2, match += 2;
  81608. Assert(*scan == *match, "match[2]?");
  81609. /* We check for insufficient lookahead only every 8th comparison;
  81610. * the 256th check will be made at strstart+258.
  81611. */
  81612. do {
  81613. } while (*++scan == *++match && *++scan == *++match &&
  81614. *++scan == *++match && *++scan == *++match &&
  81615. *++scan == *++match && *++scan == *++match &&
  81616. *++scan == *++match && *++scan == *++match &&
  81617. scan < strend);
  81618. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81619. len = MAX_MATCH - (int)(strend - scan);
  81620. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81621. s->match_start = cur_match;
  81622. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81623. }
  81624. #ifdef DEBUG
  81625. /* ===========================================================================
  81626. * Check that the match at match_start is indeed a match.
  81627. */
  81628. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81629. {
  81630. /* check that the match is indeed a match */
  81631. if (zmemcmp(s->window + match,
  81632. s->window + start, length) != EQUAL) {
  81633. fprintf(stderr, " start %u, match %u, length %d\n",
  81634. start, match, length);
  81635. do {
  81636. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81637. } while (--length != 0);
  81638. z_error("invalid match");
  81639. }
  81640. if (z_verbose > 1) {
  81641. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81642. do { putc(s->window[start++], stderr); } while (--length != 0);
  81643. }
  81644. }
  81645. #else
  81646. # define check_match(s, start, match, length)
  81647. #endif /* DEBUG */
  81648. /* ===========================================================================
  81649. * Fill the window when the lookahead becomes insufficient.
  81650. * Updates strstart and lookahead.
  81651. *
  81652. * IN assertion: lookahead < MIN_LOOKAHEAD
  81653. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81654. * At least one byte has been read, or avail_in == 0; reads are
  81655. * performed for at least two bytes (required for the zip translate_eol
  81656. * option -- not supported here).
  81657. */
  81658. local void fill_window (deflate_state *s)
  81659. {
  81660. register unsigned n, m;
  81661. register Posf *p;
  81662. unsigned more; /* Amount of free space at the end of the window. */
  81663. uInt wsize = s->w_size;
  81664. do {
  81665. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81666. /* Deal with !@#$% 64K limit: */
  81667. if (sizeof(int) <= 2) {
  81668. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81669. more = wsize;
  81670. } else if (more == (unsigned)(-1)) {
  81671. /* Very unlikely, but possible on 16 bit machine if
  81672. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81673. */
  81674. more--;
  81675. }
  81676. }
  81677. /* If the window is almost full and there is insufficient lookahead,
  81678. * move the upper half to the lower one to make room in the upper half.
  81679. */
  81680. if (s->strstart >= wsize+MAX_DIST(s)) {
  81681. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81682. s->match_start -= wsize;
  81683. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81684. s->block_start -= (long) wsize;
  81685. /* Slide the hash table (could be avoided with 32 bit values
  81686. at the expense of memory usage). We slide even when level == 0
  81687. to keep the hash table consistent if we switch back to level > 0
  81688. later. (Using level 0 permanently is not an optimal usage of
  81689. zlib, so we don't care about this pathological case.)
  81690. */
  81691. /* %%% avoid this when Z_RLE */
  81692. n = s->hash_size;
  81693. p = &s->head[n];
  81694. do {
  81695. m = *--p;
  81696. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81697. } while (--n);
  81698. n = wsize;
  81699. #ifndef FASTEST
  81700. p = &s->prev[n];
  81701. do {
  81702. m = *--p;
  81703. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81704. /* If n is not on any hash chain, prev[n] is garbage but
  81705. * its value will never be used.
  81706. */
  81707. } while (--n);
  81708. #endif
  81709. more += wsize;
  81710. }
  81711. if (s->strm->avail_in == 0) return;
  81712. /* If there was no sliding:
  81713. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81714. * more == window_size - lookahead - strstart
  81715. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81716. * => more >= window_size - 2*WSIZE + 2
  81717. * In the BIG_MEM or MMAP case (not yet supported),
  81718. * window_size == input_size + MIN_LOOKAHEAD &&
  81719. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81720. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81721. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81722. */
  81723. Assert(more >= 2, "more < 2");
  81724. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81725. s->lookahead += n;
  81726. /* Initialize the hash value now that we have some input: */
  81727. if (s->lookahead >= MIN_MATCH) {
  81728. s->ins_h = s->window[s->strstart];
  81729. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81730. #if MIN_MATCH != 3
  81731. Call UPDATE_HASH() MIN_MATCH-3 more times
  81732. #endif
  81733. }
  81734. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81735. * but this is not important since only literal bytes will be emitted.
  81736. */
  81737. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81738. }
  81739. /* ===========================================================================
  81740. * Flush the current block, with given end-of-file flag.
  81741. * IN assertion: strstart is set to the end of the current match.
  81742. */
  81743. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81744. _tr_flush_block(s, (s->block_start >= 0L ? \
  81745. (charf *)&s->window[(unsigned)s->block_start] : \
  81746. (charf *)Z_NULL), \
  81747. (ulg)((long)s->strstart - s->block_start), \
  81748. (eof)); \
  81749. s->block_start = s->strstart; \
  81750. flush_pending(s->strm); \
  81751. Tracev((stderr,"[FLUSH]")); \
  81752. }
  81753. /* Same but force premature exit if necessary. */
  81754. #define FLUSH_BLOCK(s, eof) { \
  81755. FLUSH_BLOCK_ONLY(s, eof); \
  81756. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81757. }
  81758. /* ===========================================================================
  81759. * Copy without compression as much as possible from the input stream, return
  81760. * the current block state.
  81761. * This function does not insert new strings in the dictionary since
  81762. * uncompressible data is probably not useful. This function is used
  81763. * only for the level=0 compression option.
  81764. * NOTE: this function should be optimized to avoid extra copying from
  81765. * window to pending_buf.
  81766. */
  81767. local block_state deflate_stored(deflate_state *s, int flush)
  81768. {
  81769. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81770. * to pending_buf_size, and each stored block has a 5 byte header:
  81771. */
  81772. ulg max_block_size = 0xffff;
  81773. ulg max_start;
  81774. if (max_block_size > s->pending_buf_size - 5) {
  81775. max_block_size = s->pending_buf_size - 5;
  81776. }
  81777. /* Copy as much as possible from input to output: */
  81778. for (;;) {
  81779. /* Fill the window as much as possible: */
  81780. if (s->lookahead <= 1) {
  81781. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81782. s->block_start >= (long)s->w_size, "slide too late");
  81783. fill_window(s);
  81784. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81785. if (s->lookahead == 0) break; /* flush the current block */
  81786. }
  81787. Assert(s->block_start >= 0L, "block gone");
  81788. s->strstart += s->lookahead;
  81789. s->lookahead = 0;
  81790. /* Emit a stored block if pending_buf will be full: */
  81791. max_start = s->block_start + max_block_size;
  81792. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81793. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81794. s->lookahead = (uInt)(s->strstart - max_start);
  81795. s->strstart = (uInt)max_start;
  81796. FLUSH_BLOCK(s, 0);
  81797. }
  81798. /* Flush if we may have to slide, otherwise block_start may become
  81799. * negative and the data will be gone:
  81800. */
  81801. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81802. FLUSH_BLOCK(s, 0);
  81803. }
  81804. }
  81805. FLUSH_BLOCK(s, flush == Z_FINISH);
  81806. return flush == Z_FINISH ? finish_done : block_done;
  81807. }
  81808. /* ===========================================================================
  81809. * Compress as much as possible from the input stream, return the current
  81810. * block state.
  81811. * This function does not perform lazy evaluation of matches and inserts
  81812. * new strings in the dictionary only for unmatched strings or for short
  81813. * matches. It is used only for the fast compression options.
  81814. */
  81815. local block_state deflate_fast(deflate_state *s, int flush)
  81816. {
  81817. IPos hash_head = NIL; /* head of the hash chain */
  81818. int bflush; /* set if current block must be flushed */
  81819. for (;;) {
  81820. /* Make sure that we always have enough lookahead, except
  81821. * at the end of the input file. We need MAX_MATCH bytes
  81822. * for the next match, plus MIN_MATCH bytes to insert the
  81823. * string following the next match.
  81824. */
  81825. if (s->lookahead < MIN_LOOKAHEAD) {
  81826. fill_window(s);
  81827. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81828. return need_more;
  81829. }
  81830. if (s->lookahead == 0) break; /* flush the current block */
  81831. }
  81832. /* Insert the string window[strstart .. strstart+2] in the
  81833. * dictionary, and set hash_head to the head of the hash chain:
  81834. */
  81835. if (s->lookahead >= MIN_MATCH) {
  81836. INSERT_STRING(s, s->strstart, hash_head);
  81837. }
  81838. /* Find the longest match, discarding those <= prev_length.
  81839. * At this point we have always match_length < MIN_MATCH
  81840. */
  81841. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81842. /* To simplify the code, we prevent matches with the string
  81843. * of window index 0 (in particular we have to avoid a match
  81844. * of the string with itself at the start of the input file).
  81845. */
  81846. #ifdef FASTEST
  81847. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81848. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81849. s->match_length = longest_match_fast (s, hash_head);
  81850. }
  81851. #else
  81852. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81853. s->match_length = longest_match (s, hash_head);
  81854. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81855. s->match_length = longest_match_fast (s, hash_head);
  81856. }
  81857. #endif
  81858. /* longest_match() or longest_match_fast() sets match_start */
  81859. }
  81860. if (s->match_length >= MIN_MATCH) {
  81861. check_match(s, s->strstart, s->match_start, s->match_length);
  81862. _tr_tally_dist(s, s->strstart - s->match_start,
  81863. s->match_length - MIN_MATCH, bflush);
  81864. s->lookahead -= s->match_length;
  81865. /* Insert new strings in the hash table only if the match length
  81866. * is not too large. This saves time but degrades compression.
  81867. */
  81868. #ifndef FASTEST
  81869. if (s->match_length <= s->max_insert_length &&
  81870. s->lookahead >= MIN_MATCH) {
  81871. s->match_length--; /* string at strstart already in table */
  81872. do {
  81873. s->strstart++;
  81874. INSERT_STRING(s, s->strstart, hash_head);
  81875. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81876. * always MIN_MATCH bytes ahead.
  81877. */
  81878. } while (--s->match_length != 0);
  81879. s->strstart++;
  81880. } else
  81881. #endif
  81882. {
  81883. s->strstart += s->match_length;
  81884. s->match_length = 0;
  81885. s->ins_h = s->window[s->strstart];
  81886. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81887. #if MIN_MATCH != 3
  81888. Call UPDATE_HASH() MIN_MATCH-3 more times
  81889. #endif
  81890. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81891. * matter since it will be recomputed at next deflate call.
  81892. */
  81893. }
  81894. } else {
  81895. /* No match, output a literal byte */
  81896. Tracevv((stderr,"%c", s->window[s->strstart]));
  81897. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81898. s->lookahead--;
  81899. s->strstart++;
  81900. }
  81901. if (bflush) FLUSH_BLOCK(s, 0);
  81902. }
  81903. FLUSH_BLOCK(s, flush == Z_FINISH);
  81904. return flush == Z_FINISH ? finish_done : block_done;
  81905. }
  81906. #ifndef FASTEST
  81907. /* ===========================================================================
  81908. * Same as above, but achieves better compression. We use a lazy
  81909. * evaluation for matches: a match is finally adopted only if there is
  81910. * no better match at the next window position.
  81911. */
  81912. local block_state deflate_slow(deflate_state *s, int flush)
  81913. {
  81914. IPos hash_head = NIL; /* head of hash chain */
  81915. int bflush; /* set if current block must be flushed */
  81916. /* Process the input block. */
  81917. for (;;) {
  81918. /* Make sure that we always have enough lookahead, except
  81919. * at the end of the input file. We need MAX_MATCH bytes
  81920. * for the next match, plus MIN_MATCH bytes to insert the
  81921. * string following the next match.
  81922. */
  81923. if (s->lookahead < MIN_LOOKAHEAD) {
  81924. fill_window(s);
  81925. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81926. return need_more;
  81927. }
  81928. if (s->lookahead == 0) break; /* flush the current block */
  81929. }
  81930. /* Insert the string window[strstart .. strstart+2] in the
  81931. * dictionary, and set hash_head to the head of the hash chain:
  81932. */
  81933. if (s->lookahead >= MIN_MATCH) {
  81934. INSERT_STRING(s, s->strstart, hash_head);
  81935. }
  81936. /* Find the longest match, discarding those <= prev_length.
  81937. */
  81938. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81939. s->match_length = MIN_MATCH-1;
  81940. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81941. s->strstart - hash_head <= MAX_DIST(s)) {
  81942. /* To simplify the code, we prevent matches with the string
  81943. * of window index 0 (in particular we have to avoid a match
  81944. * of the string with itself at the start of the input file).
  81945. */
  81946. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81947. s->match_length = longest_match (s, hash_head);
  81948. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81949. s->match_length = longest_match_fast (s, hash_head);
  81950. }
  81951. /* longest_match() or longest_match_fast() sets match_start */
  81952. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81953. #if TOO_FAR <= 32767
  81954. || (s->match_length == MIN_MATCH &&
  81955. s->strstart - s->match_start > TOO_FAR)
  81956. #endif
  81957. )) {
  81958. /* If prev_match is also MIN_MATCH, match_start is garbage
  81959. * but we will ignore the current match anyway.
  81960. */
  81961. s->match_length = MIN_MATCH-1;
  81962. }
  81963. }
  81964. /* If there was a match at the previous step and the current
  81965. * match is not better, output the previous match:
  81966. */
  81967. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81968. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81969. /* Do not insert strings in hash table beyond this. */
  81970. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81971. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81972. s->prev_length - MIN_MATCH, bflush);
  81973. /* Insert in hash table all strings up to the end of the match.
  81974. * strstart-1 and strstart are already inserted. If there is not
  81975. * enough lookahead, the last two strings are not inserted in
  81976. * the hash table.
  81977. */
  81978. s->lookahead -= s->prev_length-1;
  81979. s->prev_length -= 2;
  81980. do {
  81981. if (++s->strstart <= max_insert) {
  81982. INSERT_STRING(s, s->strstart, hash_head);
  81983. }
  81984. } while (--s->prev_length != 0);
  81985. s->match_available = 0;
  81986. s->match_length = MIN_MATCH-1;
  81987. s->strstart++;
  81988. if (bflush) FLUSH_BLOCK(s, 0);
  81989. } else if (s->match_available) {
  81990. /* If there was no match at the previous position, output a
  81991. * single literal. If there was a match but the current match
  81992. * is longer, truncate the previous match to a single literal.
  81993. */
  81994. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81995. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81996. if (bflush) {
  81997. FLUSH_BLOCK_ONLY(s, 0);
  81998. }
  81999. s->strstart++;
  82000. s->lookahead--;
  82001. if (s->strm->avail_out == 0) return need_more;
  82002. } else {
  82003. /* There is no previous match to compare with, wait for
  82004. * the next step to decide.
  82005. */
  82006. s->match_available = 1;
  82007. s->strstart++;
  82008. s->lookahead--;
  82009. }
  82010. }
  82011. Assert (flush != Z_NO_FLUSH, "no flush?");
  82012. if (s->match_available) {
  82013. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82014. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82015. s->match_available = 0;
  82016. }
  82017. FLUSH_BLOCK(s, flush == Z_FINISH);
  82018. return flush == Z_FINISH ? finish_done : block_done;
  82019. }
  82020. #endif /* FASTEST */
  82021. #if 0
  82022. /* ===========================================================================
  82023. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82024. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82025. * deflate switches away from Z_RLE.)
  82026. */
  82027. local block_state deflate_rle(s, flush)
  82028. deflate_state *s;
  82029. int flush;
  82030. {
  82031. int bflush; /* set if current block must be flushed */
  82032. uInt run; /* length of run */
  82033. uInt max; /* maximum length of run */
  82034. uInt prev; /* byte at distance one to match */
  82035. Bytef *scan; /* scan for end of run */
  82036. for (;;) {
  82037. /* Make sure that we always have enough lookahead, except
  82038. * at the end of the input file. We need MAX_MATCH bytes
  82039. * for the longest encodable run.
  82040. */
  82041. if (s->lookahead < MAX_MATCH) {
  82042. fill_window(s);
  82043. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82044. return need_more;
  82045. }
  82046. if (s->lookahead == 0) break; /* flush the current block */
  82047. }
  82048. /* See how many times the previous byte repeats */
  82049. run = 0;
  82050. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82051. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82052. scan = s->window + s->strstart - 1;
  82053. prev = *scan++;
  82054. do {
  82055. if (*scan++ != prev)
  82056. break;
  82057. } while (++run < max);
  82058. }
  82059. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82060. if (run >= MIN_MATCH) {
  82061. check_match(s, s->strstart, s->strstart - 1, run);
  82062. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82063. s->lookahead -= run;
  82064. s->strstart += run;
  82065. } else {
  82066. /* No match, output a literal byte */
  82067. Tracevv((stderr,"%c", s->window[s->strstart]));
  82068. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82069. s->lookahead--;
  82070. s->strstart++;
  82071. }
  82072. if (bflush) FLUSH_BLOCK(s, 0);
  82073. }
  82074. FLUSH_BLOCK(s, flush == Z_FINISH);
  82075. return flush == Z_FINISH ? finish_done : block_done;
  82076. }
  82077. #endif
  82078. /*** End of inlined file: deflate.c ***/
  82079. /*** Start of inlined file: inffast.c ***/
  82080. /*** Start of inlined file: inftrees.h ***/
  82081. /* WARNING: this file should *not* be used by applications. It is
  82082. part of the implementation of the compression library and is
  82083. subject to change. Applications should only use zlib.h.
  82084. */
  82085. #ifndef _INFTREES_H_
  82086. #define _INFTREES_H_
  82087. /* Structure for decoding tables. Each entry provides either the
  82088. information needed to do the operation requested by the code that
  82089. indexed that table entry, or it provides a pointer to another
  82090. table that indexes more bits of the code. op indicates whether
  82091. the entry is a pointer to another table, a literal, a length or
  82092. distance, an end-of-block, or an invalid code. For a table
  82093. pointer, the low four bits of op is the number of index bits of
  82094. that table. For a length or distance, the low four bits of op
  82095. is the number of extra bits to get after the code. bits is
  82096. the number of bits in this code or part of the code to drop off
  82097. of the bit buffer. val is the actual byte to output in the case
  82098. of a literal, the base length or distance, or the offset from
  82099. the current table to the next table. Each entry is four bytes. */
  82100. typedef struct {
  82101. unsigned char op; /* operation, extra bits, table bits */
  82102. unsigned char bits; /* bits in this part of the code */
  82103. unsigned short val; /* offset in table or code value */
  82104. } code;
  82105. /* op values as set by inflate_table():
  82106. 00000000 - literal
  82107. 0000tttt - table link, tttt != 0 is the number of table index bits
  82108. 0001eeee - length or distance, eeee is the number of extra bits
  82109. 01100000 - end of block
  82110. 01000000 - invalid code
  82111. */
  82112. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82113. exhaustive search was 1444 code structures (852 for length/literals
  82114. and 592 for distances, the latter actually the result of an
  82115. exhaustive search). The true maximum is not known, but the value
  82116. below is more than safe. */
  82117. #define ENOUGH 2048
  82118. #define MAXD 592
  82119. /* Type of code to build for inftable() */
  82120. typedef enum {
  82121. CODES,
  82122. LENS,
  82123. DISTS
  82124. } codetype;
  82125. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82126. unsigned codes, code FAR * FAR *table,
  82127. unsigned FAR *bits, unsigned short FAR *work));
  82128. #endif
  82129. /*** End of inlined file: inftrees.h ***/
  82130. /*** Start of inlined file: inflate.h ***/
  82131. /* WARNING: this file should *not* be used by applications. It is
  82132. part of the implementation of the compression library and is
  82133. subject to change. Applications should only use zlib.h.
  82134. */
  82135. #ifndef _INFLATE_H_
  82136. #define _INFLATE_H_
  82137. /* define NO_GZIP when compiling if you want to disable gzip header and
  82138. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82139. the crc code when it is not needed. For shared libraries, gzip decoding
  82140. should be left enabled. */
  82141. #ifndef NO_GZIP
  82142. # define GUNZIP
  82143. #endif
  82144. /* Possible inflate modes between inflate() calls */
  82145. typedef enum {
  82146. HEAD, /* i: waiting for magic header */
  82147. FLAGS, /* i: waiting for method and flags (gzip) */
  82148. TIME, /* i: waiting for modification time (gzip) */
  82149. OS, /* i: waiting for extra flags and operating system (gzip) */
  82150. EXLEN, /* i: waiting for extra length (gzip) */
  82151. EXTRA, /* i: waiting for extra bytes (gzip) */
  82152. NAME, /* i: waiting for end of file name (gzip) */
  82153. COMMENT, /* i: waiting for end of comment (gzip) */
  82154. HCRC, /* i: waiting for header crc (gzip) */
  82155. DICTID, /* i: waiting for dictionary check value */
  82156. DICT, /* waiting for inflateSetDictionary() call */
  82157. TYPE, /* i: waiting for type bits, including last-flag bit */
  82158. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82159. STORED, /* i: waiting for stored size (length and complement) */
  82160. COPY, /* i/o: waiting for input or output to copy stored block */
  82161. TABLE, /* i: waiting for dynamic block table lengths */
  82162. LENLENS, /* i: waiting for code length code lengths */
  82163. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82164. LEN, /* i: waiting for length/lit code */
  82165. LENEXT, /* i: waiting for length extra bits */
  82166. DIST, /* i: waiting for distance code */
  82167. DISTEXT, /* i: waiting for distance extra bits */
  82168. MATCH, /* o: waiting for output space to copy string */
  82169. LIT, /* o: waiting for output space to write literal */
  82170. CHECK, /* i: waiting for 32-bit check value */
  82171. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82172. DONE, /* finished check, done -- remain here until reset */
  82173. BAD, /* got a data error -- remain here until reset */
  82174. MEM, /* got an inflate() memory error -- remain here until reset */
  82175. SYNC /* looking for synchronization bytes to restart inflate() */
  82176. } inflate_mode;
  82177. /*
  82178. State transitions between above modes -
  82179. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82180. Process header:
  82181. HEAD -> (gzip) or (zlib)
  82182. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82183. NAME -> COMMENT -> HCRC -> TYPE
  82184. (zlib) -> DICTID or TYPE
  82185. DICTID -> DICT -> TYPE
  82186. Read deflate blocks:
  82187. TYPE -> STORED or TABLE or LEN or CHECK
  82188. STORED -> COPY -> TYPE
  82189. TABLE -> LENLENS -> CODELENS -> LEN
  82190. Read deflate codes:
  82191. LEN -> LENEXT or LIT or TYPE
  82192. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82193. LIT -> LEN
  82194. Process trailer:
  82195. CHECK -> LENGTH -> DONE
  82196. */
  82197. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82198. struct inflate_state {
  82199. inflate_mode mode; /* current inflate mode */
  82200. int last; /* true if processing last block */
  82201. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82202. int havedict; /* true if dictionary provided */
  82203. int flags; /* gzip header method and flags (0 if zlib) */
  82204. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82205. unsigned long check; /* protected copy of check value */
  82206. unsigned long total; /* protected copy of output count */
  82207. gz_headerp head; /* where to save gzip header information */
  82208. /* sliding window */
  82209. unsigned wbits; /* log base 2 of requested window size */
  82210. unsigned wsize; /* window size or zero if not using window */
  82211. unsigned whave; /* valid bytes in the window */
  82212. unsigned write; /* window write index */
  82213. unsigned char FAR *window; /* allocated sliding window, if needed */
  82214. /* bit accumulator */
  82215. unsigned long hold; /* input bit accumulator */
  82216. unsigned bits; /* number of bits in "in" */
  82217. /* for string and stored block copying */
  82218. unsigned length; /* literal or length of data to copy */
  82219. unsigned offset; /* distance back to copy string from */
  82220. /* for table and code decoding */
  82221. unsigned extra; /* extra bits needed */
  82222. /* fixed and dynamic code tables */
  82223. code const FAR *lencode; /* starting table for length/literal codes */
  82224. code const FAR *distcode; /* starting table for distance codes */
  82225. unsigned lenbits; /* index bits for lencode */
  82226. unsigned distbits; /* index bits for distcode */
  82227. /* dynamic table building */
  82228. unsigned ncode; /* number of code length code lengths */
  82229. unsigned nlen; /* number of length code lengths */
  82230. unsigned ndist; /* number of distance code lengths */
  82231. unsigned have; /* number of code lengths in lens[] */
  82232. code FAR *next; /* next available space in codes[] */
  82233. unsigned short lens[320]; /* temporary storage for code lengths */
  82234. unsigned short work[288]; /* work area for code table building */
  82235. code codes[ENOUGH]; /* space for code tables */
  82236. };
  82237. #endif
  82238. /*** End of inlined file: inflate.h ***/
  82239. /*** Start of inlined file: inffast.h ***/
  82240. /* WARNING: this file should *not* be used by applications. It is
  82241. part of the implementation of the compression library and is
  82242. subject to change. Applications should only use zlib.h.
  82243. */
  82244. void inflate_fast OF((z_streamp strm, unsigned start));
  82245. /*** End of inlined file: inffast.h ***/
  82246. #ifndef ASMINF
  82247. /* Allow machine dependent optimization for post-increment or pre-increment.
  82248. Based on testing to date,
  82249. Pre-increment preferred for:
  82250. - PowerPC G3 (Adler)
  82251. - MIPS R5000 (Randers-Pehrson)
  82252. Post-increment preferred for:
  82253. - none
  82254. No measurable difference:
  82255. - Pentium III (Anderson)
  82256. - M68060 (Nikl)
  82257. */
  82258. #ifdef POSTINC
  82259. # define OFF 0
  82260. # define PUP(a) *(a)++
  82261. #else
  82262. # define OFF 1
  82263. # define PUP(a) *++(a)
  82264. #endif
  82265. /*
  82266. Decode literal, length, and distance codes and write out the resulting
  82267. literal and match bytes until either not enough input or output is
  82268. available, an end-of-block is encountered, or a data error is encountered.
  82269. When large enough input and output buffers are supplied to inflate(), for
  82270. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82271. inflate execution time is spent in this routine.
  82272. Entry assumptions:
  82273. state->mode == LEN
  82274. strm->avail_in >= 6
  82275. strm->avail_out >= 258
  82276. start >= strm->avail_out
  82277. state->bits < 8
  82278. On return, state->mode is one of:
  82279. LEN -- ran out of enough output space or enough available input
  82280. TYPE -- reached end of block code, inflate() to interpret next block
  82281. BAD -- error in block data
  82282. Notes:
  82283. - The maximum input bits used by a length/distance pair is 15 bits for the
  82284. length code, 5 bits for the length extra, 15 bits for the distance code,
  82285. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82286. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82287. checking for available input while decoding.
  82288. - The maximum bytes that a single length/distance pair can output is 258
  82289. bytes, which is the maximum length that can be coded. inflate_fast()
  82290. requires strm->avail_out >= 258 for each loop to avoid checking for
  82291. output space.
  82292. */
  82293. void inflate_fast (z_streamp strm, unsigned start)
  82294. {
  82295. struct inflate_state FAR *state;
  82296. unsigned char FAR *in; /* local strm->next_in */
  82297. unsigned char FAR *last; /* while in < last, enough input available */
  82298. unsigned char FAR *out; /* local strm->next_out */
  82299. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82300. unsigned char FAR *end; /* while out < end, enough space available */
  82301. #ifdef INFLATE_STRICT
  82302. unsigned dmax; /* maximum distance from zlib header */
  82303. #endif
  82304. unsigned wsize; /* window size or zero if not using window */
  82305. unsigned whave; /* valid bytes in the window */
  82306. unsigned write; /* window write index */
  82307. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82308. unsigned long hold; /* local strm->hold */
  82309. unsigned bits; /* local strm->bits */
  82310. code const FAR *lcode; /* local strm->lencode */
  82311. code const FAR *dcode; /* local strm->distcode */
  82312. unsigned lmask; /* mask for first level of length codes */
  82313. unsigned dmask; /* mask for first level of distance codes */
  82314. code thisx; /* retrieved table entry */
  82315. unsigned op; /* code bits, operation, extra bits, or */
  82316. /* window position, window bytes to copy */
  82317. unsigned len; /* match length, unused bytes */
  82318. unsigned dist; /* match distance */
  82319. unsigned char FAR *from; /* where to copy match from */
  82320. /* copy state to local variables */
  82321. state = (struct inflate_state FAR *)strm->state;
  82322. in = strm->next_in - OFF;
  82323. last = in + (strm->avail_in - 5);
  82324. out = strm->next_out - OFF;
  82325. beg = out - (start - strm->avail_out);
  82326. end = out + (strm->avail_out - 257);
  82327. #ifdef INFLATE_STRICT
  82328. dmax = state->dmax;
  82329. #endif
  82330. wsize = state->wsize;
  82331. whave = state->whave;
  82332. write = state->write;
  82333. window = state->window;
  82334. hold = state->hold;
  82335. bits = state->bits;
  82336. lcode = state->lencode;
  82337. dcode = state->distcode;
  82338. lmask = (1U << state->lenbits) - 1;
  82339. dmask = (1U << state->distbits) - 1;
  82340. /* decode literals and length/distances until end-of-block or not enough
  82341. input data or output space */
  82342. do {
  82343. if (bits < 15) {
  82344. hold += (unsigned long)(PUP(in)) << bits;
  82345. bits += 8;
  82346. hold += (unsigned long)(PUP(in)) << bits;
  82347. bits += 8;
  82348. }
  82349. thisx = lcode[hold & lmask];
  82350. dolen:
  82351. op = (unsigned)(thisx.bits);
  82352. hold >>= op;
  82353. bits -= op;
  82354. op = (unsigned)(thisx.op);
  82355. if (op == 0) { /* literal */
  82356. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82357. "inflate: literal '%c'\n" :
  82358. "inflate: literal 0x%02x\n", thisx.val));
  82359. PUP(out) = (unsigned char)(thisx.val);
  82360. }
  82361. else if (op & 16) { /* length base */
  82362. len = (unsigned)(thisx.val);
  82363. op &= 15; /* number of extra bits */
  82364. if (op) {
  82365. if (bits < op) {
  82366. hold += (unsigned long)(PUP(in)) << bits;
  82367. bits += 8;
  82368. }
  82369. len += (unsigned)hold & ((1U << op) - 1);
  82370. hold >>= op;
  82371. bits -= op;
  82372. }
  82373. Tracevv((stderr, "inflate: length %u\n", len));
  82374. if (bits < 15) {
  82375. hold += (unsigned long)(PUP(in)) << bits;
  82376. bits += 8;
  82377. hold += (unsigned long)(PUP(in)) << bits;
  82378. bits += 8;
  82379. }
  82380. thisx = dcode[hold & dmask];
  82381. dodist:
  82382. op = (unsigned)(thisx.bits);
  82383. hold >>= op;
  82384. bits -= op;
  82385. op = (unsigned)(thisx.op);
  82386. if (op & 16) { /* distance base */
  82387. dist = (unsigned)(thisx.val);
  82388. op &= 15; /* number of extra bits */
  82389. if (bits < op) {
  82390. hold += (unsigned long)(PUP(in)) << bits;
  82391. bits += 8;
  82392. if (bits < op) {
  82393. hold += (unsigned long)(PUP(in)) << bits;
  82394. bits += 8;
  82395. }
  82396. }
  82397. dist += (unsigned)hold & ((1U << op) - 1);
  82398. #ifdef INFLATE_STRICT
  82399. if (dist > dmax) {
  82400. strm->msg = (char *)"invalid distance too far back";
  82401. state->mode = BAD;
  82402. break;
  82403. }
  82404. #endif
  82405. hold >>= op;
  82406. bits -= op;
  82407. Tracevv((stderr, "inflate: distance %u\n", dist));
  82408. op = (unsigned)(out - beg); /* max distance in output */
  82409. if (dist > op) { /* see if copy from window */
  82410. op = dist - op; /* distance back in window */
  82411. if (op > whave) {
  82412. strm->msg = (char *)"invalid distance too far back";
  82413. state->mode = BAD;
  82414. break;
  82415. }
  82416. from = window - OFF;
  82417. if (write == 0) { /* very common case */
  82418. from += wsize - op;
  82419. if (op < len) { /* some from window */
  82420. len -= op;
  82421. do {
  82422. PUP(out) = PUP(from);
  82423. } while (--op);
  82424. from = out - dist; /* rest from output */
  82425. }
  82426. }
  82427. else if (write < op) { /* wrap around window */
  82428. from += wsize + write - op;
  82429. op -= write;
  82430. if (op < len) { /* some from end of window */
  82431. len -= op;
  82432. do {
  82433. PUP(out) = PUP(from);
  82434. } while (--op);
  82435. from = window - OFF;
  82436. if (write < len) { /* some from start of window */
  82437. op = write;
  82438. len -= op;
  82439. do {
  82440. PUP(out) = PUP(from);
  82441. } while (--op);
  82442. from = out - dist; /* rest from output */
  82443. }
  82444. }
  82445. }
  82446. else { /* contiguous in window */
  82447. from += write - op;
  82448. if (op < len) { /* some from window */
  82449. len -= op;
  82450. do {
  82451. PUP(out) = PUP(from);
  82452. } while (--op);
  82453. from = out - dist; /* rest from output */
  82454. }
  82455. }
  82456. while (len > 2) {
  82457. PUP(out) = PUP(from);
  82458. PUP(out) = PUP(from);
  82459. PUP(out) = PUP(from);
  82460. len -= 3;
  82461. }
  82462. if (len) {
  82463. PUP(out) = PUP(from);
  82464. if (len > 1)
  82465. PUP(out) = PUP(from);
  82466. }
  82467. }
  82468. else {
  82469. from = out - dist; /* copy direct from output */
  82470. do { /* minimum length is three */
  82471. PUP(out) = PUP(from);
  82472. PUP(out) = PUP(from);
  82473. PUP(out) = PUP(from);
  82474. len -= 3;
  82475. } while (len > 2);
  82476. if (len) {
  82477. PUP(out) = PUP(from);
  82478. if (len > 1)
  82479. PUP(out) = PUP(from);
  82480. }
  82481. }
  82482. }
  82483. else if ((op & 64) == 0) { /* 2nd level distance code */
  82484. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82485. goto dodist;
  82486. }
  82487. else {
  82488. strm->msg = (char *)"invalid distance code";
  82489. state->mode = BAD;
  82490. break;
  82491. }
  82492. }
  82493. else if ((op & 64) == 0) { /* 2nd level length code */
  82494. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82495. goto dolen;
  82496. }
  82497. else if (op & 32) { /* end-of-block */
  82498. Tracevv((stderr, "inflate: end of block\n"));
  82499. state->mode = TYPE;
  82500. break;
  82501. }
  82502. else {
  82503. strm->msg = (char *)"invalid literal/length code";
  82504. state->mode = BAD;
  82505. break;
  82506. }
  82507. } while (in < last && out < end);
  82508. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82509. len = bits >> 3;
  82510. in -= len;
  82511. bits -= len << 3;
  82512. hold &= (1U << bits) - 1;
  82513. /* update state and return */
  82514. strm->next_in = in + OFF;
  82515. strm->next_out = out + OFF;
  82516. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82517. strm->avail_out = (unsigned)(out < end ?
  82518. 257 + (end - out) : 257 - (out - end));
  82519. state->hold = hold;
  82520. state->bits = bits;
  82521. return;
  82522. }
  82523. /*
  82524. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82525. - Using bit fields for code structure
  82526. - Different op definition to avoid & for extra bits (do & for table bits)
  82527. - Three separate decoding do-loops for direct, window, and write == 0
  82528. - Special case for distance > 1 copies to do overlapped load and store copy
  82529. - Explicit branch predictions (based on measured branch probabilities)
  82530. - Deferring match copy and interspersed it with decoding subsequent codes
  82531. - Swapping literal/length else
  82532. - Swapping window/direct else
  82533. - Larger unrolled copy loops (three is about right)
  82534. - Moving len -= 3 statement into middle of loop
  82535. */
  82536. #endif /* !ASMINF */
  82537. /*** End of inlined file: inffast.c ***/
  82538. #undef PULLBYTE
  82539. #undef LOAD
  82540. #undef RESTORE
  82541. #undef INITBITS
  82542. #undef NEEDBITS
  82543. #undef DROPBITS
  82544. #undef BYTEBITS
  82545. /*** Start of inlined file: inflate.c ***/
  82546. /*
  82547. * Change history:
  82548. *
  82549. * 1.2.beta0 24 Nov 2002
  82550. * - First version -- complete rewrite of inflate to simplify code, avoid
  82551. * creation of window when not needed, minimize use of window when it is
  82552. * needed, make inffast.c even faster, implement gzip decoding, and to
  82553. * improve code readability and style over the previous zlib inflate code
  82554. *
  82555. * 1.2.beta1 25 Nov 2002
  82556. * - Use pointers for available input and output checking in inffast.c
  82557. * - Remove input and output counters in inffast.c
  82558. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82559. * - Remove unnecessary second byte pull from length extra in inffast.c
  82560. * - Unroll direct copy to three copies per loop in inffast.c
  82561. *
  82562. * 1.2.beta2 4 Dec 2002
  82563. * - Change external routine names to reduce potential conflicts
  82564. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82565. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82566. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82567. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82568. *
  82569. * 1.2.beta3 22 Dec 2002
  82570. * - Add comments on state->bits assertion in inffast.c
  82571. * - Add comments on op field in inftrees.h
  82572. * - Fix bug in reuse of allocated window after inflateReset()
  82573. * - Remove bit fields--back to byte structure for speed
  82574. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82575. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82576. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82577. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82578. * - Use local copies of stream next and avail values, as well as local bit
  82579. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82580. *
  82581. * 1.2.beta4 1 Jan 2003
  82582. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82583. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82584. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82585. * - Rearrange window copies in inflate_fast() for speed and simplification
  82586. * - Unroll last copy for window match in inflate_fast()
  82587. * - Use local copies of window variables in inflate_fast() for speed
  82588. * - Pull out common write == 0 case for speed in inflate_fast()
  82589. * - Make op and len in inflate_fast() unsigned for consistency
  82590. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82591. * - Simplified bad distance check in inflate_fast()
  82592. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82593. * source file infback.c to provide a call-back interface to inflate for
  82594. * programs like gzip and unzip -- uses window as output buffer to avoid
  82595. * window copying
  82596. *
  82597. * 1.2.beta5 1 Jan 2003
  82598. * - Improved inflateBack() interface to allow the caller to provide initial
  82599. * input in strm.
  82600. * - Fixed stored blocks bug in inflateBack()
  82601. *
  82602. * 1.2.beta6 4 Jan 2003
  82603. * - Added comments in inffast.c on effectiveness of POSTINC
  82604. * - Typecasting all around to reduce compiler warnings
  82605. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82606. * make compilers happy
  82607. * - Changed type of window in inflateBackInit() to unsigned char *
  82608. *
  82609. * 1.2.beta7 27 Jan 2003
  82610. * - Changed many types to unsigned or unsigned short to avoid warnings
  82611. * - Added inflateCopy() function
  82612. *
  82613. * 1.2.0 9 Mar 2003
  82614. * - Changed inflateBack() interface to provide separate opaque descriptors
  82615. * for the in() and out() functions
  82616. * - Changed inflateBack() argument and in_func typedef to swap the length
  82617. * and buffer address return values for the input function
  82618. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82619. *
  82620. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82621. */
  82622. /*** Start of inlined file: inffast.h ***/
  82623. /* WARNING: this file should *not* be used by applications. It is
  82624. part of the implementation of the compression library and is
  82625. subject to change. Applications should only use zlib.h.
  82626. */
  82627. void inflate_fast OF((z_streamp strm, unsigned start));
  82628. /*** End of inlined file: inffast.h ***/
  82629. #ifdef MAKEFIXED
  82630. # ifndef BUILDFIXED
  82631. # define BUILDFIXED
  82632. # endif
  82633. #endif
  82634. /* function prototypes */
  82635. local void fixedtables OF((struct inflate_state FAR *state));
  82636. local int updatewindow OF((z_streamp strm, unsigned out));
  82637. #ifdef BUILDFIXED
  82638. void makefixed OF((void));
  82639. #endif
  82640. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82641. unsigned len));
  82642. int ZEXPORT inflateReset (z_streamp strm)
  82643. {
  82644. struct inflate_state FAR *state;
  82645. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82646. state = (struct inflate_state FAR *)strm->state;
  82647. strm->total_in = strm->total_out = state->total = 0;
  82648. strm->msg = Z_NULL;
  82649. strm->adler = 1; /* to support ill-conceived Java test suite */
  82650. state->mode = HEAD;
  82651. state->last = 0;
  82652. state->havedict = 0;
  82653. state->dmax = 32768U;
  82654. state->head = Z_NULL;
  82655. state->wsize = 0;
  82656. state->whave = 0;
  82657. state->write = 0;
  82658. state->hold = 0;
  82659. state->bits = 0;
  82660. state->lencode = state->distcode = state->next = state->codes;
  82661. Tracev((stderr, "inflate: reset\n"));
  82662. return Z_OK;
  82663. }
  82664. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82665. {
  82666. struct inflate_state FAR *state;
  82667. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82668. state = (struct inflate_state FAR *)strm->state;
  82669. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82670. value &= (1L << bits) - 1;
  82671. state->hold += value << state->bits;
  82672. state->bits += bits;
  82673. return Z_OK;
  82674. }
  82675. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82676. {
  82677. struct inflate_state FAR *state;
  82678. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82679. stream_size != (int)(sizeof(z_stream)))
  82680. return Z_VERSION_ERROR;
  82681. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82682. strm->msg = Z_NULL; /* in case we return an error */
  82683. if (strm->zalloc == (alloc_func)0) {
  82684. strm->zalloc = zcalloc;
  82685. strm->opaque = (voidpf)0;
  82686. }
  82687. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82688. state = (struct inflate_state FAR *)
  82689. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82690. if (state == Z_NULL) return Z_MEM_ERROR;
  82691. Tracev((stderr, "inflate: allocated\n"));
  82692. strm->state = (struct internal_state FAR *)state;
  82693. if (windowBits < 0) {
  82694. state->wrap = 0;
  82695. windowBits = -windowBits;
  82696. }
  82697. else {
  82698. state->wrap = (windowBits >> 4) + 1;
  82699. #ifdef GUNZIP
  82700. if (windowBits < 48) windowBits &= 15;
  82701. #endif
  82702. }
  82703. if (windowBits < 8 || windowBits > 15) {
  82704. ZFREE(strm, state);
  82705. strm->state = Z_NULL;
  82706. return Z_STREAM_ERROR;
  82707. }
  82708. state->wbits = (unsigned)windowBits;
  82709. state->window = Z_NULL;
  82710. return inflateReset(strm);
  82711. }
  82712. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82713. {
  82714. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82715. }
  82716. /*
  82717. Return state with length and distance decoding tables and index sizes set to
  82718. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82719. If BUILDFIXED is defined, then instead this routine builds the tables the
  82720. first time it's called, and returns those tables the first time and
  82721. thereafter. This reduces the size of the code by about 2K bytes, in
  82722. exchange for a little execution time. However, BUILDFIXED should not be
  82723. used for threaded applications, since the rewriting of the tables and virgin
  82724. may not be thread-safe.
  82725. */
  82726. local void fixedtables (struct inflate_state FAR *state)
  82727. {
  82728. #ifdef BUILDFIXED
  82729. static int virgin = 1;
  82730. static code *lenfix, *distfix;
  82731. static code fixed[544];
  82732. /* build fixed huffman tables if first call (may not be thread safe) */
  82733. if (virgin) {
  82734. unsigned sym, bits;
  82735. static code *next;
  82736. /* literal/length table */
  82737. sym = 0;
  82738. while (sym < 144) state->lens[sym++] = 8;
  82739. while (sym < 256) state->lens[sym++] = 9;
  82740. while (sym < 280) state->lens[sym++] = 7;
  82741. while (sym < 288) state->lens[sym++] = 8;
  82742. next = fixed;
  82743. lenfix = next;
  82744. bits = 9;
  82745. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82746. /* distance table */
  82747. sym = 0;
  82748. while (sym < 32) state->lens[sym++] = 5;
  82749. distfix = next;
  82750. bits = 5;
  82751. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82752. /* do this just once */
  82753. virgin = 0;
  82754. }
  82755. #else /* !BUILDFIXED */
  82756. /*** Start of inlined file: inffixed.h ***/
  82757. /* WARNING: this file should *not* be used by applications. It
  82758. is part of the implementation of the compression library and
  82759. is subject to change. Applications should only use zlib.h.
  82760. */
  82761. static const code lenfix[512] = {
  82762. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82763. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82764. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82765. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82766. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82767. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82768. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82769. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82770. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82771. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82772. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82773. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82774. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82775. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82776. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82777. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82778. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82779. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82780. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82781. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82782. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82783. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82784. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82785. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82786. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82787. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82788. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82789. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82790. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82791. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82792. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82793. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82794. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82795. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82796. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82797. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82798. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82799. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82800. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82801. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82802. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82803. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82804. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82805. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82806. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82807. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82808. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82809. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82810. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82811. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82812. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82813. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82814. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82815. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82816. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82817. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82818. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82819. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82820. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82821. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82822. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82823. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82824. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82825. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82826. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82827. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82828. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82829. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82830. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82831. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82832. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82833. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82834. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82835. {0,9,255}
  82836. };
  82837. static const code distfix[32] = {
  82838. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82839. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82840. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82841. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82842. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82843. {22,5,193},{64,5,0}
  82844. };
  82845. /*** End of inlined file: inffixed.h ***/
  82846. #endif /* BUILDFIXED */
  82847. state->lencode = lenfix;
  82848. state->lenbits = 9;
  82849. state->distcode = distfix;
  82850. state->distbits = 5;
  82851. }
  82852. #ifdef MAKEFIXED
  82853. #include <stdio.h>
  82854. /*
  82855. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82856. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82857. those tables to stdout, which would be piped to inffixed.h. A small program
  82858. can simply call makefixed to do this:
  82859. void makefixed(void);
  82860. int main(void)
  82861. {
  82862. makefixed();
  82863. return 0;
  82864. }
  82865. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82866. a.out > inffixed.h
  82867. */
  82868. void makefixed()
  82869. {
  82870. unsigned low, size;
  82871. struct inflate_state state;
  82872. fixedtables(&state);
  82873. puts(" /* inffixed.h -- table for decoding fixed codes");
  82874. puts(" * Generated automatically by makefixed().");
  82875. puts(" */");
  82876. puts("");
  82877. puts(" /* WARNING: this file should *not* be used by applications.");
  82878. puts(" It is part of the implementation of this library and is");
  82879. puts(" subject to change. Applications should only use zlib.h.");
  82880. puts(" */");
  82881. puts("");
  82882. size = 1U << 9;
  82883. printf(" static const code lenfix[%u] = {", size);
  82884. low = 0;
  82885. for (;;) {
  82886. if ((low % 7) == 0) printf("\n ");
  82887. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82888. state.lencode[low].val);
  82889. if (++low == size) break;
  82890. putchar(',');
  82891. }
  82892. puts("\n };");
  82893. size = 1U << 5;
  82894. printf("\n static const code distfix[%u] = {", size);
  82895. low = 0;
  82896. for (;;) {
  82897. if ((low % 6) == 0) printf("\n ");
  82898. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82899. state.distcode[low].val);
  82900. if (++low == size) break;
  82901. putchar(',');
  82902. }
  82903. puts("\n };");
  82904. }
  82905. #endif /* MAKEFIXED */
  82906. /*
  82907. Update the window with the last wsize (normally 32K) bytes written before
  82908. returning. If window does not exist yet, create it. This is only called
  82909. when a window is already in use, or when output has been written during this
  82910. inflate call, but the end of the deflate stream has not been reached yet.
  82911. It is also called to create a window for dictionary data when a dictionary
  82912. is loaded.
  82913. Providing output buffers larger than 32K to inflate() should provide a speed
  82914. advantage, since only the last 32K of output is copied to the sliding window
  82915. upon return from inflate(), and since all distances after the first 32K of
  82916. output will fall in the output data, making match copies simpler and faster.
  82917. The advantage may be dependent on the size of the processor's data caches.
  82918. */
  82919. local int updatewindow (z_streamp strm, unsigned out)
  82920. {
  82921. struct inflate_state FAR *state;
  82922. unsigned copy, dist;
  82923. state = (struct inflate_state FAR *)strm->state;
  82924. /* if it hasn't been done already, allocate space for the window */
  82925. if (state->window == Z_NULL) {
  82926. state->window = (unsigned char FAR *)
  82927. ZALLOC(strm, 1U << state->wbits,
  82928. sizeof(unsigned char));
  82929. if (state->window == Z_NULL) return 1;
  82930. }
  82931. /* if window not in use yet, initialize */
  82932. if (state->wsize == 0) {
  82933. state->wsize = 1U << state->wbits;
  82934. state->write = 0;
  82935. state->whave = 0;
  82936. }
  82937. /* copy state->wsize or less output bytes into the circular window */
  82938. copy = out - strm->avail_out;
  82939. if (copy >= state->wsize) {
  82940. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82941. state->write = 0;
  82942. state->whave = state->wsize;
  82943. }
  82944. else {
  82945. dist = state->wsize - state->write;
  82946. if (dist > copy) dist = copy;
  82947. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82948. copy -= dist;
  82949. if (copy) {
  82950. zmemcpy(state->window, strm->next_out - copy, copy);
  82951. state->write = copy;
  82952. state->whave = state->wsize;
  82953. }
  82954. else {
  82955. state->write += dist;
  82956. if (state->write == state->wsize) state->write = 0;
  82957. if (state->whave < state->wsize) state->whave += dist;
  82958. }
  82959. }
  82960. return 0;
  82961. }
  82962. /* Macros for inflate(): */
  82963. /* check function to use adler32() for zlib or crc32() for gzip */
  82964. #ifdef GUNZIP
  82965. # define UPDATE(check, buf, len) \
  82966. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82967. #else
  82968. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82969. #endif
  82970. /* check macros for header crc */
  82971. #ifdef GUNZIP
  82972. # define CRC2(check, word) \
  82973. do { \
  82974. hbuf[0] = (unsigned char)(word); \
  82975. hbuf[1] = (unsigned char)((word) >> 8); \
  82976. check = crc32(check, hbuf, 2); \
  82977. } while (0)
  82978. # define CRC4(check, word) \
  82979. do { \
  82980. hbuf[0] = (unsigned char)(word); \
  82981. hbuf[1] = (unsigned char)((word) >> 8); \
  82982. hbuf[2] = (unsigned char)((word) >> 16); \
  82983. hbuf[3] = (unsigned char)((word) >> 24); \
  82984. check = crc32(check, hbuf, 4); \
  82985. } while (0)
  82986. #endif
  82987. /* Load registers with state in inflate() for speed */
  82988. #define LOAD() \
  82989. do { \
  82990. put = strm->next_out; \
  82991. left = strm->avail_out; \
  82992. next = strm->next_in; \
  82993. have = strm->avail_in; \
  82994. hold = state->hold; \
  82995. bits = state->bits; \
  82996. } while (0)
  82997. /* Restore state from registers in inflate() */
  82998. #define RESTORE() \
  82999. do { \
  83000. strm->next_out = put; \
  83001. strm->avail_out = left; \
  83002. strm->next_in = next; \
  83003. strm->avail_in = have; \
  83004. state->hold = hold; \
  83005. state->bits = bits; \
  83006. } while (0)
  83007. /* Clear the input bit accumulator */
  83008. #define INITBITS() \
  83009. do { \
  83010. hold = 0; \
  83011. bits = 0; \
  83012. } while (0)
  83013. /* Get a byte of input into the bit accumulator, or return from inflate()
  83014. if there is no input available. */
  83015. #define PULLBYTE() \
  83016. do { \
  83017. if (have == 0) goto inf_leave; \
  83018. have--; \
  83019. hold += (unsigned long)(*next++) << bits; \
  83020. bits += 8; \
  83021. } while (0)
  83022. /* Assure that there are at least n bits in the bit accumulator. If there is
  83023. not enough available input to do that, then return from inflate(). */
  83024. #define NEEDBITS(n) \
  83025. do { \
  83026. while (bits < (unsigned)(n)) \
  83027. PULLBYTE(); \
  83028. } while (0)
  83029. /* Return the low n bits of the bit accumulator (n < 16) */
  83030. #define BITS(n) \
  83031. ((unsigned)hold & ((1U << (n)) - 1))
  83032. /* Remove n bits from the bit accumulator */
  83033. #define DROPBITS(n) \
  83034. do { \
  83035. hold >>= (n); \
  83036. bits -= (unsigned)(n); \
  83037. } while (0)
  83038. /* Remove zero to seven bits as needed to go to a byte boundary */
  83039. #define BYTEBITS() \
  83040. do { \
  83041. hold >>= bits & 7; \
  83042. bits -= bits & 7; \
  83043. } while (0)
  83044. /* Reverse the bytes in a 32-bit value */
  83045. #define REVERSE(q) \
  83046. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83047. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83048. /*
  83049. inflate() uses a state machine to process as much input data and generate as
  83050. much output data as possible before returning. The state machine is
  83051. structured roughly as follows:
  83052. for (;;) switch (state) {
  83053. ...
  83054. case STATEn:
  83055. if (not enough input data or output space to make progress)
  83056. return;
  83057. ... make progress ...
  83058. state = STATEm;
  83059. break;
  83060. ...
  83061. }
  83062. so when inflate() is called again, the same case is attempted again, and
  83063. if the appropriate resources are provided, the machine proceeds to the
  83064. next state. The NEEDBITS() macro is usually the way the state evaluates
  83065. whether it can proceed or should return. NEEDBITS() does the return if
  83066. the requested bits are not available. The typical use of the BITS macros
  83067. is:
  83068. NEEDBITS(n);
  83069. ... do something with BITS(n) ...
  83070. DROPBITS(n);
  83071. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83072. input left to load n bits into the accumulator, or it continues. BITS(n)
  83073. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83074. the low n bits off the accumulator. INITBITS() clears the accumulator
  83075. and sets the number of available bits to zero. BYTEBITS() discards just
  83076. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83077. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83078. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83079. if there is no input available. The decoding of variable length codes uses
  83080. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83081. code, and no more.
  83082. Some states loop until they get enough input, making sure that enough
  83083. state information is maintained to continue the loop where it left off
  83084. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83085. would all have to actually be part of the saved state in case NEEDBITS()
  83086. returns:
  83087. case STATEw:
  83088. while (want < need) {
  83089. NEEDBITS(n);
  83090. keep[want++] = BITS(n);
  83091. DROPBITS(n);
  83092. }
  83093. state = STATEx;
  83094. case STATEx:
  83095. As shown above, if the next state is also the next case, then the break
  83096. is omitted.
  83097. A state may also return if there is not enough output space available to
  83098. complete that state. Those states are copying stored data, writing a
  83099. literal byte, and copying a matching string.
  83100. When returning, a "goto inf_leave" is used to update the total counters,
  83101. update the check value, and determine whether any progress has been made
  83102. during that inflate() call in order to return the proper return code.
  83103. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83104. When there is a window, goto inf_leave will update the window with the last
  83105. output written. If a goto inf_leave occurs in the middle of decompression
  83106. and there is no window currently, goto inf_leave will create one and copy
  83107. output to the window for the next call of inflate().
  83108. In this implementation, the flush parameter of inflate() only affects the
  83109. return code (per zlib.h). inflate() always writes as much as possible to
  83110. strm->next_out, given the space available and the provided input--the effect
  83111. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83112. the allocation of and copying into a sliding window until necessary, which
  83113. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83114. stream available. So the only thing the flush parameter actually does is:
  83115. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83116. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83117. */
  83118. int ZEXPORT inflate (z_streamp strm, int flush)
  83119. {
  83120. struct inflate_state FAR *state;
  83121. unsigned char FAR *next; /* next input */
  83122. unsigned char FAR *put; /* next output */
  83123. unsigned have, left; /* available input and output */
  83124. unsigned long hold; /* bit buffer */
  83125. unsigned bits; /* bits in bit buffer */
  83126. unsigned in, out; /* save starting available input and output */
  83127. unsigned copy; /* number of stored or match bytes to copy */
  83128. unsigned char FAR *from; /* where to copy match bytes from */
  83129. code thisx; /* current decoding table entry */
  83130. code last; /* parent table entry */
  83131. unsigned len; /* length to copy for repeats, bits to drop */
  83132. int ret; /* return code */
  83133. #ifdef GUNZIP
  83134. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83135. #endif
  83136. static const unsigned short order[19] = /* permutation of code lengths */
  83137. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83138. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83139. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83140. return Z_STREAM_ERROR;
  83141. state = (struct inflate_state FAR *)strm->state;
  83142. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83143. LOAD();
  83144. in = have;
  83145. out = left;
  83146. ret = Z_OK;
  83147. for (;;)
  83148. switch (state->mode) {
  83149. case HEAD:
  83150. if (state->wrap == 0) {
  83151. state->mode = TYPEDO;
  83152. break;
  83153. }
  83154. NEEDBITS(16);
  83155. #ifdef GUNZIP
  83156. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83157. state->check = crc32(0L, Z_NULL, 0);
  83158. CRC2(state->check, hold);
  83159. INITBITS();
  83160. state->mode = FLAGS;
  83161. break;
  83162. }
  83163. state->flags = 0; /* expect zlib header */
  83164. if (state->head != Z_NULL)
  83165. state->head->done = -1;
  83166. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83167. #else
  83168. if (
  83169. #endif
  83170. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83171. strm->msg = (char *)"incorrect header check";
  83172. state->mode = BAD;
  83173. break;
  83174. }
  83175. if (BITS(4) != Z_DEFLATED) {
  83176. strm->msg = (char *)"unknown compression method";
  83177. state->mode = BAD;
  83178. break;
  83179. }
  83180. DROPBITS(4);
  83181. len = BITS(4) + 8;
  83182. if (len > state->wbits) {
  83183. strm->msg = (char *)"invalid window size";
  83184. state->mode = BAD;
  83185. break;
  83186. }
  83187. state->dmax = 1U << len;
  83188. Tracev((stderr, "inflate: zlib header ok\n"));
  83189. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83190. state->mode = hold & 0x200 ? DICTID : TYPE;
  83191. INITBITS();
  83192. break;
  83193. #ifdef GUNZIP
  83194. case FLAGS:
  83195. NEEDBITS(16);
  83196. state->flags = (int)(hold);
  83197. if ((state->flags & 0xff) != Z_DEFLATED) {
  83198. strm->msg = (char *)"unknown compression method";
  83199. state->mode = BAD;
  83200. break;
  83201. }
  83202. if (state->flags & 0xe000) {
  83203. strm->msg = (char *)"unknown header flags set";
  83204. state->mode = BAD;
  83205. break;
  83206. }
  83207. if (state->head != Z_NULL)
  83208. state->head->text = (int)((hold >> 8) & 1);
  83209. if (state->flags & 0x0200) CRC2(state->check, hold);
  83210. INITBITS();
  83211. state->mode = TIME;
  83212. case TIME:
  83213. NEEDBITS(32);
  83214. if (state->head != Z_NULL)
  83215. state->head->time = hold;
  83216. if (state->flags & 0x0200) CRC4(state->check, hold);
  83217. INITBITS();
  83218. state->mode = OS;
  83219. case OS:
  83220. NEEDBITS(16);
  83221. if (state->head != Z_NULL) {
  83222. state->head->xflags = (int)(hold & 0xff);
  83223. state->head->os = (int)(hold >> 8);
  83224. }
  83225. if (state->flags & 0x0200) CRC2(state->check, hold);
  83226. INITBITS();
  83227. state->mode = EXLEN;
  83228. case EXLEN:
  83229. if (state->flags & 0x0400) {
  83230. NEEDBITS(16);
  83231. state->length = (unsigned)(hold);
  83232. if (state->head != Z_NULL)
  83233. state->head->extra_len = (unsigned)hold;
  83234. if (state->flags & 0x0200) CRC2(state->check, hold);
  83235. INITBITS();
  83236. }
  83237. else if (state->head != Z_NULL)
  83238. state->head->extra = Z_NULL;
  83239. state->mode = EXTRA;
  83240. case EXTRA:
  83241. if (state->flags & 0x0400) {
  83242. copy = state->length;
  83243. if (copy > have) copy = have;
  83244. if (copy) {
  83245. if (state->head != Z_NULL &&
  83246. state->head->extra != Z_NULL) {
  83247. len = state->head->extra_len - state->length;
  83248. zmemcpy(state->head->extra + len, next,
  83249. len + copy > state->head->extra_max ?
  83250. state->head->extra_max - len : copy);
  83251. }
  83252. if (state->flags & 0x0200)
  83253. state->check = crc32(state->check, next, copy);
  83254. have -= copy;
  83255. next += copy;
  83256. state->length -= copy;
  83257. }
  83258. if (state->length) goto inf_leave;
  83259. }
  83260. state->length = 0;
  83261. state->mode = NAME;
  83262. case NAME:
  83263. if (state->flags & 0x0800) {
  83264. if (have == 0) goto inf_leave;
  83265. copy = 0;
  83266. do {
  83267. len = (unsigned)(next[copy++]);
  83268. if (state->head != Z_NULL &&
  83269. state->head->name != Z_NULL &&
  83270. state->length < state->head->name_max)
  83271. state->head->name[state->length++] = len;
  83272. } while (len && copy < have);
  83273. if (state->flags & 0x0200)
  83274. state->check = crc32(state->check, next, copy);
  83275. have -= copy;
  83276. next += copy;
  83277. if (len) goto inf_leave;
  83278. }
  83279. else if (state->head != Z_NULL)
  83280. state->head->name = Z_NULL;
  83281. state->length = 0;
  83282. state->mode = COMMENT;
  83283. case COMMENT:
  83284. if (state->flags & 0x1000) {
  83285. if (have == 0) goto inf_leave;
  83286. copy = 0;
  83287. do {
  83288. len = (unsigned)(next[copy++]);
  83289. if (state->head != Z_NULL &&
  83290. state->head->comment != Z_NULL &&
  83291. state->length < state->head->comm_max)
  83292. state->head->comment[state->length++] = len;
  83293. } while (len && copy < have);
  83294. if (state->flags & 0x0200)
  83295. state->check = crc32(state->check, next, copy);
  83296. have -= copy;
  83297. next += copy;
  83298. if (len) goto inf_leave;
  83299. }
  83300. else if (state->head != Z_NULL)
  83301. state->head->comment = Z_NULL;
  83302. state->mode = HCRC;
  83303. case HCRC:
  83304. if (state->flags & 0x0200) {
  83305. NEEDBITS(16);
  83306. if (hold != (state->check & 0xffff)) {
  83307. strm->msg = (char *)"header crc mismatch";
  83308. state->mode = BAD;
  83309. break;
  83310. }
  83311. INITBITS();
  83312. }
  83313. if (state->head != Z_NULL) {
  83314. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83315. state->head->done = 1;
  83316. }
  83317. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83318. state->mode = TYPE;
  83319. break;
  83320. #endif
  83321. case DICTID:
  83322. NEEDBITS(32);
  83323. strm->adler = state->check = REVERSE(hold);
  83324. INITBITS();
  83325. state->mode = DICT;
  83326. case DICT:
  83327. if (state->havedict == 0) {
  83328. RESTORE();
  83329. return Z_NEED_DICT;
  83330. }
  83331. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83332. state->mode = TYPE;
  83333. case TYPE:
  83334. if (flush == Z_BLOCK) goto inf_leave;
  83335. case TYPEDO:
  83336. if (state->last) {
  83337. BYTEBITS();
  83338. state->mode = CHECK;
  83339. break;
  83340. }
  83341. NEEDBITS(3);
  83342. state->last = BITS(1);
  83343. DROPBITS(1);
  83344. switch (BITS(2)) {
  83345. case 0: /* stored block */
  83346. Tracev((stderr, "inflate: stored block%s\n",
  83347. state->last ? " (last)" : ""));
  83348. state->mode = STORED;
  83349. break;
  83350. case 1: /* fixed block */
  83351. fixedtables(state);
  83352. Tracev((stderr, "inflate: fixed codes block%s\n",
  83353. state->last ? " (last)" : ""));
  83354. state->mode = LEN; /* decode codes */
  83355. break;
  83356. case 2: /* dynamic block */
  83357. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83358. state->last ? " (last)" : ""));
  83359. state->mode = TABLE;
  83360. break;
  83361. case 3:
  83362. strm->msg = (char *)"invalid block type";
  83363. state->mode = BAD;
  83364. }
  83365. DROPBITS(2);
  83366. break;
  83367. case STORED:
  83368. BYTEBITS(); /* go to byte boundary */
  83369. NEEDBITS(32);
  83370. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83371. strm->msg = (char *)"invalid stored block lengths";
  83372. state->mode = BAD;
  83373. break;
  83374. }
  83375. state->length = (unsigned)hold & 0xffff;
  83376. Tracev((stderr, "inflate: stored length %u\n",
  83377. state->length));
  83378. INITBITS();
  83379. state->mode = COPY;
  83380. case COPY:
  83381. copy = state->length;
  83382. if (copy) {
  83383. if (copy > have) copy = have;
  83384. if (copy > left) copy = left;
  83385. if (copy == 0) goto inf_leave;
  83386. zmemcpy(put, next, copy);
  83387. have -= copy;
  83388. next += copy;
  83389. left -= copy;
  83390. put += copy;
  83391. state->length -= copy;
  83392. break;
  83393. }
  83394. Tracev((stderr, "inflate: stored end\n"));
  83395. state->mode = TYPE;
  83396. break;
  83397. case TABLE:
  83398. NEEDBITS(14);
  83399. state->nlen = BITS(5) + 257;
  83400. DROPBITS(5);
  83401. state->ndist = BITS(5) + 1;
  83402. DROPBITS(5);
  83403. state->ncode = BITS(4) + 4;
  83404. DROPBITS(4);
  83405. #ifndef PKZIP_BUG_WORKAROUND
  83406. if (state->nlen > 286 || state->ndist > 30) {
  83407. strm->msg = (char *)"too many length or distance symbols";
  83408. state->mode = BAD;
  83409. break;
  83410. }
  83411. #endif
  83412. Tracev((stderr, "inflate: table sizes ok\n"));
  83413. state->have = 0;
  83414. state->mode = LENLENS;
  83415. case LENLENS:
  83416. while (state->have < state->ncode) {
  83417. NEEDBITS(3);
  83418. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83419. DROPBITS(3);
  83420. }
  83421. while (state->have < 19)
  83422. state->lens[order[state->have++]] = 0;
  83423. state->next = state->codes;
  83424. state->lencode = (code const FAR *)(state->next);
  83425. state->lenbits = 7;
  83426. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83427. &(state->lenbits), state->work);
  83428. if (ret) {
  83429. strm->msg = (char *)"invalid code lengths set";
  83430. state->mode = BAD;
  83431. break;
  83432. }
  83433. Tracev((stderr, "inflate: code lengths ok\n"));
  83434. state->have = 0;
  83435. state->mode = CODELENS;
  83436. case CODELENS:
  83437. while (state->have < state->nlen + state->ndist) {
  83438. for (;;) {
  83439. thisx = state->lencode[BITS(state->lenbits)];
  83440. if ((unsigned)(thisx.bits) <= bits) break;
  83441. PULLBYTE();
  83442. }
  83443. if (thisx.val < 16) {
  83444. NEEDBITS(thisx.bits);
  83445. DROPBITS(thisx.bits);
  83446. state->lens[state->have++] = thisx.val;
  83447. }
  83448. else {
  83449. if (thisx.val == 16) {
  83450. NEEDBITS(thisx.bits + 2);
  83451. DROPBITS(thisx.bits);
  83452. if (state->have == 0) {
  83453. strm->msg = (char *)"invalid bit length repeat";
  83454. state->mode = BAD;
  83455. break;
  83456. }
  83457. len = state->lens[state->have - 1];
  83458. copy = 3 + BITS(2);
  83459. DROPBITS(2);
  83460. }
  83461. else if (thisx.val == 17) {
  83462. NEEDBITS(thisx.bits + 3);
  83463. DROPBITS(thisx.bits);
  83464. len = 0;
  83465. copy = 3 + BITS(3);
  83466. DROPBITS(3);
  83467. }
  83468. else {
  83469. NEEDBITS(thisx.bits + 7);
  83470. DROPBITS(thisx.bits);
  83471. len = 0;
  83472. copy = 11 + BITS(7);
  83473. DROPBITS(7);
  83474. }
  83475. if (state->have + copy > state->nlen + state->ndist) {
  83476. strm->msg = (char *)"invalid bit length repeat";
  83477. state->mode = BAD;
  83478. break;
  83479. }
  83480. while (copy--)
  83481. state->lens[state->have++] = (unsigned short)len;
  83482. }
  83483. }
  83484. /* handle error breaks in while */
  83485. if (state->mode == BAD) break;
  83486. /* build code tables */
  83487. state->next = state->codes;
  83488. state->lencode = (code const FAR *)(state->next);
  83489. state->lenbits = 9;
  83490. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83491. &(state->lenbits), state->work);
  83492. if (ret) {
  83493. strm->msg = (char *)"invalid literal/lengths set";
  83494. state->mode = BAD;
  83495. break;
  83496. }
  83497. state->distcode = (code const FAR *)(state->next);
  83498. state->distbits = 6;
  83499. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83500. &(state->next), &(state->distbits), state->work);
  83501. if (ret) {
  83502. strm->msg = (char *)"invalid distances set";
  83503. state->mode = BAD;
  83504. break;
  83505. }
  83506. Tracev((stderr, "inflate: codes ok\n"));
  83507. state->mode = LEN;
  83508. case LEN:
  83509. if (have >= 6 && left >= 258) {
  83510. RESTORE();
  83511. inflate_fast(strm, out);
  83512. LOAD();
  83513. break;
  83514. }
  83515. for (;;) {
  83516. thisx = state->lencode[BITS(state->lenbits)];
  83517. if ((unsigned)(thisx.bits) <= bits) break;
  83518. PULLBYTE();
  83519. }
  83520. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83521. last = thisx;
  83522. for (;;) {
  83523. thisx = state->lencode[last.val +
  83524. (BITS(last.bits + last.op) >> last.bits)];
  83525. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83526. PULLBYTE();
  83527. }
  83528. DROPBITS(last.bits);
  83529. }
  83530. DROPBITS(thisx.bits);
  83531. state->length = (unsigned)thisx.val;
  83532. if ((int)(thisx.op) == 0) {
  83533. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83534. "inflate: literal '%c'\n" :
  83535. "inflate: literal 0x%02x\n", thisx.val));
  83536. state->mode = LIT;
  83537. break;
  83538. }
  83539. if (thisx.op & 32) {
  83540. Tracevv((stderr, "inflate: end of block\n"));
  83541. state->mode = TYPE;
  83542. break;
  83543. }
  83544. if (thisx.op & 64) {
  83545. strm->msg = (char *)"invalid literal/length code";
  83546. state->mode = BAD;
  83547. break;
  83548. }
  83549. state->extra = (unsigned)(thisx.op) & 15;
  83550. state->mode = LENEXT;
  83551. case LENEXT:
  83552. if (state->extra) {
  83553. NEEDBITS(state->extra);
  83554. state->length += BITS(state->extra);
  83555. DROPBITS(state->extra);
  83556. }
  83557. Tracevv((stderr, "inflate: length %u\n", state->length));
  83558. state->mode = DIST;
  83559. case DIST:
  83560. for (;;) {
  83561. thisx = state->distcode[BITS(state->distbits)];
  83562. if ((unsigned)(thisx.bits) <= bits) break;
  83563. PULLBYTE();
  83564. }
  83565. if ((thisx.op & 0xf0) == 0) {
  83566. last = thisx;
  83567. for (;;) {
  83568. thisx = state->distcode[last.val +
  83569. (BITS(last.bits + last.op) >> last.bits)];
  83570. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83571. PULLBYTE();
  83572. }
  83573. DROPBITS(last.bits);
  83574. }
  83575. DROPBITS(thisx.bits);
  83576. if (thisx.op & 64) {
  83577. strm->msg = (char *)"invalid distance code";
  83578. state->mode = BAD;
  83579. break;
  83580. }
  83581. state->offset = (unsigned)thisx.val;
  83582. state->extra = (unsigned)(thisx.op) & 15;
  83583. state->mode = DISTEXT;
  83584. case DISTEXT:
  83585. if (state->extra) {
  83586. NEEDBITS(state->extra);
  83587. state->offset += BITS(state->extra);
  83588. DROPBITS(state->extra);
  83589. }
  83590. #ifdef INFLATE_STRICT
  83591. if (state->offset > state->dmax) {
  83592. strm->msg = (char *)"invalid distance too far back";
  83593. state->mode = BAD;
  83594. break;
  83595. }
  83596. #endif
  83597. if (state->offset > state->whave + out - left) {
  83598. strm->msg = (char *)"invalid distance too far back";
  83599. state->mode = BAD;
  83600. break;
  83601. }
  83602. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83603. state->mode = MATCH;
  83604. case MATCH:
  83605. if (left == 0) goto inf_leave;
  83606. copy = out - left;
  83607. if (state->offset > copy) { /* copy from window */
  83608. copy = state->offset - copy;
  83609. if (copy > state->write) {
  83610. copy -= state->write;
  83611. from = state->window + (state->wsize - copy);
  83612. }
  83613. else
  83614. from = state->window + (state->write - copy);
  83615. if (copy > state->length) copy = state->length;
  83616. }
  83617. else { /* copy from output */
  83618. from = put - state->offset;
  83619. copy = state->length;
  83620. }
  83621. if (copy > left) copy = left;
  83622. left -= copy;
  83623. state->length -= copy;
  83624. do {
  83625. *put++ = *from++;
  83626. } while (--copy);
  83627. if (state->length == 0) state->mode = LEN;
  83628. break;
  83629. case LIT:
  83630. if (left == 0) goto inf_leave;
  83631. *put++ = (unsigned char)(state->length);
  83632. left--;
  83633. state->mode = LEN;
  83634. break;
  83635. case CHECK:
  83636. if (state->wrap) {
  83637. NEEDBITS(32);
  83638. out -= left;
  83639. strm->total_out += out;
  83640. state->total += out;
  83641. if (out)
  83642. strm->adler = state->check =
  83643. UPDATE(state->check, put - out, out);
  83644. out = left;
  83645. if ((
  83646. #ifdef GUNZIP
  83647. state->flags ? hold :
  83648. #endif
  83649. REVERSE(hold)) != state->check) {
  83650. strm->msg = (char *)"incorrect data check";
  83651. state->mode = BAD;
  83652. break;
  83653. }
  83654. INITBITS();
  83655. Tracev((stderr, "inflate: check matches trailer\n"));
  83656. }
  83657. #ifdef GUNZIP
  83658. state->mode = LENGTH;
  83659. case LENGTH:
  83660. if (state->wrap && state->flags) {
  83661. NEEDBITS(32);
  83662. if (hold != (state->total & 0xffffffffUL)) {
  83663. strm->msg = (char *)"incorrect length check";
  83664. state->mode = BAD;
  83665. break;
  83666. }
  83667. INITBITS();
  83668. Tracev((stderr, "inflate: length matches trailer\n"));
  83669. }
  83670. #endif
  83671. state->mode = DONE;
  83672. case DONE:
  83673. ret = Z_STREAM_END;
  83674. goto inf_leave;
  83675. case BAD:
  83676. ret = Z_DATA_ERROR;
  83677. goto inf_leave;
  83678. case MEM:
  83679. return Z_MEM_ERROR;
  83680. case SYNC:
  83681. default:
  83682. return Z_STREAM_ERROR;
  83683. }
  83684. /*
  83685. Return from inflate(), updating the total counts and the check value.
  83686. If there was no progress during the inflate() call, return a buffer
  83687. error. Call updatewindow() to create and/or update the window state.
  83688. Note: a memory error from inflate() is non-recoverable.
  83689. */
  83690. inf_leave:
  83691. RESTORE();
  83692. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83693. if (updatewindow(strm, out)) {
  83694. state->mode = MEM;
  83695. return Z_MEM_ERROR;
  83696. }
  83697. in -= strm->avail_in;
  83698. out -= strm->avail_out;
  83699. strm->total_in += in;
  83700. strm->total_out += out;
  83701. state->total += out;
  83702. if (state->wrap && out)
  83703. strm->adler = state->check =
  83704. UPDATE(state->check, strm->next_out - out, out);
  83705. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83706. (state->mode == TYPE ? 128 : 0);
  83707. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83708. ret = Z_BUF_ERROR;
  83709. return ret;
  83710. }
  83711. int ZEXPORT inflateEnd (z_streamp strm)
  83712. {
  83713. struct inflate_state FAR *state;
  83714. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83715. return Z_STREAM_ERROR;
  83716. state = (struct inflate_state FAR *)strm->state;
  83717. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83718. ZFREE(strm, strm->state);
  83719. strm->state = Z_NULL;
  83720. Tracev((stderr, "inflate: end\n"));
  83721. return Z_OK;
  83722. }
  83723. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83724. {
  83725. struct inflate_state FAR *state;
  83726. unsigned long id_;
  83727. /* check state */
  83728. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83729. state = (struct inflate_state FAR *)strm->state;
  83730. if (state->wrap != 0 && state->mode != DICT)
  83731. return Z_STREAM_ERROR;
  83732. /* check for correct dictionary id */
  83733. if (state->mode == DICT) {
  83734. id_ = adler32(0L, Z_NULL, 0);
  83735. id_ = adler32(id_, dictionary, dictLength);
  83736. if (id_ != state->check)
  83737. return Z_DATA_ERROR;
  83738. }
  83739. /* copy dictionary to window */
  83740. if (updatewindow(strm, strm->avail_out)) {
  83741. state->mode = MEM;
  83742. return Z_MEM_ERROR;
  83743. }
  83744. if (dictLength > state->wsize) {
  83745. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83746. state->wsize);
  83747. state->whave = state->wsize;
  83748. }
  83749. else {
  83750. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83751. dictLength);
  83752. state->whave = dictLength;
  83753. }
  83754. state->havedict = 1;
  83755. Tracev((stderr, "inflate: dictionary set\n"));
  83756. return Z_OK;
  83757. }
  83758. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83759. {
  83760. struct inflate_state FAR *state;
  83761. /* check state */
  83762. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83763. state = (struct inflate_state FAR *)strm->state;
  83764. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83765. /* save header structure */
  83766. state->head = head;
  83767. head->done = 0;
  83768. return Z_OK;
  83769. }
  83770. /*
  83771. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83772. or when out of input. When called, *have is the number of pattern bytes
  83773. found in order so far, in 0..3. On return *have is updated to the new
  83774. state. If on return *have equals four, then the pattern was found and the
  83775. return value is how many bytes were read including the last byte of the
  83776. pattern. If *have is less than four, then the pattern has not been found
  83777. yet and the return value is len. In the latter case, syncsearch() can be
  83778. called again with more data and the *have state. *have is initialized to
  83779. zero for the first call.
  83780. */
  83781. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83782. {
  83783. unsigned got;
  83784. unsigned next;
  83785. got = *have;
  83786. next = 0;
  83787. while (next < len && got < 4) {
  83788. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83789. got++;
  83790. else if (buf[next])
  83791. got = 0;
  83792. else
  83793. got = 4 - got;
  83794. next++;
  83795. }
  83796. *have = got;
  83797. return next;
  83798. }
  83799. int ZEXPORT inflateSync (z_streamp strm)
  83800. {
  83801. unsigned len; /* number of bytes to look at or looked at */
  83802. unsigned long in, out; /* temporary to save total_in and total_out */
  83803. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83804. struct inflate_state FAR *state;
  83805. /* check parameters */
  83806. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83807. state = (struct inflate_state FAR *)strm->state;
  83808. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83809. /* if first time, start search in bit buffer */
  83810. if (state->mode != SYNC) {
  83811. state->mode = SYNC;
  83812. state->hold <<= state->bits & 7;
  83813. state->bits -= state->bits & 7;
  83814. len = 0;
  83815. while (state->bits >= 8) {
  83816. buf[len++] = (unsigned char)(state->hold);
  83817. state->hold >>= 8;
  83818. state->bits -= 8;
  83819. }
  83820. state->have = 0;
  83821. syncsearch(&(state->have), buf, len);
  83822. }
  83823. /* search available input */
  83824. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83825. strm->avail_in -= len;
  83826. strm->next_in += len;
  83827. strm->total_in += len;
  83828. /* return no joy or set up to restart inflate() on a new block */
  83829. if (state->have != 4) return Z_DATA_ERROR;
  83830. in = strm->total_in; out = strm->total_out;
  83831. inflateReset(strm);
  83832. strm->total_in = in; strm->total_out = out;
  83833. state->mode = TYPE;
  83834. return Z_OK;
  83835. }
  83836. /*
  83837. Returns true if inflate is currently at the end of a block generated by
  83838. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83839. implementation to provide an additional safety check. PPP uses
  83840. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83841. block. When decompressing, PPP checks that at the end of input packet,
  83842. inflate is waiting for these length bytes.
  83843. */
  83844. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83845. {
  83846. struct inflate_state FAR *state;
  83847. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83848. state = (struct inflate_state FAR *)strm->state;
  83849. return state->mode == STORED && state->bits == 0;
  83850. }
  83851. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83852. {
  83853. struct inflate_state FAR *state;
  83854. struct inflate_state FAR *copy;
  83855. unsigned char FAR *window;
  83856. unsigned wsize;
  83857. /* check input */
  83858. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83859. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83860. return Z_STREAM_ERROR;
  83861. state = (struct inflate_state FAR *)source->state;
  83862. /* allocate space */
  83863. copy = (struct inflate_state FAR *)
  83864. ZALLOC(source, 1, sizeof(struct inflate_state));
  83865. if (copy == Z_NULL) return Z_MEM_ERROR;
  83866. window = Z_NULL;
  83867. if (state->window != Z_NULL) {
  83868. window = (unsigned char FAR *)
  83869. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83870. if (window == Z_NULL) {
  83871. ZFREE(source, copy);
  83872. return Z_MEM_ERROR;
  83873. }
  83874. }
  83875. /* copy state */
  83876. zmemcpy(dest, source, sizeof(z_stream));
  83877. zmemcpy(copy, state, sizeof(struct inflate_state));
  83878. if (state->lencode >= state->codes &&
  83879. state->lencode <= state->codes + ENOUGH - 1) {
  83880. copy->lencode = copy->codes + (state->lencode - state->codes);
  83881. copy->distcode = copy->codes + (state->distcode - state->codes);
  83882. }
  83883. copy->next = copy->codes + (state->next - state->codes);
  83884. if (window != Z_NULL) {
  83885. wsize = 1U << state->wbits;
  83886. zmemcpy(window, state->window, wsize);
  83887. }
  83888. copy->window = window;
  83889. dest->state = (struct internal_state FAR *)copy;
  83890. return Z_OK;
  83891. }
  83892. /*** End of inlined file: inflate.c ***/
  83893. /*** Start of inlined file: inftrees.c ***/
  83894. #define MAXBITS 15
  83895. const char inflate_copyright[] =
  83896. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83897. /*
  83898. If you use the zlib library in a product, an acknowledgment is welcome
  83899. in the documentation of your product. If for some reason you cannot
  83900. include such an acknowledgment, I would appreciate that you keep this
  83901. copyright string in the executable of your product.
  83902. */
  83903. /*
  83904. Build a set of tables to decode the provided canonical Huffman code.
  83905. The code lengths are lens[0..codes-1]. The result starts at *table,
  83906. whose indices are 0..2^bits-1. work is a writable array of at least
  83907. lens shorts, which is used as a work area. type is the type of code
  83908. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83909. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83910. on return points to the next available entry's address. bits is the
  83911. requested root table index bits, and on return it is the actual root
  83912. table index bits. It will differ if the request is greater than the
  83913. longest code or if it is less than the shortest code.
  83914. */
  83915. int inflate_table (codetype type,
  83916. unsigned short FAR *lens,
  83917. unsigned codes,
  83918. code FAR * FAR *table,
  83919. unsigned FAR *bits,
  83920. unsigned short FAR *work)
  83921. {
  83922. unsigned len; /* a code's length in bits */
  83923. unsigned sym; /* index of code symbols */
  83924. unsigned min, max; /* minimum and maximum code lengths */
  83925. unsigned root; /* number of index bits for root table */
  83926. unsigned curr; /* number of index bits for current table */
  83927. unsigned drop; /* code bits to drop for sub-table */
  83928. int left; /* number of prefix codes available */
  83929. unsigned used; /* code entries in table used */
  83930. unsigned huff; /* Huffman code */
  83931. unsigned incr; /* for incrementing code, index */
  83932. unsigned fill; /* index for replicating entries */
  83933. unsigned low; /* low bits for current root entry */
  83934. unsigned mask; /* mask for low root bits */
  83935. code thisx; /* table entry for duplication */
  83936. code FAR *next; /* next available space in table */
  83937. const unsigned short FAR *base; /* base value table to use */
  83938. const unsigned short FAR *extra; /* extra bits table to use */
  83939. int end; /* use base and extra for symbol > end */
  83940. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83941. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83942. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83943. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83944. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83945. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83946. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83947. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83948. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83949. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83950. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83951. 8193, 12289, 16385, 24577, 0, 0};
  83952. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83953. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83954. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83955. 28, 28, 29, 29, 64, 64};
  83956. /*
  83957. Process a set of code lengths to create a canonical Huffman code. The
  83958. code lengths are lens[0..codes-1]. Each length corresponds to the
  83959. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83960. symbols by length from short to long, and retaining the symbol order
  83961. for codes with equal lengths. Then the code starts with all zero bits
  83962. for the first code of the shortest length, and the codes are integer
  83963. increments for the same length, and zeros are appended as the length
  83964. increases. For the deflate format, these bits are stored backwards
  83965. from their more natural integer increment ordering, and so when the
  83966. decoding tables are built in the large loop below, the integer codes
  83967. are incremented backwards.
  83968. This routine assumes, but does not check, that all of the entries in
  83969. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83970. 1..MAXBITS is interpreted as that code length. zero means that that
  83971. symbol does not occur in this code.
  83972. The codes are sorted by computing a count of codes for each length,
  83973. creating from that a table of starting indices for each length in the
  83974. sorted table, and then entering the symbols in order in the sorted
  83975. table. The sorted table is work[], with that space being provided by
  83976. the caller.
  83977. The length counts are used for other purposes as well, i.e. finding
  83978. the minimum and maximum length codes, determining if there are any
  83979. codes at all, checking for a valid set of lengths, and looking ahead
  83980. at length counts to determine sub-table sizes when building the
  83981. decoding tables.
  83982. */
  83983. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83984. for (len = 0; len <= MAXBITS; len++)
  83985. count[len] = 0;
  83986. for (sym = 0; sym < codes; sym++)
  83987. count[lens[sym]]++;
  83988. /* bound code lengths, force root to be within code lengths */
  83989. root = *bits;
  83990. for (max = MAXBITS; max >= 1; max--)
  83991. if (count[max] != 0) break;
  83992. if (root > max) root = max;
  83993. if (max == 0) { /* no symbols to code at all */
  83994. thisx.op = (unsigned char)64; /* invalid code marker */
  83995. thisx.bits = (unsigned char)1;
  83996. thisx.val = (unsigned short)0;
  83997. *(*table)++ = thisx; /* make a table to force an error */
  83998. *(*table)++ = thisx;
  83999. *bits = 1;
  84000. return 0; /* no symbols, but wait for decoding to report error */
  84001. }
  84002. for (min = 1; min <= MAXBITS; min++)
  84003. if (count[min] != 0) break;
  84004. if (root < min) root = min;
  84005. /* check for an over-subscribed or incomplete set of lengths */
  84006. left = 1;
  84007. for (len = 1; len <= MAXBITS; len++) {
  84008. left <<= 1;
  84009. left -= count[len];
  84010. if (left < 0) return -1; /* over-subscribed */
  84011. }
  84012. if (left > 0 && (type == CODES || max != 1))
  84013. return -1; /* incomplete set */
  84014. /* generate offsets into symbol table for each length for sorting */
  84015. offs[1] = 0;
  84016. for (len = 1; len < MAXBITS; len++)
  84017. offs[len + 1] = offs[len] + count[len];
  84018. /* sort symbols by length, by symbol order within each length */
  84019. for (sym = 0; sym < codes; sym++)
  84020. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84021. /*
  84022. Create and fill in decoding tables. In this loop, the table being
  84023. filled is at next and has curr index bits. The code being used is huff
  84024. with length len. That code is converted to an index by dropping drop
  84025. bits off of the bottom. For codes where len is less than drop + curr,
  84026. those top drop + curr - len bits are incremented through all values to
  84027. fill the table with replicated entries.
  84028. root is the number of index bits for the root table. When len exceeds
  84029. root, sub-tables are created pointed to by the root entry with an index
  84030. of the low root bits of huff. This is saved in low to check for when a
  84031. new sub-table should be started. drop is zero when the root table is
  84032. being filled, and drop is root when sub-tables are being filled.
  84033. When a new sub-table is needed, it is necessary to look ahead in the
  84034. code lengths to determine what size sub-table is needed. The length
  84035. counts are used for this, and so count[] is decremented as codes are
  84036. entered in the tables.
  84037. used keeps track of how many table entries have been allocated from the
  84038. provided *table space. It is checked when a LENS table is being made
  84039. against the space in *table, ENOUGH, minus the maximum space needed by
  84040. the worst case distance code, MAXD. This should never happen, but the
  84041. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84042. This assumes that when type == LENS, bits == 9.
  84043. sym increments through all symbols, and the loop terminates when
  84044. all codes of length max, i.e. all codes, have been processed. This
  84045. routine permits incomplete codes, so another loop after this one fills
  84046. in the rest of the decoding tables with invalid code markers.
  84047. */
  84048. /* set up for code type */
  84049. switch (type) {
  84050. case CODES:
  84051. base = extra = work; /* dummy value--not used */
  84052. end = 19;
  84053. break;
  84054. case LENS:
  84055. base = lbase;
  84056. base -= 257;
  84057. extra = lext;
  84058. extra -= 257;
  84059. end = 256;
  84060. break;
  84061. default: /* DISTS */
  84062. base = dbase;
  84063. extra = dext;
  84064. end = -1;
  84065. }
  84066. /* initialize state for loop */
  84067. huff = 0; /* starting code */
  84068. sym = 0; /* starting code symbol */
  84069. len = min; /* starting code length */
  84070. next = *table; /* current table to fill in */
  84071. curr = root; /* current table index bits */
  84072. drop = 0; /* current bits to drop from code for index */
  84073. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84074. used = 1U << root; /* use root table entries */
  84075. mask = used - 1; /* mask for comparing low */
  84076. /* check available table space */
  84077. if (type == LENS && used >= ENOUGH - MAXD)
  84078. return 1;
  84079. /* process all codes and make table entries */
  84080. for (;;) {
  84081. /* create table entry */
  84082. thisx.bits = (unsigned char)(len - drop);
  84083. if ((int)(work[sym]) < end) {
  84084. thisx.op = (unsigned char)0;
  84085. thisx.val = work[sym];
  84086. }
  84087. else if ((int)(work[sym]) > end) {
  84088. thisx.op = (unsigned char)(extra[work[sym]]);
  84089. thisx.val = base[work[sym]];
  84090. }
  84091. else {
  84092. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84093. thisx.val = 0;
  84094. }
  84095. /* replicate for those indices with low len bits equal to huff */
  84096. incr = 1U << (len - drop);
  84097. fill = 1U << curr;
  84098. min = fill; /* save offset to next table */
  84099. do {
  84100. fill -= incr;
  84101. next[(huff >> drop) + fill] = thisx;
  84102. } while (fill != 0);
  84103. /* backwards increment the len-bit code huff */
  84104. incr = 1U << (len - 1);
  84105. while (huff & incr)
  84106. incr >>= 1;
  84107. if (incr != 0) {
  84108. huff &= incr - 1;
  84109. huff += incr;
  84110. }
  84111. else
  84112. huff = 0;
  84113. /* go to next symbol, update count, len */
  84114. sym++;
  84115. if (--(count[len]) == 0) {
  84116. if (len == max) break;
  84117. len = lens[work[sym]];
  84118. }
  84119. /* create new sub-table if needed */
  84120. if (len > root && (huff & mask) != low) {
  84121. /* if first time, transition to sub-tables */
  84122. if (drop == 0)
  84123. drop = root;
  84124. /* increment past last table */
  84125. next += min; /* here min is 1 << curr */
  84126. /* determine length of next table */
  84127. curr = len - drop;
  84128. left = (int)(1 << curr);
  84129. while (curr + drop < max) {
  84130. left -= count[curr + drop];
  84131. if (left <= 0) break;
  84132. curr++;
  84133. left <<= 1;
  84134. }
  84135. /* check for enough space */
  84136. used += 1U << curr;
  84137. if (type == LENS && used >= ENOUGH - MAXD)
  84138. return 1;
  84139. /* point entry in root table to sub-table */
  84140. low = huff & mask;
  84141. (*table)[low].op = (unsigned char)curr;
  84142. (*table)[low].bits = (unsigned char)root;
  84143. (*table)[low].val = (unsigned short)(next - *table);
  84144. }
  84145. }
  84146. /*
  84147. Fill in rest of table for incomplete codes. This loop is similar to the
  84148. loop above in incrementing huff for table indices. It is assumed that
  84149. len is equal to curr + drop, so there is no loop needed to increment
  84150. through high index bits. When the current sub-table is filled, the loop
  84151. drops back to the root table to fill in any remaining entries there.
  84152. */
  84153. thisx.op = (unsigned char)64; /* invalid code marker */
  84154. thisx.bits = (unsigned char)(len - drop);
  84155. thisx.val = (unsigned short)0;
  84156. while (huff != 0) {
  84157. /* when done with sub-table, drop back to root table */
  84158. if (drop != 0 && (huff & mask) != low) {
  84159. drop = 0;
  84160. len = root;
  84161. next = *table;
  84162. thisx.bits = (unsigned char)len;
  84163. }
  84164. /* put invalid code marker in table */
  84165. next[huff >> drop] = thisx;
  84166. /* backwards increment the len-bit code huff */
  84167. incr = 1U << (len - 1);
  84168. while (huff & incr)
  84169. incr >>= 1;
  84170. if (incr != 0) {
  84171. huff &= incr - 1;
  84172. huff += incr;
  84173. }
  84174. else
  84175. huff = 0;
  84176. }
  84177. /* set return parameters */
  84178. *table += used;
  84179. *bits = root;
  84180. return 0;
  84181. }
  84182. /*** End of inlined file: inftrees.c ***/
  84183. /*** Start of inlined file: trees.c ***/
  84184. /*
  84185. * ALGORITHM
  84186. *
  84187. * The "deflation" process uses several Huffman trees. The more
  84188. * common source values are represented by shorter bit sequences.
  84189. *
  84190. * Each code tree is stored in a compressed form which is itself
  84191. * a Huffman encoding of the lengths of all the code strings (in
  84192. * ascending order by source values). The actual code strings are
  84193. * reconstructed from the lengths in the inflate process, as described
  84194. * in the deflate specification.
  84195. *
  84196. * REFERENCES
  84197. *
  84198. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84199. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84200. *
  84201. * Storer, James A.
  84202. * Data Compression: Methods and Theory, pp. 49-50.
  84203. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84204. *
  84205. * Sedgewick, R.
  84206. * Algorithms, p290.
  84207. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84208. */
  84209. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84210. /* #define GEN_TREES_H */
  84211. #ifdef DEBUG
  84212. # include <ctype.h>
  84213. #endif
  84214. /* ===========================================================================
  84215. * Constants
  84216. */
  84217. #define MAX_BL_BITS 7
  84218. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84219. #define END_BLOCK 256
  84220. /* end of block literal code */
  84221. #define REP_3_6 16
  84222. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84223. #define REPZ_3_10 17
  84224. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84225. #define REPZ_11_138 18
  84226. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84227. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84228. = {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};
  84229. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84230. = {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};
  84231. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84232. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84233. local const uch bl_order[BL_CODES]
  84234. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84235. /* The lengths of the bit length codes are sent in order of decreasing
  84236. * probability, to avoid transmitting the lengths for unused bit length codes.
  84237. */
  84238. #define Buf_size (8 * 2*sizeof(char))
  84239. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84240. * more than 16 bits on some systems.)
  84241. */
  84242. /* ===========================================================================
  84243. * Local data. These are initialized only once.
  84244. */
  84245. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84246. #if defined(GEN_TREES_H) || !defined(STDC)
  84247. /* non ANSI compilers may not accept trees.h */
  84248. local ct_data static_ltree[L_CODES+2];
  84249. /* The static literal tree. Since the bit lengths are imposed, there is no
  84250. * need for the L_CODES extra codes used during heap construction. However
  84251. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84252. * below).
  84253. */
  84254. local ct_data static_dtree[D_CODES];
  84255. /* The static distance tree. (Actually a trivial tree since all codes use
  84256. * 5 bits.)
  84257. */
  84258. uch _dist_code[DIST_CODE_LEN];
  84259. /* Distance codes. The first 256 values correspond to the distances
  84260. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84261. * the 15 bit distances.
  84262. */
  84263. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84264. /* length code for each normalized match length (0 == MIN_MATCH) */
  84265. local int base_length[LENGTH_CODES];
  84266. /* First normalized length for each code (0 = MIN_MATCH) */
  84267. local int base_dist[D_CODES];
  84268. /* First normalized distance for each code (0 = distance of 1) */
  84269. #else
  84270. /*** Start of inlined file: trees.h ***/
  84271. local const ct_data static_ltree[L_CODES+2] = {
  84272. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84273. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84274. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84275. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84276. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84277. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84278. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84279. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84280. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84281. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84282. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84283. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84284. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84285. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84286. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84287. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84288. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84289. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84290. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84291. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84292. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84293. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84294. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84295. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84296. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84297. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84298. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84299. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84300. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84301. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84302. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84303. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84304. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84305. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84306. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84307. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84308. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84309. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84310. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84311. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84312. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84313. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84314. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84315. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84316. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84317. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84318. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84319. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84320. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84321. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84322. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84323. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84324. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84325. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84326. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84327. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84328. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84329. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84330. };
  84331. local const ct_data static_dtree[D_CODES] = {
  84332. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84333. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84334. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84335. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84336. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84337. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84338. };
  84339. const uch _dist_code[DIST_CODE_LEN] = {
  84340. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84341. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84342. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84343. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84344. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84345. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84346. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84347. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84348. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84349. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84350. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84351. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84352. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84353. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84354. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84355. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84356. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84357. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84358. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84359. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84360. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84361. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84362. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84363. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84364. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84365. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84366. };
  84367. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84368. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84369. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84370. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84371. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84372. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84373. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84374. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84375. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84376. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84377. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84378. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84379. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84380. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84381. };
  84382. local const int base_length[LENGTH_CODES] = {
  84383. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84384. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84385. };
  84386. local const int base_dist[D_CODES] = {
  84387. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84388. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84389. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84390. };
  84391. /*** End of inlined file: trees.h ***/
  84392. #endif /* GEN_TREES_H */
  84393. struct static_tree_desc_s {
  84394. const ct_data *static_tree; /* static tree or NULL */
  84395. const intf *extra_bits; /* extra bits for each code or NULL */
  84396. int extra_base; /* base index for extra_bits */
  84397. int elems; /* max number of elements in the tree */
  84398. int max_length; /* max bit length for the codes */
  84399. };
  84400. local static_tree_desc static_l_desc =
  84401. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84402. local static_tree_desc static_d_desc =
  84403. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84404. local static_tree_desc static_bl_desc =
  84405. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84406. /* ===========================================================================
  84407. * Local (static) routines in this file.
  84408. */
  84409. local void tr_static_init OF((void));
  84410. local void init_block OF((deflate_state *s));
  84411. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84412. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84413. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84414. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84415. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84416. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84417. local int build_bl_tree OF((deflate_state *s));
  84418. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84419. int blcodes));
  84420. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84421. ct_data *dtree));
  84422. local void set_data_type OF((deflate_state *s));
  84423. local unsigned bi_reverse OF((unsigned value, int length));
  84424. local void bi_windup OF((deflate_state *s));
  84425. local void bi_flush OF((deflate_state *s));
  84426. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84427. int header));
  84428. #ifdef GEN_TREES_H
  84429. local void gen_trees_header OF((void));
  84430. #endif
  84431. #ifndef DEBUG
  84432. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84433. /* Send a code of the given tree. c and tree must not have side effects */
  84434. #else /* DEBUG */
  84435. # define send_code(s, c, tree) \
  84436. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84437. send_bits(s, tree[c].Code, tree[c].Len); }
  84438. #endif
  84439. /* ===========================================================================
  84440. * Output a short LSB first on the stream.
  84441. * IN assertion: there is enough room in pendingBuf.
  84442. */
  84443. #define put_short(s, w) { \
  84444. put_byte(s, (uch)((w) & 0xff)); \
  84445. put_byte(s, (uch)((ush)(w) >> 8)); \
  84446. }
  84447. /* ===========================================================================
  84448. * Send a value on a given number of bits.
  84449. * IN assertion: length <= 16 and value fits in length bits.
  84450. */
  84451. #ifdef DEBUG
  84452. local void send_bits OF((deflate_state *s, int value, int length));
  84453. local void send_bits (deflate_state *s, int value, int length)
  84454. {
  84455. Tracevv((stderr," l %2d v %4x ", length, value));
  84456. Assert(length > 0 && length <= 15, "invalid length");
  84457. s->bits_sent += (ulg)length;
  84458. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84459. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84460. * unused bits in value.
  84461. */
  84462. if (s->bi_valid > (int)Buf_size - length) {
  84463. s->bi_buf |= (value << s->bi_valid);
  84464. put_short(s, s->bi_buf);
  84465. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84466. s->bi_valid += length - Buf_size;
  84467. } else {
  84468. s->bi_buf |= value << s->bi_valid;
  84469. s->bi_valid += length;
  84470. }
  84471. }
  84472. #else /* !DEBUG */
  84473. #define send_bits(s, value, length) \
  84474. { int len = length;\
  84475. if (s->bi_valid > (int)Buf_size - len) {\
  84476. int val = value;\
  84477. s->bi_buf |= (val << s->bi_valid);\
  84478. put_short(s, s->bi_buf);\
  84479. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84480. s->bi_valid += len - Buf_size;\
  84481. } else {\
  84482. s->bi_buf |= (value) << s->bi_valid;\
  84483. s->bi_valid += len;\
  84484. }\
  84485. }
  84486. #endif /* DEBUG */
  84487. /* the arguments must not have side effects */
  84488. /* ===========================================================================
  84489. * Initialize the various 'constant' tables.
  84490. */
  84491. local void tr_static_init()
  84492. {
  84493. #if defined(GEN_TREES_H) || !defined(STDC)
  84494. static int static_init_done = 0;
  84495. int n; /* iterates over tree elements */
  84496. int bits; /* bit counter */
  84497. int length; /* length value */
  84498. int code; /* code value */
  84499. int dist; /* distance index */
  84500. ush bl_count[MAX_BITS+1];
  84501. /* number of codes at each bit length for an optimal tree */
  84502. if (static_init_done) return;
  84503. /* For some embedded targets, global variables are not initialized: */
  84504. static_l_desc.static_tree = static_ltree;
  84505. static_l_desc.extra_bits = extra_lbits;
  84506. static_d_desc.static_tree = static_dtree;
  84507. static_d_desc.extra_bits = extra_dbits;
  84508. static_bl_desc.extra_bits = extra_blbits;
  84509. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84510. length = 0;
  84511. for (code = 0; code < LENGTH_CODES-1; code++) {
  84512. base_length[code] = length;
  84513. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84514. _length_code[length++] = (uch)code;
  84515. }
  84516. }
  84517. Assert (length == 256, "tr_static_init: length != 256");
  84518. /* Note that the length 255 (match length 258) can be represented
  84519. * in two different ways: code 284 + 5 bits or code 285, so we
  84520. * overwrite length_code[255] to use the best encoding:
  84521. */
  84522. _length_code[length-1] = (uch)code;
  84523. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84524. dist = 0;
  84525. for (code = 0 ; code < 16; code++) {
  84526. base_dist[code] = dist;
  84527. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84528. _dist_code[dist++] = (uch)code;
  84529. }
  84530. }
  84531. Assert (dist == 256, "tr_static_init: dist != 256");
  84532. dist >>= 7; /* from now on, all distances are divided by 128 */
  84533. for ( ; code < D_CODES; code++) {
  84534. base_dist[code] = dist << 7;
  84535. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84536. _dist_code[256 + dist++] = (uch)code;
  84537. }
  84538. }
  84539. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84540. /* Construct the codes of the static literal tree */
  84541. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84542. n = 0;
  84543. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84544. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84545. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84546. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84547. /* Codes 286 and 287 do not exist, but we must include them in the
  84548. * tree construction to get a canonical Huffman tree (longest code
  84549. * all ones)
  84550. */
  84551. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84552. /* The static distance tree is trivial: */
  84553. for (n = 0; n < D_CODES; n++) {
  84554. static_dtree[n].Len = 5;
  84555. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84556. }
  84557. static_init_done = 1;
  84558. # ifdef GEN_TREES_H
  84559. gen_trees_header();
  84560. # endif
  84561. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84562. }
  84563. /* ===========================================================================
  84564. * Genererate the file trees.h describing the static trees.
  84565. */
  84566. #ifdef GEN_TREES_H
  84567. # ifndef DEBUG
  84568. # include <stdio.h>
  84569. # endif
  84570. # define SEPARATOR(i, last, width) \
  84571. ((i) == (last)? "\n};\n\n" : \
  84572. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84573. void gen_trees_header()
  84574. {
  84575. FILE *header = fopen("trees.h", "w");
  84576. int i;
  84577. Assert (header != NULL, "Can't open trees.h");
  84578. fprintf(header,
  84579. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84580. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84581. for (i = 0; i < L_CODES+2; i++) {
  84582. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84583. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84584. }
  84585. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84586. for (i = 0; i < D_CODES; i++) {
  84587. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84588. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84589. }
  84590. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84591. for (i = 0; i < DIST_CODE_LEN; i++) {
  84592. fprintf(header, "%2u%s", _dist_code[i],
  84593. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84594. }
  84595. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84596. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84597. fprintf(header, "%2u%s", _length_code[i],
  84598. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84599. }
  84600. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84601. for (i = 0; i < LENGTH_CODES; i++) {
  84602. fprintf(header, "%1u%s", base_length[i],
  84603. SEPARATOR(i, LENGTH_CODES-1, 20));
  84604. }
  84605. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84606. for (i = 0; i < D_CODES; i++) {
  84607. fprintf(header, "%5u%s", base_dist[i],
  84608. SEPARATOR(i, D_CODES-1, 10));
  84609. }
  84610. fclose(header);
  84611. }
  84612. #endif /* GEN_TREES_H */
  84613. /* ===========================================================================
  84614. * Initialize the tree data structures for a new zlib stream.
  84615. */
  84616. void _tr_init(deflate_state *s)
  84617. {
  84618. tr_static_init();
  84619. s->l_desc.dyn_tree = s->dyn_ltree;
  84620. s->l_desc.stat_desc = &static_l_desc;
  84621. s->d_desc.dyn_tree = s->dyn_dtree;
  84622. s->d_desc.stat_desc = &static_d_desc;
  84623. s->bl_desc.dyn_tree = s->bl_tree;
  84624. s->bl_desc.stat_desc = &static_bl_desc;
  84625. s->bi_buf = 0;
  84626. s->bi_valid = 0;
  84627. s->last_eob_len = 8; /* enough lookahead for inflate */
  84628. #ifdef DEBUG
  84629. s->compressed_len = 0L;
  84630. s->bits_sent = 0L;
  84631. #endif
  84632. /* Initialize the first block of the first file: */
  84633. init_block(s);
  84634. }
  84635. /* ===========================================================================
  84636. * Initialize a new block.
  84637. */
  84638. local void init_block (deflate_state *s)
  84639. {
  84640. int n; /* iterates over tree elements */
  84641. /* Initialize the trees. */
  84642. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84643. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84644. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84645. s->dyn_ltree[END_BLOCK].Freq = 1;
  84646. s->opt_len = s->static_len = 0L;
  84647. s->last_lit = s->matches = 0;
  84648. }
  84649. #define SMALLEST 1
  84650. /* Index within the heap array of least frequent node in the Huffman tree */
  84651. /* ===========================================================================
  84652. * Remove the smallest element from the heap and recreate the heap with
  84653. * one less element. Updates heap and heap_len.
  84654. */
  84655. #define pqremove(s, tree, top) \
  84656. {\
  84657. top = s->heap[SMALLEST]; \
  84658. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84659. pqdownheap(s, tree, SMALLEST); \
  84660. }
  84661. /* ===========================================================================
  84662. * Compares to subtrees, using the tree depth as tie breaker when
  84663. * the subtrees have equal frequency. This minimizes the worst case length.
  84664. */
  84665. #define smaller(tree, n, m, depth) \
  84666. (tree[n].Freq < tree[m].Freq || \
  84667. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84668. /* ===========================================================================
  84669. * Restore the heap property by moving down the tree starting at node k,
  84670. * exchanging a node with the smallest of its two sons if necessary, stopping
  84671. * when the heap property is re-established (each father smaller than its
  84672. * two sons).
  84673. */
  84674. local void pqdownheap (deflate_state *s,
  84675. ct_data *tree, /* the tree to restore */
  84676. int k) /* node to move down */
  84677. {
  84678. int v = s->heap[k];
  84679. int j = k << 1; /* left son of k */
  84680. while (j <= s->heap_len) {
  84681. /* Set j to the smallest of the two sons: */
  84682. if (j < s->heap_len &&
  84683. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84684. j++;
  84685. }
  84686. /* Exit if v is smaller than both sons */
  84687. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84688. /* Exchange v with the smallest son */
  84689. s->heap[k] = s->heap[j]; k = j;
  84690. /* And continue down the tree, setting j to the left son of k */
  84691. j <<= 1;
  84692. }
  84693. s->heap[k] = v;
  84694. }
  84695. /* ===========================================================================
  84696. * Compute the optimal bit lengths for a tree and update the total bit length
  84697. * for the current block.
  84698. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84699. * above are the tree nodes sorted by increasing frequency.
  84700. * OUT assertions: the field len is set to the optimal bit length, the
  84701. * array bl_count contains the frequencies for each bit length.
  84702. * The length opt_len is updated; static_len is also updated if stree is
  84703. * not null.
  84704. */
  84705. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84706. {
  84707. ct_data *tree = desc->dyn_tree;
  84708. int max_code = desc->max_code;
  84709. const ct_data *stree = desc->stat_desc->static_tree;
  84710. const intf *extra = desc->stat_desc->extra_bits;
  84711. int base = desc->stat_desc->extra_base;
  84712. int max_length = desc->stat_desc->max_length;
  84713. int h; /* heap index */
  84714. int n, m; /* iterate over the tree elements */
  84715. int bits; /* bit length */
  84716. int xbits; /* extra bits */
  84717. ush f; /* frequency */
  84718. int overflow = 0; /* number of elements with bit length too large */
  84719. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84720. /* In a first pass, compute the optimal bit lengths (which may
  84721. * overflow in the case of the bit length tree).
  84722. */
  84723. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84724. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84725. n = s->heap[h];
  84726. bits = tree[tree[n].Dad].Len + 1;
  84727. if (bits > max_length) bits = max_length, overflow++;
  84728. tree[n].Len = (ush)bits;
  84729. /* We overwrite tree[n].Dad which is no longer needed */
  84730. if (n > max_code) continue; /* not a leaf node */
  84731. s->bl_count[bits]++;
  84732. xbits = 0;
  84733. if (n >= base) xbits = extra[n-base];
  84734. f = tree[n].Freq;
  84735. s->opt_len += (ulg)f * (bits + xbits);
  84736. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84737. }
  84738. if (overflow == 0) return;
  84739. Trace((stderr,"\nbit length overflow\n"));
  84740. /* This happens for example on obj2 and pic of the Calgary corpus */
  84741. /* Find the first bit length which could increase: */
  84742. do {
  84743. bits = max_length-1;
  84744. while (s->bl_count[bits] == 0) bits--;
  84745. s->bl_count[bits]--; /* move one leaf down the tree */
  84746. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84747. s->bl_count[max_length]--;
  84748. /* The brother of the overflow item also moves one step up,
  84749. * but this does not affect bl_count[max_length]
  84750. */
  84751. overflow -= 2;
  84752. } while (overflow > 0);
  84753. /* Now recompute all bit lengths, scanning in increasing frequency.
  84754. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84755. * lengths instead of fixing only the wrong ones. This idea is taken
  84756. * from 'ar' written by Haruhiko Okumura.)
  84757. */
  84758. for (bits = max_length; bits != 0; bits--) {
  84759. n = s->bl_count[bits];
  84760. while (n != 0) {
  84761. m = s->heap[--h];
  84762. if (m > max_code) continue;
  84763. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84764. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84765. s->opt_len += ((long)bits - (long)tree[m].Len)
  84766. *(long)tree[m].Freq;
  84767. tree[m].Len = (ush)bits;
  84768. }
  84769. n--;
  84770. }
  84771. }
  84772. }
  84773. /* ===========================================================================
  84774. * Generate the codes for a given tree and bit counts (which need not be
  84775. * optimal).
  84776. * IN assertion: the array bl_count contains the bit length statistics for
  84777. * the given tree and the field len is set for all tree elements.
  84778. * OUT assertion: the field code is set for all tree elements of non
  84779. * zero code length.
  84780. */
  84781. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84782. int max_code, /* largest code with non zero frequency */
  84783. ushf *bl_count) /* number of codes at each bit length */
  84784. {
  84785. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84786. ush code = 0; /* running code value */
  84787. int bits; /* bit index */
  84788. int n; /* code index */
  84789. /* The distribution counts are first used to generate the code values
  84790. * without bit reversal.
  84791. */
  84792. for (bits = 1; bits <= MAX_BITS; bits++) {
  84793. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84794. }
  84795. /* Check that the bit counts in bl_count are consistent. The last code
  84796. * must be all ones.
  84797. */
  84798. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84799. "inconsistent bit counts");
  84800. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84801. for (n = 0; n <= max_code; n++) {
  84802. int len = tree[n].Len;
  84803. if (len == 0) continue;
  84804. /* Now reverse the bits */
  84805. tree[n].Code = bi_reverse(next_code[len]++, len);
  84806. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84807. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84808. }
  84809. }
  84810. /* ===========================================================================
  84811. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84812. * Update the total bit length for the current block.
  84813. * IN assertion: the field freq is set for all tree elements.
  84814. * OUT assertions: the fields len and code are set to the optimal bit length
  84815. * and corresponding code. The length opt_len is updated; static_len is
  84816. * also updated if stree is not null. The field max_code is set.
  84817. */
  84818. local void build_tree (deflate_state *s,
  84819. tree_desc *desc) /* the tree descriptor */
  84820. {
  84821. ct_data *tree = desc->dyn_tree;
  84822. const ct_data *stree = desc->stat_desc->static_tree;
  84823. int elems = desc->stat_desc->elems;
  84824. int n, m; /* iterate over heap elements */
  84825. int max_code = -1; /* largest code with non zero frequency */
  84826. int node; /* new node being created */
  84827. /* Construct the initial heap, with least frequent element in
  84828. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84829. * heap[0] is not used.
  84830. */
  84831. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84832. for (n = 0; n < elems; n++) {
  84833. if (tree[n].Freq != 0) {
  84834. s->heap[++(s->heap_len)] = max_code = n;
  84835. s->depth[n] = 0;
  84836. } else {
  84837. tree[n].Len = 0;
  84838. }
  84839. }
  84840. /* The pkzip format requires that at least one distance code exists,
  84841. * and that at least one bit should be sent even if there is only one
  84842. * possible code. So to avoid special checks later on we force at least
  84843. * two codes of non zero frequency.
  84844. */
  84845. while (s->heap_len < 2) {
  84846. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84847. tree[node].Freq = 1;
  84848. s->depth[node] = 0;
  84849. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84850. /* node is 0 or 1 so it does not have extra bits */
  84851. }
  84852. desc->max_code = max_code;
  84853. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84854. * establish sub-heaps of increasing lengths:
  84855. */
  84856. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84857. /* Construct the Huffman tree by repeatedly combining the least two
  84858. * frequent nodes.
  84859. */
  84860. node = elems; /* next internal node of the tree */
  84861. do {
  84862. pqremove(s, tree, n); /* n = node of least frequency */
  84863. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84864. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84865. s->heap[--(s->heap_max)] = m;
  84866. /* Create a new node father of n and m */
  84867. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84868. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84869. s->depth[n] : s->depth[m]) + 1);
  84870. tree[n].Dad = tree[m].Dad = (ush)node;
  84871. #ifdef DUMP_BL_TREE
  84872. if (tree == s->bl_tree) {
  84873. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84874. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84875. }
  84876. #endif
  84877. /* and insert the new node in the heap */
  84878. s->heap[SMALLEST] = node++;
  84879. pqdownheap(s, tree, SMALLEST);
  84880. } while (s->heap_len >= 2);
  84881. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84882. /* At this point, the fields freq and dad are set. We can now
  84883. * generate the bit lengths.
  84884. */
  84885. gen_bitlen(s, (tree_desc *)desc);
  84886. /* The field len is now set, we can generate the bit codes */
  84887. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84888. }
  84889. /* ===========================================================================
  84890. * Scan a literal or distance tree to determine the frequencies of the codes
  84891. * in the bit length tree.
  84892. */
  84893. local void scan_tree (deflate_state *s,
  84894. ct_data *tree, /* the tree to be scanned */
  84895. int max_code) /* and its largest code of non zero frequency */
  84896. {
  84897. int n; /* iterates over all tree elements */
  84898. int prevlen = -1; /* last emitted length */
  84899. int curlen; /* length of current code */
  84900. int nextlen = tree[0].Len; /* length of next code */
  84901. int count = 0; /* repeat count of the current code */
  84902. int max_count = 7; /* max repeat count */
  84903. int min_count = 4; /* min repeat count */
  84904. if (nextlen == 0) max_count = 138, min_count = 3;
  84905. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84906. for (n = 0; n <= max_code; n++) {
  84907. curlen = nextlen; nextlen = tree[n+1].Len;
  84908. if (++count < max_count && curlen == nextlen) {
  84909. continue;
  84910. } else if (count < min_count) {
  84911. s->bl_tree[curlen].Freq += count;
  84912. } else if (curlen != 0) {
  84913. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84914. s->bl_tree[REP_3_6].Freq++;
  84915. } else if (count <= 10) {
  84916. s->bl_tree[REPZ_3_10].Freq++;
  84917. } else {
  84918. s->bl_tree[REPZ_11_138].Freq++;
  84919. }
  84920. count = 0; prevlen = curlen;
  84921. if (nextlen == 0) {
  84922. max_count = 138, min_count = 3;
  84923. } else if (curlen == nextlen) {
  84924. max_count = 6, min_count = 3;
  84925. } else {
  84926. max_count = 7, min_count = 4;
  84927. }
  84928. }
  84929. }
  84930. /* ===========================================================================
  84931. * Send a literal or distance tree in compressed form, using the codes in
  84932. * bl_tree.
  84933. */
  84934. local void send_tree (deflate_state *s,
  84935. ct_data *tree, /* the tree to be scanned */
  84936. int max_code) /* and its largest code of non zero frequency */
  84937. {
  84938. int n; /* iterates over all tree elements */
  84939. int prevlen = -1; /* last emitted length */
  84940. int curlen; /* length of current code */
  84941. int nextlen = tree[0].Len; /* length of next code */
  84942. int count = 0; /* repeat count of the current code */
  84943. int max_count = 7; /* max repeat count */
  84944. int min_count = 4; /* min repeat count */
  84945. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84946. if (nextlen == 0) max_count = 138, min_count = 3;
  84947. for (n = 0; n <= max_code; n++) {
  84948. curlen = nextlen; nextlen = tree[n+1].Len;
  84949. if (++count < max_count && curlen == nextlen) {
  84950. continue;
  84951. } else if (count < min_count) {
  84952. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84953. } else if (curlen != 0) {
  84954. if (curlen != prevlen) {
  84955. send_code(s, curlen, s->bl_tree); count--;
  84956. }
  84957. Assert(count >= 3 && count <= 6, " 3_6?");
  84958. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84959. } else if (count <= 10) {
  84960. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84961. } else {
  84962. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84963. }
  84964. count = 0; prevlen = curlen;
  84965. if (nextlen == 0) {
  84966. max_count = 138, min_count = 3;
  84967. } else if (curlen == nextlen) {
  84968. max_count = 6, min_count = 3;
  84969. } else {
  84970. max_count = 7, min_count = 4;
  84971. }
  84972. }
  84973. }
  84974. /* ===========================================================================
  84975. * Construct the Huffman tree for the bit lengths and return the index in
  84976. * bl_order of the last bit length code to send.
  84977. */
  84978. local int build_bl_tree (deflate_state *s)
  84979. {
  84980. int max_blindex; /* index of last bit length code of non zero freq */
  84981. /* Determine the bit length frequencies for literal and distance trees */
  84982. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84983. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84984. /* Build the bit length tree: */
  84985. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84986. /* opt_len now includes the length of the tree representations, except
  84987. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84988. */
  84989. /* Determine the number of bit length codes to send. The pkzip format
  84990. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84991. * 3 but the actual value used is 4.)
  84992. */
  84993. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84994. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84995. }
  84996. /* Update opt_len to include the bit length tree and counts */
  84997. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84998. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84999. s->opt_len, s->static_len));
  85000. return max_blindex;
  85001. }
  85002. /* ===========================================================================
  85003. * Send the header for a block using dynamic Huffman trees: the counts, the
  85004. * lengths of the bit length codes, the literal tree and the distance tree.
  85005. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85006. */
  85007. local void send_all_trees (deflate_state *s,
  85008. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85009. {
  85010. int rank; /* index in bl_order */
  85011. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85012. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85013. "too many codes");
  85014. Tracev((stderr, "\nbl counts: "));
  85015. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85016. send_bits(s, dcodes-1, 5);
  85017. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85018. for (rank = 0; rank < blcodes; rank++) {
  85019. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85020. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85021. }
  85022. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85023. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85024. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85025. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85026. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85027. }
  85028. /* ===========================================================================
  85029. * Send a stored block
  85030. */
  85031. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85032. {
  85033. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85034. #ifdef DEBUG
  85035. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85036. s->compressed_len += (stored_len + 4) << 3;
  85037. #endif
  85038. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85039. }
  85040. /* ===========================================================================
  85041. * Send one empty static block to give enough lookahead for inflate.
  85042. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85043. * The current inflate code requires 9 bits of lookahead. If the
  85044. * last two codes for the previous block (real code plus EOB) were coded
  85045. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85046. * the last real code. In this case we send two empty static blocks instead
  85047. * of one. (There are no problems if the previous block is stored or fixed.)
  85048. * To simplify the code, we assume the worst case of last real code encoded
  85049. * on one bit only.
  85050. */
  85051. void _tr_align (deflate_state *s)
  85052. {
  85053. send_bits(s, STATIC_TREES<<1, 3);
  85054. send_code(s, END_BLOCK, static_ltree);
  85055. #ifdef DEBUG
  85056. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85057. #endif
  85058. bi_flush(s);
  85059. /* Of the 10 bits for the empty block, we have already sent
  85060. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85061. * the EOB of the previous block) was thus at least one plus the length
  85062. * of the EOB plus what we have just sent of the empty static block.
  85063. */
  85064. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85065. send_bits(s, STATIC_TREES<<1, 3);
  85066. send_code(s, END_BLOCK, static_ltree);
  85067. #ifdef DEBUG
  85068. s->compressed_len += 10L;
  85069. #endif
  85070. bi_flush(s);
  85071. }
  85072. s->last_eob_len = 7;
  85073. }
  85074. /* ===========================================================================
  85075. * Determine the best encoding for the current block: dynamic trees, static
  85076. * trees or store, and output the encoded block to the zip file.
  85077. */
  85078. void _tr_flush_block (deflate_state *s,
  85079. charf *buf, /* input block, or NULL if too old */
  85080. ulg stored_len, /* length of input block */
  85081. int eof) /* true if this is the last block for a file */
  85082. {
  85083. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85084. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85085. /* Build the Huffman trees unless a stored block is forced */
  85086. if (s->level > 0) {
  85087. /* Check if the file is binary or text */
  85088. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85089. set_data_type(s);
  85090. /* Construct the literal and distance trees */
  85091. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85092. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85093. s->static_len));
  85094. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85095. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85096. s->static_len));
  85097. /* At this point, opt_len and static_len are the total bit lengths of
  85098. * the compressed block data, excluding the tree representations.
  85099. */
  85100. /* Build the bit length tree for the above two trees, and get the index
  85101. * in bl_order of the last bit length code to send.
  85102. */
  85103. max_blindex = build_bl_tree(s);
  85104. /* Determine the best encoding. Compute the block lengths in bytes. */
  85105. opt_lenb = (s->opt_len+3+7)>>3;
  85106. static_lenb = (s->static_len+3+7)>>3;
  85107. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85108. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85109. s->last_lit));
  85110. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85111. } else {
  85112. Assert(buf != (char*)0, "lost buf");
  85113. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85114. }
  85115. #ifdef FORCE_STORED
  85116. if (buf != (char*)0) { /* force stored block */
  85117. #else
  85118. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85119. /* 4: two words for the lengths */
  85120. #endif
  85121. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85122. * Otherwise we can't have processed more than WSIZE input bytes since
  85123. * the last block flush, because compression would have been
  85124. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85125. * transform a block into a stored block.
  85126. */
  85127. _tr_stored_block(s, buf, stored_len, eof);
  85128. #ifdef FORCE_STATIC
  85129. } else if (static_lenb >= 0) { /* force static trees */
  85130. #else
  85131. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85132. #endif
  85133. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85134. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85135. #ifdef DEBUG
  85136. s->compressed_len += 3 + s->static_len;
  85137. #endif
  85138. } else {
  85139. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85140. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85141. max_blindex+1);
  85142. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85143. #ifdef DEBUG
  85144. s->compressed_len += 3 + s->opt_len;
  85145. #endif
  85146. }
  85147. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85148. /* The above check is made mod 2^32, for files larger than 512 MB
  85149. * and uLong implemented on 32 bits.
  85150. */
  85151. init_block(s);
  85152. if (eof) {
  85153. bi_windup(s);
  85154. #ifdef DEBUG
  85155. s->compressed_len += 7; /* align on byte boundary */
  85156. #endif
  85157. }
  85158. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85159. s->compressed_len-7*eof));
  85160. }
  85161. /* ===========================================================================
  85162. * Save the match info and tally the frequency counts. Return true if
  85163. * the current block must be flushed.
  85164. */
  85165. int _tr_tally (deflate_state *s,
  85166. unsigned dist, /* distance of matched string */
  85167. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85168. {
  85169. s->d_buf[s->last_lit] = (ush)dist;
  85170. s->l_buf[s->last_lit++] = (uch)lc;
  85171. if (dist == 0) {
  85172. /* lc is the unmatched char */
  85173. s->dyn_ltree[lc].Freq++;
  85174. } else {
  85175. s->matches++;
  85176. /* Here, lc is the match length - MIN_MATCH */
  85177. dist--; /* dist = match distance - 1 */
  85178. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85179. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85180. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85181. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85182. s->dyn_dtree[d_code(dist)].Freq++;
  85183. }
  85184. #ifdef TRUNCATE_BLOCK
  85185. /* Try to guess if it is profitable to stop the current block here */
  85186. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85187. /* Compute an upper bound for the compressed length */
  85188. ulg out_length = (ulg)s->last_lit*8L;
  85189. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85190. int dcode;
  85191. for (dcode = 0; dcode < D_CODES; dcode++) {
  85192. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85193. (5L+extra_dbits[dcode]);
  85194. }
  85195. out_length >>= 3;
  85196. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85197. s->last_lit, in_length, out_length,
  85198. 100L - out_length*100L/in_length));
  85199. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85200. }
  85201. #endif
  85202. return (s->last_lit == s->lit_bufsize-1);
  85203. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85204. * on 16 bit machines and because stored blocks are restricted to
  85205. * 64K-1 bytes.
  85206. */
  85207. }
  85208. /* ===========================================================================
  85209. * Send the block data compressed using the given Huffman trees
  85210. */
  85211. local void compress_block (deflate_state *s,
  85212. ct_data *ltree, /* literal tree */
  85213. ct_data *dtree) /* distance tree */
  85214. {
  85215. unsigned dist; /* distance of matched string */
  85216. int lc; /* match length or unmatched char (if dist == 0) */
  85217. unsigned lx = 0; /* running index in l_buf */
  85218. unsigned code; /* the code to send */
  85219. int extra; /* number of extra bits to send */
  85220. if (s->last_lit != 0) do {
  85221. dist = s->d_buf[lx];
  85222. lc = s->l_buf[lx++];
  85223. if (dist == 0) {
  85224. send_code(s, lc, ltree); /* send a literal byte */
  85225. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85226. } else {
  85227. /* Here, lc is the match length - MIN_MATCH */
  85228. code = _length_code[lc];
  85229. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85230. extra = extra_lbits[code];
  85231. if (extra != 0) {
  85232. lc -= base_length[code];
  85233. send_bits(s, lc, extra); /* send the extra length bits */
  85234. }
  85235. dist--; /* dist is now the match distance - 1 */
  85236. code = d_code(dist);
  85237. Assert (code < D_CODES, "bad d_code");
  85238. send_code(s, code, dtree); /* send the distance code */
  85239. extra = extra_dbits[code];
  85240. if (extra != 0) {
  85241. dist -= base_dist[code];
  85242. send_bits(s, dist, extra); /* send the extra distance bits */
  85243. }
  85244. } /* literal or match pair ? */
  85245. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85246. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85247. "pendingBuf overflow");
  85248. } while (lx < s->last_lit);
  85249. send_code(s, END_BLOCK, ltree);
  85250. s->last_eob_len = ltree[END_BLOCK].Len;
  85251. }
  85252. /* ===========================================================================
  85253. * Set the data type to BINARY or TEXT, using a crude approximation:
  85254. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85255. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85256. * IN assertion: the fields Freq of dyn_ltree are set.
  85257. */
  85258. local void set_data_type (deflate_state *s)
  85259. {
  85260. int n;
  85261. for (n = 0; n < 9; n++)
  85262. if (s->dyn_ltree[n].Freq != 0)
  85263. break;
  85264. if (n == 9)
  85265. for (n = 14; n < 32; n++)
  85266. if (s->dyn_ltree[n].Freq != 0)
  85267. break;
  85268. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85269. }
  85270. /* ===========================================================================
  85271. * Reverse the first len bits of a code, using straightforward code (a faster
  85272. * method would use a table)
  85273. * IN assertion: 1 <= len <= 15
  85274. */
  85275. local unsigned bi_reverse (unsigned code, int len)
  85276. {
  85277. register unsigned res = 0;
  85278. do {
  85279. res |= code & 1;
  85280. code >>= 1, res <<= 1;
  85281. } while (--len > 0);
  85282. return res >> 1;
  85283. }
  85284. /* ===========================================================================
  85285. * Flush the bit buffer, keeping at most 7 bits in it.
  85286. */
  85287. local void bi_flush (deflate_state *s)
  85288. {
  85289. if (s->bi_valid == 16) {
  85290. put_short(s, s->bi_buf);
  85291. s->bi_buf = 0;
  85292. s->bi_valid = 0;
  85293. } else if (s->bi_valid >= 8) {
  85294. put_byte(s, (Byte)s->bi_buf);
  85295. s->bi_buf >>= 8;
  85296. s->bi_valid -= 8;
  85297. }
  85298. }
  85299. /* ===========================================================================
  85300. * Flush the bit buffer and align the output on a byte boundary
  85301. */
  85302. local void bi_windup (deflate_state *s)
  85303. {
  85304. if (s->bi_valid > 8) {
  85305. put_short(s, s->bi_buf);
  85306. } else if (s->bi_valid > 0) {
  85307. put_byte(s, (Byte)s->bi_buf);
  85308. }
  85309. s->bi_buf = 0;
  85310. s->bi_valid = 0;
  85311. #ifdef DEBUG
  85312. s->bits_sent = (s->bits_sent+7) & ~7;
  85313. #endif
  85314. }
  85315. /* ===========================================================================
  85316. * Copy a stored block, storing first the length and its
  85317. * one's complement if requested.
  85318. */
  85319. local void copy_block(deflate_state *s,
  85320. charf *buf, /* the input data */
  85321. unsigned len, /* its length */
  85322. int header) /* true if block header must be written */
  85323. {
  85324. bi_windup(s); /* align on byte boundary */
  85325. s->last_eob_len = 8; /* enough lookahead for inflate */
  85326. if (header) {
  85327. put_short(s, (ush)len);
  85328. put_short(s, (ush)~len);
  85329. #ifdef DEBUG
  85330. s->bits_sent += 2*16;
  85331. #endif
  85332. }
  85333. #ifdef DEBUG
  85334. s->bits_sent += (ulg)len<<3;
  85335. #endif
  85336. while (len--) {
  85337. put_byte(s, *buf++);
  85338. }
  85339. }
  85340. /*** End of inlined file: trees.c ***/
  85341. /*** Start of inlined file: zutil.c ***/
  85342. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85343. #ifndef NO_DUMMY_DECL
  85344. struct internal_state {int dummy;}; /* for buggy compilers */
  85345. #endif
  85346. const char * const z_errmsg[10] = {
  85347. "need dictionary", /* Z_NEED_DICT 2 */
  85348. "stream end", /* Z_STREAM_END 1 */
  85349. "", /* Z_OK 0 */
  85350. "file error", /* Z_ERRNO (-1) */
  85351. "stream error", /* Z_STREAM_ERROR (-2) */
  85352. "data error", /* Z_DATA_ERROR (-3) */
  85353. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85354. "buffer error", /* Z_BUF_ERROR (-5) */
  85355. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85356. ""};
  85357. /*const char * ZEXPORT zlibVersion()
  85358. {
  85359. return ZLIB_VERSION;
  85360. }
  85361. uLong ZEXPORT zlibCompileFlags()
  85362. {
  85363. uLong flags;
  85364. flags = 0;
  85365. switch (sizeof(uInt)) {
  85366. case 2: break;
  85367. case 4: flags += 1; break;
  85368. case 8: flags += 2; break;
  85369. default: flags += 3;
  85370. }
  85371. switch (sizeof(uLong)) {
  85372. case 2: break;
  85373. case 4: flags += 1 << 2; break;
  85374. case 8: flags += 2 << 2; break;
  85375. default: flags += 3 << 2;
  85376. }
  85377. switch (sizeof(voidpf)) {
  85378. case 2: break;
  85379. case 4: flags += 1 << 4; break;
  85380. case 8: flags += 2 << 4; break;
  85381. default: flags += 3 << 4;
  85382. }
  85383. switch (sizeof(z_off_t)) {
  85384. case 2: break;
  85385. case 4: flags += 1 << 6; break;
  85386. case 8: flags += 2 << 6; break;
  85387. default: flags += 3 << 6;
  85388. }
  85389. #ifdef DEBUG
  85390. flags += 1 << 8;
  85391. #endif
  85392. #if defined(ASMV) || defined(ASMINF)
  85393. flags += 1 << 9;
  85394. #endif
  85395. #ifdef ZLIB_WINAPI
  85396. flags += 1 << 10;
  85397. #endif
  85398. #ifdef BUILDFIXED
  85399. flags += 1 << 12;
  85400. #endif
  85401. #ifdef DYNAMIC_CRC_TABLE
  85402. flags += 1 << 13;
  85403. #endif
  85404. #ifdef NO_GZCOMPRESS
  85405. flags += 1L << 16;
  85406. #endif
  85407. #ifdef NO_GZIP
  85408. flags += 1L << 17;
  85409. #endif
  85410. #ifdef PKZIP_BUG_WORKAROUND
  85411. flags += 1L << 20;
  85412. #endif
  85413. #ifdef FASTEST
  85414. flags += 1L << 21;
  85415. #endif
  85416. #ifdef STDC
  85417. # ifdef NO_vsnprintf
  85418. flags += 1L << 25;
  85419. # ifdef HAS_vsprintf_void
  85420. flags += 1L << 26;
  85421. # endif
  85422. # else
  85423. # ifdef HAS_vsnprintf_void
  85424. flags += 1L << 26;
  85425. # endif
  85426. # endif
  85427. #else
  85428. flags += 1L << 24;
  85429. # ifdef NO_snprintf
  85430. flags += 1L << 25;
  85431. # ifdef HAS_sprintf_void
  85432. flags += 1L << 26;
  85433. # endif
  85434. # else
  85435. # ifdef HAS_snprintf_void
  85436. flags += 1L << 26;
  85437. # endif
  85438. # endif
  85439. #endif
  85440. return flags;
  85441. }*/
  85442. #ifdef DEBUG
  85443. # ifndef verbose
  85444. # define verbose 0
  85445. # endif
  85446. int z_verbose = verbose;
  85447. void z_error (const char *m)
  85448. {
  85449. fprintf(stderr, "%s\n", m);
  85450. exit(1);
  85451. }
  85452. #endif
  85453. /* exported to allow conversion of error code to string for compress() and
  85454. * uncompress()
  85455. */
  85456. const char * ZEXPORT zError(int err)
  85457. {
  85458. return ERR_MSG(err);
  85459. }
  85460. #if defined(_WIN32_WCE)
  85461. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85462. * errno. We define it as a global variable to simplify porting.
  85463. * Its value is always 0 and should not be used.
  85464. */
  85465. int errno = 0;
  85466. #endif
  85467. #ifndef HAVE_MEMCPY
  85468. void zmemcpy(dest, source, len)
  85469. Bytef* dest;
  85470. const Bytef* source;
  85471. uInt len;
  85472. {
  85473. if (len == 0) return;
  85474. do {
  85475. *dest++ = *source++; /* ??? to be unrolled */
  85476. } while (--len != 0);
  85477. }
  85478. int zmemcmp(s1, s2, len)
  85479. const Bytef* s1;
  85480. const Bytef* s2;
  85481. uInt len;
  85482. {
  85483. uInt j;
  85484. for (j = 0; j < len; j++) {
  85485. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85486. }
  85487. return 0;
  85488. }
  85489. void zmemzero(dest, len)
  85490. Bytef* dest;
  85491. uInt len;
  85492. {
  85493. if (len == 0) return;
  85494. do {
  85495. *dest++ = 0; /* ??? to be unrolled */
  85496. } while (--len != 0);
  85497. }
  85498. #endif
  85499. #ifdef SYS16BIT
  85500. #ifdef __TURBOC__
  85501. /* Turbo C in 16-bit mode */
  85502. # define MY_ZCALLOC
  85503. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85504. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85505. * must fix the pointer. Warning: the pointer must be put back to its
  85506. * original form in order to free it, use zcfree().
  85507. */
  85508. #define MAX_PTR 10
  85509. /* 10*64K = 640K */
  85510. local int next_ptr = 0;
  85511. typedef struct ptr_table_s {
  85512. voidpf org_ptr;
  85513. voidpf new_ptr;
  85514. } ptr_table;
  85515. local ptr_table table[MAX_PTR];
  85516. /* This table is used to remember the original form of pointers
  85517. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85518. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85519. * protected from concurrent access. This hack doesn't work anyway on
  85520. * a protected system like OS/2. Use Microsoft C instead.
  85521. */
  85522. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85523. {
  85524. voidpf buf = opaque; /* just to make some compilers happy */
  85525. ulg bsize = (ulg)items*size;
  85526. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85527. * will return a usable pointer which doesn't have to be normalized.
  85528. */
  85529. if (bsize < 65520L) {
  85530. buf = farmalloc(bsize);
  85531. if (*(ush*)&buf != 0) return buf;
  85532. } else {
  85533. buf = farmalloc(bsize + 16L);
  85534. }
  85535. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85536. table[next_ptr].org_ptr = buf;
  85537. /* Normalize the pointer to seg:0 */
  85538. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85539. *(ush*)&buf = 0;
  85540. table[next_ptr++].new_ptr = buf;
  85541. return buf;
  85542. }
  85543. void zcfree (voidpf opaque, voidpf ptr)
  85544. {
  85545. int n;
  85546. if (*(ush*)&ptr != 0) { /* object < 64K */
  85547. farfree(ptr);
  85548. return;
  85549. }
  85550. /* Find the original pointer */
  85551. for (n = 0; n < next_ptr; n++) {
  85552. if (ptr != table[n].new_ptr) continue;
  85553. farfree(table[n].org_ptr);
  85554. while (++n < next_ptr) {
  85555. table[n-1] = table[n];
  85556. }
  85557. next_ptr--;
  85558. return;
  85559. }
  85560. ptr = opaque; /* just to make some compilers happy */
  85561. Assert(0, "zcfree: ptr not found");
  85562. }
  85563. #endif /* __TURBOC__ */
  85564. #ifdef M_I86
  85565. /* Microsoft C in 16-bit mode */
  85566. # define MY_ZCALLOC
  85567. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85568. # define _halloc halloc
  85569. # define _hfree hfree
  85570. #endif
  85571. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85572. {
  85573. if (opaque) opaque = 0; /* to make compiler happy */
  85574. return _halloc((long)items, size);
  85575. }
  85576. void zcfree (voidpf opaque, voidpf ptr)
  85577. {
  85578. if (opaque) opaque = 0; /* to make compiler happy */
  85579. _hfree(ptr);
  85580. }
  85581. #endif /* M_I86 */
  85582. #endif /* SYS16BIT */
  85583. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85584. #ifndef STDC
  85585. extern voidp malloc OF((uInt size));
  85586. extern voidp calloc OF((uInt items, uInt size));
  85587. extern void free OF((voidpf ptr));
  85588. #endif
  85589. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85590. {
  85591. if (opaque) items += size - size; /* make compiler happy */
  85592. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85593. (voidpf)calloc(items, size);
  85594. }
  85595. void zcfree (voidpf opaque, voidpf ptr)
  85596. {
  85597. free(ptr);
  85598. if (opaque) return; /* make compiler happy */
  85599. }
  85600. #endif /* MY_ZCALLOC */
  85601. /*** End of inlined file: zutil.c ***/
  85602. #undef Byte
  85603. #else
  85604. #include <zlib.h>
  85605. #endif
  85606. }
  85607. #if JUCE_MSVC
  85608. #pragma warning (pop)
  85609. #endif
  85610. BEGIN_JUCE_NAMESPACE
  85611. // internal helper object that holds the zlib structures so they don't have to be
  85612. // included publicly.
  85613. class GZIPDecompressHelper
  85614. {
  85615. public:
  85616. GZIPDecompressHelper (const bool noWrap)
  85617. : finished (true),
  85618. needsDictionary (false),
  85619. error (true),
  85620. streamIsValid (false),
  85621. data (0),
  85622. dataSize (0)
  85623. {
  85624. using namespace zlibNamespace;
  85625. zerostruct (stream);
  85626. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85627. finished = error = ! streamIsValid;
  85628. }
  85629. ~GZIPDecompressHelper()
  85630. {
  85631. using namespace zlibNamespace;
  85632. if (streamIsValid)
  85633. inflateEnd (&stream);
  85634. }
  85635. bool needsInput() const throw() { return dataSize <= 0; }
  85636. void setInput (uint8* const data_, const int size) throw()
  85637. {
  85638. data = data_;
  85639. dataSize = size;
  85640. }
  85641. int doNextBlock (uint8* const dest, const int destSize)
  85642. {
  85643. using namespace zlibNamespace;
  85644. if (streamIsValid && data != 0 && ! finished)
  85645. {
  85646. stream.next_in = data;
  85647. stream.next_out = dest;
  85648. stream.avail_in = dataSize;
  85649. stream.avail_out = destSize;
  85650. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85651. {
  85652. case Z_STREAM_END:
  85653. finished = true;
  85654. // deliberate fall-through
  85655. case Z_OK:
  85656. data += dataSize - stream.avail_in;
  85657. dataSize = stream.avail_in;
  85658. return destSize - stream.avail_out;
  85659. case Z_NEED_DICT:
  85660. needsDictionary = true;
  85661. data += dataSize - stream.avail_in;
  85662. dataSize = stream.avail_in;
  85663. break;
  85664. case Z_DATA_ERROR:
  85665. case Z_MEM_ERROR:
  85666. error = true;
  85667. default:
  85668. break;
  85669. }
  85670. }
  85671. return 0;
  85672. }
  85673. bool finished, needsDictionary, error, streamIsValid;
  85674. private:
  85675. zlibNamespace::z_stream stream;
  85676. uint8* data;
  85677. int dataSize;
  85678. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85679. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85680. };
  85681. const int gzipDecompBufferSize = 32768;
  85682. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85683. const bool deleteSourceWhenDestroyed,
  85684. const bool noWrap_,
  85685. const int64 uncompressedStreamLength_)
  85686. : sourceStream (sourceStream_),
  85687. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85688. uncompressedStreamLength (uncompressedStreamLength_),
  85689. noWrap (noWrap_),
  85690. isEof (false),
  85691. activeBufferSize (0),
  85692. originalSourcePos (sourceStream_->getPosition()),
  85693. currentPos (0),
  85694. buffer (gzipDecompBufferSize),
  85695. helper (new GZIPDecompressHelper (noWrap_))
  85696. {
  85697. }
  85698. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85699. {
  85700. }
  85701. int64 GZIPDecompressorInputStream::getTotalLength()
  85702. {
  85703. return uncompressedStreamLength;
  85704. }
  85705. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85706. {
  85707. if ((howMany > 0) && ! isEof)
  85708. {
  85709. jassert (destBuffer != 0);
  85710. if (destBuffer != 0)
  85711. {
  85712. int numRead = 0;
  85713. uint8* d = static_cast <uint8*> (destBuffer);
  85714. while (! helper->error)
  85715. {
  85716. const int n = helper->doNextBlock (d, howMany);
  85717. currentPos += n;
  85718. if (n == 0)
  85719. {
  85720. if (helper->finished || helper->needsDictionary)
  85721. {
  85722. isEof = true;
  85723. return numRead;
  85724. }
  85725. if (helper->needsInput())
  85726. {
  85727. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85728. if (activeBufferSize > 0)
  85729. {
  85730. helper->setInput (buffer, activeBufferSize);
  85731. }
  85732. else
  85733. {
  85734. isEof = true;
  85735. return numRead;
  85736. }
  85737. }
  85738. }
  85739. else
  85740. {
  85741. numRead += n;
  85742. howMany -= n;
  85743. d += n;
  85744. if (howMany <= 0)
  85745. return numRead;
  85746. }
  85747. }
  85748. }
  85749. }
  85750. return 0;
  85751. }
  85752. bool GZIPDecompressorInputStream::isExhausted()
  85753. {
  85754. return helper->error || isEof;
  85755. }
  85756. int64 GZIPDecompressorInputStream::getPosition()
  85757. {
  85758. return currentPos;
  85759. }
  85760. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85761. {
  85762. if (newPos < currentPos)
  85763. {
  85764. // to go backwards, reset the stream and start again..
  85765. isEof = false;
  85766. activeBufferSize = 0;
  85767. currentPos = 0;
  85768. helper = new GZIPDecompressHelper (noWrap);
  85769. sourceStream->setPosition (originalSourcePos);
  85770. }
  85771. skipNextBytes (newPos - currentPos);
  85772. return true;
  85773. }
  85774. END_JUCE_NAMESPACE
  85775. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85776. #endif
  85777. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85778. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85779. #if JUCE_USE_FLAC
  85780. #if JUCE_WINDOWS
  85781. #include <windows.h>
  85782. #endif
  85783. namespace FlacNamespace
  85784. {
  85785. #if JUCE_INCLUDE_FLAC_CODE
  85786. #if JUCE_MSVC
  85787. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85788. #endif
  85789. #define FLAC__NO_DLL 1
  85790. #if ! defined (SIZE_MAX)
  85791. #define SIZE_MAX 0xffffffff
  85792. #endif
  85793. #define __STDC_LIMIT_MACROS 1
  85794. /*** Start of inlined file: all.h ***/
  85795. #ifndef FLAC__ALL_H
  85796. #define FLAC__ALL_H
  85797. /*** Start of inlined file: export.h ***/
  85798. #ifndef FLAC__EXPORT_H
  85799. #define FLAC__EXPORT_H
  85800. /** \file include/FLAC/export.h
  85801. *
  85802. * \brief
  85803. * This module contains #defines and symbols for exporting function
  85804. * calls, and providing version information and compiled-in features.
  85805. *
  85806. * See the \link flac_export export \endlink module.
  85807. */
  85808. /** \defgroup flac_export FLAC/export.h: export symbols
  85809. * \ingroup flac
  85810. *
  85811. * \brief
  85812. * This module contains #defines and symbols for exporting function
  85813. * calls, and providing version information and compiled-in features.
  85814. *
  85815. * If you are compiling with MSVC and will link to the static library
  85816. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85817. * make sure the symbols are exported properly.
  85818. *
  85819. * \{
  85820. */
  85821. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85822. #define FLAC_API
  85823. #else
  85824. #ifdef FLAC_API_EXPORTS
  85825. #define FLAC_API _declspec(dllexport)
  85826. #else
  85827. #define FLAC_API _declspec(dllimport)
  85828. #endif
  85829. #endif
  85830. /** These #defines will mirror the libtool-based library version number, see
  85831. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85832. */
  85833. #define FLAC_API_VERSION_CURRENT 10
  85834. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85835. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85836. #ifdef __cplusplus
  85837. extern "C" {
  85838. #endif
  85839. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85840. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85841. #ifdef __cplusplus
  85842. }
  85843. #endif
  85844. /* \} */
  85845. #endif
  85846. /*** End of inlined file: export.h ***/
  85847. /*** Start of inlined file: assert.h ***/
  85848. #ifndef FLAC__ASSERT_H
  85849. #define FLAC__ASSERT_H
  85850. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85851. #ifdef DEBUG
  85852. #include <assert.h>
  85853. #define FLAC__ASSERT(x) assert(x)
  85854. #define FLAC__ASSERT_DECLARATION(x) x
  85855. #else
  85856. #define FLAC__ASSERT(x)
  85857. #define FLAC__ASSERT_DECLARATION(x)
  85858. #endif
  85859. #endif
  85860. /*** End of inlined file: assert.h ***/
  85861. /*** Start of inlined file: callback.h ***/
  85862. #ifndef FLAC__CALLBACK_H
  85863. #define FLAC__CALLBACK_H
  85864. /*** Start of inlined file: ordinals.h ***/
  85865. #ifndef FLAC__ORDINALS_H
  85866. #define FLAC__ORDINALS_H
  85867. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85868. #include <inttypes.h>
  85869. #endif
  85870. typedef signed char FLAC__int8;
  85871. typedef unsigned char FLAC__uint8;
  85872. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85873. typedef __int16 FLAC__int16;
  85874. typedef __int32 FLAC__int32;
  85875. typedef __int64 FLAC__int64;
  85876. typedef unsigned __int16 FLAC__uint16;
  85877. typedef unsigned __int32 FLAC__uint32;
  85878. typedef unsigned __int64 FLAC__uint64;
  85879. #elif defined(__EMX__)
  85880. typedef short FLAC__int16;
  85881. typedef long FLAC__int32;
  85882. typedef long long FLAC__int64;
  85883. typedef unsigned short FLAC__uint16;
  85884. typedef unsigned long FLAC__uint32;
  85885. typedef unsigned long long FLAC__uint64;
  85886. #else
  85887. typedef int16_t FLAC__int16;
  85888. typedef int32_t FLAC__int32;
  85889. typedef int64_t FLAC__int64;
  85890. typedef uint16_t FLAC__uint16;
  85891. typedef uint32_t FLAC__uint32;
  85892. typedef uint64_t FLAC__uint64;
  85893. #endif
  85894. typedef int FLAC__bool;
  85895. typedef FLAC__uint8 FLAC__byte;
  85896. #ifdef true
  85897. #undef true
  85898. #endif
  85899. #ifdef false
  85900. #undef false
  85901. #endif
  85902. #ifndef __cplusplus
  85903. #define true 1
  85904. #define false 0
  85905. #endif
  85906. #endif
  85907. /*** End of inlined file: ordinals.h ***/
  85908. #include <stdlib.h> /* for size_t */
  85909. /** \file include/FLAC/callback.h
  85910. *
  85911. * \brief
  85912. * This module defines the structures for describing I/O callbacks
  85913. * to the other FLAC interfaces.
  85914. *
  85915. * See the detailed documentation for callbacks in the
  85916. * \link flac_callbacks callbacks \endlink module.
  85917. */
  85918. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85919. * \ingroup flac
  85920. *
  85921. * \brief
  85922. * This module defines the structures for describing I/O callbacks
  85923. * to the other FLAC interfaces.
  85924. *
  85925. * The purpose of the I/O callback functions is to create a common way
  85926. * for the metadata interfaces to handle I/O.
  85927. *
  85928. * Originally the metadata interfaces required filenames as the way of
  85929. * specifying FLAC files to operate on. This is problematic in some
  85930. * environments so there is an additional option to specify a set of
  85931. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85932. *
  85933. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85934. * opaque structure for a data source.
  85935. *
  85936. * The callback function prototypes are similar (but not identical) to the
  85937. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85938. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85939. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85940. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85941. * is required. \warning You generally CANNOT directly use fseek or ftell
  85942. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85943. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85944. * large files. You will have to find an equivalent function (e.g. ftello),
  85945. * or write a wrapper. The same is true for feof() since this is usually
  85946. * implemented as a macro, not as a function whose address can be taken.
  85947. *
  85948. * \{
  85949. */
  85950. #ifdef __cplusplus
  85951. extern "C" {
  85952. #endif
  85953. /** This is the opaque handle type used by the callbacks. Typically
  85954. * this is a \c FILE* or address of a file descriptor.
  85955. */
  85956. typedef void* FLAC__IOHandle;
  85957. /** Signature for the read callback.
  85958. * The signature and semantics match POSIX fread() implementations
  85959. * and can generally be used interchangeably.
  85960. *
  85961. * \param ptr The address of the read buffer.
  85962. * \param size The size of the records to be read.
  85963. * \param nmemb The number of records to be read.
  85964. * \param handle The handle to the data source.
  85965. * \retval size_t
  85966. * The number of records read.
  85967. */
  85968. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85969. /** Signature for the write callback.
  85970. * The signature and semantics match POSIX fwrite() implementations
  85971. * and can generally be used interchangeably.
  85972. *
  85973. * \param ptr The address of the write buffer.
  85974. * \param size The size of the records to be written.
  85975. * \param nmemb The number of records to be written.
  85976. * \param handle The handle to the data source.
  85977. * \retval size_t
  85978. * The number of records written.
  85979. */
  85980. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85981. /** Signature for the seek callback.
  85982. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85983. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85984. * and 32-bits wide.
  85985. *
  85986. * \param handle The handle to the data source.
  85987. * \param offset The new position, relative to \a whence
  85988. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85989. * \retval int
  85990. * \c 0 on success, \c -1 on error.
  85991. */
  85992. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85993. /** Signature for the tell callback.
  85994. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85995. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85996. * and 32-bits wide.
  85997. *
  85998. * \param handle The handle to the data source.
  85999. * \retval FLAC__int64
  86000. * The current position on success, \c -1 on error.
  86001. */
  86002. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86003. /** Signature for the EOF callback.
  86004. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86005. * on many systems, feof() is a macro, so in this case a wrapper function
  86006. * must be provided instead.
  86007. *
  86008. * \param handle The handle to the data source.
  86009. * \retval int
  86010. * \c 0 if not at end of file, nonzero if at end of file.
  86011. */
  86012. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86013. /** Signature for the close callback.
  86014. * The signature and semantics match POSIX fclose() implementations
  86015. * and can generally be used interchangeably.
  86016. *
  86017. * \param handle The handle to the data source.
  86018. * \retval int
  86019. * \c 0 on success, \c EOF on error.
  86020. */
  86021. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86022. /** A structure for holding a set of callbacks.
  86023. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86024. * describe which of the callbacks are required. The ones that are not
  86025. * required may be set to NULL.
  86026. *
  86027. * If the seek requirement for an interface is optional, you can signify that
  86028. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86029. */
  86030. typedef struct {
  86031. FLAC__IOCallback_Read read;
  86032. FLAC__IOCallback_Write write;
  86033. FLAC__IOCallback_Seek seek;
  86034. FLAC__IOCallback_Tell tell;
  86035. FLAC__IOCallback_Eof eof;
  86036. FLAC__IOCallback_Close close;
  86037. } FLAC__IOCallbacks;
  86038. /* \} */
  86039. #ifdef __cplusplus
  86040. }
  86041. #endif
  86042. #endif
  86043. /*** End of inlined file: callback.h ***/
  86044. /*** Start of inlined file: format.h ***/
  86045. #ifndef FLAC__FORMAT_H
  86046. #define FLAC__FORMAT_H
  86047. #ifdef __cplusplus
  86048. extern "C" {
  86049. #endif
  86050. /** \file include/FLAC/format.h
  86051. *
  86052. * \brief
  86053. * This module contains structure definitions for the representation
  86054. * of FLAC format components in memory. These are the basic
  86055. * structures used by the rest of the interfaces.
  86056. *
  86057. * See the detailed documentation in the
  86058. * \link flac_format format \endlink module.
  86059. */
  86060. /** \defgroup flac_format FLAC/format.h: format components
  86061. * \ingroup flac
  86062. *
  86063. * \brief
  86064. * This module contains structure definitions for the representation
  86065. * of FLAC format components in memory. These are the basic
  86066. * structures used by the rest of the interfaces.
  86067. *
  86068. * First, you should be familiar with the
  86069. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86070. * follow directly from the specification. As a user of libFLAC, the
  86071. * interesting parts really are the structures that describe the frame
  86072. * header and metadata blocks.
  86073. *
  86074. * The format structures here are very primitive, designed to store
  86075. * information in an efficient way. Reading information from the
  86076. * structures is easy but creating or modifying them directly is
  86077. * more complex. For the most part, as a user of a library, editing
  86078. * is not necessary; however, for metadata blocks it is, so there are
  86079. * convenience functions provided in the \link flac_metadata metadata
  86080. * module \endlink to simplify the manipulation of metadata blocks.
  86081. *
  86082. * \note
  86083. * It's not the best convention, but symbols ending in _LEN are in bits
  86084. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86085. * global variables because they are usually used when declaring byte
  86086. * arrays and some compilers require compile-time knowledge of array
  86087. * sizes when declared on the stack.
  86088. *
  86089. * \{
  86090. */
  86091. /*
  86092. Most of the values described in this file are defined by the FLAC
  86093. format specification. There is nothing to tune here.
  86094. */
  86095. /** The largest legal metadata type code. */
  86096. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86097. /** The minimum block size, in samples, permitted by the format. */
  86098. #define FLAC__MIN_BLOCK_SIZE (16u)
  86099. /** The maximum block size, in samples, permitted by the format. */
  86100. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86101. /** The maximum block size, in samples, permitted by the FLAC subset for
  86102. * sample rates up to 48kHz. */
  86103. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86104. /** The maximum number of channels permitted by the format. */
  86105. #define FLAC__MAX_CHANNELS (8u)
  86106. /** The minimum sample resolution permitted by the format. */
  86107. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86108. /** The maximum sample resolution permitted by the format. */
  86109. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86110. /** The maximum sample resolution permitted by libFLAC.
  86111. *
  86112. * \warning
  86113. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86114. * the reference encoder/decoder is currently limited to 24 bits because
  86115. * of prevalent 32-bit math, so make sure and use this value when
  86116. * appropriate.
  86117. */
  86118. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86119. /** The maximum sample rate permitted by the format. The value is
  86120. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86121. * as to why.
  86122. */
  86123. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86124. /** The maximum LPC order permitted by the format. */
  86125. #define FLAC__MAX_LPC_ORDER (32u)
  86126. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86127. * up to 48kHz. */
  86128. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86129. /** The minimum quantized linear predictor coefficient precision
  86130. * permitted by the format.
  86131. */
  86132. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86133. /** The maximum quantized linear predictor coefficient precision
  86134. * permitted by the format.
  86135. */
  86136. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86137. /** The maximum order of the fixed predictors permitted by the format. */
  86138. #define FLAC__MAX_FIXED_ORDER (4u)
  86139. /** The maximum Rice partition order permitted by the format. */
  86140. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86141. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86142. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86143. /** The version string of the release, stamped onto the libraries and binaries.
  86144. *
  86145. * \note
  86146. * This does not correspond to the shared library version number, which
  86147. * is used to determine binary compatibility.
  86148. */
  86149. extern FLAC_API const char *FLAC__VERSION_STRING;
  86150. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86151. * This is a NUL-terminated ASCII string; when inserted into the
  86152. * VORBIS_COMMENT the trailing null is stripped.
  86153. */
  86154. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86155. /** The byte string representation of the beginning of a FLAC stream. */
  86156. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86157. /** The 32-bit integer big-endian representation of the beginning of
  86158. * a FLAC stream.
  86159. */
  86160. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86161. /** The length of the FLAC signature in bits. */
  86162. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86163. /** The length of the FLAC signature in bytes. */
  86164. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86165. /*****************************************************************************
  86166. *
  86167. * Subframe structures
  86168. *
  86169. *****************************************************************************/
  86170. /*****************************************************************************/
  86171. /** An enumeration of the available entropy coding methods. */
  86172. typedef enum {
  86173. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86174. /**< Residual is coded by partitioning into contexts, each with it's own
  86175. * 4-bit Rice parameter. */
  86176. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86177. /**< Residual is coded by partitioning into contexts, each with it's own
  86178. * 5-bit Rice parameter. */
  86179. } FLAC__EntropyCodingMethodType;
  86180. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86181. *
  86182. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86183. * give the string equivalent. The contents should not be modified.
  86184. */
  86185. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86186. /** Contents of a Rice partitioned residual
  86187. */
  86188. typedef struct {
  86189. unsigned *parameters;
  86190. /**< The Rice parameters for each context. */
  86191. unsigned *raw_bits;
  86192. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86193. * partitions and zero for unescaped partitions.
  86194. */
  86195. unsigned capacity_by_order;
  86196. /**< The capacity of the \a parameters and \a raw_bits arrays
  86197. * specified as an order, i.e. the number of array elements
  86198. * allocated is 2 ^ \a capacity_by_order.
  86199. */
  86200. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86201. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86202. */
  86203. typedef struct {
  86204. unsigned order;
  86205. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86206. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86207. /**< The context's Rice parameters and/or raw bits. */
  86208. } FLAC__EntropyCodingMethod_PartitionedRice;
  86209. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86210. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86211. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86212. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86213. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86214. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86215. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86216. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86217. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86218. */
  86219. typedef struct {
  86220. FLAC__EntropyCodingMethodType type;
  86221. union {
  86222. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86223. } data;
  86224. } FLAC__EntropyCodingMethod;
  86225. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86226. /*****************************************************************************/
  86227. /** An enumeration of the available subframe types. */
  86228. typedef enum {
  86229. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86230. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86231. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86232. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86233. } FLAC__SubframeType;
  86234. /** Maps a FLAC__SubframeType to a C string.
  86235. *
  86236. * Using a FLAC__SubframeType as the index to this array will
  86237. * give the string equivalent. The contents should not be modified.
  86238. */
  86239. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86240. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86241. */
  86242. typedef struct {
  86243. FLAC__int32 value; /**< The constant signal value. */
  86244. } FLAC__Subframe_Constant;
  86245. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86246. */
  86247. typedef struct {
  86248. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86249. } FLAC__Subframe_Verbatim;
  86250. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86251. */
  86252. typedef struct {
  86253. FLAC__EntropyCodingMethod entropy_coding_method;
  86254. /**< The residual coding method. */
  86255. unsigned order;
  86256. /**< The polynomial order. */
  86257. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86258. /**< Warmup samples to prime the predictor, length == order. */
  86259. const FLAC__int32 *residual;
  86260. /**< The residual signal, length == (blocksize minus order) samples. */
  86261. } FLAC__Subframe_Fixed;
  86262. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86263. */
  86264. typedef struct {
  86265. FLAC__EntropyCodingMethod entropy_coding_method;
  86266. /**< The residual coding method. */
  86267. unsigned order;
  86268. /**< The FIR order. */
  86269. unsigned qlp_coeff_precision;
  86270. /**< Quantized FIR filter coefficient precision in bits. */
  86271. int quantization_level;
  86272. /**< The qlp coeff shift needed. */
  86273. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86274. /**< FIR filter coefficients. */
  86275. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86276. /**< Warmup samples to prime the predictor, length == order. */
  86277. const FLAC__int32 *residual;
  86278. /**< The residual signal, length == (blocksize minus order) samples. */
  86279. } FLAC__Subframe_LPC;
  86280. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86281. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86282. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86283. */
  86284. typedef struct {
  86285. FLAC__SubframeType type;
  86286. union {
  86287. FLAC__Subframe_Constant constant;
  86288. FLAC__Subframe_Fixed fixed;
  86289. FLAC__Subframe_LPC lpc;
  86290. FLAC__Subframe_Verbatim verbatim;
  86291. } data;
  86292. unsigned wasted_bits;
  86293. } FLAC__Subframe;
  86294. /** == 1 (bit)
  86295. *
  86296. * This used to be a zero-padding bit (hence the name
  86297. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86298. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86299. * to mean something else.
  86300. */
  86301. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86302. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86303. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86304. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86305. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86306. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86307. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86308. /*****************************************************************************/
  86309. /*****************************************************************************
  86310. *
  86311. * Frame structures
  86312. *
  86313. *****************************************************************************/
  86314. /** An enumeration of the available channel assignments. */
  86315. typedef enum {
  86316. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86317. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86318. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86319. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86320. } FLAC__ChannelAssignment;
  86321. /** Maps a FLAC__ChannelAssignment to a C string.
  86322. *
  86323. * Using a FLAC__ChannelAssignment as the index to this array will
  86324. * give the string equivalent. The contents should not be modified.
  86325. */
  86326. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86327. /** An enumeration of the possible frame numbering methods. */
  86328. typedef enum {
  86329. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86330. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86331. } FLAC__FrameNumberType;
  86332. /** Maps a FLAC__FrameNumberType to a C string.
  86333. *
  86334. * Using a FLAC__FrameNumberType as the index to this array will
  86335. * give the string equivalent. The contents should not be modified.
  86336. */
  86337. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86338. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86339. */
  86340. typedef struct {
  86341. unsigned blocksize;
  86342. /**< The number of samples per subframe. */
  86343. unsigned sample_rate;
  86344. /**< The sample rate in Hz. */
  86345. unsigned channels;
  86346. /**< The number of channels (== number of subframes). */
  86347. FLAC__ChannelAssignment channel_assignment;
  86348. /**< The channel assignment for the frame. */
  86349. unsigned bits_per_sample;
  86350. /**< The sample resolution. */
  86351. FLAC__FrameNumberType number_type;
  86352. /**< The numbering scheme used for the frame. As a convenience, the
  86353. * decoder will always convert a frame number to a sample number because
  86354. * the rules are complex. */
  86355. union {
  86356. FLAC__uint32 frame_number;
  86357. FLAC__uint64 sample_number;
  86358. } number;
  86359. /**< The frame number or sample number of first sample in frame;
  86360. * use the \a number_type value to determine which to use. */
  86361. FLAC__uint8 crc;
  86362. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86363. * of the raw frame header bytes, meaning everything before the CRC byte
  86364. * including the sync code.
  86365. */
  86366. } FLAC__FrameHeader;
  86367. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86368. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86369. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86370. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86371. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86372. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86373. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86374. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86375. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86376. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86377. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86378. */
  86379. typedef struct {
  86380. FLAC__uint16 crc;
  86381. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86382. * 0) of the bytes before the crc, back to and including the frame header
  86383. * sync code.
  86384. */
  86385. } FLAC__FrameFooter;
  86386. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86387. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86388. */
  86389. typedef struct {
  86390. FLAC__FrameHeader header;
  86391. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86392. FLAC__FrameFooter footer;
  86393. } FLAC__Frame;
  86394. /*****************************************************************************/
  86395. /*****************************************************************************
  86396. *
  86397. * Meta-data structures
  86398. *
  86399. *****************************************************************************/
  86400. /** An enumeration of the available metadata block types. */
  86401. typedef enum {
  86402. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86403. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86404. FLAC__METADATA_TYPE_PADDING = 1,
  86405. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86406. FLAC__METADATA_TYPE_APPLICATION = 2,
  86407. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86408. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86409. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86410. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86411. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86412. FLAC__METADATA_TYPE_CUESHEET = 5,
  86413. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86414. FLAC__METADATA_TYPE_PICTURE = 6,
  86415. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86416. FLAC__METADATA_TYPE_UNDEFINED = 7
  86417. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86418. } FLAC__MetadataType;
  86419. /** Maps a FLAC__MetadataType to a C string.
  86420. *
  86421. * Using a FLAC__MetadataType as the index to this array will
  86422. * give the string equivalent. The contents should not be modified.
  86423. */
  86424. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86425. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86426. */
  86427. typedef struct {
  86428. unsigned min_blocksize, max_blocksize;
  86429. unsigned min_framesize, max_framesize;
  86430. unsigned sample_rate;
  86431. unsigned channels;
  86432. unsigned bits_per_sample;
  86433. FLAC__uint64 total_samples;
  86434. FLAC__byte md5sum[16];
  86435. } FLAC__StreamMetadata_StreamInfo;
  86436. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86437. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86438. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86439. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86440. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86441. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86442. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86443. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86444. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86445. /** The total stream length of the STREAMINFO block in bytes. */
  86446. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86447. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86448. */
  86449. typedef struct {
  86450. int dummy;
  86451. /**< Conceptually this is an empty struct since we don't store the
  86452. * padding bytes. Empty structs are not allowed by some C compilers,
  86453. * hence the dummy.
  86454. */
  86455. } FLAC__StreamMetadata_Padding;
  86456. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86457. */
  86458. typedef struct {
  86459. FLAC__byte id[4];
  86460. FLAC__byte *data;
  86461. } FLAC__StreamMetadata_Application;
  86462. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86463. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86464. */
  86465. typedef struct {
  86466. FLAC__uint64 sample_number;
  86467. /**< The sample number of the target frame. */
  86468. FLAC__uint64 stream_offset;
  86469. /**< The offset, in bytes, of the target frame with respect to
  86470. * beginning of the first frame. */
  86471. unsigned frame_samples;
  86472. /**< The number of samples in the target frame. */
  86473. } FLAC__StreamMetadata_SeekPoint;
  86474. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86475. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86476. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86477. /** The total stream length of a seek point in bytes. */
  86478. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86479. /** The value used in the \a sample_number field of
  86480. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86481. * point (== 0xffffffffffffffff).
  86482. */
  86483. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86484. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86485. *
  86486. * \note From the format specification:
  86487. * - The seek points must be sorted by ascending sample number.
  86488. * - Each seek point's sample number must be the first sample of the
  86489. * target frame.
  86490. * - Each seek point's sample number must be unique within the table.
  86491. * - Existence of a SEEKTABLE block implies a correct setting of
  86492. * total_samples in the stream_info block.
  86493. * - Behavior is undefined when more than one SEEKTABLE block is
  86494. * present in a stream.
  86495. */
  86496. typedef struct {
  86497. unsigned num_points;
  86498. FLAC__StreamMetadata_SeekPoint *points;
  86499. } FLAC__StreamMetadata_SeekTable;
  86500. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86501. *
  86502. * For convenience, the APIs maintain a trailing NUL character at the end of
  86503. * \a entry which is not counted toward \a length, i.e.
  86504. * \code strlen(entry) == length \endcode
  86505. */
  86506. typedef struct {
  86507. FLAC__uint32 length;
  86508. FLAC__byte *entry;
  86509. } FLAC__StreamMetadata_VorbisComment_Entry;
  86510. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86511. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86512. */
  86513. typedef struct {
  86514. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86515. FLAC__uint32 num_comments;
  86516. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86517. } FLAC__StreamMetadata_VorbisComment;
  86518. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86519. /** FLAC CUESHEET track index structure. (See the
  86520. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86521. * the full description of each field.)
  86522. */
  86523. typedef struct {
  86524. FLAC__uint64 offset;
  86525. /**< Offset in samples, relative to the track offset, of the index
  86526. * point.
  86527. */
  86528. FLAC__byte number;
  86529. /**< The index point number. */
  86530. } FLAC__StreamMetadata_CueSheet_Index;
  86531. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86532. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86533. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86534. /** FLAC CUESHEET track structure. (See the
  86535. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86536. * the full description of each field.)
  86537. */
  86538. typedef struct {
  86539. FLAC__uint64 offset;
  86540. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86541. FLAC__byte number;
  86542. /**< The track number. */
  86543. char isrc[13];
  86544. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86545. unsigned type:1;
  86546. /**< The track type: 0 for audio, 1 for non-audio. */
  86547. unsigned pre_emphasis:1;
  86548. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86549. FLAC__byte num_indices;
  86550. /**< The number of track index points. */
  86551. FLAC__StreamMetadata_CueSheet_Index *indices;
  86552. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86553. } FLAC__StreamMetadata_CueSheet_Track;
  86554. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86555. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86556. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86557. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86558. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86559. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86560. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86561. /** FLAC CUESHEET structure. (See the
  86562. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86563. * for the full description of each field.)
  86564. */
  86565. typedef struct {
  86566. char media_catalog_number[129];
  86567. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86568. * general, the media catalog number may be 0 to 128 bytes long; any
  86569. * unused characters should be right-padded with NUL characters.
  86570. */
  86571. FLAC__uint64 lead_in;
  86572. /**< The number of lead-in samples. */
  86573. FLAC__bool is_cd;
  86574. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86575. unsigned num_tracks;
  86576. /**< The number of tracks. */
  86577. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86578. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86579. } FLAC__StreamMetadata_CueSheet;
  86580. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86581. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86582. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86583. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86584. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86585. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86586. typedef enum {
  86587. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86588. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86589. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86590. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86591. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86592. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86593. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86594. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86595. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86596. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86597. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86598. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86599. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86600. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86601. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86602. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86603. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86604. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86605. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86606. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86607. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86608. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86609. } FLAC__StreamMetadata_Picture_Type;
  86610. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86611. *
  86612. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86613. * will give the string equivalent. The contents should not be
  86614. * modified.
  86615. */
  86616. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86617. /** FLAC PICTURE structure. (See the
  86618. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86619. * for the full description of each field.)
  86620. */
  86621. typedef struct {
  86622. FLAC__StreamMetadata_Picture_Type type;
  86623. /**< The kind of picture stored. */
  86624. char *mime_type;
  86625. /**< Picture data's MIME type, in ASCII printable characters
  86626. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86627. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86628. * MIME type of '-->' is also allowed, in which case the picture
  86629. * data should be a complete URL. In file storage, the MIME type is
  86630. * stored as a 32-bit length followed by the ASCII string with no NUL
  86631. * terminator, but is converted to a plain C string in this structure
  86632. * for convenience.
  86633. */
  86634. FLAC__byte *description;
  86635. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86636. * the description is stored as a 32-bit length followed by the UTF-8
  86637. * string with no NUL terminator, but is converted to a plain C string
  86638. * in this structure for convenience.
  86639. */
  86640. FLAC__uint32 width;
  86641. /**< Picture's width in pixels. */
  86642. FLAC__uint32 height;
  86643. /**< Picture's height in pixels. */
  86644. FLAC__uint32 depth;
  86645. /**< Picture's color depth in bits-per-pixel. */
  86646. FLAC__uint32 colors;
  86647. /**< For indexed palettes (like GIF), picture's number of colors (the
  86648. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86649. */
  86650. FLAC__uint32 data_length;
  86651. /**< Length of binary picture data in bytes. */
  86652. FLAC__byte *data;
  86653. /**< Binary picture data. */
  86654. } FLAC__StreamMetadata_Picture;
  86655. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86656. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86657. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86658. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86659. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86660. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86661. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86662. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86663. /** Structure that is used when a metadata block of unknown type is loaded.
  86664. * The contents are opaque. The structure is used only internally to
  86665. * correctly handle unknown metadata.
  86666. */
  86667. typedef struct {
  86668. FLAC__byte *data;
  86669. } FLAC__StreamMetadata_Unknown;
  86670. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86671. */
  86672. typedef struct {
  86673. FLAC__MetadataType type;
  86674. /**< The type of the metadata block; used determine which member of the
  86675. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86676. * then \a data.unknown must be used. */
  86677. FLAC__bool is_last;
  86678. /**< \c true if this metadata block is the last, else \a false */
  86679. unsigned length;
  86680. /**< Length, in bytes, of the block data as it appears in the stream. */
  86681. union {
  86682. FLAC__StreamMetadata_StreamInfo stream_info;
  86683. FLAC__StreamMetadata_Padding padding;
  86684. FLAC__StreamMetadata_Application application;
  86685. FLAC__StreamMetadata_SeekTable seek_table;
  86686. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86687. FLAC__StreamMetadata_CueSheet cue_sheet;
  86688. FLAC__StreamMetadata_Picture picture;
  86689. FLAC__StreamMetadata_Unknown unknown;
  86690. } data;
  86691. /**< Polymorphic block data; use the \a type value to determine which
  86692. * to use. */
  86693. } FLAC__StreamMetadata;
  86694. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86695. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86696. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86697. /** The total stream length of a metadata block header in bytes. */
  86698. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86699. /*****************************************************************************/
  86700. /*****************************************************************************
  86701. *
  86702. * Utility functions
  86703. *
  86704. *****************************************************************************/
  86705. /** Tests that a sample rate is valid for FLAC.
  86706. *
  86707. * \param sample_rate The sample rate to test for compliance.
  86708. * \retval FLAC__bool
  86709. * \c true if the given sample rate conforms to the specification, else
  86710. * \c false.
  86711. */
  86712. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86713. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86714. * for valid sample rates are slightly more complex since the rate has to
  86715. * be expressible completely in the frame header.
  86716. *
  86717. * \param sample_rate The sample rate to test for compliance.
  86718. * \retval FLAC__bool
  86719. * \c true if the given sample rate conforms to the specification for the
  86720. * subset, else \c false.
  86721. */
  86722. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86723. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86724. * comment specification.
  86725. *
  86726. * Vorbis comment names must be composed only of characters from
  86727. * [0x20-0x3C,0x3E-0x7D].
  86728. *
  86729. * \param name A NUL-terminated string to be checked.
  86730. * \assert
  86731. * \code name != NULL \endcode
  86732. * \retval FLAC__bool
  86733. * \c false if entry name is illegal, else \c true.
  86734. */
  86735. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86736. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86737. * comment specification.
  86738. *
  86739. * Vorbis comment values must be valid UTF-8 sequences.
  86740. *
  86741. * \param value A string to be checked.
  86742. * \param length A the length of \a value in bytes. May be
  86743. * \c (unsigned)(-1) to indicate that \a value is a plain
  86744. * UTF-8 NUL-terminated string.
  86745. * \assert
  86746. * \code value != NULL \endcode
  86747. * \retval FLAC__bool
  86748. * \c false if entry name is illegal, else \c true.
  86749. */
  86750. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86751. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86752. * comment specification.
  86753. *
  86754. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86755. * 'value' must be legal according to
  86756. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86757. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86758. *
  86759. * \param entry An entry to be checked.
  86760. * \param length The length of \a entry in bytes.
  86761. * \assert
  86762. * \code value != NULL \endcode
  86763. * \retval FLAC__bool
  86764. * \c false if entry name is illegal, else \c true.
  86765. */
  86766. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86767. /** Check a seek table to see if it conforms to the FLAC specification.
  86768. * See the format specification for limits on the contents of the
  86769. * seek table.
  86770. *
  86771. * \param seek_table A pointer to a seek table to be checked.
  86772. * \assert
  86773. * \code seek_table != NULL \endcode
  86774. * \retval FLAC__bool
  86775. * \c false if seek table is illegal, else \c true.
  86776. */
  86777. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86778. /** Sort a seek table's seek points according to the format specification.
  86779. * This includes a "unique-ification" step to remove duplicates, i.e.
  86780. * seek points with identical \a sample_number values. Duplicate seek
  86781. * points are converted into placeholder points and sorted to the end of
  86782. * the table.
  86783. *
  86784. * \param seek_table A pointer to a seek table to be sorted.
  86785. * \assert
  86786. * \code seek_table != NULL \endcode
  86787. * \retval unsigned
  86788. * The number of duplicate seek points converted into placeholders.
  86789. */
  86790. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86791. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86792. * See the format specification for limits on the contents of the
  86793. * cue sheet.
  86794. *
  86795. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86796. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86797. * stringent requirements for a CD-DA (audio) disc.
  86798. * \param violation Address of a pointer to a string. If there is a
  86799. * violation, a pointer to a string explanation of the
  86800. * violation will be returned here. \a violation may be
  86801. * \c NULL if you don't need the returned string. Do not
  86802. * free the returned string; it will always point to static
  86803. * data.
  86804. * \assert
  86805. * \code cue_sheet != NULL \endcode
  86806. * \retval FLAC__bool
  86807. * \c false if cue sheet is illegal, else \c true.
  86808. */
  86809. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86810. /** Check picture data to see if it conforms to the FLAC specification.
  86811. * See the format specification for limits on the contents of the
  86812. * PICTURE block.
  86813. *
  86814. * \param picture A pointer to existing picture data to be checked.
  86815. * \param violation Address of a pointer to a string. If there is a
  86816. * violation, a pointer to a string explanation of the
  86817. * violation will be returned here. \a violation may be
  86818. * \c NULL if you don't need the returned string. Do not
  86819. * free the returned string; it will always point to static
  86820. * data.
  86821. * \assert
  86822. * \code picture != NULL \endcode
  86823. * \retval FLAC__bool
  86824. * \c false if picture data is illegal, else \c true.
  86825. */
  86826. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86827. /* \} */
  86828. #ifdef __cplusplus
  86829. }
  86830. #endif
  86831. #endif
  86832. /*** End of inlined file: format.h ***/
  86833. /*** Start of inlined file: metadata.h ***/
  86834. #ifndef FLAC__METADATA_H
  86835. #define FLAC__METADATA_H
  86836. #include <sys/types.h> /* for off_t */
  86837. /* --------------------------------------------------------------------
  86838. (For an example of how all these routines are used, see the source
  86839. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86840. metaflac in src/metaflac/)
  86841. ------------------------------------------------------------------*/
  86842. /** \file include/FLAC/metadata.h
  86843. *
  86844. * \brief
  86845. * This module provides functions for creating and manipulating FLAC
  86846. * metadata blocks in memory, and three progressively more powerful
  86847. * interfaces for traversing and editing metadata in FLAC files.
  86848. *
  86849. * See the detailed documentation for each interface in the
  86850. * \link flac_metadata metadata \endlink module.
  86851. */
  86852. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86853. * \ingroup flac
  86854. *
  86855. * \brief
  86856. * This module provides functions for creating and manipulating FLAC
  86857. * metadata blocks in memory, and three progressively more powerful
  86858. * interfaces for traversing and editing metadata in native FLAC files.
  86859. * Note that currently only the Chain interface (level 2) supports Ogg
  86860. * FLAC files, and it is read-only i.e. no writing back changed
  86861. * metadata to file.
  86862. *
  86863. * There are three metadata interfaces of increasing complexity:
  86864. *
  86865. * Level 0:
  86866. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86867. * PICTURE blocks.
  86868. *
  86869. * Level 1:
  86870. * Read-write access to all metadata blocks. This level is write-
  86871. * efficient in most cases (more on this below), and uses less memory
  86872. * than level 2.
  86873. *
  86874. * Level 2:
  86875. * Read-write access to all metadata blocks. This level is write-
  86876. * efficient in all cases, but uses more memory since all metadata for
  86877. * the whole file is read into memory and manipulated before writing
  86878. * out again.
  86879. *
  86880. * What do we mean by efficient? Since FLAC metadata appears at the
  86881. * beginning of the file, when writing metadata back to a FLAC file
  86882. * it is possible to grow or shrink the metadata such that the entire
  86883. * file must be rewritten. However, if the size remains the same during
  86884. * changes or PADDING blocks are utilized, only the metadata needs to be
  86885. * overwritten, which is much faster.
  86886. *
  86887. * Efficient means the whole file is rewritten at most one time, and only
  86888. * when necessary. Level 1 is not efficient only in the case that you
  86889. * cause more than one metadata block to grow or shrink beyond what can
  86890. * be accomodated by padding. In this case you should probably use level
  86891. * 2, which allows you to edit all the metadata for a file in memory and
  86892. * write it out all at once.
  86893. *
  86894. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86895. * front of the file.
  86896. *
  86897. * All levels access files via their filenames. In addition, level 2
  86898. * has additional alternative read and write functions that take an I/O
  86899. * handle and callbacks, for situations where access by filename is not
  86900. * possible.
  86901. *
  86902. * In addition to the three interfaces, this module defines functions for
  86903. * creating and manipulating various metadata objects in memory. As we see
  86904. * from the Format module, FLAC metadata blocks in memory are very primitive
  86905. * structures for storing information in an efficient way. Reading
  86906. * information from the structures is easy but creating or modifying them
  86907. * directly is more complex. The metadata object routines here facilitate
  86908. * this by taking care of the consistency and memory management drudgery.
  86909. *
  86910. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86911. * metadata however, you will not probably not need these.
  86912. *
  86913. * From a dependency standpoint, none of the encoders or decoders require
  86914. * the metadata module. This is so that embedded users can strip out the
  86915. * metadata module from libFLAC to reduce the size and complexity.
  86916. */
  86917. #ifdef __cplusplus
  86918. extern "C" {
  86919. #endif
  86920. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86921. * \ingroup flac_metadata
  86922. *
  86923. * \brief
  86924. * The level 0 interface consists of individual routines to read the
  86925. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86926. * only a filename.
  86927. *
  86928. * They try to skip any ID3v2 tag at the head of the file.
  86929. *
  86930. * \{
  86931. */
  86932. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86933. * will try to skip any ID3v2 tag at the head of the file.
  86934. *
  86935. * \param filename The path to the FLAC file to read.
  86936. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86937. * FLAC__StreamMetadata is a simple structure with no
  86938. * memory allocation involved, you pass the address of
  86939. * an existing structure. It need not be initialized.
  86940. * \assert
  86941. * \code filename != NULL \endcode
  86942. * \code streaminfo != NULL \endcode
  86943. * \retval FLAC__bool
  86944. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86945. * \c false if there was a memory allocation error, a file decoder error,
  86946. * or the file contained no STREAMINFO block. (A memory allocation error
  86947. * is possible because this function must set up a file decoder.)
  86948. */
  86949. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86950. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86951. * function will try to skip any ID3v2 tag at the head of the file.
  86952. *
  86953. * \param filename The path to the FLAC file to read.
  86954. * \param tags The address where the returned pointer will be
  86955. * stored. The \a tags object must be deleted by
  86956. * the caller using FLAC__metadata_object_delete().
  86957. * \assert
  86958. * \code filename != NULL \endcode
  86959. * \code tags != NULL \endcode
  86960. * \retval FLAC__bool
  86961. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86962. * and \a *tags will be set to the address of the metadata structure.
  86963. * Returns \c false if there was a memory allocation error, a file
  86964. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86965. * \a *tags will be set to \c NULL.
  86966. */
  86967. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86968. /** Read the CUESHEET metadata block of the given FLAC file. This
  86969. * function will try to skip any ID3v2 tag at the head of the file.
  86970. *
  86971. * \param filename The path to the FLAC file to read.
  86972. * \param cuesheet The address where the returned pointer will be
  86973. * stored. The \a cuesheet object must be deleted by
  86974. * the caller using FLAC__metadata_object_delete().
  86975. * \assert
  86976. * \code filename != NULL \endcode
  86977. * \code cuesheet != NULL \endcode
  86978. * \retval FLAC__bool
  86979. * \c true if a valid CUESHEET block was read from \a filename,
  86980. * and \a *cuesheet will be set to the address of the metadata
  86981. * structure. Returns \c false if there was a memory allocation
  86982. * error, a file decoder error, or the file contained no CUESHEET
  86983. * block, and \a *cuesheet will be set to \c NULL.
  86984. */
  86985. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86986. /** Read a PICTURE metadata block of the given FLAC file. This
  86987. * function will try to skip any ID3v2 tag at the head of the file.
  86988. * Since there can be more than one PICTURE block in a file, this
  86989. * function takes a number of parameters that act as constraints to
  86990. * the search. The PICTURE block with the largest area matching all
  86991. * the constraints will be returned, or \a *picture will be set to
  86992. * \c NULL if there was no such block.
  86993. *
  86994. * \param filename The path to the FLAC file to read.
  86995. * \param picture The address where the returned pointer will be
  86996. * stored. The \a picture object must be deleted by
  86997. * the caller using FLAC__metadata_object_delete().
  86998. * \param type The desired picture type. Use \c -1 to mean
  86999. * "any type".
  87000. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87001. * string will be matched exactly. Use \c NULL to
  87002. * mean "any MIME type".
  87003. * \param description The desired description. The string will be
  87004. * matched exactly. Use \c NULL to mean "any
  87005. * description".
  87006. * \param max_width The maximum width in pixels desired. Use
  87007. * \c (unsigned)(-1) to mean "any width".
  87008. * \param max_height The maximum height in pixels desired. Use
  87009. * \c (unsigned)(-1) to mean "any height".
  87010. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87011. * Use \c (unsigned)(-1) to mean "any depth".
  87012. * \param max_colors The maximum number of colors desired. Use
  87013. * \c (unsigned)(-1) to mean "any number of colors".
  87014. * \assert
  87015. * \code filename != NULL \endcode
  87016. * \code picture != NULL \endcode
  87017. * \retval FLAC__bool
  87018. * \c true if a valid PICTURE block was read from \a filename,
  87019. * and \a *picture will be set to the address of the metadata
  87020. * structure. Returns \c false if there was a memory allocation
  87021. * error, a file decoder error, or the file contained no PICTURE
  87022. * block, and \a *picture will be set to \c NULL.
  87023. */
  87024. 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);
  87025. /* \} */
  87026. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87027. * \ingroup flac_metadata
  87028. *
  87029. * \brief
  87030. * The level 1 interface provides read-write access to FLAC file metadata and
  87031. * operates directly on the FLAC file.
  87032. *
  87033. * The general usage of this interface is:
  87034. *
  87035. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87036. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87037. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87038. * see if the file is writable, or only read access is allowed.
  87039. * - Use FLAC__metadata_simple_iterator_next() and
  87040. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87041. * This is does not read the actual blocks themselves.
  87042. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87043. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87044. * forward from the front of the file.
  87045. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87046. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87047. * the current iterator position. The returned object is yours to modify
  87048. * and free.
  87049. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87050. * back. You must have write permission to the original file. Make sure to
  87051. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87052. * below.
  87053. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87054. * Use the object creation functions from
  87055. * \link flac_metadata_object here \endlink to generate new objects.
  87056. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87057. * currently referred to by the iterator, or replace it with padding.
  87058. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87059. * finished.
  87060. *
  87061. * \note
  87062. * The FLAC file remains open the whole time between
  87063. * FLAC__metadata_simple_iterator_init() and
  87064. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87065. * the file during this time.
  87066. *
  87067. * \note
  87068. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87069. * FLAC__StreamMetadata objects. These are managed automatically.
  87070. *
  87071. * \note
  87072. * If any of the modification functions
  87073. * (FLAC__metadata_simple_iterator_set_block(),
  87074. * FLAC__metadata_simple_iterator_delete_block(),
  87075. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87076. * you should delete the iterator as it may no longer be valid.
  87077. *
  87078. * \{
  87079. */
  87080. struct FLAC__Metadata_SimpleIterator;
  87081. /** The opaque structure definition for the level 1 iterator type.
  87082. * See the
  87083. * \link flac_metadata_level1 metadata level 1 module \endlink
  87084. * for a detailed description.
  87085. */
  87086. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87087. /** Status type for FLAC__Metadata_SimpleIterator.
  87088. *
  87089. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87090. */
  87091. typedef enum {
  87092. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87093. /**< The iterator is in the normal OK state */
  87094. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87095. /**< The data passed into a function violated the function's usage criteria */
  87096. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87097. /**< The iterator could not open the target file */
  87098. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87099. /**< The iterator could not find the FLAC signature at the start of the file */
  87100. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87101. /**< The iterator tried to write to a file that was not writable */
  87102. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87103. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87104. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87105. /**< The iterator encountered an error while reading the FLAC file */
  87106. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87107. /**< The iterator encountered an error while seeking in the FLAC file */
  87108. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87109. /**< The iterator encountered an error while writing the FLAC file */
  87110. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87111. /**< The iterator encountered an error renaming the FLAC file */
  87112. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87113. /**< The iterator encountered an error removing the temporary file */
  87114. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87115. /**< Memory allocation failed */
  87116. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87117. /**< The caller violated an assertion or an unexpected error occurred */
  87118. } FLAC__Metadata_SimpleIteratorStatus;
  87119. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87120. *
  87121. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87122. * will give the string equivalent. The contents should not be modified.
  87123. */
  87124. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87125. /** Create a new iterator instance.
  87126. *
  87127. * \retval FLAC__Metadata_SimpleIterator*
  87128. * \c NULL if there was an error allocating memory, else the new instance.
  87129. */
  87130. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87131. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87132. *
  87133. * \param iterator A pointer to an existing iterator.
  87134. * \assert
  87135. * \code iterator != NULL \endcode
  87136. */
  87137. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87138. /** Get the current status of the iterator. Call this after a function
  87139. * returns \c false to get the reason for the error. Also resets the status
  87140. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87141. *
  87142. * \param iterator A pointer to an existing iterator.
  87143. * \assert
  87144. * \code iterator != NULL \endcode
  87145. * \retval FLAC__Metadata_SimpleIteratorStatus
  87146. * The current status of the iterator.
  87147. */
  87148. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87149. /** Initialize the iterator to point to the first metadata block in the
  87150. * given FLAC file.
  87151. *
  87152. * \param iterator A pointer to an existing iterator.
  87153. * \param filename The path to the FLAC file.
  87154. * \param read_only If \c true, the FLAC file will be opened
  87155. * in read-only mode; if \c false, the FLAC
  87156. * file will be opened for edit even if no
  87157. * edits are performed.
  87158. * \param preserve_file_stats If \c true, the owner and modification
  87159. * time will be preserved even if the FLAC
  87160. * file is written to.
  87161. * \assert
  87162. * \code iterator != NULL \endcode
  87163. * \code filename != NULL \endcode
  87164. * \retval FLAC__bool
  87165. * \c false if a memory allocation error occurs, the file can't be
  87166. * opened, or another error occurs, else \c true.
  87167. */
  87168. 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);
  87169. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87170. * FLAC__metadata_simple_iterator_set_block() and
  87171. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87172. *
  87173. * \param iterator A pointer to an existing iterator.
  87174. * \assert
  87175. * \code iterator != NULL \endcode
  87176. * \retval FLAC__bool
  87177. * See above.
  87178. */
  87179. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87180. /** Moves the iterator forward one metadata block, returning \c false if
  87181. * already at the end.
  87182. *
  87183. * \param iterator A pointer to an existing initialized iterator.
  87184. * \assert
  87185. * \code iterator != NULL \endcode
  87186. * \a iterator has been successfully initialized with
  87187. * FLAC__metadata_simple_iterator_init()
  87188. * \retval FLAC__bool
  87189. * \c false if already at the last metadata block of the chain, else
  87190. * \c true.
  87191. */
  87192. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87193. /** Moves the iterator backward one metadata block, returning \c false if
  87194. * already at the beginning.
  87195. *
  87196. * \param iterator A pointer to an existing initialized iterator.
  87197. * \assert
  87198. * \code iterator != NULL \endcode
  87199. * \a iterator has been successfully initialized with
  87200. * FLAC__metadata_simple_iterator_init()
  87201. * \retval FLAC__bool
  87202. * \c false if already at the first metadata block of the chain, else
  87203. * \c true.
  87204. */
  87205. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87206. /** Returns a flag telling if the current metadata block is the last.
  87207. *
  87208. * \param iterator A pointer to an existing initialized iterator.
  87209. * \assert
  87210. * \code iterator != NULL \endcode
  87211. * \a iterator has been successfully initialized with
  87212. * FLAC__metadata_simple_iterator_init()
  87213. * \retval FLAC__bool
  87214. * \c true if the current metadata block is the last in the file,
  87215. * else \c false.
  87216. */
  87217. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87218. /** Get the offset of the metadata block at the current position. This
  87219. * avoids reading the actual block data which can save time for large
  87220. * blocks.
  87221. *
  87222. * \param iterator A pointer to an existing initialized iterator.
  87223. * \assert
  87224. * \code iterator != NULL \endcode
  87225. * \a iterator has been successfully initialized with
  87226. * FLAC__metadata_simple_iterator_init()
  87227. * \retval off_t
  87228. * The offset of the metadata block at the current iterator position.
  87229. * This is the byte offset relative to the beginning of the file of
  87230. * the current metadata block's header.
  87231. */
  87232. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87233. /** Get the type of the metadata block at the current position. This
  87234. * avoids reading the actual block data which can save time for large
  87235. * blocks.
  87236. *
  87237. * \param iterator A pointer to an existing initialized iterator.
  87238. * \assert
  87239. * \code iterator != NULL \endcode
  87240. * \a iterator has been successfully initialized with
  87241. * FLAC__metadata_simple_iterator_init()
  87242. * \retval FLAC__MetadataType
  87243. * The type of the metadata block at the current iterator position.
  87244. */
  87245. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87246. /** Get the length of the metadata block at the current position. This
  87247. * avoids reading the actual block data which can save time for large
  87248. * blocks.
  87249. *
  87250. * \param iterator A pointer to an existing initialized iterator.
  87251. * \assert
  87252. * \code iterator != NULL \endcode
  87253. * \a iterator has been successfully initialized with
  87254. * FLAC__metadata_simple_iterator_init()
  87255. * \retval unsigned
  87256. * The length of the metadata block at the current iterator position.
  87257. * The is same length as that in the
  87258. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87259. * i.e. the length of the metadata body that follows the header.
  87260. */
  87261. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87262. /** Get the application ID of the \c APPLICATION block at the current
  87263. * position. This avoids reading the actual block data which can save
  87264. * time for large blocks.
  87265. *
  87266. * \param iterator A pointer to an existing initialized iterator.
  87267. * \param id A pointer to a buffer of at least \c 4 bytes where
  87268. * the ID will be stored.
  87269. * \assert
  87270. * \code iterator != NULL \endcode
  87271. * \code id != NULL \endcode
  87272. * \a iterator has been successfully initialized with
  87273. * FLAC__metadata_simple_iterator_init()
  87274. * \retval FLAC__bool
  87275. * \c true if the ID was successfully read, else \c false, in which
  87276. * case you should check FLAC__metadata_simple_iterator_status() to
  87277. * find out why. If the status is
  87278. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87279. * current metadata block is not an \c APPLICATION block. Otherwise
  87280. * if the status is
  87281. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87282. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87283. * occurred and the iterator can no longer be used.
  87284. */
  87285. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87286. /** Get the metadata block at the current position. You can modify the
  87287. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87288. * write it back to the FLAC file.
  87289. *
  87290. * You must call FLAC__metadata_object_delete() on the returned object
  87291. * when you are finished with it.
  87292. *
  87293. * \param iterator A pointer to an existing initialized iterator.
  87294. * \assert
  87295. * \code iterator != NULL \endcode
  87296. * \a iterator has been successfully initialized with
  87297. * FLAC__metadata_simple_iterator_init()
  87298. * \retval FLAC__StreamMetadata*
  87299. * The current metadata block, or \c NULL if there was a memory
  87300. * allocation error.
  87301. */
  87302. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87303. /** Write a block back to the FLAC file. This function tries to be
  87304. * as efficient as possible; how the block is actually written is
  87305. * shown by the following:
  87306. *
  87307. * Existing block is a STREAMINFO block and the new block is a
  87308. * STREAMINFO block: the new block is written in place. Make sure
  87309. * you know what you're doing when changing the values of a
  87310. * STREAMINFO block.
  87311. *
  87312. * Existing block is a STREAMINFO block and the new block is a
  87313. * not a STREAMINFO block: this is an error since the first block
  87314. * must be a STREAMINFO block. Returns \c false without altering the
  87315. * file.
  87316. *
  87317. * Existing block is not a STREAMINFO block and the new block is a
  87318. * STREAMINFO block: this is an error since there may be only one
  87319. * STREAMINFO block. Returns \c false without altering the file.
  87320. *
  87321. * Existing block and new block are the same length: the existing
  87322. * block will be replaced by the new block, written in place.
  87323. *
  87324. * Existing block is longer than new block: if use_padding is \c true,
  87325. * the existing block will be overwritten in place with the new
  87326. * block followed by a PADDING block, if possible, to make the total
  87327. * size the same as the existing block. Remember that a padding
  87328. * block requires at least four bytes so if the difference in size
  87329. * between the new block and existing block is less than that, the
  87330. * entire file will have to be rewritten, using the new block's
  87331. * exact size. If use_padding is \c false, the entire file will be
  87332. * rewritten, replacing the existing block by the new block.
  87333. *
  87334. * Existing block is shorter than new block: if use_padding is \c true,
  87335. * the function will try and expand the new block into the following
  87336. * PADDING block, if it exists and doing so won't shrink the PADDING
  87337. * block to less than 4 bytes. If there is no following PADDING
  87338. * block, or it will shrink to less than 4 bytes, or use_padding is
  87339. * \c false, the entire file is rewritten, replacing the existing block
  87340. * with the new block. Note that in this case any following PADDING
  87341. * block is preserved as is.
  87342. *
  87343. * After writing the block, the iterator will remain in the same
  87344. * place, i.e. pointing to the new block.
  87345. *
  87346. * \param iterator A pointer to an existing initialized iterator.
  87347. * \param block The block to set.
  87348. * \param use_padding See above.
  87349. * \assert
  87350. * \code iterator != NULL \endcode
  87351. * \a iterator has been successfully initialized with
  87352. * FLAC__metadata_simple_iterator_init()
  87353. * \code block != NULL \endcode
  87354. * \retval FLAC__bool
  87355. * \c true if successful, else \c false.
  87356. */
  87357. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87358. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87359. * except that instead of writing over an existing block, it appends
  87360. * a block after the existing block. \a use_padding is again used to
  87361. * tell the function to try an expand into following padding in an
  87362. * attempt to avoid rewriting the entire file.
  87363. *
  87364. * This function will fail and return \c false if given a STREAMINFO
  87365. * block.
  87366. *
  87367. * After writing the block, the iterator will be pointing to the
  87368. * new block.
  87369. *
  87370. * \param iterator A pointer to an existing initialized iterator.
  87371. * \param block The block to set.
  87372. * \param use_padding See above.
  87373. * \assert
  87374. * \code iterator != NULL \endcode
  87375. * \a iterator has been successfully initialized with
  87376. * FLAC__metadata_simple_iterator_init()
  87377. * \code block != NULL \endcode
  87378. * \retval FLAC__bool
  87379. * \c true if successful, else \c false.
  87380. */
  87381. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87382. /** Deletes the block at the current position. This will cause the
  87383. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87384. * in which case the block will be replaced by an equal-sized PADDING
  87385. * block. The iterator will be left pointing to the block before the
  87386. * one just deleted.
  87387. *
  87388. * You may not delete the STREAMINFO block.
  87389. *
  87390. * \param iterator A pointer to an existing initialized iterator.
  87391. * \param use_padding See above.
  87392. * \assert
  87393. * \code iterator != NULL \endcode
  87394. * \a iterator has been successfully initialized with
  87395. * FLAC__metadata_simple_iterator_init()
  87396. * \retval FLAC__bool
  87397. * \c true if successful, else \c false.
  87398. */
  87399. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87400. /* \} */
  87401. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87402. * \ingroup flac_metadata
  87403. *
  87404. * \brief
  87405. * The level 2 interface provides read-write access to FLAC file metadata;
  87406. * all metadata is read into memory, operated on in memory, and then written
  87407. * to file, which is more efficient than level 1 when editing multiple blocks.
  87408. *
  87409. * Currently Ogg FLAC is supported for read only, via
  87410. * FLAC__metadata_chain_read_ogg() but a subsequent
  87411. * FLAC__metadata_chain_write() will fail.
  87412. *
  87413. * The general usage of this interface is:
  87414. *
  87415. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87416. * linked list of FLAC metadata blocks.
  87417. * - Read all metadata into the the chain from a FLAC file using
  87418. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87419. * check the status.
  87420. * - Optionally, consolidate the padding using
  87421. * FLAC__metadata_chain_merge_padding() or
  87422. * FLAC__metadata_chain_sort_padding().
  87423. * - Create a new iterator using FLAC__metadata_iterator_new()
  87424. * - Initialize the iterator to point to the first element in the chain
  87425. * using FLAC__metadata_iterator_init()
  87426. * - Traverse the chain using FLAC__metadata_iterator_next and
  87427. * FLAC__metadata_iterator_prev().
  87428. * - Get a block for reading or modification using
  87429. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87430. * inside the chain is returned, so the block is yours to modify.
  87431. * Changes will be reflected in the FLAC file when you write the
  87432. * chain. You can also add and delete blocks (see functions below).
  87433. * - When done, write out the chain using FLAC__metadata_chain_write().
  87434. * Make sure to read the whole comment to the function below.
  87435. * - Delete the chain using FLAC__metadata_chain_delete().
  87436. *
  87437. * \note
  87438. * Even though the FLAC file is not open while the chain is being
  87439. * manipulated, you must not alter the file externally during
  87440. * this time. The chain assumes the FLAC file will not change
  87441. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87442. * and FLAC__metadata_chain_write().
  87443. *
  87444. * \note
  87445. * Do not modify the is_last, length, or type fields of returned
  87446. * FLAC__StreamMetadata objects. These are managed automatically.
  87447. *
  87448. * \note
  87449. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87450. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87451. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87452. * become owned by the chain and they will be deleted when the chain is
  87453. * deleted.
  87454. *
  87455. * \{
  87456. */
  87457. struct FLAC__Metadata_Chain;
  87458. /** The opaque structure definition for the level 2 chain type.
  87459. */
  87460. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87461. struct FLAC__Metadata_Iterator;
  87462. /** The opaque structure definition for the level 2 iterator type.
  87463. */
  87464. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87465. typedef enum {
  87466. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87467. /**< The chain is in the normal OK state */
  87468. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87469. /**< The data passed into a function violated the function's usage criteria */
  87470. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87471. /**< The chain could not open the target file */
  87472. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87473. /**< The chain could not find the FLAC signature at the start of the file */
  87474. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87475. /**< The chain tried to write to a file that was not writable */
  87476. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87477. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87478. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87479. /**< The chain encountered an error while reading the FLAC file */
  87480. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87481. /**< The chain encountered an error while seeking in the FLAC file */
  87482. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87483. /**< The chain encountered an error while writing the FLAC file */
  87484. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87485. /**< The chain encountered an error renaming the FLAC file */
  87486. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87487. /**< The chain encountered an error removing the temporary file */
  87488. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87489. /**< Memory allocation failed */
  87490. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87491. /**< The caller violated an assertion or an unexpected error occurred */
  87492. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87493. /**< One or more of the required callbacks was NULL */
  87494. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87495. /**< FLAC__metadata_chain_write() was called on a chain read by
  87496. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87497. * or
  87498. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87499. * was called on a chain read by
  87500. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87501. * Matching read/write methods must always be used. */
  87502. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87503. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87504. * chain write requires a tempfile; use
  87505. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87506. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87507. * called when the chain write does not require a tempfile; use
  87508. * FLAC__metadata_chain_write_with_callbacks() instead.
  87509. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87510. * before writing via callbacks. */
  87511. } FLAC__Metadata_ChainStatus;
  87512. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87513. *
  87514. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87515. * will give the string equivalent. The contents should not be modified.
  87516. */
  87517. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87518. /*********** FLAC__Metadata_Chain ***********/
  87519. /** Create a new chain instance.
  87520. *
  87521. * \retval FLAC__Metadata_Chain*
  87522. * \c NULL if there was an error allocating memory, else the new instance.
  87523. */
  87524. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87525. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87526. *
  87527. * \param chain A pointer to an existing chain.
  87528. * \assert
  87529. * \code chain != NULL \endcode
  87530. */
  87531. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87532. /** Get the current status of the chain. Call this after a function
  87533. * returns \c false to get the reason for the error. Also resets the
  87534. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87535. *
  87536. * \param chain A pointer to an existing chain.
  87537. * \assert
  87538. * \code chain != NULL \endcode
  87539. * \retval FLAC__Metadata_ChainStatus
  87540. * The current status of the chain.
  87541. */
  87542. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87543. /** Read all metadata from a FLAC file into the chain.
  87544. *
  87545. * \param chain A pointer to an existing chain.
  87546. * \param filename The path to the FLAC file to read.
  87547. * \assert
  87548. * \code chain != NULL \endcode
  87549. * \code filename != NULL \endcode
  87550. * \retval FLAC__bool
  87551. * \c true if a valid list of metadata blocks was read from
  87552. * \a filename, else \c false. On failure, check the status with
  87553. * FLAC__metadata_chain_status().
  87554. */
  87555. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87556. /** Read all metadata from an Ogg FLAC file into the chain.
  87557. *
  87558. * \note Ogg FLAC metadata data writing is not supported yet and
  87559. * FLAC__metadata_chain_write() will fail.
  87560. *
  87561. * \param chain A pointer to an existing chain.
  87562. * \param filename The path to the Ogg FLAC file to read.
  87563. * \assert
  87564. * \code chain != NULL \endcode
  87565. * \code filename != NULL \endcode
  87566. * \retval FLAC__bool
  87567. * \c true if a valid list of metadata blocks was read from
  87568. * \a filename, else \c false. On failure, check the status with
  87569. * FLAC__metadata_chain_status().
  87570. */
  87571. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87572. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87573. *
  87574. * The \a handle need only be open for reading, but must be seekable.
  87575. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87576. * for Windows).
  87577. *
  87578. * \param chain A pointer to an existing chain.
  87579. * \param handle The I/O handle of the FLAC stream to read. The
  87580. * handle will NOT be closed after the metadata is read;
  87581. * that is the duty of the caller.
  87582. * \param callbacks
  87583. * A set of callbacks to use for I/O. The mandatory
  87584. * callbacks are \a read, \a seek, and \a tell.
  87585. * \assert
  87586. * \code chain != NULL \endcode
  87587. * \retval FLAC__bool
  87588. * \c true if a valid list of metadata blocks was read from
  87589. * \a handle, else \c false. On failure, check the status with
  87590. * FLAC__metadata_chain_status().
  87591. */
  87592. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87593. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87594. *
  87595. * The \a handle need only be open for reading, but must be seekable.
  87596. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87597. * for Windows).
  87598. *
  87599. * \note Ogg FLAC metadata data writing is not supported yet and
  87600. * FLAC__metadata_chain_write() will fail.
  87601. *
  87602. * \param chain A pointer to an existing chain.
  87603. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87604. * handle will NOT be closed after the metadata is read;
  87605. * that is the duty of the caller.
  87606. * \param callbacks
  87607. * A set of callbacks to use for I/O. The mandatory
  87608. * callbacks are \a read, \a seek, and \a tell.
  87609. * \assert
  87610. * \code chain != NULL \endcode
  87611. * \retval FLAC__bool
  87612. * \c true if a valid list of metadata blocks was read from
  87613. * \a handle, else \c false. On failure, check the status with
  87614. * FLAC__metadata_chain_status().
  87615. */
  87616. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87617. /** Checks if writing the given chain would require the use of a
  87618. * temporary file, or if it could be written in place.
  87619. *
  87620. * Under certain conditions, padding can be utilized so that writing
  87621. * edited metadata back to the FLAC file does not require rewriting the
  87622. * entire file. If rewriting is required, then a temporary workfile is
  87623. * required. When writing metadata using callbacks, you must check
  87624. * this function to know whether to call
  87625. * FLAC__metadata_chain_write_with_callbacks() or
  87626. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87627. * writing with FLAC__metadata_chain_write(), the temporary file is
  87628. * handled internally.
  87629. *
  87630. * \param chain A pointer to an existing chain.
  87631. * \param use_padding
  87632. * Whether or not padding will be allowed to be used
  87633. * during the write. The value of \a use_padding given
  87634. * here must match the value later passed to
  87635. * FLAC__metadata_chain_write_with_callbacks() or
  87636. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87637. * \assert
  87638. * \code chain != NULL \endcode
  87639. * \retval FLAC__bool
  87640. * \c true if writing the current chain would require a tempfile, or
  87641. * \c false if metadata can be written in place.
  87642. */
  87643. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87644. /** Write all metadata out to the FLAC file. This function tries to be as
  87645. * efficient as possible; how the metadata is actually written is shown by
  87646. * the following:
  87647. *
  87648. * If the current chain is the same size as the existing metadata, the new
  87649. * data is written in place.
  87650. *
  87651. * If the current chain is longer than the existing metadata, and
  87652. * \a use_padding is \c true, and the last block is a PADDING block of
  87653. * sufficient length, the function will truncate the final padding block
  87654. * so that the overall size of the metadata is the same as the existing
  87655. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87656. * the above conditions are met, the entire FLAC file must be rewritten.
  87657. * If you want to use padding this way it is a good idea to call
  87658. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87659. * amount of padding to work with, unless you need to preserve ordering
  87660. * of the PADDING blocks for some reason.
  87661. *
  87662. * If the current chain is shorter than the existing metadata, and
  87663. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87664. * is extended to make the overall size the same as the existing data. If
  87665. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87666. * PADDING block is added to the end of the new data to make it the same
  87667. * size as the existing data (if possible, see the note to
  87668. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87669. * and the new data is written in place. If none of the above apply or
  87670. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87671. *
  87672. * If \a preserve_file_stats is \c true, the owner and modification time will
  87673. * be preserved even if the FLAC file is written.
  87674. *
  87675. * For this write function to be used, the chain must have been read with
  87676. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87677. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87678. *
  87679. * \param chain A pointer to an existing chain.
  87680. * \param use_padding See above.
  87681. * \param preserve_file_stats See above.
  87682. * \assert
  87683. * \code chain != NULL \endcode
  87684. * \retval FLAC__bool
  87685. * \c true if the write succeeded, else \c false. On failure,
  87686. * check the status with FLAC__metadata_chain_status().
  87687. */
  87688. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87689. /** Write all metadata out to a FLAC stream via callbacks.
  87690. *
  87691. * (See FLAC__metadata_chain_write() for the details on how padding is
  87692. * used to write metadata in place if possible.)
  87693. *
  87694. * The \a handle must be open for updating and be seekable. The
  87695. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87696. * for Windows).
  87697. *
  87698. * For this write function to be used, the chain must have been read with
  87699. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87700. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87701. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87702. * \c false.
  87703. *
  87704. * \param chain A pointer to an existing chain.
  87705. * \param use_padding See FLAC__metadata_chain_write()
  87706. * \param handle The I/O handle of the FLAC stream to write. The
  87707. * handle will NOT be closed after the metadata is
  87708. * written; that is the duty of the caller.
  87709. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87710. * callbacks are \a write and \a seek.
  87711. * \assert
  87712. * \code chain != NULL \endcode
  87713. * \retval FLAC__bool
  87714. * \c true if the write succeeded, else \c false. On failure,
  87715. * check the status with FLAC__metadata_chain_status().
  87716. */
  87717. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87718. /** Write all metadata out to a FLAC stream via callbacks.
  87719. *
  87720. * (See FLAC__metadata_chain_write() for the details on how padding is
  87721. * used to write metadata in place if possible.)
  87722. *
  87723. * This version of the write-with-callbacks function must be used when
  87724. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87725. * this function, you must supply an I/O handle corresponding to the
  87726. * FLAC file to edit, and a temporary handle to which the new FLAC
  87727. * file will be written. It is the caller's job to move this temporary
  87728. * FLAC file on top of the original FLAC file to complete the metadata
  87729. * edit.
  87730. *
  87731. * The \a handle must be open for reading and be seekable. The
  87732. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87733. * for Windows).
  87734. *
  87735. * The \a temp_handle must be open for writing. The
  87736. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87737. * for Windows). It should be an empty stream, or at least positioned
  87738. * at the start-of-file (in which case it is the caller's duty to
  87739. * truncate it on return).
  87740. *
  87741. * For this write function to be used, the chain must have been read with
  87742. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87743. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87744. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87745. * \c true.
  87746. *
  87747. * \param chain A pointer to an existing chain.
  87748. * \param use_padding See FLAC__metadata_chain_write()
  87749. * \param handle The I/O handle of the original FLAC stream to read.
  87750. * The handle will NOT be closed after the metadata is
  87751. * written; that is the duty of the caller.
  87752. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87753. * The mandatory callbacks are \a read, \a seek, and
  87754. * \a eof.
  87755. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87756. * handle will NOT be closed after the metadata is
  87757. * written; that is the duty of the caller.
  87758. * \param temp_callbacks
  87759. * A set of callbacks to use for I/O on temp_handle.
  87760. * The only mandatory callback is \a write.
  87761. * \assert
  87762. * \code chain != NULL \endcode
  87763. * \retval FLAC__bool
  87764. * \c true if the write succeeded, else \c false. On failure,
  87765. * check the status with FLAC__metadata_chain_status().
  87766. */
  87767. 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);
  87768. /** Merge adjacent PADDING blocks into a single block.
  87769. *
  87770. * \note This function does not write to the FLAC file, it only
  87771. * modifies the chain.
  87772. *
  87773. * \warning Any iterator on the current chain will become invalid after this
  87774. * call. You should delete the iterator and get a new one.
  87775. *
  87776. * \param chain A pointer to an existing chain.
  87777. * \assert
  87778. * \code chain != NULL \endcode
  87779. */
  87780. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87781. /** This function will move all PADDING blocks to the end on the metadata,
  87782. * then merge them into a single block.
  87783. *
  87784. * \note This function does not write to the FLAC file, it only
  87785. * modifies the chain.
  87786. *
  87787. * \warning Any iterator on the current chain will become invalid after this
  87788. * call. You should delete the iterator and get a new one.
  87789. *
  87790. * \param chain A pointer to an existing chain.
  87791. * \assert
  87792. * \code chain != NULL \endcode
  87793. */
  87794. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87795. /*********** FLAC__Metadata_Iterator ***********/
  87796. /** Create a new iterator instance.
  87797. *
  87798. * \retval FLAC__Metadata_Iterator*
  87799. * \c NULL if there was an error allocating memory, else the new instance.
  87800. */
  87801. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87802. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87803. *
  87804. * \param iterator A pointer to an existing iterator.
  87805. * \assert
  87806. * \code iterator != NULL \endcode
  87807. */
  87808. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87809. /** Initialize the iterator to point to the first metadata block in the
  87810. * given chain.
  87811. *
  87812. * \param iterator A pointer to an existing iterator.
  87813. * \param chain A pointer to an existing and initialized (read) chain.
  87814. * \assert
  87815. * \code iterator != NULL \endcode
  87816. * \code chain != NULL \endcode
  87817. */
  87818. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87819. /** Moves the iterator forward one metadata block, returning \c false if
  87820. * already at the end.
  87821. *
  87822. * \param iterator A pointer to an existing initialized iterator.
  87823. * \assert
  87824. * \code iterator != NULL \endcode
  87825. * \a iterator has been successfully initialized with
  87826. * FLAC__metadata_iterator_init()
  87827. * \retval FLAC__bool
  87828. * \c false if already at the last metadata block of the chain, else
  87829. * \c true.
  87830. */
  87831. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87832. /** Moves the iterator backward one metadata block, returning \c false if
  87833. * already at the beginning.
  87834. *
  87835. * \param iterator A pointer to an existing initialized iterator.
  87836. * \assert
  87837. * \code iterator != NULL \endcode
  87838. * \a iterator has been successfully initialized with
  87839. * FLAC__metadata_iterator_init()
  87840. * \retval FLAC__bool
  87841. * \c false if already at the first metadata block of the chain, else
  87842. * \c true.
  87843. */
  87844. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87845. /** Get the type of the metadata block at the current position.
  87846. *
  87847. * \param iterator A pointer to an existing initialized iterator.
  87848. * \assert
  87849. * \code iterator != NULL \endcode
  87850. * \a iterator has been successfully initialized with
  87851. * FLAC__metadata_iterator_init()
  87852. * \retval FLAC__MetadataType
  87853. * The type of the metadata block at the current iterator position.
  87854. */
  87855. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87856. /** Get the metadata block at the current position. You can modify
  87857. * the block in place but must write the chain before the changes
  87858. * are reflected to the FLAC file. You do not need to call
  87859. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87860. * the pointer returned by FLAC__metadata_iterator_get_block()
  87861. * points directly into the chain.
  87862. *
  87863. * \warning
  87864. * Do not call FLAC__metadata_object_delete() on the returned object;
  87865. * to delete a block use FLAC__metadata_iterator_delete_block().
  87866. *
  87867. * \param iterator A pointer to an existing initialized iterator.
  87868. * \assert
  87869. * \code iterator != NULL \endcode
  87870. * \a iterator has been successfully initialized with
  87871. * FLAC__metadata_iterator_init()
  87872. * \retval FLAC__StreamMetadata*
  87873. * The current metadata block.
  87874. */
  87875. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87876. /** Set the metadata block at the current position, replacing the existing
  87877. * block. The new block passed in becomes owned by the chain and it will be
  87878. * deleted when the chain is deleted.
  87879. *
  87880. * \param iterator A pointer to an existing initialized iterator.
  87881. * \param block A pointer to a metadata block.
  87882. * \assert
  87883. * \code iterator != NULL \endcode
  87884. * \a iterator has been successfully initialized with
  87885. * FLAC__metadata_iterator_init()
  87886. * \code block != NULL \endcode
  87887. * \retval FLAC__bool
  87888. * \c false if the conditions in the above description are not met, or
  87889. * a memory allocation error occurs, otherwise \c true.
  87890. */
  87891. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87892. /** Removes the current block from the chain. If \a replace_with_padding is
  87893. * \c true, the block will instead be replaced with a padding block of equal
  87894. * size. You can not delete the STREAMINFO block. The iterator will be
  87895. * left pointing to the block before the one just "deleted", even if
  87896. * \a replace_with_padding is \c true.
  87897. *
  87898. * \param iterator A pointer to an existing initialized iterator.
  87899. * \param replace_with_padding See above.
  87900. * \assert
  87901. * \code iterator != NULL \endcode
  87902. * \a iterator has been successfully initialized with
  87903. * FLAC__metadata_iterator_init()
  87904. * \retval FLAC__bool
  87905. * \c false if the conditions in the above description are not met,
  87906. * otherwise \c true.
  87907. */
  87908. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87909. /** Insert a new block before the current block. You cannot insert a block
  87910. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87911. * as there can be only one, the one that already exists at the head when you
  87912. * read in a chain. The chain takes ownership of the new block and it will be
  87913. * deleted when the chain is deleted. The iterator will be left pointing to
  87914. * the new block.
  87915. *
  87916. * \param iterator A pointer to an existing initialized iterator.
  87917. * \param block A pointer to a metadata block to insert.
  87918. * \assert
  87919. * \code iterator != NULL \endcode
  87920. * \a iterator has been successfully initialized with
  87921. * FLAC__metadata_iterator_init()
  87922. * \retval FLAC__bool
  87923. * \c false if the conditions in the above description are not met, or
  87924. * a memory allocation error occurs, otherwise \c true.
  87925. */
  87926. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87927. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87928. * block as there can be only one, the one that already exists at the head when
  87929. * you read in a chain. The chain takes ownership of the new block and it will
  87930. * be deleted when the chain is deleted. The iterator will be left pointing to
  87931. * the new block.
  87932. *
  87933. * \param iterator A pointer to an existing initialized iterator.
  87934. * \param block A pointer to a metadata block to insert.
  87935. * \assert
  87936. * \code iterator != NULL \endcode
  87937. * \a iterator has been successfully initialized with
  87938. * FLAC__metadata_iterator_init()
  87939. * \retval FLAC__bool
  87940. * \c false if the conditions in the above description are not met, or
  87941. * a memory allocation error occurs, otherwise \c true.
  87942. */
  87943. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87944. /* \} */
  87945. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87946. * \ingroup flac_metadata
  87947. *
  87948. * \brief
  87949. * This module contains methods for manipulating FLAC metadata objects.
  87950. *
  87951. * Since many are variable length we have to be careful about the memory
  87952. * management. We decree that all pointers to data in the object are
  87953. * owned by the object and memory-managed by the object.
  87954. *
  87955. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87956. * functions to create all instances. When using the
  87957. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87958. * \a copy to \c true to have the function make it's own copy of the data, or
  87959. * to \c false to give the object ownership of your data. In the latter case
  87960. * your pointer must be freeable by free() and will be free()d when the object
  87961. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87962. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87963. * the length argument is 0 and the \a copy argument is \c false.
  87964. *
  87965. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87966. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87967. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87968. * case of a memory allocation error.
  87969. *
  87970. * We don't have the convenience of C++ here, so note that the library relies
  87971. * on you to keep the types straight. In other words, if you pass, for
  87972. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87973. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87974. * failure.
  87975. *
  87976. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87977. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87978. * toward the length or stored in the stream, but it can make working with plain
  87979. * comments (those that don't contain embedded-NULs in the value) easier.
  87980. * Entries passed into these functions have trailing NULs added if missing, and
  87981. * returned entries are guaranteed to have a trailing NUL.
  87982. *
  87983. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87984. * comment entry/name/value will first validate that it complies with the Vorbis
  87985. * comment specification and return false if it does not.
  87986. *
  87987. * There is no need to recalculate the length field on metadata blocks you
  87988. * have modified. They will be calculated automatically before they are
  87989. * written back to a file.
  87990. *
  87991. * \{
  87992. */
  87993. /** Create a new metadata object instance of the given type.
  87994. *
  87995. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87996. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87997. * the vendor string set (but zero comments).
  87998. *
  87999. * Do not pass in a value greater than or equal to
  88000. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88001. * doing.
  88002. *
  88003. * \param type Type of object to create
  88004. * \retval FLAC__StreamMetadata*
  88005. * \c NULL if there was an error allocating memory or the type code is
  88006. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88007. */
  88008. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88009. /** Create a copy of an existing metadata object.
  88010. *
  88011. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88012. * object is also copied. The caller takes ownership of the new block and
  88013. * is responsible for freeing it with FLAC__metadata_object_delete().
  88014. *
  88015. * \param object Pointer to object to copy.
  88016. * \assert
  88017. * \code object != NULL \endcode
  88018. * \retval FLAC__StreamMetadata*
  88019. * \c NULL if there was an error allocating memory, else the new instance.
  88020. */
  88021. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88022. /** Free a metadata object. Deletes the object pointed to by \a object.
  88023. *
  88024. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88025. * object is also deleted.
  88026. *
  88027. * \param object A pointer to an existing object.
  88028. * \assert
  88029. * \code object != NULL \endcode
  88030. */
  88031. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88032. /** Compares two metadata objects.
  88033. *
  88034. * The compare is "deep", i.e. dynamically allocated data within the
  88035. * object is also compared.
  88036. *
  88037. * \param block1 A pointer to an existing object.
  88038. * \param block2 A pointer to an existing object.
  88039. * \assert
  88040. * \code block1 != NULL \endcode
  88041. * \code block2 != NULL \endcode
  88042. * \retval FLAC__bool
  88043. * \c true if objects are identical, else \c false.
  88044. */
  88045. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88046. /** Sets the application data of an APPLICATION block.
  88047. *
  88048. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88049. * takes ownership of the pointer. The existing data will be freed if this
  88050. * function is successful, otherwise the original data will remain if \a copy
  88051. * is \c true and malloc() fails.
  88052. *
  88053. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88054. *
  88055. * \param object A pointer to an existing APPLICATION object.
  88056. * \param data A pointer to the data to set.
  88057. * \param length The length of \a data in bytes.
  88058. * \param copy See above.
  88059. * \assert
  88060. * \code object != NULL \endcode
  88061. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88062. * \code (data != NULL && length > 0) ||
  88063. * (data == NULL && length == 0 && copy == false) \endcode
  88064. * \retval FLAC__bool
  88065. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88066. */
  88067. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88068. /** Resize the seekpoint array.
  88069. *
  88070. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88071. * points will be added to the end.
  88072. *
  88073. * \param object A pointer to an existing SEEKTABLE object.
  88074. * \param new_num_points The desired length of the array; may be \c 0.
  88075. * \assert
  88076. * \code object != NULL \endcode
  88077. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88078. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88079. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88080. * \retval FLAC__bool
  88081. * \c false if memory allocation error, else \c true.
  88082. */
  88083. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88084. /** Set a seekpoint in a seektable.
  88085. *
  88086. * \param object A pointer to an existing SEEKTABLE object.
  88087. * \param point_num Index into seekpoint array to set.
  88088. * \param point The point to set.
  88089. * \assert
  88090. * \code object != NULL \endcode
  88091. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88092. * \code object->data.seek_table.num_points > point_num \endcode
  88093. */
  88094. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88095. /** Insert a seekpoint into a seektable.
  88096. *
  88097. * \param object A pointer to an existing SEEKTABLE object.
  88098. * \param point_num Index into seekpoint array to set.
  88099. * \param point The point to set.
  88100. * \assert
  88101. * \code object != NULL \endcode
  88102. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88103. * \code object->data.seek_table.num_points >= point_num \endcode
  88104. * \retval FLAC__bool
  88105. * \c false if memory allocation error, else \c true.
  88106. */
  88107. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88108. /** Delete a seekpoint from a seektable.
  88109. *
  88110. * \param object A pointer to an existing SEEKTABLE object.
  88111. * \param point_num Index into seekpoint array to set.
  88112. * \assert
  88113. * \code object != NULL \endcode
  88114. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88115. * \code object->data.seek_table.num_points > point_num \endcode
  88116. * \retval FLAC__bool
  88117. * \c false if memory allocation error, else \c true.
  88118. */
  88119. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88120. /** Check a seektable to see if it conforms to the FLAC specification.
  88121. * See the format specification for limits on the contents of the
  88122. * seektable.
  88123. *
  88124. * \param object A pointer to an existing SEEKTABLE object.
  88125. * \assert
  88126. * \code object != NULL \endcode
  88127. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88128. * \retval FLAC__bool
  88129. * \c false if seek table is illegal, else \c true.
  88130. */
  88131. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88132. /** Append a number of placeholder points to the end of a seek table.
  88133. *
  88134. * \note
  88135. * As with the other ..._seektable_template_... functions, you should
  88136. * call FLAC__metadata_object_seektable_template_sort() when finished
  88137. * to make the seek table legal.
  88138. *
  88139. * \param object A pointer to an existing SEEKTABLE object.
  88140. * \param num The number of placeholder points to append.
  88141. * \assert
  88142. * \code object != NULL \endcode
  88143. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88144. * \retval FLAC__bool
  88145. * \c false if memory allocation fails, else \c true.
  88146. */
  88147. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88148. /** Append a specific seek point template to the end of a seek table.
  88149. *
  88150. * \note
  88151. * As with the other ..._seektable_template_... functions, you should
  88152. * call FLAC__metadata_object_seektable_template_sort() when finished
  88153. * to make the seek table legal.
  88154. *
  88155. * \param object A pointer to an existing SEEKTABLE object.
  88156. * \param sample_number The sample number of the seek point template.
  88157. * \assert
  88158. * \code object != NULL \endcode
  88159. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88160. * \retval FLAC__bool
  88161. * \c false if memory allocation fails, else \c true.
  88162. */
  88163. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88164. /** Append specific seek point templates to the end of a seek table.
  88165. *
  88166. * \note
  88167. * As with the other ..._seektable_template_... functions, you should
  88168. * call FLAC__metadata_object_seektable_template_sort() when finished
  88169. * to make the seek table legal.
  88170. *
  88171. * \param object A pointer to an existing SEEKTABLE object.
  88172. * \param sample_numbers An array of sample numbers for the seek points.
  88173. * \param num The number of seek point templates to append.
  88174. * \assert
  88175. * \code object != NULL \endcode
  88176. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88177. * \retval FLAC__bool
  88178. * \c false if memory allocation fails, else \c true.
  88179. */
  88180. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88181. /** Append a set of evenly-spaced seek point templates to the end of a
  88182. * seek table.
  88183. *
  88184. * \note
  88185. * As with the other ..._seektable_template_... functions, you should
  88186. * call FLAC__metadata_object_seektable_template_sort() when finished
  88187. * to make the seek table legal.
  88188. *
  88189. * \param object A pointer to an existing SEEKTABLE object.
  88190. * \param num The number of placeholder points to append.
  88191. * \param total_samples The total number of samples to be encoded;
  88192. * the seekpoints will be spaced approximately
  88193. * \a total_samples / \a num samples apart.
  88194. * \assert
  88195. * \code object != NULL \endcode
  88196. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88197. * \code total_samples > 0 \endcode
  88198. * \retval FLAC__bool
  88199. * \c false if memory allocation fails, else \c true.
  88200. */
  88201. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88202. /** Append a set of evenly-spaced seek point templates to the end of a
  88203. * seek table.
  88204. *
  88205. * \note
  88206. * As with the other ..._seektable_template_... functions, you should
  88207. * call FLAC__metadata_object_seektable_template_sort() when finished
  88208. * to make the seek table legal.
  88209. *
  88210. * \param object A pointer to an existing SEEKTABLE object.
  88211. * \param samples The number of samples apart to space the placeholder
  88212. * points. The first point will be at sample \c 0, the
  88213. * second at sample \a samples, then 2*\a samples, and
  88214. * so on. As long as \a samples and \a total_samples
  88215. * are greater than \c 0, there will always be at least
  88216. * one seekpoint at sample \c 0.
  88217. * \param total_samples The total number of samples to be encoded;
  88218. * the seekpoints will be spaced
  88219. * \a samples samples apart.
  88220. * \assert
  88221. * \code object != NULL \endcode
  88222. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88223. * \code samples > 0 \endcode
  88224. * \code total_samples > 0 \endcode
  88225. * \retval FLAC__bool
  88226. * \c false if memory allocation fails, else \c true.
  88227. */
  88228. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88229. /** Sort a seek table's seek points according to the format specification,
  88230. * removing duplicates.
  88231. *
  88232. * \param object A pointer to a seek table to be sorted.
  88233. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88234. * If \c true, duplicates are deleted and the seek table is
  88235. * shrunk appropriately; the number of placeholder points
  88236. * present in the seek table will be the same after the call
  88237. * as before.
  88238. * \assert
  88239. * \code object != NULL \endcode
  88240. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88241. * \retval FLAC__bool
  88242. * \c false if realloc() fails, else \c true.
  88243. */
  88244. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88245. /** Sets the vendor string in a VORBIS_COMMENT block.
  88246. *
  88247. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88248. * one already.
  88249. *
  88250. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88251. * takes ownership of the \c entry.entry pointer.
  88252. *
  88253. * \note If this function returns \c false, the caller still owns the
  88254. * pointer.
  88255. *
  88256. * \param object A pointer to an existing VORBIS_COMMENT object.
  88257. * \param entry The entry to set the vendor string to.
  88258. * \param copy See above.
  88259. * \assert
  88260. * \code object != NULL \endcode
  88261. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88262. * \code (entry.entry != NULL && entry.length > 0) ||
  88263. * (entry.entry == NULL && entry.length == 0) \endcode
  88264. * \retval FLAC__bool
  88265. * \c false if memory allocation fails or \a entry does not comply with the
  88266. * Vorbis comment specification, else \c true.
  88267. */
  88268. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88269. /** Resize the comment array.
  88270. *
  88271. * If the size shrinks, elements will truncated; if it grows, new empty
  88272. * fields will be added to the end.
  88273. *
  88274. * \param object A pointer to an existing VORBIS_COMMENT object.
  88275. * \param new_num_comments The desired length of the array; may be \c 0.
  88276. * \assert
  88277. * \code object != NULL \endcode
  88278. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88279. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88280. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88281. * \retval FLAC__bool
  88282. * \c false if memory allocation fails, else \c true.
  88283. */
  88284. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88285. /** Sets a comment in a VORBIS_COMMENT block.
  88286. *
  88287. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88288. * one already.
  88289. *
  88290. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88291. * takes ownership of the \c entry.entry pointer.
  88292. *
  88293. * \note If this function returns \c false, the caller still owns the
  88294. * pointer.
  88295. *
  88296. * \param object A pointer to an existing VORBIS_COMMENT object.
  88297. * \param comment_num Index into comment array to set.
  88298. * \param entry The entry to set the comment to.
  88299. * \param copy See above.
  88300. * \assert
  88301. * \code object != NULL \endcode
  88302. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88303. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88304. * \code (entry.entry != NULL && entry.length > 0) ||
  88305. * (entry.entry == NULL && entry.length == 0) \endcode
  88306. * \retval FLAC__bool
  88307. * \c false if memory allocation fails or \a entry does not comply with the
  88308. * Vorbis comment specification, else \c true.
  88309. */
  88310. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88311. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88312. *
  88313. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88314. * one already.
  88315. *
  88316. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88317. * takes ownership of the \c entry.entry pointer.
  88318. *
  88319. * \note If this function returns \c false, the caller still owns the
  88320. * pointer.
  88321. *
  88322. * \param object A pointer to an existing VORBIS_COMMENT object.
  88323. * \param comment_num The index at which to insert the comment. The comments
  88324. * at and after \a comment_num move right one position.
  88325. * To append a comment to the end, set \a comment_num to
  88326. * \c object->data.vorbis_comment.num_comments .
  88327. * \param entry The comment to insert.
  88328. * \param copy See above.
  88329. * \assert
  88330. * \code object != NULL \endcode
  88331. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88332. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88333. * \code (entry.entry != NULL && entry.length > 0) ||
  88334. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88335. * \retval FLAC__bool
  88336. * \c false if memory allocation fails or \a entry does not comply with the
  88337. * Vorbis comment specification, else \c true.
  88338. */
  88339. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88340. /** Appends a comment to a VORBIS_COMMENT block.
  88341. *
  88342. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88343. * one already.
  88344. *
  88345. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88346. * takes ownership of the \c entry.entry pointer.
  88347. *
  88348. * \note If this function returns \c false, the caller still owns the
  88349. * pointer.
  88350. *
  88351. * \param object A pointer to an existing VORBIS_COMMENT object.
  88352. * \param entry The comment to insert.
  88353. * \param copy See above.
  88354. * \assert
  88355. * \code object != NULL \endcode
  88356. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88357. * \code (entry.entry != NULL && entry.length > 0) ||
  88358. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88359. * \retval FLAC__bool
  88360. * \c false if memory allocation fails or \a entry does not comply with the
  88361. * Vorbis comment specification, else \c true.
  88362. */
  88363. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88364. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88365. *
  88366. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88367. * one already.
  88368. *
  88369. * Depending on the the value of \a all, either all or just the first comment
  88370. * whose field name(s) match the given entry's name will be replaced by the
  88371. * given entry. If no comments match, \a entry will simply be appended.
  88372. *
  88373. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88374. * takes ownership of the \c entry.entry pointer.
  88375. *
  88376. * \note If this function returns \c false, the caller still owns the
  88377. * pointer.
  88378. *
  88379. * \param object A pointer to an existing VORBIS_COMMENT object.
  88380. * \param entry The comment to insert.
  88381. * \param all If \c true, all comments whose field name matches
  88382. * \a entry's field name will be removed, and \a entry will
  88383. * be inserted at the position of the first matching
  88384. * comment. If \c false, only the first comment whose
  88385. * field name matches \a entry's field name will be
  88386. * replaced with \a entry.
  88387. * \param copy See above.
  88388. * \assert
  88389. * \code object != NULL \endcode
  88390. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88391. * \code (entry.entry != NULL && entry.length > 0) ||
  88392. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88393. * \retval FLAC__bool
  88394. * \c false if memory allocation fails or \a entry does not comply with the
  88395. * Vorbis comment specification, else \c true.
  88396. */
  88397. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88398. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88399. *
  88400. * \param object A pointer to an existing VORBIS_COMMENT object.
  88401. * \param comment_num The index of the comment to delete.
  88402. * \assert
  88403. * \code object != NULL \endcode
  88404. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88405. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88406. * \retval FLAC__bool
  88407. * \c false if realloc() fails, else \c true.
  88408. */
  88409. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88410. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88411. *
  88412. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88413. * memory and shall be owned by the caller. For convenience the entry will
  88414. * have a terminating NUL.
  88415. *
  88416. * \param entry A pointer to a Vorbis comment entry. The entry's
  88417. * \c entry pointer should not point to allocated
  88418. * memory as it will be overwritten.
  88419. * \param field_name The field name in ASCII, \c NUL terminated.
  88420. * \param field_value The field value in UTF-8, \c NUL terminated.
  88421. * \assert
  88422. * \code entry != NULL \endcode
  88423. * \code field_name != NULL \endcode
  88424. * \code field_value != NULL \endcode
  88425. * \retval FLAC__bool
  88426. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88427. * not comply with the Vorbis comment specification, else \c true.
  88428. */
  88429. 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);
  88430. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88431. *
  88432. * The returned pointers to name and value will be allocated by malloc()
  88433. * and shall be owned by the caller.
  88434. *
  88435. * \param entry An existing Vorbis comment entry.
  88436. * \param field_name The address of where the returned pointer to the
  88437. * field name will be stored.
  88438. * \param field_value The address of where the returned pointer to the
  88439. * field value will be stored.
  88440. * \assert
  88441. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88442. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88443. * \code field_name != NULL \endcode
  88444. * \code field_value != NULL \endcode
  88445. * \retval FLAC__bool
  88446. * \c false if memory allocation fails or \a entry does not comply with the
  88447. * Vorbis comment specification, else \c true.
  88448. */
  88449. 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);
  88450. /** Check if the given Vorbis comment entry's field name matches the given
  88451. * field name.
  88452. *
  88453. * \param entry An existing Vorbis comment entry.
  88454. * \param field_name The field name to check.
  88455. * \param field_name_length The length of \a field_name, not including the
  88456. * terminating \c NUL.
  88457. * \assert
  88458. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88459. * \retval FLAC__bool
  88460. * \c true if the field names match, else \c false
  88461. */
  88462. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88463. /** Find a Vorbis comment with the given field name.
  88464. *
  88465. * The search begins at entry number \a offset; use an offset of 0 to
  88466. * search from the beginning of the comment array.
  88467. *
  88468. * \param object A pointer to an existing VORBIS_COMMENT object.
  88469. * \param offset The offset into the comment array from where to start
  88470. * the search.
  88471. * \param field_name The field name of the comment to find.
  88472. * \assert
  88473. * \code object != NULL \endcode
  88474. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88475. * \code field_name != NULL \endcode
  88476. * \retval int
  88477. * The offset in the comment array of the first comment whose field
  88478. * name matches \a field_name, or \c -1 if no match was found.
  88479. */
  88480. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88481. /** Remove first Vorbis comment matching the given field name.
  88482. *
  88483. * \param object A pointer to an existing VORBIS_COMMENT object.
  88484. * \param field_name The field name of comment to delete.
  88485. * \assert
  88486. * \code object != NULL \endcode
  88487. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88488. * \retval int
  88489. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88490. * \c 1 for one matching entry deleted.
  88491. */
  88492. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88493. /** Remove all Vorbis comments matching the given field name.
  88494. *
  88495. * \param object A pointer to an existing VORBIS_COMMENT object.
  88496. * \param field_name The field name of comments to delete.
  88497. * \assert
  88498. * \code object != NULL \endcode
  88499. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88500. * \retval int
  88501. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88502. * else the number of matching entries deleted.
  88503. */
  88504. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88505. /** Create a new CUESHEET track instance.
  88506. *
  88507. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88508. *
  88509. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88510. * \c NULL if there was an error allocating memory, else the new instance.
  88511. */
  88512. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88513. /** Create a copy of an existing CUESHEET track object.
  88514. *
  88515. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88516. * object is also copied. The caller takes ownership of the new object and
  88517. * is responsible for freeing it with
  88518. * FLAC__metadata_object_cuesheet_track_delete().
  88519. *
  88520. * \param object Pointer to object to copy.
  88521. * \assert
  88522. * \code object != NULL \endcode
  88523. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88524. * \c NULL if there was an error allocating memory, else the new instance.
  88525. */
  88526. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88527. /** Delete a CUESHEET track object
  88528. *
  88529. * \param object A pointer to an existing CUESHEET track object.
  88530. * \assert
  88531. * \code object != NULL \endcode
  88532. */
  88533. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88534. /** Resize a track's index point array.
  88535. *
  88536. * If the size shrinks, elements will truncated; if it grows, new blank
  88537. * indices will be added to the end.
  88538. *
  88539. * \param object A pointer to an existing CUESHEET object.
  88540. * \param track_num The index of the track to modify. NOTE: this is not
  88541. * necessarily the same as the track's \a number field.
  88542. * \param new_num_indices The desired length of the array; may be \c 0.
  88543. * \assert
  88544. * \code object != NULL \endcode
  88545. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88546. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88547. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88548. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88549. * \retval FLAC__bool
  88550. * \c false if memory allocation error, else \c true.
  88551. */
  88552. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88553. /** Insert an index point in a CUESHEET track at the given index.
  88554. *
  88555. * \param object A pointer to an existing CUESHEET object.
  88556. * \param track_num The index of the track to modify. NOTE: this is not
  88557. * necessarily the same as the track's \a number field.
  88558. * \param index_num The index into the track's index array at which to
  88559. * insert the index point. NOTE: this is not necessarily
  88560. * the same as the index point's \a number field. The
  88561. * indices at and after \a index_num move right one
  88562. * position. To append an index point to the end, set
  88563. * \a index_num to
  88564. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88565. * \param index The index point to insert.
  88566. * \assert
  88567. * \code object != NULL \endcode
  88568. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88569. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88570. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88571. * \retval FLAC__bool
  88572. * \c false if realloc() fails, else \c true.
  88573. */
  88574. 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);
  88575. /** Insert a blank index point in a CUESHEET track at the given index.
  88576. *
  88577. * A blank index point is one in which all field values are zero.
  88578. *
  88579. * \param object A pointer to an existing CUESHEET object.
  88580. * \param track_num The index of the track to modify. NOTE: this is not
  88581. * necessarily the same as the track's \a number field.
  88582. * \param index_num The index into the track's index array at which to
  88583. * insert the index point. NOTE: this is not necessarily
  88584. * the same as the index point's \a number field. The
  88585. * indices at and after \a index_num move right one
  88586. * position. To append an index point to the end, set
  88587. * \a index_num to
  88588. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88589. * \assert
  88590. * \code object != NULL \endcode
  88591. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88592. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88593. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88594. * \retval FLAC__bool
  88595. * \c false if realloc() fails, else \c true.
  88596. */
  88597. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88598. /** Delete an index point in a CUESHEET track at the given index.
  88599. *
  88600. * \param object A pointer to an existing CUESHEET object.
  88601. * \param track_num The index into the track array of the track to
  88602. * modify. NOTE: this is not necessarily the same
  88603. * as the track's \a number field.
  88604. * \param index_num The index into the track's index array of the index
  88605. * to delete. NOTE: this is not necessarily the same
  88606. * as the index's \a number field.
  88607. * \assert
  88608. * \code object != NULL \endcode
  88609. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88610. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88611. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88612. * \retval FLAC__bool
  88613. * \c false if realloc() fails, else \c true.
  88614. */
  88615. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88616. /** Resize the track array.
  88617. *
  88618. * If the size shrinks, elements will truncated; if it grows, new blank
  88619. * tracks will be added to the end.
  88620. *
  88621. * \param object A pointer to an existing CUESHEET object.
  88622. * \param new_num_tracks The desired length of the array; may be \c 0.
  88623. * \assert
  88624. * \code object != NULL \endcode
  88625. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88626. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88627. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88628. * \retval FLAC__bool
  88629. * \c false if memory allocation error, else \c true.
  88630. */
  88631. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88632. /** Sets a track in a CUESHEET block.
  88633. *
  88634. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88635. * takes ownership of the \a track pointer.
  88636. *
  88637. * \param object A pointer to an existing CUESHEET object.
  88638. * \param track_num Index into track array to set. NOTE: this is not
  88639. * necessarily the same as the track's \a number field.
  88640. * \param track The track to set the track to. You may safely pass in
  88641. * a const pointer if \a copy is \c true.
  88642. * \param copy See above.
  88643. * \assert
  88644. * \code object != NULL \endcode
  88645. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88646. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88647. * \code (track->indices != NULL && track->num_indices > 0) ||
  88648. * (track->indices == NULL && track->num_indices == 0)
  88649. * \retval FLAC__bool
  88650. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88651. */
  88652. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88653. /** Insert a track in a CUESHEET block at the given index.
  88654. *
  88655. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88656. * takes ownership of the \a track pointer.
  88657. *
  88658. * \param object A pointer to an existing CUESHEET object.
  88659. * \param track_num The index at which to insert the track. NOTE: this
  88660. * is not necessarily the same as the track's \a number
  88661. * field. The tracks at and after \a track_num move right
  88662. * one position. To append a track to the end, set
  88663. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88664. * \param track The track to insert. You may safely pass in a const
  88665. * pointer if \a copy is \c true.
  88666. * \param copy See above.
  88667. * \assert
  88668. * \code object != NULL \endcode
  88669. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88670. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88671. * \retval FLAC__bool
  88672. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88673. */
  88674. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88675. /** Insert a blank track in a CUESHEET block at the given index.
  88676. *
  88677. * A blank track is one in which all field values are zero.
  88678. *
  88679. * \param object A pointer to an existing CUESHEET object.
  88680. * \param track_num The index at which to insert the track. NOTE: this
  88681. * is not necessarily the same as the track's \a number
  88682. * field. The tracks at and after \a track_num move right
  88683. * one position. To append a track to the end, set
  88684. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88685. * \assert
  88686. * \code object != NULL \endcode
  88687. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88688. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88689. * \retval FLAC__bool
  88690. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88691. */
  88692. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88693. /** Delete a track in a CUESHEET block at the given index.
  88694. *
  88695. * \param object A pointer to an existing CUESHEET object.
  88696. * \param track_num The index into the track array of the track to
  88697. * delete. NOTE: this is not necessarily the same
  88698. * as the track's \a number field.
  88699. * \assert
  88700. * \code object != NULL \endcode
  88701. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88702. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88703. * \retval FLAC__bool
  88704. * \c false if realloc() fails, else \c true.
  88705. */
  88706. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88707. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88708. * See the format specification for limits on the contents of the
  88709. * cue sheet.
  88710. *
  88711. * \param object A pointer to an existing CUESHEET object.
  88712. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88713. * stringent requirements for a CD-DA (audio) disc.
  88714. * \param violation Address of a pointer to a string. If there is a
  88715. * violation, a pointer to a string explanation of the
  88716. * violation will be returned here. \a violation may be
  88717. * \c NULL if you don't need the returned string. Do not
  88718. * free the returned string; it will always point to static
  88719. * data.
  88720. * \assert
  88721. * \code object != NULL \endcode
  88722. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88723. * \retval FLAC__bool
  88724. * \c false if cue sheet is illegal, else \c true.
  88725. */
  88726. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88727. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88728. * assumes the cue sheet corresponds to a CD; the result is undefined
  88729. * if the cuesheet's is_cd bit is not set.
  88730. *
  88731. * \param object A pointer to an existing CUESHEET object.
  88732. * \assert
  88733. * \code object != NULL \endcode
  88734. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88735. * \retval FLAC__uint32
  88736. * The unsigned integer representation of the CDDB/freedb ID
  88737. */
  88738. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88739. /** Sets the MIME type of a PICTURE block.
  88740. *
  88741. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88742. * takes ownership of the pointer. The existing string will be freed if this
  88743. * function is successful, otherwise the original string will remain if \a copy
  88744. * is \c true and malloc() fails.
  88745. *
  88746. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88747. *
  88748. * \param object A pointer to an existing PICTURE object.
  88749. * \param mime_type A pointer to the MIME type string. The string must be
  88750. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88751. * is done.
  88752. * \param copy See above.
  88753. * \assert
  88754. * \code object != NULL \endcode
  88755. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88756. * \code (mime_type != NULL) \endcode
  88757. * \retval FLAC__bool
  88758. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88759. */
  88760. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88761. /** Sets the description of a PICTURE block.
  88762. *
  88763. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88764. * takes ownership of the pointer. The existing string will be freed if this
  88765. * function is successful, otherwise the original string will remain if \a copy
  88766. * is \c true and malloc() fails.
  88767. *
  88768. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88769. *
  88770. * \param object A pointer to an existing PICTURE object.
  88771. * \param description A pointer to the description string. The string must be
  88772. * valid UTF-8, NUL-terminated. No validation is done.
  88773. * \param copy See above.
  88774. * \assert
  88775. * \code object != NULL \endcode
  88776. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88777. * \code (description != NULL) \endcode
  88778. * \retval FLAC__bool
  88779. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88780. */
  88781. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88782. /** Sets the picture data of a PICTURE block.
  88783. *
  88784. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88785. * takes ownership of the pointer. Also sets the \a data_length field of the
  88786. * metadata object to what is passed in as the \a length parameter. The
  88787. * existing data will be freed if this function is successful, otherwise the
  88788. * original data and data_length will remain if \a copy is \c true and
  88789. * malloc() fails.
  88790. *
  88791. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88792. *
  88793. * \param object A pointer to an existing PICTURE object.
  88794. * \param data A pointer to the data to set.
  88795. * \param length The length of \a data in bytes.
  88796. * \param copy See above.
  88797. * \assert
  88798. * \code object != NULL \endcode
  88799. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88800. * \code (data != NULL && length > 0) ||
  88801. * (data == NULL && length == 0 && copy == false) \endcode
  88802. * \retval FLAC__bool
  88803. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88804. */
  88805. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88806. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88807. * See the format specification for limits on the contents of the
  88808. * PICTURE block.
  88809. *
  88810. * \param object A pointer to existing PICTURE block to be checked.
  88811. * \param violation Address of a pointer to a string. If there is a
  88812. * violation, a pointer to a string explanation of the
  88813. * violation will be returned here. \a violation may be
  88814. * \c NULL if you don't need the returned string. Do not
  88815. * free the returned string; it will always point to static
  88816. * data.
  88817. * \assert
  88818. * \code object != NULL \endcode
  88819. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88820. * \retval FLAC__bool
  88821. * \c false if PICTURE block is illegal, else \c true.
  88822. */
  88823. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88824. /* \} */
  88825. #ifdef __cplusplus
  88826. }
  88827. #endif
  88828. #endif
  88829. /*** End of inlined file: metadata.h ***/
  88830. /*** Start of inlined file: stream_decoder.h ***/
  88831. #ifndef FLAC__STREAM_DECODER_H
  88832. #define FLAC__STREAM_DECODER_H
  88833. #include <stdio.h> /* for FILE */
  88834. #ifdef __cplusplus
  88835. extern "C" {
  88836. #endif
  88837. /** \file include/FLAC/stream_decoder.h
  88838. *
  88839. * \brief
  88840. * This module contains the functions which implement the stream
  88841. * decoder.
  88842. *
  88843. * See the detailed documentation in the
  88844. * \link flac_stream_decoder stream decoder \endlink module.
  88845. */
  88846. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88847. * \ingroup flac
  88848. *
  88849. * \brief
  88850. * This module describes the decoder layers provided by libFLAC.
  88851. *
  88852. * The stream decoder can be used to decode complete streams either from
  88853. * the client via callbacks, or directly from a file, depending on how
  88854. * it is initialized. When decoding via callbacks, the client provides
  88855. * callbacks for reading FLAC data and writing decoded samples, and
  88856. * handling metadata and errors. If the client also supplies seek-related
  88857. * callback, the decoder function for sample-accurate seeking within the
  88858. * FLAC input is also available. When decoding from a file, the client
  88859. * needs only supply a filename or open \c FILE* and write/metadata/error
  88860. * callbacks; the rest of the callbacks are supplied internally. For more
  88861. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88862. */
  88863. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88864. * \ingroup flac_decoder
  88865. *
  88866. * \brief
  88867. * This module contains the functions which implement the stream
  88868. * decoder.
  88869. *
  88870. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88871. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88872. *
  88873. * The basic usage of this decoder is as follows:
  88874. * - The program creates an instance of a decoder using
  88875. * FLAC__stream_decoder_new().
  88876. * - The program overrides the default settings using
  88877. * FLAC__stream_decoder_set_*() functions.
  88878. * - The program initializes the instance to validate the settings and
  88879. * prepare for decoding using
  88880. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88881. * or FLAC__stream_decoder_init_file() for native FLAC,
  88882. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88883. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88884. * - The program calls the FLAC__stream_decoder_process_*() functions
  88885. * to decode data, which subsequently calls the callbacks.
  88886. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88887. * which flushes the input and output and resets the decoder to the
  88888. * uninitialized state.
  88889. * - The instance may be used again or deleted with
  88890. * FLAC__stream_decoder_delete().
  88891. *
  88892. * In more detail, the program will create a new instance by calling
  88893. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88894. * functions to override the default decoder options, and call
  88895. * one of the FLAC__stream_decoder_init_*() functions.
  88896. *
  88897. * There are three initialization functions for native FLAC, one for
  88898. * setting up the decoder to decode FLAC data from the client via
  88899. * callbacks, and two for decoding directly from a FLAC file.
  88900. *
  88901. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88902. * You must also supply several callbacks for handling I/O. Some (like
  88903. * seeking) are optional, depending on the capabilities of the input.
  88904. *
  88905. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88906. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88907. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88908. * the other callbacks internally.
  88909. *
  88910. * There are three similarly-named init functions for decoding from Ogg
  88911. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88912. * library has been built with Ogg support.
  88913. *
  88914. * Once the decoder is initialized, your program will call one of several
  88915. * functions to start the decoding process:
  88916. *
  88917. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88918. * most one metadata block or audio frame and return, calling either the
  88919. * metadata callback or write callback, respectively, once. If the decoder
  88920. * loses sync it will return with only the error callback being called.
  88921. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88922. * to process the stream from the current location and stop upon reaching
  88923. * the first audio frame. The client will get one metadata, write, or error
  88924. * callback per metadata block, audio frame, or sync error, respectively.
  88925. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88926. * to process the stream from the current location until the read callback
  88927. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88928. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88929. * write, or error callback per metadata block, audio frame, or sync error,
  88930. * respectively.
  88931. *
  88932. * When the decoder has finished decoding (normally or through an abort),
  88933. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88934. * ensures the decoder is in the correct state and frees memory. Then the
  88935. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88936. * again to decode another stream.
  88937. *
  88938. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88939. * At any point after the stream decoder has been initialized, the client can
  88940. * call this function to seek to an exact sample within the stream.
  88941. * Subsequently, the first time the write callback is called it will be
  88942. * passed a (possibly partial) block starting at that sample.
  88943. *
  88944. * If the client cannot seek via the callback interface provided, but still
  88945. * has another way of seeking, it can flush the decoder using
  88946. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88947. * through the read callback.
  88948. *
  88949. * The stream decoder also provides MD5 signature checking. If this is
  88950. * turned on before initialization, FLAC__stream_decoder_finish() will
  88951. * report when the decoded MD5 signature does not match the one stored
  88952. * in the STREAMINFO block. MD5 checking is automatically turned off
  88953. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88954. * in the STREAMINFO block or when a seek is attempted.
  88955. *
  88956. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88957. * attention. By default, the decoder only calls the metadata_callback for
  88958. * the STREAMINFO block. These functions allow you to tell the decoder
  88959. * explicitly which blocks to parse and return via the metadata_callback
  88960. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88961. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88962. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88963. * which blocks to return. Remember that metadata blocks can potentially
  88964. * be big (for example, cover art) so filtering out the ones you don't
  88965. * use can reduce the memory requirements of the decoder. Also note the
  88966. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88967. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88968. * filtering APPLICATION blocks based on the application ID.
  88969. *
  88970. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88971. * they still can legally be filtered from the metadata_callback.
  88972. *
  88973. * \note
  88974. * The "set" functions may only be called when the decoder is in the
  88975. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88976. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88977. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88978. * return \c true, otherwise \c false.
  88979. *
  88980. * \note
  88981. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88982. * defaults, including the callbacks.
  88983. *
  88984. * \{
  88985. */
  88986. /** State values for a FLAC__StreamDecoder
  88987. *
  88988. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88989. */
  88990. typedef enum {
  88991. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88992. /**< The decoder is ready to search for metadata. */
  88993. FLAC__STREAM_DECODER_READ_METADATA,
  88994. /**< The decoder is ready to or is in the process of reading metadata. */
  88995. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88996. /**< The decoder is ready to or is in the process of searching for the
  88997. * frame sync code.
  88998. */
  88999. FLAC__STREAM_DECODER_READ_FRAME,
  89000. /**< The decoder is ready to or is in the process of reading a frame. */
  89001. FLAC__STREAM_DECODER_END_OF_STREAM,
  89002. /**< The decoder has reached the end of the stream. */
  89003. FLAC__STREAM_DECODER_OGG_ERROR,
  89004. /**< An error occurred in the underlying Ogg layer. */
  89005. FLAC__STREAM_DECODER_SEEK_ERROR,
  89006. /**< An error occurred while seeking. The decoder must be flushed
  89007. * with FLAC__stream_decoder_flush() or reset with
  89008. * FLAC__stream_decoder_reset() before decoding can continue.
  89009. */
  89010. FLAC__STREAM_DECODER_ABORTED,
  89011. /**< The decoder was aborted by the read callback. */
  89012. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89013. /**< An error occurred allocating memory. The decoder is in an invalid
  89014. * state and can no longer be used.
  89015. */
  89016. FLAC__STREAM_DECODER_UNINITIALIZED
  89017. /**< The decoder is in the uninitialized state; one of the
  89018. * FLAC__stream_decoder_init_*() functions must be called before samples
  89019. * can be processed.
  89020. */
  89021. } FLAC__StreamDecoderState;
  89022. /** Maps a FLAC__StreamDecoderState to a C string.
  89023. *
  89024. * Using a FLAC__StreamDecoderState as the index to this array
  89025. * will give the string equivalent. The contents should not be modified.
  89026. */
  89027. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89028. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89029. */
  89030. typedef enum {
  89031. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89032. /**< Initialization was successful. */
  89033. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89034. /**< The library was not compiled with support for the given container
  89035. * format.
  89036. */
  89037. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89038. /**< A required callback was not supplied. */
  89039. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89040. /**< An error occurred allocating memory. */
  89041. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89042. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89043. * FLAC__stream_decoder_init_ogg_file(). */
  89044. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89045. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89046. * already initialized, usually because
  89047. * FLAC__stream_decoder_finish() was not called.
  89048. */
  89049. } FLAC__StreamDecoderInitStatus;
  89050. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89051. *
  89052. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89053. * will give the string equivalent. The contents should not be modified.
  89054. */
  89055. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89056. /** Return values for the FLAC__StreamDecoder read callback.
  89057. */
  89058. typedef enum {
  89059. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89060. /**< The read was OK and decoding can continue. */
  89061. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89062. /**< The read was attempted while at the end of the stream. Note that
  89063. * the client must only return this value when the read callback was
  89064. * called when already at the end of the stream. Otherwise, if the read
  89065. * itself moves to the end of the stream, the client should still return
  89066. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89067. * the next read callback it should return
  89068. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89069. * of \c 0.
  89070. */
  89071. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89072. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89073. } FLAC__StreamDecoderReadStatus;
  89074. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89075. *
  89076. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89077. * will give the string equivalent. The contents should not be modified.
  89078. */
  89079. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89080. /** Return values for the FLAC__StreamDecoder seek callback.
  89081. */
  89082. typedef enum {
  89083. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89084. /**< The seek was OK and decoding can continue. */
  89085. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89086. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89087. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89088. /**< Client does not support seeking. */
  89089. } FLAC__StreamDecoderSeekStatus;
  89090. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89091. *
  89092. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89093. * will give the string equivalent. The contents should not be modified.
  89094. */
  89095. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89096. /** Return values for the FLAC__StreamDecoder tell callback.
  89097. */
  89098. typedef enum {
  89099. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89100. /**< The tell was OK and decoding can continue. */
  89101. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89102. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89103. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89104. /**< Client does not support telling the position. */
  89105. } FLAC__StreamDecoderTellStatus;
  89106. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89107. *
  89108. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89109. * will give the string equivalent. The contents should not be modified.
  89110. */
  89111. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89112. /** Return values for the FLAC__StreamDecoder length callback.
  89113. */
  89114. typedef enum {
  89115. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89116. /**< The length call was OK and decoding can continue. */
  89117. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89118. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89119. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89120. /**< Client does not support reporting the length. */
  89121. } FLAC__StreamDecoderLengthStatus;
  89122. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89123. *
  89124. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89125. * will give the string equivalent. The contents should not be modified.
  89126. */
  89127. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89128. /** Return values for the FLAC__StreamDecoder write callback.
  89129. */
  89130. typedef enum {
  89131. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89132. /**< The write was OK and decoding can continue. */
  89133. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89134. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89135. } FLAC__StreamDecoderWriteStatus;
  89136. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89137. *
  89138. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89139. * will give the string equivalent. The contents should not be modified.
  89140. */
  89141. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89142. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89143. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89144. * all. The rest could be caused by bad sync (false synchronization on
  89145. * data that is not the start of a frame) or corrupted data. The error
  89146. * itself is the decoder's best guess at what happened assuming a correct
  89147. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89148. * could be caused by a correct sync on the start of a frame, but some
  89149. * data in the frame header was corrupted. Or it could be the result of
  89150. * syncing on a point the stream that looked like the starting of a frame
  89151. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89152. * could be because the decoder encountered a valid frame made by a future
  89153. * version of the encoder which it cannot parse, or because of a false
  89154. * sync making it appear as though an encountered frame was generated by
  89155. * a future encoder.
  89156. */
  89157. typedef enum {
  89158. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89159. /**< An error in the stream caused the decoder to lose synchronization. */
  89160. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89161. /**< The decoder encountered a corrupted frame header. */
  89162. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89163. /**< The frame's data did not match the CRC in the footer. */
  89164. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89165. /**< The decoder encountered reserved fields in use in the stream. */
  89166. } FLAC__StreamDecoderErrorStatus;
  89167. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89168. *
  89169. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89170. * will give the string equivalent. The contents should not be modified.
  89171. */
  89172. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89173. /***********************************************************************
  89174. *
  89175. * class FLAC__StreamDecoder
  89176. *
  89177. ***********************************************************************/
  89178. struct FLAC__StreamDecoderProtected;
  89179. struct FLAC__StreamDecoderPrivate;
  89180. /** The opaque structure definition for the stream decoder type.
  89181. * See the \link flac_stream_decoder stream decoder module \endlink
  89182. * for a detailed description.
  89183. */
  89184. typedef struct {
  89185. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89186. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89187. } FLAC__StreamDecoder;
  89188. /** Signature for the read callback.
  89189. *
  89190. * A function pointer matching this signature must be passed to
  89191. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89192. * called when the decoder needs more input data. The address of the
  89193. * buffer to be filled is supplied, along with the number of bytes the
  89194. * buffer can hold. The callback may choose to supply less data and
  89195. * modify the byte count but must be careful not to overflow the buffer.
  89196. * The callback then returns a status code chosen from
  89197. * FLAC__StreamDecoderReadStatus.
  89198. *
  89199. * Here is an example of a read callback for stdio streams:
  89200. * \code
  89201. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89202. * {
  89203. * FILE *file = ((MyClientData*)client_data)->file;
  89204. * if(*bytes > 0) {
  89205. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89206. * if(ferror(file))
  89207. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89208. * else if(*bytes == 0)
  89209. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89210. * else
  89211. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89212. * }
  89213. * else
  89214. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89215. * }
  89216. * \endcode
  89217. *
  89218. * \note In general, FLAC__StreamDecoder functions which change the
  89219. * state should not be called on the \a decoder while in the callback.
  89220. *
  89221. * \param decoder The decoder instance calling the callback.
  89222. * \param buffer A pointer to a location for the callee to store
  89223. * data to be decoded.
  89224. * \param bytes A pointer to the size of the buffer. On entry
  89225. * to the callback, it contains the maximum number
  89226. * of bytes that may be stored in \a buffer. The
  89227. * callee must set it to the actual number of bytes
  89228. * stored (0 in case of error or end-of-stream) before
  89229. * returning.
  89230. * \param client_data The callee's client data set through
  89231. * FLAC__stream_decoder_init_*().
  89232. * \retval FLAC__StreamDecoderReadStatus
  89233. * The callee's return status. Note that the callback should return
  89234. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89235. * zero bytes were read and there is no more data to be read.
  89236. */
  89237. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89238. /** Signature for the seek callback.
  89239. *
  89240. * A function pointer matching this signature may be passed to
  89241. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89242. * called when the decoder needs to seek the input stream. The decoder
  89243. * will pass the absolute byte offset to seek to, 0 meaning the
  89244. * beginning of the stream.
  89245. *
  89246. * Here is an example of a seek callback for stdio streams:
  89247. * \code
  89248. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89249. * {
  89250. * FILE *file = ((MyClientData*)client_data)->file;
  89251. * if(file == stdin)
  89252. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89253. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89254. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89255. * else
  89256. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89257. * }
  89258. * \endcode
  89259. *
  89260. * \note In general, FLAC__StreamDecoder functions which change the
  89261. * state should not be called on the \a decoder while in the callback.
  89262. *
  89263. * \param decoder The decoder instance calling the callback.
  89264. * \param absolute_byte_offset The offset from the beginning of the stream
  89265. * to seek to.
  89266. * \param client_data The callee's client data set through
  89267. * FLAC__stream_decoder_init_*().
  89268. * \retval FLAC__StreamDecoderSeekStatus
  89269. * The callee's return status.
  89270. */
  89271. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89272. /** Signature for the tell callback.
  89273. *
  89274. * A function pointer matching this signature may be passed to
  89275. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89276. * called when the decoder wants to know the current position of the
  89277. * stream. The callback should return the byte offset from the
  89278. * beginning of the stream.
  89279. *
  89280. * Here is an example of a tell callback for stdio streams:
  89281. * \code
  89282. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89283. * {
  89284. * FILE *file = ((MyClientData*)client_data)->file;
  89285. * off_t pos;
  89286. * if(file == stdin)
  89287. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89288. * else if((pos = ftello(file)) < 0)
  89289. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89290. * else {
  89291. * *absolute_byte_offset = (FLAC__uint64)pos;
  89292. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89293. * }
  89294. * }
  89295. * \endcode
  89296. *
  89297. * \note In general, FLAC__StreamDecoder functions which change the
  89298. * state should not be called on the \a decoder while in the callback.
  89299. *
  89300. * \param decoder The decoder instance calling the callback.
  89301. * \param absolute_byte_offset A pointer to storage for the current offset
  89302. * from the beginning of the stream.
  89303. * \param client_data The callee's client data set through
  89304. * FLAC__stream_decoder_init_*().
  89305. * \retval FLAC__StreamDecoderTellStatus
  89306. * The callee's return status.
  89307. */
  89308. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89309. /** Signature for the length callback.
  89310. *
  89311. * A function pointer matching this signature may be passed to
  89312. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89313. * called when the decoder wants to know the total length of the stream
  89314. * in bytes.
  89315. *
  89316. * Here is an example of a length callback for stdio streams:
  89317. * \code
  89318. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89319. * {
  89320. * FILE *file = ((MyClientData*)client_data)->file;
  89321. * struct stat filestats;
  89322. *
  89323. * if(file == stdin)
  89324. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89325. * else if(fstat(fileno(file), &filestats) != 0)
  89326. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89327. * else {
  89328. * *stream_length = (FLAC__uint64)filestats.st_size;
  89329. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89330. * }
  89331. * }
  89332. * \endcode
  89333. *
  89334. * \note In general, FLAC__StreamDecoder functions which change the
  89335. * state should not be called on the \a decoder while in the callback.
  89336. *
  89337. * \param decoder The decoder instance calling the callback.
  89338. * \param stream_length A pointer to storage for the length of the stream
  89339. * in bytes.
  89340. * \param client_data The callee's client data set through
  89341. * FLAC__stream_decoder_init_*().
  89342. * \retval FLAC__StreamDecoderLengthStatus
  89343. * The callee's return status.
  89344. */
  89345. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89346. /** Signature for the EOF callback.
  89347. *
  89348. * A function pointer matching this signature may be passed to
  89349. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89350. * called when the decoder needs to know if the end of the stream has
  89351. * been reached.
  89352. *
  89353. * Here is an example of a EOF callback for stdio streams:
  89354. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89355. * \code
  89356. * {
  89357. * FILE *file = ((MyClientData*)client_data)->file;
  89358. * return feof(file)? true : false;
  89359. * }
  89360. * \endcode
  89361. *
  89362. * \note In general, FLAC__StreamDecoder functions which change the
  89363. * state should not be called on the \a decoder while in the callback.
  89364. *
  89365. * \param decoder The decoder instance calling the callback.
  89366. * \param client_data The callee's client data set through
  89367. * FLAC__stream_decoder_init_*().
  89368. * \retval FLAC__bool
  89369. * \c true if the currently at the end of the stream, else \c false.
  89370. */
  89371. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89372. /** Signature for the write callback.
  89373. *
  89374. * A function pointer matching this signature must be passed to one of
  89375. * the FLAC__stream_decoder_init_*() functions.
  89376. * The supplied function will be called when the decoder has decoded a
  89377. * single audio frame. The decoder will pass the frame metadata as well
  89378. * as an array of pointers (one for each channel) pointing to the
  89379. * decoded audio.
  89380. *
  89381. * \note In general, FLAC__StreamDecoder functions which change the
  89382. * state should not be called on the \a decoder while in the callback.
  89383. *
  89384. * \param decoder The decoder instance calling the callback.
  89385. * \param frame The description of the decoded frame. See
  89386. * FLAC__Frame.
  89387. * \param buffer An array of pointers to decoded channels of data.
  89388. * Each pointer will point to an array of signed
  89389. * samples of length \a frame->header.blocksize.
  89390. * Channels will be ordered according to the FLAC
  89391. * specification; see the documentation for the
  89392. * <A HREF="../format.html#frame_header">frame header</A>.
  89393. * \param client_data The callee's client data set through
  89394. * FLAC__stream_decoder_init_*().
  89395. * \retval FLAC__StreamDecoderWriteStatus
  89396. * The callee's return status.
  89397. */
  89398. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89399. /** Signature for the metadata callback.
  89400. *
  89401. * A function pointer matching this signature must be passed to one of
  89402. * the FLAC__stream_decoder_init_*() functions.
  89403. * The supplied function will be called when the decoder has decoded a
  89404. * metadata block. In a valid FLAC file there will always be one
  89405. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89406. * These will be supplied by the decoder in the same order as they
  89407. * appear in the stream and always before the first audio frame (i.e.
  89408. * write callback). The metadata block that is passed in must not be
  89409. * modified, and it doesn't live beyond the callback, so you should make
  89410. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89411. * elsewhere. Since metadata blocks can potentially be large, by
  89412. * default the decoder only calls the metadata callback for the
  89413. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89414. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89415. *
  89416. * \note In general, FLAC__StreamDecoder functions which change the
  89417. * state should not be called on the \a decoder while in the callback.
  89418. *
  89419. * \param decoder The decoder instance calling the callback.
  89420. * \param metadata The decoded metadata block.
  89421. * \param client_data The callee's client data set through
  89422. * FLAC__stream_decoder_init_*().
  89423. */
  89424. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89425. /** Signature for the error callback.
  89426. *
  89427. * A function pointer matching this signature must be passed to one of
  89428. * the FLAC__stream_decoder_init_*() functions.
  89429. * The supplied function will be called whenever an error occurs during
  89430. * decoding.
  89431. *
  89432. * \note In general, FLAC__StreamDecoder functions which change the
  89433. * state should not be called on the \a decoder while in the callback.
  89434. *
  89435. * \param decoder The decoder instance calling the callback.
  89436. * \param status The error encountered by the decoder.
  89437. * \param client_data The callee's client data set through
  89438. * FLAC__stream_decoder_init_*().
  89439. */
  89440. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89441. /***********************************************************************
  89442. *
  89443. * Class constructor/destructor
  89444. *
  89445. ***********************************************************************/
  89446. /** Create a new stream decoder instance. The instance is created with
  89447. * default settings; see the individual FLAC__stream_decoder_set_*()
  89448. * functions for each setting's default.
  89449. *
  89450. * \retval FLAC__StreamDecoder*
  89451. * \c NULL if there was an error allocating memory, else the new instance.
  89452. */
  89453. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89454. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89455. *
  89456. * \param decoder A pointer to an existing decoder.
  89457. * \assert
  89458. * \code decoder != NULL \endcode
  89459. */
  89460. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89461. /***********************************************************************
  89462. *
  89463. * Public class method prototypes
  89464. *
  89465. ***********************************************************************/
  89466. /** Set the serial number for the FLAC stream within the Ogg container.
  89467. * The default behavior is to use the serial number of the first Ogg
  89468. * page. Setting a serial number here will explicitly specify which
  89469. * stream is to be decoded.
  89470. *
  89471. * \note
  89472. * This does not need to be set for native FLAC decoding.
  89473. *
  89474. * \default \c use serial number of first page
  89475. * \param decoder A decoder instance to set.
  89476. * \param serial_number See above.
  89477. * \assert
  89478. * \code decoder != NULL \endcode
  89479. * \retval FLAC__bool
  89480. * \c false if the decoder is already initialized, else \c true.
  89481. */
  89482. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89483. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89484. * compute the MD5 signature of the unencoded audio data while decoding
  89485. * and compare it to the signature from the STREAMINFO block, if it
  89486. * exists, during FLAC__stream_decoder_finish().
  89487. *
  89488. * MD5 signature checking will be turned off (until the next
  89489. * FLAC__stream_decoder_reset()) if there is no signature in the
  89490. * STREAMINFO block or when a seek is attempted.
  89491. *
  89492. * Clients that do not use the MD5 check should leave this off to speed
  89493. * up decoding.
  89494. *
  89495. * \default \c false
  89496. * \param decoder A decoder instance to set.
  89497. * \param value Flag value (see above).
  89498. * \assert
  89499. * \code decoder != NULL \endcode
  89500. * \retval FLAC__bool
  89501. * \c false if the decoder is already initialized, else \c true.
  89502. */
  89503. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89504. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89505. *
  89506. * \default By default, only the \c STREAMINFO block is returned via the
  89507. * metadata callback.
  89508. * \param decoder A decoder instance to set.
  89509. * \param type See above.
  89510. * \assert
  89511. * \code decoder != NULL \endcode
  89512. * \a type is valid
  89513. * \retval FLAC__bool
  89514. * \c false if the decoder is already initialized, else \c true.
  89515. */
  89516. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89517. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89518. * given \a id.
  89519. *
  89520. * \default By default, only the \c STREAMINFO block is returned via the
  89521. * metadata callback.
  89522. * \param decoder A decoder instance to set.
  89523. * \param id See above.
  89524. * \assert
  89525. * \code decoder != NULL \endcode
  89526. * \code id != NULL \endcode
  89527. * \retval FLAC__bool
  89528. * \c false if the decoder is already initialized, else \c true.
  89529. */
  89530. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89531. /** Direct the decoder to pass on all metadata blocks of any type.
  89532. *
  89533. * \default By default, only the \c STREAMINFO block is returned via the
  89534. * metadata callback.
  89535. * \param decoder A decoder instance to set.
  89536. * \assert
  89537. * \code decoder != NULL \endcode
  89538. * \retval FLAC__bool
  89539. * \c false if the decoder is already initialized, else \c true.
  89540. */
  89541. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89542. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89543. *
  89544. * \default By default, only the \c STREAMINFO block is returned via the
  89545. * metadata callback.
  89546. * \param decoder A decoder instance to set.
  89547. * \param type See above.
  89548. * \assert
  89549. * \code decoder != NULL \endcode
  89550. * \a type is valid
  89551. * \retval FLAC__bool
  89552. * \c false if the decoder is already initialized, else \c true.
  89553. */
  89554. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89555. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89556. * the given \a id.
  89557. *
  89558. * \default By default, only the \c STREAMINFO block is returned via the
  89559. * metadata callback.
  89560. * \param decoder A decoder instance to set.
  89561. * \param id See above.
  89562. * \assert
  89563. * \code decoder != NULL \endcode
  89564. * \code id != NULL \endcode
  89565. * \retval FLAC__bool
  89566. * \c false if the decoder is already initialized, else \c true.
  89567. */
  89568. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89569. /** Direct the decoder to filter out all metadata blocks of any type.
  89570. *
  89571. * \default By default, only the \c STREAMINFO block is returned via the
  89572. * metadata callback.
  89573. * \param decoder A decoder instance to set.
  89574. * \assert
  89575. * \code decoder != NULL \endcode
  89576. * \retval FLAC__bool
  89577. * \c false if the decoder is already initialized, else \c true.
  89578. */
  89579. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89580. /** Get the current decoder state.
  89581. *
  89582. * \param decoder A decoder instance to query.
  89583. * \assert
  89584. * \code decoder != NULL \endcode
  89585. * \retval FLAC__StreamDecoderState
  89586. * The current decoder state.
  89587. */
  89588. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89589. /** Get the current decoder state as a C string.
  89590. *
  89591. * \param decoder A decoder instance to query.
  89592. * \assert
  89593. * \code decoder != NULL \endcode
  89594. * \retval const char *
  89595. * The decoder state as a C string. Do not modify the contents.
  89596. */
  89597. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89598. /** Get the "MD5 signature checking" flag.
  89599. * This is the value of the setting, not whether or not the decoder is
  89600. * currently checking the MD5 (remember, it can be turned off automatically
  89601. * by a seek). When the decoder is reset the flag will be restored to the
  89602. * value returned by this function.
  89603. *
  89604. * \param decoder A decoder instance to query.
  89605. * \assert
  89606. * \code decoder != NULL \endcode
  89607. * \retval FLAC__bool
  89608. * See above.
  89609. */
  89610. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89611. /** Get the total number of samples in the stream being decoded.
  89612. * Will only be valid after decoding has started and will contain the
  89613. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89614. *
  89615. * \param decoder A decoder instance to query.
  89616. * \assert
  89617. * \code decoder != NULL \endcode
  89618. * \retval unsigned
  89619. * See above.
  89620. */
  89621. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89622. /** Get the current number of channels in the stream being decoded.
  89623. * Will only be valid after decoding has started and will contain the
  89624. * value from the most recently decoded frame header.
  89625. *
  89626. * \param decoder A decoder instance to query.
  89627. * \assert
  89628. * \code decoder != NULL \endcode
  89629. * \retval unsigned
  89630. * See above.
  89631. */
  89632. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89633. /** Get the current channel assignment in the stream being decoded.
  89634. * Will only be valid after decoding has started and will contain the
  89635. * value from the most recently decoded frame header.
  89636. *
  89637. * \param decoder A decoder instance to query.
  89638. * \assert
  89639. * \code decoder != NULL \endcode
  89640. * \retval FLAC__ChannelAssignment
  89641. * See above.
  89642. */
  89643. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89644. /** Get the current sample resolution in the stream being decoded.
  89645. * Will only be valid after decoding has started and will contain the
  89646. * value from the most recently decoded frame header.
  89647. *
  89648. * \param decoder A decoder instance to query.
  89649. * \assert
  89650. * \code decoder != NULL \endcode
  89651. * \retval unsigned
  89652. * See above.
  89653. */
  89654. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89655. /** Get the current sample rate in Hz of the stream being decoded.
  89656. * Will only be valid after decoding has started and will contain the
  89657. * value from the most recently decoded frame header.
  89658. *
  89659. * \param decoder A decoder instance to query.
  89660. * \assert
  89661. * \code decoder != NULL \endcode
  89662. * \retval unsigned
  89663. * See above.
  89664. */
  89665. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89666. /** Get the current blocksize of the stream being decoded.
  89667. * Will only be valid after decoding has started and will contain the
  89668. * value from the most recently decoded frame header.
  89669. *
  89670. * \param decoder A decoder instance to query.
  89671. * \assert
  89672. * \code decoder != NULL \endcode
  89673. * \retval unsigned
  89674. * See above.
  89675. */
  89676. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89677. /** Returns the decoder's current read position within the stream.
  89678. * The position is the byte offset from the start of the stream.
  89679. * Bytes before this position have been fully decoded. Note that
  89680. * there may still be undecoded bytes in the decoder's read FIFO.
  89681. * The returned position is correct even after a seek.
  89682. *
  89683. * \warning This function currently only works for native FLAC,
  89684. * not Ogg FLAC streams.
  89685. *
  89686. * \param decoder A decoder instance to query.
  89687. * \param position Address at which to return the desired position.
  89688. * \assert
  89689. * \code decoder != NULL \endcode
  89690. * \code position != NULL \endcode
  89691. * \retval FLAC__bool
  89692. * \c true if successful, \c false if the stream is not native FLAC,
  89693. * or there was an error from the 'tell' callback or it returned
  89694. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89695. */
  89696. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89697. /** Initialize the decoder instance to decode native FLAC streams.
  89698. *
  89699. * This flavor of initialization sets up the decoder to decode from a
  89700. * native FLAC stream. I/O is performed via callbacks to the client.
  89701. * For decoding from a plain file via filename or open FILE*,
  89702. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89703. * provide a simpler interface.
  89704. *
  89705. * This function should be called after FLAC__stream_decoder_new() and
  89706. * FLAC__stream_decoder_set_*() but before any of the
  89707. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89708. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89709. * if initialization succeeded.
  89710. *
  89711. * \param decoder An uninitialized decoder instance.
  89712. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89713. * pointer must not be \c NULL.
  89714. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89715. * pointer may be \c NULL if seeking is not
  89716. * supported. If \a seek_callback is not \c NULL then a
  89717. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89718. * Alternatively, a dummy seek callback that just
  89719. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89720. * may also be supplied, all though this is slightly
  89721. * less efficient for the decoder.
  89722. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89723. * pointer may be \c NULL if not supported by the client. If
  89724. * \a seek_callback is not \c NULL then a
  89725. * \a tell_callback must also be supplied.
  89726. * Alternatively, a dummy tell callback that just
  89727. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89728. * may also be supplied, all though this is slightly
  89729. * less efficient for the decoder.
  89730. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89731. * pointer may be \c NULL if not supported by the client. If
  89732. * \a seek_callback is not \c NULL then a
  89733. * \a length_callback must also be supplied.
  89734. * Alternatively, a dummy length callback that just
  89735. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89736. * may also be supplied, all though this is slightly
  89737. * less efficient for the decoder.
  89738. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89739. * pointer may be \c NULL if not supported by the client. If
  89740. * \a seek_callback is not \c NULL then a
  89741. * \a eof_callback must also be supplied.
  89742. * Alternatively, a dummy length callback that just
  89743. * returns \c false
  89744. * may also be supplied, all though this is slightly
  89745. * less efficient for the decoder.
  89746. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89747. * pointer must not be \c NULL.
  89748. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89749. * pointer may be \c NULL if the callback is not
  89750. * desired.
  89751. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89752. * pointer must not be \c NULL.
  89753. * \param client_data This value will be supplied to callbacks in their
  89754. * \a client_data argument.
  89755. * \assert
  89756. * \code decoder != NULL \endcode
  89757. * \retval FLAC__StreamDecoderInitStatus
  89758. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89759. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89760. */
  89761. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89762. FLAC__StreamDecoder *decoder,
  89763. FLAC__StreamDecoderReadCallback read_callback,
  89764. FLAC__StreamDecoderSeekCallback seek_callback,
  89765. FLAC__StreamDecoderTellCallback tell_callback,
  89766. FLAC__StreamDecoderLengthCallback length_callback,
  89767. FLAC__StreamDecoderEofCallback eof_callback,
  89768. FLAC__StreamDecoderWriteCallback write_callback,
  89769. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89770. FLAC__StreamDecoderErrorCallback error_callback,
  89771. void *client_data
  89772. );
  89773. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89774. *
  89775. * This flavor of initialization sets up the decoder to decode from a
  89776. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89777. * client. For decoding from a plain file via filename or open FILE*,
  89778. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89779. * provide a simpler interface.
  89780. *
  89781. * This function should be called after FLAC__stream_decoder_new() and
  89782. * FLAC__stream_decoder_set_*() but before any of the
  89783. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89784. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89785. * if initialization succeeded.
  89786. *
  89787. * \note Support for Ogg FLAC in the library is optional. If this
  89788. * library has been built without support for Ogg FLAC, this function
  89789. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89790. *
  89791. * \param decoder An uninitialized decoder instance.
  89792. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89793. * pointer must not be \c NULL.
  89794. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89795. * pointer may be \c NULL if seeking is not
  89796. * supported. If \a seek_callback is not \c NULL then a
  89797. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89798. * Alternatively, a dummy seek callback that just
  89799. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89800. * may also be supplied, all though this is slightly
  89801. * less efficient for the decoder.
  89802. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89803. * pointer may be \c NULL if not supported by the client. If
  89804. * \a seek_callback is not \c NULL then a
  89805. * \a tell_callback must also be supplied.
  89806. * Alternatively, a dummy tell callback that just
  89807. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89808. * may also be supplied, all though this is slightly
  89809. * less efficient for the decoder.
  89810. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89811. * pointer may be \c NULL if not supported by the client. If
  89812. * \a seek_callback is not \c NULL then a
  89813. * \a length_callback must also be supplied.
  89814. * Alternatively, a dummy length callback that just
  89815. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89816. * may also be supplied, all though this is slightly
  89817. * less efficient for the decoder.
  89818. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89819. * pointer may be \c NULL if not supported by the client. If
  89820. * \a seek_callback is not \c NULL then a
  89821. * \a eof_callback must also be supplied.
  89822. * Alternatively, a dummy length callback that just
  89823. * returns \c false
  89824. * may also be supplied, all though this is slightly
  89825. * less efficient for the decoder.
  89826. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89827. * pointer must not be \c NULL.
  89828. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89829. * pointer may be \c NULL if the callback is not
  89830. * desired.
  89831. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89832. * pointer must not be \c NULL.
  89833. * \param client_data This value will be supplied to callbacks in their
  89834. * \a client_data argument.
  89835. * \assert
  89836. * \code decoder != NULL \endcode
  89837. * \retval FLAC__StreamDecoderInitStatus
  89838. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89839. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89840. */
  89841. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89842. FLAC__StreamDecoder *decoder,
  89843. FLAC__StreamDecoderReadCallback read_callback,
  89844. FLAC__StreamDecoderSeekCallback seek_callback,
  89845. FLAC__StreamDecoderTellCallback tell_callback,
  89846. FLAC__StreamDecoderLengthCallback length_callback,
  89847. FLAC__StreamDecoderEofCallback eof_callback,
  89848. FLAC__StreamDecoderWriteCallback write_callback,
  89849. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89850. FLAC__StreamDecoderErrorCallback error_callback,
  89851. void *client_data
  89852. );
  89853. /** Initialize the decoder instance to decode native FLAC files.
  89854. *
  89855. * This flavor of initialization sets up the decoder to decode from a
  89856. * plain native FLAC file. For non-stdio streams, you must use
  89857. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89858. *
  89859. * This function should be called after FLAC__stream_decoder_new() and
  89860. * FLAC__stream_decoder_set_*() but before any of the
  89861. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89862. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89863. * if initialization succeeded.
  89864. *
  89865. * \param decoder An uninitialized decoder instance.
  89866. * \param file An open FLAC file. The file should have been
  89867. * opened with mode \c "rb" and rewound. The file
  89868. * becomes owned by the decoder and should not be
  89869. * manipulated by the client while decoding.
  89870. * Unless \a file is \c stdin, it will be closed
  89871. * when FLAC__stream_decoder_finish() is called.
  89872. * Note however that seeking will not work when
  89873. * decoding from \c stdout since it is not seekable.
  89874. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89875. * pointer must not be \c NULL.
  89876. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89877. * pointer may be \c NULL if the callback is not
  89878. * desired.
  89879. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89880. * pointer must not be \c NULL.
  89881. * \param client_data This value will be supplied to callbacks in their
  89882. * \a client_data argument.
  89883. * \assert
  89884. * \code decoder != NULL \endcode
  89885. * \code file != NULL \endcode
  89886. * \retval FLAC__StreamDecoderInitStatus
  89887. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89888. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89889. */
  89890. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89891. FLAC__StreamDecoder *decoder,
  89892. FILE *file,
  89893. FLAC__StreamDecoderWriteCallback write_callback,
  89894. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89895. FLAC__StreamDecoderErrorCallback error_callback,
  89896. void *client_data
  89897. );
  89898. /** Initialize the decoder instance to decode Ogg FLAC files.
  89899. *
  89900. * This flavor of initialization sets up the decoder to decode from a
  89901. * plain Ogg FLAC file. For non-stdio streams, you must use
  89902. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89903. *
  89904. * This function should be called after FLAC__stream_decoder_new() and
  89905. * FLAC__stream_decoder_set_*() but before any of the
  89906. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89907. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89908. * if initialization succeeded.
  89909. *
  89910. * \note Support for Ogg FLAC in the library is optional. If this
  89911. * library has been built without support for Ogg FLAC, this function
  89912. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89913. *
  89914. * \param decoder An uninitialized decoder instance.
  89915. * \param file An open FLAC file. The file should have been
  89916. * opened with mode \c "rb" and rewound. The file
  89917. * becomes owned by the decoder and should not be
  89918. * manipulated by the client while decoding.
  89919. * Unless \a file is \c stdin, it will be closed
  89920. * when FLAC__stream_decoder_finish() is called.
  89921. * Note however that seeking will not work when
  89922. * decoding from \c stdout since it is not seekable.
  89923. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89924. * pointer must not be \c NULL.
  89925. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89926. * pointer may be \c NULL if the callback is not
  89927. * desired.
  89928. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89929. * pointer must not be \c NULL.
  89930. * \param client_data This value will be supplied to callbacks in their
  89931. * \a client_data argument.
  89932. * \assert
  89933. * \code decoder != NULL \endcode
  89934. * \code file != NULL \endcode
  89935. * \retval FLAC__StreamDecoderInitStatus
  89936. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89937. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89938. */
  89939. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89940. FLAC__StreamDecoder *decoder,
  89941. FILE *file,
  89942. FLAC__StreamDecoderWriteCallback write_callback,
  89943. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89944. FLAC__StreamDecoderErrorCallback error_callback,
  89945. void *client_data
  89946. );
  89947. /** Initialize the decoder instance to decode native FLAC files.
  89948. *
  89949. * This flavor of initialization sets up the decoder to decode from a plain
  89950. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89951. * example, with Unicode filenames on Windows), you must use
  89952. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89953. * and provide callbacks for the I/O.
  89954. *
  89955. * This function should be called after FLAC__stream_decoder_new() and
  89956. * FLAC__stream_decoder_set_*() but before any of the
  89957. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89958. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89959. * if initialization succeeded.
  89960. *
  89961. * \param decoder An uninitialized decoder instance.
  89962. * \param filename The name of the file to decode from. The file will
  89963. * be opened with fopen(). Use \c NULL to decode from
  89964. * \c stdin. Note that \c stdin is not seekable.
  89965. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89966. * pointer must not be \c NULL.
  89967. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89968. * pointer may be \c NULL if the callback is not
  89969. * desired.
  89970. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89971. * pointer must not be \c NULL.
  89972. * \param client_data This value will be supplied to callbacks in their
  89973. * \a client_data argument.
  89974. * \assert
  89975. * \code decoder != NULL \endcode
  89976. * \retval FLAC__StreamDecoderInitStatus
  89977. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89978. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89979. */
  89980. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89981. FLAC__StreamDecoder *decoder,
  89982. const char *filename,
  89983. FLAC__StreamDecoderWriteCallback write_callback,
  89984. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89985. FLAC__StreamDecoderErrorCallback error_callback,
  89986. void *client_data
  89987. );
  89988. /** Initialize the decoder instance to decode Ogg FLAC files.
  89989. *
  89990. * This flavor of initialization sets up the decoder to decode from a plain
  89991. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89992. * example, with Unicode filenames on Windows), you must use
  89993. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89994. * and provide callbacks for the I/O.
  89995. *
  89996. * This function should be called after FLAC__stream_decoder_new() and
  89997. * FLAC__stream_decoder_set_*() but before any of the
  89998. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89999. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90000. * if initialization succeeded.
  90001. *
  90002. * \note Support for Ogg FLAC in the library is optional. If this
  90003. * library has been built without support for Ogg FLAC, this function
  90004. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90005. *
  90006. * \param decoder An uninitialized decoder instance.
  90007. * \param filename The name of the file to decode from. The file will
  90008. * be opened with fopen(). Use \c NULL to decode from
  90009. * \c stdin. Note that \c stdin is not seekable.
  90010. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90011. * pointer must not be \c NULL.
  90012. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90013. * pointer may be \c NULL if the callback is not
  90014. * desired.
  90015. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90016. * pointer must not be \c NULL.
  90017. * \param client_data This value will be supplied to callbacks in their
  90018. * \a client_data argument.
  90019. * \assert
  90020. * \code decoder != NULL \endcode
  90021. * \retval FLAC__StreamDecoderInitStatus
  90022. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90023. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90024. */
  90025. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90026. FLAC__StreamDecoder *decoder,
  90027. const char *filename,
  90028. FLAC__StreamDecoderWriteCallback write_callback,
  90029. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90030. FLAC__StreamDecoderErrorCallback error_callback,
  90031. void *client_data
  90032. );
  90033. /** Finish the decoding process.
  90034. * Flushes the decoding buffer, releases resources, resets the decoder
  90035. * settings to their defaults, and returns the decoder state to
  90036. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90037. *
  90038. * In the event of a prematurely-terminated decode, it is not strictly
  90039. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90040. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90041. * with a FLAC__stream_decoder_finish().
  90042. *
  90043. * \param decoder An uninitialized decoder instance.
  90044. * \assert
  90045. * \code decoder != NULL \endcode
  90046. * \retval FLAC__bool
  90047. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90048. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90049. * signature does not match the one computed by the decoder; else
  90050. * \c true.
  90051. */
  90052. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90053. /** Flush the stream input.
  90054. * The decoder's input buffer will be cleared and the state set to
  90055. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90056. * off MD5 checking.
  90057. *
  90058. * \param decoder A decoder instance.
  90059. * \assert
  90060. * \code decoder != NULL \endcode
  90061. * \retval FLAC__bool
  90062. * \c true if successful, else \c false if a memory allocation
  90063. * error occurs (in which case the state will be set to
  90064. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90065. */
  90066. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90067. /** Reset the decoding process.
  90068. * The decoder's input buffer will be cleared and the state set to
  90069. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90070. * FLAC__stream_decoder_finish() except that the settings are
  90071. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90072. * before decoding again. MD5 checking will be restored to its original
  90073. * setting.
  90074. *
  90075. * If the decoder is seekable, or was initialized with
  90076. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90077. * the decoder will also attempt to seek to the beginning of the file.
  90078. * If this rewind fails, this function will return \c false. It follows
  90079. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90080. * \c stdin.
  90081. *
  90082. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90083. * and is not seekable (i.e. no seek callback was provided or the seek
  90084. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90085. * is the duty of the client to start feeding data from the beginning of
  90086. * the stream on the next FLAC__stream_decoder_process() or
  90087. * FLAC__stream_decoder_process_interleaved() call.
  90088. *
  90089. * \param decoder A decoder instance.
  90090. * \assert
  90091. * \code decoder != NULL \endcode
  90092. * \retval FLAC__bool
  90093. * \c true if successful, else \c false if a memory allocation occurs
  90094. * (in which case the state will be set to
  90095. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90096. * occurs (the state will be unchanged).
  90097. */
  90098. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90099. /** Decode one metadata block or audio frame.
  90100. * This version instructs the decoder to decode a either a single metadata
  90101. * block or a single frame and stop, unless the callbacks return a fatal
  90102. * error or the read callback returns
  90103. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90104. *
  90105. * As the decoder needs more input it will call the read callback.
  90106. * Depending on what was decoded, the metadata or write callback will be
  90107. * called with the decoded metadata block or audio frame.
  90108. *
  90109. * Unless there is a fatal read error or end of stream, this function
  90110. * will return once one whole frame is decoded. In other words, if the
  90111. * stream is not synchronized or points to a corrupt frame header, the
  90112. * decoder will continue to try and resync until it gets to a valid
  90113. * frame, then decode one frame, then return. If the decoder points to
  90114. * a frame whose frame CRC in the frame footer does not match the
  90115. * computed frame CRC, this function will issue a
  90116. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90117. * error callback, and return, having decoded one complete, although
  90118. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90119. * correct length to the write callback.)
  90120. *
  90121. * \param decoder An initialized decoder instance.
  90122. * \assert
  90123. * \code decoder != NULL \endcode
  90124. * \retval FLAC__bool
  90125. * \c false if any fatal read, write, or memory allocation error
  90126. * occurred (meaning decoding must stop), else \c true; for more
  90127. * information about the decoder, check the decoder state with
  90128. * FLAC__stream_decoder_get_state().
  90129. */
  90130. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90131. /** Decode until the end of the metadata.
  90132. * This version instructs the decoder to decode from the current position
  90133. * and continue until all the metadata has been read, or until the
  90134. * callbacks return a fatal error or the read callback returns
  90135. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90136. *
  90137. * As the decoder needs more input it will call the read callback.
  90138. * As each metadata block is decoded, the metadata callback will be called
  90139. * with the decoded metadata.
  90140. *
  90141. * \param decoder An initialized decoder instance.
  90142. * \assert
  90143. * \code decoder != NULL \endcode
  90144. * \retval FLAC__bool
  90145. * \c false if any fatal read, write, or memory allocation error
  90146. * occurred (meaning decoding must stop), else \c true; for more
  90147. * information about the decoder, check the decoder state with
  90148. * FLAC__stream_decoder_get_state().
  90149. */
  90150. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90151. /** Decode until the end of the stream.
  90152. * This version instructs the decoder to decode from the current position
  90153. * and continue until the end of stream (the read callback returns
  90154. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90155. * callbacks return a fatal error.
  90156. *
  90157. * As the decoder needs more input it will call the read callback.
  90158. * As each metadata block and frame is decoded, the metadata or write
  90159. * callback will be called with the decoded metadata or frame.
  90160. *
  90161. * \param decoder An initialized decoder instance.
  90162. * \assert
  90163. * \code decoder != NULL \endcode
  90164. * \retval FLAC__bool
  90165. * \c false if any fatal read, write, or memory allocation error
  90166. * occurred (meaning decoding must stop), else \c true; for more
  90167. * information about the decoder, check the decoder state with
  90168. * FLAC__stream_decoder_get_state().
  90169. */
  90170. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90171. /** Skip one audio frame.
  90172. * This version instructs the decoder to 'skip' a single frame and stop,
  90173. * unless the callbacks return a fatal error or the read callback returns
  90174. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90175. *
  90176. * The decoding flow is the same as what occurs when
  90177. * FLAC__stream_decoder_process_single() is called to process an audio
  90178. * frame, except that this function does not decode the parsed data into
  90179. * PCM or call the write callback. The integrity of the frame is still
  90180. * checked the same way as in the other process functions.
  90181. *
  90182. * This function will return once one whole frame is skipped, in the
  90183. * same way that FLAC__stream_decoder_process_single() will return once
  90184. * one whole frame is decoded.
  90185. *
  90186. * This function can be used in more quickly determining FLAC frame
  90187. * boundaries when decoding of the actual data is not needed, for
  90188. * example when an application is separating a FLAC stream into frames
  90189. * for editing or storing in a container. To do this, the application
  90190. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90191. * to the next frame, then use
  90192. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90193. * boundary.
  90194. *
  90195. * This function should only be called when the stream has advanced
  90196. * past all the metadata, otherwise it will return \c false.
  90197. *
  90198. * \param decoder An initialized decoder instance not in a metadata
  90199. * state.
  90200. * \assert
  90201. * \code decoder != NULL \endcode
  90202. * \retval FLAC__bool
  90203. * \c false if any fatal read, write, or memory allocation error
  90204. * occurred (meaning decoding must stop), or if the decoder
  90205. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90206. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90207. * information about the decoder, check the decoder state with
  90208. * FLAC__stream_decoder_get_state().
  90209. */
  90210. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90211. /** Flush the input and seek to an absolute sample.
  90212. * Decoding will resume at the given sample. Note that because of
  90213. * this, the next write callback may contain a partial block. The
  90214. * client must support seeking the input or this function will fail
  90215. * and return \c false. Furthermore, if the decoder state is
  90216. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90217. * with FLAC__stream_decoder_flush() or reset with
  90218. * FLAC__stream_decoder_reset() before decoding can continue.
  90219. *
  90220. * \param decoder A decoder instance.
  90221. * \param sample The target sample number to seek to.
  90222. * \assert
  90223. * \code decoder != NULL \endcode
  90224. * \retval FLAC__bool
  90225. * \c true if successful, else \c false.
  90226. */
  90227. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90228. /* \} */
  90229. #ifdef __cplusplus
  90230. }
  90231. #endif
  90232. #endif
  90233. /*** End of inlined file: stream_decoder.h ***/
  90234. /*** Start of inlined file: stream_encoder.h ***/
  90235. #ifndef FLAC__STREAM_ENCODER_H
  90236. #define FLAC__STREAM_ENCODER_H
  90237. #include <stdio.h> /* for FILE */
  90238. #ifdef __cplusplus
  90239. extern "C" {
  90240. #endif
  90241. /** \file include/FLAC/stream_encoder.h
  90242. *
  90243. * \brief
  90244. * This module contains the functions which implement the stream
  90245. * encoder.
  90246. *
  90247. * See the detailed documentation in the
  90248. * \link flac_stream_encoder stream encoder \endlink module.
  90249. */
  90250. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90251. * \ingroup flac
  90252. *
  90253. * \brief
  90254. * This module describes the encoder layers provided by libFLAC.
  90255. *
  90256. * The stream encoder can be used to encode complete streams either to the
  90257. * client via callbacks, or directly to a file, depending on how it is
  90258. * initialized. When encoding via callbacks, the client provides a write
  90259. * callback which will be called whenever FLAC data is ready to be written.
  90260. * If the client also supplies a seek callback, the encoder will also
  90261. * automatically handle the writing back of metadata discovered while
  90262. * encoding, like stream info, seek points offsets, etc. When encoding to
  90263. * a file, the client needs only supply a filename or open \c FILE* and an
  90264. * optional progress callback for periodic notification of progress; the
  90265. * write and seek callbacks are supplied internally. For more info see the
  90266. * \link flac_stream_encoder stream encoder \endlink module.
  90267. */
  90268. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90269. * \ingroup flac_encoder
  90270. *
  90271. * \brief
  90272. * This module contains the functions which implement the stream
  90273. * encoder.
  90274. *
  90275. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90276. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90277. *
  90278. * The basic usage of this encoder is as follows:
  90279. * - The program creates an instance of an encoder using
  90280. * FLAC__stream_encoder_new().
  90281. * - The program overrides the default settings using
  90282. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90283. * functions should be called:
  90284. * - FLAC__stream_encoder_set_channels()
  90285. * - FLAC__stream_encoder_set_bits_per_sample()
  90286. * - FLAC__stream_encoder_set_sample_rate()
  90287. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90288. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90289. * - If the application wants to control the compression level or set its own
  90290. * metadata, then the following should also be called:
  90291. * - FLAC__stream_encoder_set_compression_level()
  90292. * - FLAC__stream_encoder_set_verify()
  90293. * - FLAC__stream_encoder_set_metadata()
  90294. * - The rest of the set functions should only be called if the client needs
  90295. * exact control over how the audio is compressed; thorough understanding
  90296. * of the FLAC format is necessary to achieve good results.
  90297. * - The program initializes the instance to validate the settings and
  90298. * prepare for encoding using
  90299. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90300. * or FLAC__stream_encoder_init_file() for native FLAC
  90301. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90302. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90303. * - The program calls FLAC__stream_encoder_process() or
  90304. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90305. * subsequently calls the callbacks when there is encoder data ready
  90306. * to be written.
  90307. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90308. * which causes the encoder to encode any data still in its input pipe,
  90309. * update the metadata with the final encoding statistics if output
  90310. * seeking is possible, and finally reset the encoder to the
  90311. * uninitialized state.
  90312. * - The instance may be used again or deleted with
  90313. * FLAC__stream_encoder_delete().
  90314. *
  90315. * In more detail, the stream encoder functions similarly to the
  90316. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90317. * callbacks and more options. Typically the client will create a new
  90318. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90319. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90320. * calling one of the FLAC__stream_encoder_init_*() functions.
  90321. *
  90322. * Unlike the decoders, the stream encoder has many options that can
  90323. * affect the speed and compression ratio. When setting these parameters
  90324. * you should have some basic knowledge of the format (see the
  90325. * <A HREF="../documentation.html#format">user-level documentation</A>
  90326. * or the <A HREF="../format.html">formal description</A>). The
  90327. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90328. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90329. * functions will do this, so make sure to pay attention to the state
  90330. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90331. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90332. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90333. * the constructor.
  90334. *
  90335. * There are three initialization functions for native FLAC, one for
  90336. * setting up the encoder to encode FLAC data to the client via
  90337. * callbacks, and two for encoding directly to a file.
  90338. *
  90339. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90340. * You must also supply a write callback which will be called anytime
  90341. * there is raw encoded data to write. If the client can seek the output
  90342. * it is best to also supply seek and tell callbacks, as this allows the
  90343. * encoder to go back after encoding is finished to write back
  90344. * information that was collected while encoding, like seek point offsets,
  90345. * frame sizes, etc.
  90346. *
  90347. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90348. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90349. * filename or open \c FILE*; the encoder will handle all the callbacks
  90350. * internally. You may also supply a progress callback for periodic
  90351. * notification of the encoding progress.
  90352. *
  90353. * There are three similarly-named init functions for encoding to Ogg
  90354. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90355. * library has been built with Ogg support.
  90356. *
  90357. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90358. * call the write callback several times, once with the \c fLaC signature,
  90359. * and once for each encoded metadata block. Note that for Ogg FLAC
  90360. * encoding you will usually get at least twice the number of callbacks than
  90361. * with native FLAC, one for the Ogg page header and one for the page body.
  90362. *
  90363. * After initializing the instance, the client may feed audio data to the
  90364. * encoder in one of two ways:
  90365. *
  90366. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90367. * will pass an array of pointers to buffers, one for each channel, to
  90368. * the encoder, each of the same length. The samples need not be
  90369. * block-aligned, but each channel should have the same number of samples.
  90370. * - Channel interleaved, through
  90371. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90372. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90373. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90374. * Again, the samples need not be block-aligned but they must be
  90375. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90376. * the last value channelN_sampleM.
  90377. *
  90378. * Note that for either process call, each sample in the buffers should be a
  90379. * signed integer, right-justified to the resolution set by
  90380. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90381. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90382. *
  90383. * When the client is finished encoding data, it calls
  90384. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90385. * data still in its input pipe, and call the metadata callback with the
  90386. * final encoding statistics. Then the instance may be deleted with
  90387. * FLAC__stream_encoder_delete() or initialized again to encode another
  90388. * stream.
  90389. *
  90390. * For programs that write their own metadata, but that do not know the
  90391. * actual metadata until after encoding, it is advantageous to instruct
  90392. * the encoder to write a PADDING block of the correct size, so that
  90393. * instead of rewriting the whole stream after encoding, the program can
  90394. * just overwrite the PADDING block. If only the maximum size of the
  90395. * metadata is known, the program can write a slightly larger padding
  90396. * block, then split it after encoding.
  90397. *
  90398. * Make sure you understand how lengths are calculated. All FLAC metadata
  90399. * blocks have a 4 byte header which contains the type and length. This
  90400. * length does not include the 4 bytes of the header. See the format page
  90401. * for the specification of metadata blocks and their lengths.
  90402. *
  90403. * \note
  90404. * If you are writing the FLAC data to a file via callbacks, make sure it
  90405. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90406. * after the first encoding pass, the encoder will try to seek back to the
  90407. * beginning of the stream, to the STREAMINFO block, to write some data
  90408. * there. (If using FLAC__stream_encoder_init*_file() or
  90409. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90410. *
  90411. * \note
  90412. * The "set" functions may only be called when the encoder is in the
  90413. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90414. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90415. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90416. * return \c true, otherwise \c false.
  90417. *
  90418. * \note
  90419. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90420. * defaults.
  90421. *
  90422. * \{
  90423. */
  90424. /** State values for a FLAC__StreamEncoder.
  90425. *
  90426. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90427. *
  90428. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90429. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90430. * must be deleted with FLAC__stream_encoder_delete().
  90431. */
  90432. typedef enum {
  90433. FLAC__STREAM_ENCODER_OK = 0,
  90434. /**< The encoder is in the normal OK state and samples can be processed. */
  90435. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90436. /**< The encoder is in the uninitialized state; one of the
  90437. * FLAC__stream_encoder_init_*() functions must be called before samples
  90438. * can be processed.
  90439. */
  90440. FLAC__STREAM_ENCODER_OGG_ERROR,
  90441. /**< An error occurred in the underlying Ogg layer. */
  90442. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90443. /**< An error occurred in the underlying verify stream decoder;
  90444. * check FLAC__stream_encoder_get_verify_decoder_state().
  90445. */
  90446. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90447. /**< The verify decoder detected a mismatch between the original
  90448. * audio signal and the decoded audio signal.
  90449. */
  90450. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90451. /**< One of the callbacks returned a fatal error. */
  90452. FLAC__STREAM_ENCODER_IO_ERROR,
  90453. /**< An I/O error occurred while opening/reading/writing a file.
  90454. * Check \c errno.
  90455. */
  90456. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90457. /**< An error occurred while writing the stream; usually, the
  90458. * write_callback returned an error.
  90459. */
  90460. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90461. /**< Memory allocation failed. */
  90462. } FLAC__StreamEncoderState;
  90463. /** Maps a FLAC__StreamEncoderState to a C string.
  90464. *
  90465. * Using a FLAC__StreamEncoderState as the index to this array
  90466. * will give the string equivalent. The contents should not be modified.
  90467. */
  90468. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90469. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90470. */
  90471. typedef enum {
  90472. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90473. /**< Initialization was successful. */
  90474. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90475. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90476. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90477. /**< The library was not compiled with support for the given container
  90478. * format.
  90479. */
  90480. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90481. /**< A required callback was not supplied. */
  90482. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90483. /**< The encoder has an invalid setting for number of channels. */
  90484. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90485. /**< The encoder has an invalid setting for bits-per-sample.
  90486. * FLAC supports 4-32 bps but the reference encoder currently supports
  90487. * only up to 24 bps.
  90488. */
  90489. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90490. /**< The encoder has an invalid setting for the input sample rate. */
  90491. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90492. /**< The encoder has an invalid setting for the block size. */
  90493. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90494. /**< The encoder has an invalid setting for the maximum LPC order. */
  90495. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90496. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90497. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90498. /**< The specified block size is less than the maximum LPC order. */
  90499. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90500. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90501. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90502. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90503. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90504. * - One of the metadata blocks contains an undefined type
  90505. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90506. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90507. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90508. */
  90509. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90510. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90511. * already initialized, usually because
  90512. * FLAC__stream_encoder_finish() was not called.
  90513. */
  90514. } FLAC__StreamEncoderInitStatus;
  90515. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90516. *
  90517. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90518. * will give the string equivalent. The contents should not be modified.
  90519. */
  90520. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90521. /** Return values for the FLAC__StreamEncoder read callback.
  90522. */
  90523. typedef enum {
  90524. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90525. /**< The read was OK and decoding can continue. */
  90526. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90527. /**< The read was attempted at the end of the stream. */
  90528. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90529. /**< An unrecoverable error occurred. */
  90530. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90531. /**< Client does not support reading back from the output. */
  90532. } FLAC__StreamEncoderReadStatus;
  90533. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90534. *
  90535. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90536. * will give the string equivalent. The contents should not be modified.
  90537. */
  90538. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90539. /** Return values for the FLAC__StreamEncoder write callback.
  90540. */
  90541. typedef enum {
  90542. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90543. /**< The write was OK and encoding can continue. */
  90544. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90545. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90546. } FLAC__StreamEncoderWriteStatus;
  90547. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90548. *
  90549. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90550. * will give the string equivalent. The contents should not be modified.
  90551. */
  90552. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90553. /** Return values for the FLAC__StreamEncoder seek callback.
  90554. */
  90555. typedef enum {
  90556. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90557. /**< The seek was OK and encoding can continue. */
  90558. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90559. /**< An unrecoverable error occurred. */
  90560. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90561. /**< Client does not support seeking. */
  90562. } FLAC__StreamEncoderSeekStatus;
  90563. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90564. *
  90565. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90566. * will give the string equivalent. The contents should not be modified.
  90567. */
  90568. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90569. /** Return values for the FLAC__StreamEncoder tell callback.
  90570. */
  90571. typedef enum {
  90572. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90573. /**< The tell was OK and encoding can continue. */
  90574. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90575. /**< An unrecoverable error occurred. */
  90576. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90577. /**< Client does not support seeking. */
  90578. } FLAC__StreamEncoderTellStatus;
  90579. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90580. *
  90581. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90582. * will give the string equivalent. The contents should not be modified.
  90583. */
  90584. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90585. /***********************************************************************
  90586. *
  90587. * class FLAC__StreamEncoder
  90588. *
  90589. ***********************************************************************/
  90590. struct FLAC__StreamEncoderProtected;
  90591. struct FLAC__StreamEncoderPrivate;
  90592. /** The opaque structure definition for the stream encoder type.
  90593. * See the \link flac_stream_encoder stream encoder module \endlink
  90594. * for a detailed description.
  90595. */
  90596. typedef struct {
  90597. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90598. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90599. } FLAC__StreamEncoder;
  90600. /** Signature for the read callback.
  90601. *
  90602. * A function pointer matching this signature must be passed to
  90603. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90604. * The supplied function will be called when the encoder needs to read back
  90605. * encoded data. This happens during the metadata callback, when the encoder
  90606. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90607. * while encoding. The address of the buffer to be filled is supplied, along
  90608. * with the number of bytes the buffer can hold. The callback may choose to
  90609. * supply less data and modify the byte count but must be careful not to
  90610. * overflow the buffer. The callback then returns a status code chosen from
  90611. * FLAC__StreamEncoderReadStatus.
  90612. *
  90613. * Here is an example of a read callback for stdio streams:
  90614. * \code
  90615. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90616. * {
  90617. * FILE *file = ((MyClientData*)client_data)->file;
  90618. * if(*bytes > 0) {
  90619. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90620. * if(ferror(file))
  90621. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90622. * else if(*bytes == 0)
  90623. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90624. * else
  90625. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90626. * }
  90627. * else
  90628. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90629. * }
  90630. * \endcode
  90631. *
  90632. * \note In general, FLAC__StreamEncoder functions which change the
  90633. * state should not be called on the \a encoder while in the callback.
  90634. *
  90635. * \param encoder The encoder instance calling the callback.
  90636. * \param buffer A pointer to a location for the callee to store
  90637. * data to be encoded.
  90638. * \param bytes A pointer to the size of the buffer. On entry
  90639. * to the callback, it contains the maximum number
  90640. * of bytes that may be stored in \a buffer. The
  90641. * callee must set it to the actual number of bytes
  90642. * stored (0 in case of error or end-of-stream) before
  90643. * returning.
  90644. * \param client_data The callee's client data set through
  90645. * FLAC__stream_encoder_set_client_data().
  90646. * \retval FLAC__StreamEncoderReadStatus
  90647. * The callee's return status.
  90648. */
  90649. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90650. /** Signature for the write callback.
  90651. *
  90652. * A function pointer matching this signature must be passed to
  90653. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90654. * by the encoder anytime there is raw encoded data ready to write. It may
  90655. * include metadata mixed with encoded audio frames and the data is not
  90656. * guaranteed to be aligned on frame or metadata block boundaries.
  90657. *
  90658. * The only duty of the callback is to write out the \a bytes worth of data
  90659. * in \a buffer to the current position in the output stream. The arguments
  90660. * \a samples and \a current_frame are purely informational. If \a samples
  90661. * is greater than \c 0, then \a current_frame will hold the current frame
  90662. * number that is being written; otherwise it indicates that the write
  90663. * callback is being called to write metadata.
  90664. *
  90665. * \note
  90666. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90667. * write callback will be called twice when writing each audio
  90668. * frame; once for the page header, and once for the page body.
  90669. * When writing the page header, the \a samples argument to the
  90670. * write callback will be \c 0.
  90671. *
  90672. * \note In general, FLAC__StreamEncoder functions which change the
  90673. * state should not be called on the \a encoder while in the callback.
  90674. *
  90675. * \param encoder The encoder instance calling the callback.
  90676. * \param buffer An array of encoded data of length \a bytes.
  90677. * \param bytes The byte length of \a buffer.
  90678. * \param samples The number of samples encoded by \a buffer.
  90679. * \c 0 has a special meaning; see above.
  90680. * \param current_frame The number of the current frame being encoded.
  90681. * \param client_data The callee's client data set through
  90682. * FLAC__stream_encoder_init_*().
  90683. * \retval FLAC__StreamEncoderWriteStatus
  90684. * The callee's return status.
  90685. */
  90686. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90687. /** Signature for the seek callback.
  90688. *
  90689. * A function pointer matching this signature may be passed to
  90690. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90691. * when the encoder needs to seek the output stream. The encoder will pass
  90692. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90693. *
  90694. * Here is an example of a seek callback for stdio streams:
  90695. * \code
  90696. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90697. * {
  90698. * FILE *file = ((MyClientData*)client_data)->file;
  90699. * if(file == stdin)
  90700. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90701. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90702. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90703. * else
  90704. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90705. * }
  90706. * \endcode
  90707. *
  90708. * \note In general, FLAC__StreamEncoder functions which change the
  90709. * state should not be called on the \a encoder while in the callback.
  90710. *
  90711. * \param encoder The encoder instance calling the callback.
  90712. * \param absolute_byte_offset The offset from the beginning of the stream
  90713. * to seek to.
  90714. * \param client_data The callee's client data set through
  90715. * FLAC__stream_encoder_init_*().
  90716. * \retval FLAC__StreamEncoderSeekStatus
  90717. * The callee's return status.
  90718. */
  90719. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90720. /** Signature for the tell callback.
  90721. *
  90722. * A function pointer matching this signature may be passed to
  90723. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90724. * when the encoder needs to know the current position of the output stream.
  90725. *
  90726. * \warning
  90727. * The callback must return the true current byte offset of the output to
  90728. * which the encoder is writing. If you are buffering the output, make
  90729. * sure and take this into account. If you are writing directly to a
  90730. * FILE* from your write callback, ftell() is sufficient. If you are
  90731. * writing directly to a file descriptor from your write callback, you
  90732. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90733. * these points to rewrite metadata after encoding.
  90734. *
  90735. * Here is an example of a tell callback for stdio streams:
  90736. * \code
  90737. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90738. * {
  90739. * FILE *file = ((MyClientData*)client_data)->file;
  90740. * off_t pos;
  90741. * if(file == stdin)
  90742. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90743. * else if((pos = ftello(file)) < 0)
  90744. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90745. * else {
  90746. * *absolute_byte_offset = (FLAC__uint64)pos;
  90747. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90748. * }
  90749. * }
  90750. * \endcode
  90751. *
  90752. * \note In general, FLAC__StreamEncoder functions which change the
  90753. * state should not be called on the \a encoder while in the callback.
  90754. *
  90755. * \param encoder The encoder instance calling the callback.
  90756. * \param absolute_byte_offset The address at which to store the current
  90757. * position of the output.
  90758. * \param client_data The callee's client data set through
  90759. * FLAC__stream_encoder_init_*().
  90760. * \retval FLAC__StreamEncoderTellStatus
  90761. * The callee's return status.
  90762. */
  90763. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90764. /** Signature for the metadata callback.
  90765. *
  90766. * A function pointer matching this signature may be passed to
  90767. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90768. * once at the end of encoding with the populated STREAMINFO structure. This
  90769. * is so the client can seek back to the beginning of the file and write the
  90770. * STREAMINFO block with the correct statistics after encoding (like
  90771. * minimum/maximum frame size and total samples).
  90772. *
  90773. * \note In general, FLAC__StreamEncoder functions which change the
  90774. * state should not be called on the \a encoder while in the callback.
  90775. *
  90776. * \param encoder The encoder instance calling the callback.
  90777. * \param metadata The final populated STREAMINFO block.
  90778. * \param client_data The callee's client data set through
  90779. * FLAC__stream_encoder_init_*().
  90780. */
  90781. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90782. /** Signature for the progress callback.
  90783. *
  90784. * A function pointer matching this signature may be passed to
  90785. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90786. * The supplied function will be called when the encoder has finished
  90787. * writing a frame. The \c total_frames_estimate argument to the
  90788. * callback will be based on the value from
  90789. * FLAC__stream_encoder_set_total_samples_estimate().
  90790. *
  90791. * \note In general, FLAC__StreamEncoder functions which change the
  90792. * state should not be called on the \a encoder while in the callback.
  90793. *
  90794. * \param encoder The encoder instance calling the callback.
  90795. * \param bytes_written Bytes written so far.
  90796. * \param samples_written Samples written so far.
  90797. * \param frames_written Frames written so far.
  90798. * \param total_frames_estimate The estimate of the total number of
  90799. * frames to be written.
  90800. * \param client_data The callee's client data set through
  90801. * FLAC__stream_encoder_init_*().
  90802. */
  90803. 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);
  90804. /***********************************************************************
  90805. *
  90806. * Class constructor/destructor
  90807. *
  90808. ***********************************************************************/
  90809. /** Create a new stream encoder instance. The instance is created with
  90810. * default settings; see the individual FLAC__stream_encoder_set_*()
  90811. * functions for each setting's default.
  90812. *
  90813. * \retval FLAC__StreamEncoder*
  90814. * \c NULL if there was an error allocating memory, else the new instance.
  90815. */
  90816. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90817. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90818. *
  90819. * \param encoder A pointer to an existing encoder.
  90820. * \assert
  90821. * \code encoder != NULL \endcode
  90822. */
  90823. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90824. /***********************************************************************
  90825. *
  90826. * Public class method prototypes
  90827. *
  90828. ***********************************************************************/
  90829. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90830. *
  90831. * \note
  90832. * This does not need to be set for native FLAC encoding.
  90833. *
  90834. * \note
  90835. * It is recommended to set a serial number explicitly as the default of '0'
  90836. * may collide with other streams.
  90837. *
  90838. * \default \c 0
  90839. * \param encoder An encoder instance to set.
  90840. * \param serial_number See above.
  90841. * \assert
  90842. * \code encoder != NULL \endcode
  90843. * \retval FLAC__bool
  90844. * \c false if the encoder is already initialized, else \c true.
  90845. */
  90846. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90847. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90848. * encoded output by feeding it through an internal decoder and comparing
  90849. * the original signal against the decoded signal. If a mismatch occurs,
  90850. * the process call will return \c false. Note that this will slow the
  90851. * encoding process by the extra time required for decoding and comparison.
  90852. *
  90853. * \default \c false
  90854. * \param encoder An encoder instance to set.
  90855. * \param value Flag value (see above).
  90856. * \assert
  90857. * \code encoder != NULL \endcode
  90858. * \retval FLAC__bool
  90859. * \c false if the encoder is already initialized, else \c true.
  90860. */
  90861. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90862. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90863. * the encoder will comply with the Subset and will check the
  90864. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90865. * comply. If \c false, the settings may take advantage of the full
  90866. * range that the format allows.
  90867. *
  90868. * Make sure you know what it entails before setting this to \c false.
  90869. *
  90870. * \default \c true
  90871. * \param encoder An encoder instance to set.
  90872. * \param value Flag value (see above).
  90873. * \assert
  90874. * \code encoder != NULL \endcode
  90875. * \retval FLAC__bool
  90876. * \c false if the encoder is already initialized, else \c true.
  90877. */
  90878. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90879. /** Set the number of channels to be encoded.
  90880. *
  90881. * \default \c 2
  90882. * \param encoder An encoder instance to set.
  90883. * \param value See above.
  90884. * \assert
  90885. * \code encoder != NULL \endcode
  90886. * \retval FLAC__bool
  90887. * \c false if the encoder is already initialized, else \c true.
  90888. */
  90889. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90890. /** Set the sample resolution of the input to be encoded.
  90891. *
  90892. * \warning
  90893. * Do not feed the encoder data that is wider than the value you
  90894. * set here or you will generate an invalid stream.
  90895. *
  90896. * \default \c 16
  90897. * \param encoder An encoder instance to set.
  90898. * \param value See above.
  90899. * \assert
  90900. * \code encoder != NULL \endcode
  90901. * \retval FLAC__bool
  90902. * \c false if the encoder is already initialized, else \c true.
  90903. */
  90904. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90905. /** Set the sample rate (in Hz) of the input to be encoded.
  90906. *
  90907. * \default \c 44100
  90908. * \param encoder An encoder instance to set.
  90909. * \param value See above.
  90910. * \assert
  90911. * \code encoder != NULL \endcode
  90912. * \retval FLAC__bool
  90913. * \c false if the encoder is already initialized, else \c true.
  90914. */
  90915. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90916. /** Set the compression level
  90917. *
  90918. * The compression level is roughly proportional to the amount of effort
  90919. * the encoder expends to compress the file. A higher level usually
  90920. * means more computation but higher compression. The default level is
  90921. * suitable for most applications.
  90922. *
  90923. * Currently the levels range from \c 0 (fastest, least compression) to
  90924. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90925. * treated as \c 8.
  90926. *
  90927. * This function automatically calls the following other \c _set_
  90928. * functions with appropriate values, so the client does not need to
  90929. * unless it specifically wants to override them:
  90930. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90931. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90932. * - FLAC__stream_encoder_set_apodization()
  90933. * - FLAC__stream_encoder_set_max_lpc_order()
  90934. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90935. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90936. * - FLAC__stream_encoder_set_do_escape_coding()
  90937. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90938. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90939. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90940. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90941. *
  90942. * The actual values set for each level are:
  90943. * <table>
  90944. * <tr>
  90945. * <td><b>level</b><td>
  90946. * <td>do mid-side stereo<td>
  90947. * <td>loose mid-side stereo<td>
  90948. * <td>apodization<td>
  90949. * <td>max lpc order<td>
  90950. * <td>qlp coeff precision<td>
  90951. * <td>qlp coeff prec search<td>
  90952. * <td>escape coding<td>
  90953. * <td>exhaustive model search<td>
  90954. * <td>min residual partition order<td>
  90955. * <td>max residual partition order<td>
  90956. * <td>rice parameter search dist<td>
  90957. * </tr>
  90958. * <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>
  90959. * <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>
  90960. * <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>
  90961. * <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>
  90962. * <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>
  90963. * <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>
  90964. * <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>
  90965. * <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>
  90966. * <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>
  90967. * </table>
  90968. *
  90969. * \default \c 5
  90970. * \param encoder An encoder instance to set.
  90971. * \param value See above.
  90972. * \assert
  90973. * \code encoder != NULL \endcode
  90974. * \retval FLAC__bool
  90975. * \c false if the encoder is already initialized, else \c true.
  90976. */
  90977. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90978. /** Set the blocksize to use while encoding.
  90979. *
  90980. * The number of samples to use per frame. Use \c 0 to let the encoder
  90981. * estimate a blocksize; this is usually best.
  90982. *
  90983. * \default \c 0
  90984. * \param encoder An encoder instance to set.
  90985. * \param value See above.
  90986. * \assert
  90987. * \code encoder != NULL \endcode
  90988. * \retval FLAC__bool
  90989. * \c false if the encoder is already initialized, else \c true.
  90990. */
  90991. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90992. /** Set to \c true to enable mid-side encoding on stereo input. The
  90993. * number of channels must be 2 for this to have any effect. Set to
  90994. * \c false to use only independent channel coding.
  90995. *
  90996. * \default \c false
  90997. * \param encoder An encoder instance to set.
  90998. * \param value Flag value (see above).
  90999. * \assert
  91000. * \code encoder != NULL \endcode
  91001. * \retval FLAC__bool
  91002. * \c false if the encoder is already initialized, else \c true.
  91003. */
  91004. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91005. /** Set to \c true to enable adaptive switching between mid-side and
  91006. * left-right encoding on stereo input. Set to \c false to use
  91007. * exhaustive searching. Setting this to \c true requires
  91008. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91009. * \c true in order to have any effect.
  91010. *
  91011. * \default \c false
  91012. * \param encoder An encoder instance to set.
  91013. * \param value Flag value (see above).
  91014. * \assert
  91015. * \code encoder != NULL \endcode
  91016. * \retval FLAC__bool
  91017. * \c false if the encoder is already initialized, else \c true.
  91018. */
  91019. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91020. /** Sets the apodization function(s) the encoder will use when windowing
  91021. * audio data for LPC analysis.
  91022. *
  91023. * The \a specification is a plain ASCII string which specifies exactly
  91024. * which functions to use. There may be more than one (up to 32),
  91025. * separated by \c ';' characters. Some functions take one or more
  91026. * comma-separated arguments in parentheses.
  91027. *
  91028. * The available functions are \c bartlett, \c bartlett_hann,
  91029. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91030. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91031. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91032. *
  91033. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91034. * (0<STDDEV<=0.5).
  91035. *
  91036. * For \c tukey(P), P specifies the fraction of the window that is
  91037. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91038. * corresponds to \c hann.
  91039. *
  91040. * Example specifications are \c "blackman" or
  91041. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91042. *
  91043. * Any function that is specified erroneously is silently dropped. Up
  91044. * to 32 functions are kept, the rest are dropped. If the specification
  91045. * is empty the encoder defaults to \c "tukey(0.5)".
  91046. *
  91047. * When more than one function is specified, then for every subframe the
  91048. * encoder will try each of them separately and choose the window that
  91049. * results in the smallest compressed subframe.
  91050. *
  91051. * Note that each function specified causes the encoder to occupy a
  91052. * floating point array in which to store the window.
  91053. *
  91054. * \default \c "tukey(0.5)"
  91055. * \param encoder An encoder instance to set.
  91056. * \param specification See above.
  91057. * \assert
  91058. * \code encoder != NULL \endcode
  91059. * \code specification != NULL \endcode
  91060. * \retval FLAC__bool
  91061. * \c false if the encoder is already initialized, else \c true.
  91062. */
  91063. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91064. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91065. *
  91066. * \default \c 0
  91067. * \param encoder An encoder instance to set.
  91068. * \param value See above.
  91069. * \assert
  91070. * \code encoder != NULL \endcode
  91071. * \retval FLAC__bool
  91072. * \c false if the encoder is already initialized, else \c true.
  91073. */
  91074. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91075. /** Set the precision, in bits, of the quantized linear predictor
  91076. * coefficients, or \c 0 to let the encoder select it based on the
  91077. * blocksize.
  91078. *
  91079. * \note
  91080. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91081. * be less than 32.
  91082. *
  91083. * \default \c 0
  91084. * \param encoder An encoder instance to set.
  91085. * \param value See above.
  91086. * \assert
  91087. * \code encoder != NULL \endcode
  91088. * \retval FLAC__bool
  91089. * \c false if the encoder is already initialized, else \c true.
  91090. */
  91091. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91092. /** Set to \c false to use only the specified quantized linear predictor
  91093. * coefficient precision, or \c true to search neighboring precision
  91094. * values and use the best one.
  91095. *
  91096. * \default \c false
  91097. * \param encoder An encoder instance to set.
  91098. * \param value See above.
  91099. * \assert
  91100. * \code encoder != NULL \endcode
  91101. * \retval FLAC__bool
  91102. * \c false if the encoder is already initialized, else \c true.
  91103. */
  91104. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91105. /** Deprecated. Setting this value has no effect.
  91106. *
  91107. * \default \c false
  91108. * \param encoder An encoder instance to set.
  91109. * \param value See above.
  91110. * \assert
  91111. * \code encoder != NULL \endcode
  91112. * \retval FLAC__bool
  91113. * \c false if the encoder is already initialized, else \c true.
  91114. */
  91115. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91116. /** Set to \c false to let the encoder estimate the best model order
  91117. * based on the residual signal energy, or \c true to force the
  91118. * encoder to evaluate all order models and select the best.
  91119. *
  91120. * \default \c false
  91121. * \param encoder An encoder instance to set.
  91122. * \param value See above.
  91123. * \assert
  91124. * \code encoder != NULL \endcode
  91125. * \retval FLAC__bool
  91126. * \c false if the encoder is already initialized, else \c true.
  91127. */
  91128. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91129. /** Set the minimum partition order to search when coding the residual.
  91130. * This is used in tandem with
  91131. * FLAC__stream_encoder_set_max_residual_partition_order().
  91132. *
  91133. * The partition order determines the context size in the residual.
  91134. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91135. *
  91136. * Set both min and max values to \c 0 to force a single context,
  91137. * whose Rice parameter is based on the residual signal variance.
  91138. * Otherwise, set a min and max order, and the encoder will search
  91139. * all orders, using the mean of each context for its Rice parameter,
  91140. * and use the best.
  91141. *
  91142. * \default \c 0
  91143. * \param encoder An encoder instance to set.
  91144. * \param value See above.
  91145. * \assert
  91146. * \code encoder != NULL \endcode
  91147. * \retval FLAC__bool
  91148. * \c false if the encoder is already initialized, else \c true.
  91149. */
  91150. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91151. /** Set the maximum partition order to search when coding the residual.
  91152. * This is used in tandem with
  91153. * FLAC__stream_encoder_set_min_residual_partition_order().
  91154. *
  91155. * The partition order determines the context size in the residual.
  91156. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91157. *
  91158. * Set both min and max values to \c 0 to force a single context,
  91159. * whose Rice parameter is based on the residual signal variance.
  91160. * Otherwise, set a min and max order, and the encoder will search
  91161. * all orders, using the mean of each context for its Rice parameter,
  91162. * and use the best.
  91163. *
  91164. * \default \c 0
  91165. * \param encoder An encoder instance to set.
  91166. * \param value See above.
  91167. * \assert
  91168. * \code encoder != NULL \endcode
  91169. * \retval FLAC__bool
  91170. * \c false if the encoder is already initialized, else \c true.
  91171. */
  91172. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91173. /** Deprecated. Setting this value has no effect.
  91174. *
  91175. * \default \c 0
  91176. * \param encoder An encoder instance to set.
  91177. * \param value See above.
  91178. * \assert
  91179. * \code encoder != NULL \endcode
  91180. * \retval FLAC__bool
  91181. * \c false if the encoder is already initialized, else \c true.
  91182. */
  91183. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91184. /** Set an estimate of the total samples that will be encoded.
  91185. * This is merely an estimate and may be set to \c 0 if unknown.
  91186. * This value will be written to the STREAMINFO block before encoding,
  91187. * and can remove the need for the caller to rewrite the value later
  91188. * if the value is known before encoding.
  91189. *
  91190. * \default \c 0
  91191. * \param encoder An encoder instance to set.
  91192. * \param value See above.
  91193. * \assert
  91194. * \code encoder != NULL \endcode
  91195. * \retval FLAC__bool
  91196. * \c false if the encoder is already initialized, else \c true.
  91197. */
  91198. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91199. /** Set the metadata blocks to be emitted to the stream before encoding.
  91200. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91201. * array of pointers to metadata blocks. The array is non-const since
  91202. * the encoder may need to change the \a is_last flag inside them, and
  91203. * in some cases update seek point offsets. Otherwise, the encoder will
  91204. * not modify or free the blocks. It is up to the caller to free the
  91205. * metadata blocks after encoding finishes.
  91206. *
  91207. * \note
  91208. * The encoder stores only copies of the pointers in the \a metadata array;
  91209. * the metadata blocks themselves must survive at least until after
  91210. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91211. *
  91212. * \note
  91213. * The STREAMINFO block is always written and no STREAMINFO block may
  91214. * occur in the supplied array.
  91215. *
  91216. * \note
  91217. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91218. * in the \a metadata array, but the client has specified that it does not
  91219. * support seeking, then the SEEKTABLE will be written verbatim. However
  91220. * by itself this is not very useful as the client will not know the stream
  91221. * offsets for the seekpoints ahead of time. In order to get a proper
  91222. * seektable the client must support seeking. See next note.
  91223. *
  91224. * \note
  91225. * SEEKTABLE blocks are handled specially. Since you will not know
  91226. * the values for the seek point stream offsets, you should pass in
  91227. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91228. * required sample numbers (or placeholder points), with \c 0 for the
  91229. * \a frame_samples and \a stream_offset fields for each point. If the
  91230. * client has specified that it supports seeking by providing a seek
  91231. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91232. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91233. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91234. * then while it is encoding the encoder will fill the stream offsets in
  91235. * for you and when encoding is finished, it will seek back and write the
  91236. * real values into the SEEKTABLE block in the stream. There are helper
  91237. * routines for manipulating seektable template blocks; see metadata.h:
  91238. * FLAC__metadata_object_seektable_template_*(). If the client does
  91239. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91240. * will slow down or remove the ability to seek in the FLAC stream.
  91241. *
  91242. * \note
  91243. * The encoder instance \b will modify the first \c SEEKTABLE block
  91244. * as it transforms the template to a valid seektable while encoding,
  91245. * but it is still up to the caller to free all metadata blocks after
  91246. * encoding.
  91247. *
  91248. * \note
  91249. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91250. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91251. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91252. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91253. * block is present in the \a metadata array, libFLAC will write an
  91254. * empty one, containing only the vendor string.
  91255. *
  91256. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91257. * the second metadata block of the stream. The encoder already supplies
  91258. * the STREAMINFO block automatically. If \a metadata does not contain a
  91259. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91260. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91261. * first, the init function will reorder \a metadata by moving the
  91262. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91263. * blocks will remain as they were.
  91264. *
  91265. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91266. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91267. * return \c false.
  91268. *
  91269. * \default \c NULL, 0
  91270. * \param encoder An encoder instance to set.
  91271. * \param metadata See above.
  91272. * \param num_blocks See above.
  91273. * \assert
  91274. * \code encoder != NULL \endcode
  91275. * \retval FLAC__bool
  91276. * \c false if the encoder is already initialized, else \c true.
  91277. * \c false if the encoder is already initialized, or if
  91278. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91279. */
  91280. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91281. /** Get the current encoder state.
  91282. *
  91283. * \param encoder An encoder instance to query.
  91284. * \assert
  91285. * \code encoder != NULL \endcode
  91286. * \retval FLAC__StreamEncoderState
  91287. * The current encoder state.
  91288. */
  91289. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91290. /** Get the state of the verify stream decoder.
  91291. * Useful when the stream encoder state is
  91292. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91293. *
  91294. * \param encoder An encoder instance to query.
  91295. * \assert
  91296. * \code encoder != NULL \endcode
  91297. * \retval FLAC__StreamDecoderState
  91298. * The verify stream decoder state.
  91299. */
  91300. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91301. /** Get the current encoder state as a C string.
  91302. * This version automatically resolves
  91303. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91304. * verify decoder's state.
  91305. *
  91306. * \param encoder A encoder instance to query.
  91307. * \assert
  91308. * \code encoder != NULL \endcode
  91309. * \retval const char *
  91310. * The encoder state as a C string. Do not modify the contents.
  91311. */
  91312. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91313. /** Get relevant values about the nature of a verify decoder error.
  91314. * Useful when the stream encoder state is
  91315. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91316. * be addresses in which the stats will be returned, or NULL if value
  91317. * is not desired.
  91318. *
  91319. * \param encoder An encoder instance to query.
  91320. * \param absolute_sample The absolute sample number of the mismatch.
  91321. * \param frame_number The number of the frame in which the mismatch occurred.
  91322. * \param channel The channel in which the mismatch occurred.
  91323. * \param sample The number of the sample (relative to the frame) in
  91324. * which the mismatch occurred.
  91325. * \param expected The expected value for the sample in question.
  91326. * \param got The actual value returned by the decoder.
  91327. * \assert
  91328. * \code encoder != NULL \endcode
  91329. */
  91330. 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);
  91331. /** Get the "verify" flag.
  91332. *
  91333. * \param encoder An encoder instance to query.
  91334. * \assert
  91335. * \code encoder != NULL \endcode
  91336. * \retval FLAC__bool
  91337. * See FLAC__stream_encoder_set_verify().
  91338. */
  91339. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91340. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91341. *
  91342. * \param encoder An encoder instance to query.
  91343. * \assert
  91344. * \code encoder != NULL \endcode
  91345. * \retval FLAC__bool
  91346. * See FLAC__stream_encoder_set_streamable_subset().
  91347. */
  91348. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91349. /** Get the number of input channels being processed.
  91350. *
  91351. * \param encoder An encoder instance to query.
  91352. * \assert
  91353. * \code encoder != NULL \endcode
  91354. * \retval unsigned
  91355. * See FLAC__stream_encoder_set_channels().
  91356. */
  91357. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91358. /** Get the input sample resolution setting.
  91359. *
  91360. * \param encoder An encoder instance to query.
  91361. * \assert
  91362. * \code encoder != NULL \endcode
  91363. * \retval unsigned
  91364. * See FLAC__stream_encoder_set_bits_per_sample().
  91365. */
  91366. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91367. /** Get the input sample rate setting.
  91368. *
  91369. * \param encoder An encoder instance to query.
  91370. * \assert
  91371. * \code encoder != NULL \endcode
  91372. * \retval unsigned
  91373. * See FLAC__stream_encoder_set_sample_rate().
  91374. */
  91375. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91376. /** Get the blocksize setting.
  91377. *
  91378. * \param encoder An encoder instance to query.
  91379. * \assert
  91380. * \code encoder != NULL \endcode
  91381. * \retval unsigned
  91382. * See FLAC__stream_encoder_set_blocksize().
  91383. */
  91384. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91385. /** Get the "mid/side stereo coding" flag.
  91386. *
  91387. * \param encoder An encoder instance to query.
  91388. * \assert
  91389. * \code encoder != NULL \endcode
  91390. * \retval FLAC__bool
  91391. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91392. */
  91393. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91394. /** Get the "adaptive mid/side switching" flag.
  91395. *
  91396. * \param encoder An encoder instance to query.
  91397. * \assert
  91398. * \code encoder != NULL \endcode
  91399. * \retval FLAC__bool
  91400. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91401. */
  91402. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91403. /** Get the maximum LPC order setting.
  91404. *
  91405. * \param encoder An encoder instance to query.
  91406. * \assert
  91407. * \code encoder != NULL \endcode
  91408. * \retval unsigned
  91409. * See FLAC__stream_encoder_set_max_lpc_order().
  91410. */
  91411. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91412. /** Get the quantized linear predictor coefficient precision setting.
  91413. *
  91414. * \param encoder An encoder instance to query.
  91415. * \assert
  91416. * \code encoder != NULL \endcode
  91417. * \retval unsigned
  91418. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91419. */
  91420. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91421. /** Get the qlp coefficient precision search flag.
  91422. *
  91423. * \param encoder An encoder instance to query.
  91424. * \assert
  91425. * \code encoder != NULL \endcode
  91426. * \retval FLAC__bool
  91427. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91428. */
  91429. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91430. /** Get the "escape coding" flag.
  91431. *
  91432. * \param encoder An encoder instance to query.
  91433. * \assert
  91434. * \code encoder != NULL \endcode
  91435. * \retval FLAC__bool
  91436. * See FLAC__stream_encoder_set_do_escape_coding().
  91437. */
  91438. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91439. /** Get the exhaustive model search flag.
  91440. *
  91441. * \param encoder An encoder instance to query.
  91442. * \assert
  91443. * \code encoder != NULL \endcode
  91444. * \retval FLAC__bool
  91445. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91446. */
  91447. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91448. /** Get the minimum residual partition order setting.
  91449. *
  91450. * \param encoder An encoder instance to query.
  91451. * \assert
  91452. * \code encoder != NULL \endcode
  91453. * \retval unsigned
  91454. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91455. */
  91456. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91457. /** Get maximum residual partition order setting.
  91458. *
  91459. * \param encoder An encoder instance to query.
  91460. * \assert
  91461. * \code encoder != NULL \endcode
  91462. * \retval unsigned
  91463. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91464. */
  91465. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91466. /** Get the Rice parameter search distance setting.
  91467. *
  91468. * \param encoder An encoder instance to query.
  91469. * \assert
  91470. * \code encoder != NULL \endcode
  91471. * \retval unsigned
  91472. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91473. */
  91474. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91475. /** Get the previously set estimate of the total samples to be encoded.
  91476. * The encoder merely mimics back the value given to
  91477. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91478. * other way of knowing how many samples the client will encode.
  91479. *
  91480. * \param encoder An encoder instance to set.
  91481. * \assert
  91482. * \code encoder != NULL \endcode
  91483. * \retval FLAC__uint64
  91484. * See FLAC__stream_encoder_get_total_samples_estimate().
  91485. */
  91486. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91487. /** Initialize the encoder instance to encode native FLAC streams.
  91488. *
  91489. * This flavor of initialization sets up the encoder to encode to a
  91490. * native FLAC stream. I/O is performed via callbacks to the client.
  91491. * For encoding to a plain file via filename or open \c FILE*,
  91492. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91493. * provide a simpler interface.
  91494. *
  91495. * This function should be called after FLAC__stream_encoder_new() and
  91496. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91497. * or FLAC__stream_encoder_process_interleaved().
  91498. * initialization succeeded.
  91499. *
  91500. * The call to FLAC__stream_encoder_init_stream() currently will also
  91501. * immediately call the write callback several times, once with the \c fLaC
  91502. * signature, and once for each encoded metadata block.
  91503. *
  91504. * \param encoder An uninitialized encoder instance.
  91505. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91506. * pointer must not be \c NULL.
  91507. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91508. * pointer may be \c NULL if seeking is not
  91509. * supported. The encoder uses seeking to go back
  91510. * and write some some stream statistics to the
  91511. * STREAMINFO block; this is recommended but not
  91512. * necessary to create a valid FLAC stream. If
  91513. * \a seek_callback is not \c NULL then a
  91514. * \a tell_callback must also be supplied.
  91515. * Alternatively, a dummy seek callback that just
  91516. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91517. * may also be supplied, all though this is slightly
  91518. * less efficient for the encoder.
  91519. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91520. * pointer may be \c NULL if seeking is not
  91521. * supported. If \a seek_callback is \c NULL then
  91522. * this argument will be ignored. If
  91523. * \a seek_callback is not \c NULL then a
  91524. * \a tell_callback must also be supplied.
  91525. * Alternatively, a dummy tell callback that just
  91526. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91527. * may also be supplied, all though this is slightly
  91528. * less efficient for the encoder.
  91529. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91530. * pointer may be \c NULL if the callback is not
  91531. * desired. If the client provides a seek callback,
  91532. * this function is not necessary as the encoder
  91533. * will automatically seek back and update the
  91534. * STREAMINFO block. It may also be \c NULL if the
  91535. * client does not support seeking, since it will
  91536. * have no way of going back to update the
  91537. * STREAMINFO. However the client can still supply
  91538. * a callback if it would like to know the details
  91539. * from the STREAMINFO.
  91540. * \param client_data This value will be supplied to callbacks in their
  91541. * \a client_data argument.
  91542. * \assert
  91543. * \code encoder != NULL \endcode
  91544. * \retval FLAC__StreamEncoderInitStatus
  91545. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91546. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91547. */
  91548. 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);
  91549. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91550. *
  91551. * This flavor of initialization sets up the encoder to encode to a FLAC
  91552. * stream in an Ogg container. I/O is performed via callbacks to the
  91553. * client. For encoding to a plain file via filename or open \c FILE*,
  91554. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91555. * provide a simpler interface.
  91556. *
  91557. * This function should be called after FLAC__stream_encoder_new() and
  91558. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91559. * or FLAC__stream_encoder_process_interleaved().
  91560. * initialization succeeded.
  91561. *
  91562. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91563. * immediately call the write callback several times to write the metadata
  91564. * packets.
  91565. *
  91566. * \param encoder An uninitialized encoder instance.
  91567. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91568. * pointer must not be \c NULL if \a seek_callback
  91569. * is non-NULL since they are both needed to be
  91570. * able to write data back to the Ogg FLAC stream
  91571. * in the post-encode phase.
  91572. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91573. * pointer must not be \c NULL.
  91574. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91575. * pointer may be \c NULL if seeking is not
  91576. * supported. The encoder uses seeking to go back
  91577. * and write some some stream statistics to the
  91578. * STREAMINFO block; this is recommended but not
  91579. * necessary to create a valid FLAC stream. If
  91580. * \a seek_callback is not \c NULL then a
  91581. * \a tell_callback must also be supplied.
  91582. * Alternatively, a dummy seek callback that just
  91583. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91584. * may also be supplied, all though this is slightly
  91585. * less efficient for the encoder.
  91586. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91587. * pointer may be \c NULL if seeking is not
  91588. * supported. If \a seek_callback is \c NULL then
  91589. * this argument will be ignored. If
  91590. * \a seek_callback is not \c NULL then a
  91591. * \a tell_callback must also be supplied.
  91592. * Alternatively, a dummy tell callback that just
  91593. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91594. * may also be supplied, all though this is slightly
  91595. * less efficient for the encoder.
  91596. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91597. * pointer may be \c NULL if the callback is not
  91598. * desired. If the client provides a seek callback,
  91599. * this function is not necessary as the encoder
  91600. * will automatically seek back and update the
  91601. * STREAMINFO block. It may also be \c NULL if the
  91602. * client does not support seeking, since it will
  91603. * have no way of going back to update the
  91604. * STREAMINFO. However the client can still supply
  91605. * a callback if it would like to know the details
  91606. * from the STREAMINFO.
  91607. * \param client_data This value will be supplied to callbacks in their
  91608. * \a client_data argument.
  91609. * \assert
  91610. * \code encoder != NULL \endcode
  91611. * \retval FLAC__StreamEncoderInitStatus
  91612. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91613. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91614. */
  91615. 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);
  91616. /** Initialize the encoder instance to encode native FLAC files.
  91617. *
  91618. * This flavor of initialization sets up the encoder to encode to a
  91619. * plain native FLAC file. For non-stdio streams, you must use
  91620. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91621. *
  91622. * This function should be called after FLAC__stream_encoder_new() and
  91623. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91624. * or FLAC__stream_encoder_process_interleaved().
  91625. * initialization succeeded.
  91626. *
  91627. * \param encoder An uninitialized encoder instance.
  91628. * \param file An open file. The file should have been opened
  91629. * with mode \c "w+b" and rewound. The file
  91630. * becomes owned by the encoder and should not be
  91631. * manipulated by the client while encoding.
  91632. * Unless \a file is \c stdout, it will be closed
  91633. * when FLAC__stream_encoder_finish() is called.
  91634. * Note however that a proper SEEKTABLE cannot be
  91635. * created when encoding to \c stdout since it is
  91636. * not seekable.
  91637. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91638. * pointer may be \c NULL if the callback is not
  91639. * desired.
  91640. * \param client_data This value will be supplied to callbacks in their
  91641. * \a client_data argument.
  91642. * \assert
  91643. * \code encoder != NULL \endcode
  91644. * \code file != NULL \endcode
  91645. * \retval FLAC__StreamEncoderInitStatus
  91646. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91647. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91648. */
  91649. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91650. /** Initialize the encoder instance to encode Ogg FLAC files.
  91651. *
  91652. * This flavor of initialization sets up the encoder to encode to a
  91653. * plain Ogg FLAC file. For non-stdio streams, you must use
  91654. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91655. *
  91656. * This function should be called after FLAC__stream_encoder_new() and
  91657. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91658. * or FLAC__stream_encoder_process_interleaved().
  91659. * initialization succeeded.
  91660. *
  91661. * \param encoder An uninitialized encoder instance.
  91662. * \param file An open file. The file should have been opened
  91663. * with mode \c "w+b" and rewound. The file
  91664. * becomes owned by the encoder and should not be
  91665. * manipulated by the client while encoding.
  91666. * Unless \a file is \c stdout, it will be closed
  91667. * when FLAC__stream_encoder_finish() is called.
  91668. * Note however that a proper SEEKTABLE cannot be
  91669. * created when encoding to \c stdout since it is
  91670. * not seekable.
  91671. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91672. * pointer may be \c NULL if the callback is not
  91673. * desired.
  91674. * \param client_data This value will be supplied to callbacks in their
  91675. * \a client_data argument.
  91676. * \assert
  91677. * \code encoder != NULL \endcode
  91678. * \code file != NULL \endcode
  91679. * \retval FLAC__StreamEncoderInitStatus
  91680. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91681. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91682. */
  91683. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91684. /** Initialize the encoder instance to encode native FLAC files.
  91685. *
  91686. * This flavor of initialization sets up the encoder to encode to a plain
  91687. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91688. * with Unicode filenames on Windows), you must use
  91689. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91690. * and provide callbacks for the I/O.
  91691. *
  91692. * This function should be called after FLAC__stream_encoder_new() and
  91693. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91694. * or FLAC__stream_encoder_process_interleaved().
  91695. * initialization succeeded.
  91696. *
  91697. * \param encoder An uninitialized encoder instance.
  91698. * \param filename The name of the file to encode to. The file will
  91699. * be opened with fopen(). Use \c NULL to encode to
  91700. * \c stdout. Note however that a proper SEEKTABLE
  91701. * cannot be created when encoding to \c stdout since
  91702. * it is not seekable.
  91703. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91704. * pointer may be \c NULL if the callback is not
  91705. * desired.
  91706. * \param client_data This value will be supplied to callbacks in their
  91707. * \a client_data argument.
  91708. * \assert
  91709. * \code encoder != NULL \endcode
  91710. * \retval FLAC__StreamEncoderInitStatus
  91711. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91712. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91713. */
  91714. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91715. /** Initialize the encoder instance to encode Ogg FLAC files.
  91716. *
  91717. * This flavor of initialization sets up the encoder to encode to a plain
  91718. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91719. * with Unicode filenames on Windows), you must use
  91720. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91721. * and provide callbacks for the I/O.
  91722. *
  91723. * This function should be called after FLAC__stream_encoder_new() and
  91724. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91725. * or FLAC__stream_encoder_process_interleaved().
  91726. * initialization succeeded.
  91727. *
  91728. * \param encoder An uninitialized encoder instance.
  91729. * \param filename The name of the file to encode to. The file will
  91730. * be opened with fopen(). Use \c NULL to encode to
  91731. * \c stdout. Note however that a proper SEEKTABLE
  91732. * cannot be created when encoding to \c stdout since
  91733. * it is not seekable.
  91734. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91735. * pointer may be \c NULL if the callback is not
  91736. * desired.
  91737. * \param client_data This value will be supplied to callbacks in their
  91738. * \a client_data argument.
  91739. * \assert
  91740. * \code encoder != NULL \endcode
  91741. * \retval FLAC__StreamEncoderInitStatus
  91742. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91743. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91744. */
  91745. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91746. /** Finish the encoding process.
  91747. * Flushes the encoding buffer, releases resources, resets the encoder
  91748. * settings to their defaults, and returns the encoder state to
  91749. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91750. * one or more write callbacks before returning, and will generate
  91751. * a metadata callback.
  91752. *
  91753. * Note that in the course of processing the last frame, errors can
  91754. * occur, so the caller should be sure to check the return value to
  91755. * ensure the file was encoded properly.
  91756. *
  91757. * In the event of a prematurely-terminated encode, it is not strictly
  91758. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91759. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91760. * with a FLAC__stream_encoder_finish().
  91761. *
  91762. * \param encoder An uninitialized encoder instance.
  91763. * \assert
  91764. * \code encoder != NULL \endcode
  91765. * \retval FLAC__bool
  91766. * \c false if an error occurred processing the last frame; or if verify
  91767. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91768. * verify mismatch; else \c true. If \c false, caller should check the
  91769. * state with FLAC__stream_encoder_get_state() for more information
  91770. * about the error.
  91771. */
  91772. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91773. /** Submit data for encoding.
  91774. * This version allows you to supply the input data via an array of
  91775. * pointers, each pointer pointing to an array of \a samples samples
  91776. * representing one channel. The samples need not be block-aligned,
  91777. * but each channel should have the same number of samples. Each sample
  91778. * should be a signed integer, right-justified to the resolution set by
  91779. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91780. * resolution is 16 bits per sample, the samples should all be in the
  91781. * range [-32768,32767].
  91782. *
  91783. * For applications where channel order is important, channels must
  91784. * follow the order as described in the
  91785. * <A HREF="../format.html#frame_header">frame header</A>.
  91786. *
  91787. * \param encoder An initialized encoder instance in the OK state.
  91788. * \param buffer An array of pointers to each channel's signal.
  91789. * \param samples The number of samples in one channel.
  91790. * \assert
  91791. * \code encoder != NULL \endcode
  91792. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91793. * \retval FLAC__bool
  91794. * \c true if successful, else \c false; in this case, check the
  91795. * encoder state with FLAC__stream_encoder_get_state() to see what
  91796. * went wrong.
  91797. */
  91798. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91799. /** Submit data for encoding.
  91800. * This version allows you to supply the input data where the channels
  91801. * are interleaved into a single array (i.e. channel0_sample0,
  91802. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91803. * The samples need not be block-aligned but they must be
  91804. * sample-aligned, i.e. the first value should be channel0_sample0
  91805. * and the last value channelN_sampleM. Each sample should be a signed
  91806. * integer, right-justified to the resolution set by
  91807. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91808. * resolution is 16 bits per sample, the samples should all be in the
  91809. * range [-32768,32767].
  91810. *
  91811. * For applications where channel order is important, channels must
  91812. * follow the order as described in the
  91813. * <A HREF="../format.html#frame_header">frame header</A>.
  91814. *
  91815. * \param encoder An initialized encoder instance in the OK state.
  91816. * \param buffer An array of channel-interleaved data (see above).
  91817. * \param samples The number of samples in one channel, the same as for
  91818. * FLAC__stream_encoder_process(). For example, if
  91819. * encoding two channels, \c 1000 \a samples corresponds
  91820. * to a \a buffer of 2000 values.
  91821. * \assert
  91822. * \code encoder != NULL \endcode
  91823. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91824. * \retval FLAC__bool
  91825. * \c true if successful, else \c false; in this case, check the
  91826. * encoder state with FLAC__stream_encoder_get_state() to see what
  91827. * went wrong.
  91828. */
  91829. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91830. /* \} */
  91831. #ifdef __cplusplus
  91832. }
  91833. #endif
  91834. #endif
  91835. /*** End of inlined file: stream_encoder.h ***/
  91836. #ifdef _MSC_VER
  91837. /* OPT: an MSVC built-in would be better */
  91838. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91839. {
  91840. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91841. return (x>>16) | (x<<16);
  91842. }
  91843. #endif
  91844. #if defined(_MSC_VER) && defined(_X86_)
  91845. /* OPT: an MSVC built-in would be better */
  91846. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91847. {
  91848. __asm {
  91849. mov edx, start
  91850. mov ecx, len
  91851. test ecx, ecx
  91852. loop1:
  91853. jz done1
  91854. mov eax, [edx]
  91855. bswap eax
  91856. mov [edx], eax
  91857. add edx, 4
  91858. dec ecx
  91859. jmp short loop1
  91860. done1:
  91861. }
  91862. }
  91863. #endif
  91864. /** \mainpage
  91865. *
  91866. * \section intro Introduction
  91867. *
  91868. * This is the documentation for the FLAC C and C++ APIs. It is
  91869. * highly interconnected; this introduction should give you a top
  91870. * level idea of the structure and how to find the information you
  91871. * need. As a prerequisite you should have at least a basic
  91872. * knowledge of the FLAC format, documented
  91873. * <A HREF="../format.html">here</A>.
  91874. *
  91875. * \section c_api FLAC C API
  91876. *
  91877. * The FLAC C API is the interface to libFLAC, a set of structures
  91878. * describing the components of FLAC streams, and functions for
  91879. * encoding and decoding streams, as well as manipulating FLAC
  91880. * metadata in files. The public include files will be installed
  91881. * in your include area (for example /usr/include/FLAC/...).
  91882. *
  91883. * By writing a little code and linking against libFLAC, it is
  91884. * relatively easy to add FLAC support to another program. The
  91885. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91886. * Complete source code of libFLAC as well as the command-line
  91887. * encoder and plugins is available and is a useful source of
  91888. * examples.
  91889. *
  91890. * Aside from encoders and decoders, libFLAC provides a powerful
  91891. * metadata interface for manipulating metadata in FLAC files. It
  91892. * allows the user to add, delete, and modify FLAC metadata blocks
  91893. * and it can automatically take advantage of PADDING blocks to avoid
  91894. * rewriting the entire FLAC file when changing the size of the
  91895. * metadata.
  91896. *
  91897. * libFLAC usually only requires the standard C library and C math
  91898. * library. In particular, threading is not used so there is no
  91899. * dependency on a thread library. However, libFLAC does not use
  91900. * global variables and should be thread-safe.
  91901. *
  91902. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91903. * However the metadata editing interfaces currently have limited
  91904. * read-only support for Ogg FLAC files.
  91905. *
  91906. * \section cpp_api FLAC C++ API
  91907. *
  91908. * The FLAC C++ API is a set of classes that encapsulate the
  91909. * structures and functions in libFLAC. They provide slightly more
  91910. * functionality with respect to metadata but are otherwise
  91911. * equivalent. For the most part, they share the same usage as
  91912. * their counterparts in libFLAC, and the FLAC C API documentation
  91913. * can be used as a supplement. The public include files
  91914. * for the C++ API will be installed in your include area (for
  91915. * example /usr/include/FLAC++/...).
  91916. *
  91917. * libFLAC++ is also licensed under
  91918. * <A HREF="../license.html">Xiph's BSD license</A>.
  91919. *
  91920. * \section getting_started Getting Started
  91921. *
  91922. * A good starting point for learning the API is to browse through
  91923. * the <A HREF="modules.html">modules</A>. Modules are logical
  91924. * groupings of related functions or classes, which correspond roughly
  91925. * to header files or sections of header files. Each module includes a
  91926. * detailed description of the general usage of its functions or
  91927. * classes.
  91928. *
  91929. * From there you can go on to look at the documentation of
  91930. * individual functions. You can see different views of the individual
  91931. * functions through the links in top bar across this page.
  91932. *
  91933. * If you prefer a more hands-on approach, you can jump right to some
  91934. * <A HREF="../documentation_example_code.html">example code</A>.
  91935. *
  91936. * \section porting_guide Porting Guide
  91937. *
  91938. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91939. * has been introduced which gives detailed instructions on how to
  91940. * port your code to newer versions of FLAC.
  91941. *
  91942. * \section embedded_developers Embedded Developers
  91943. *
  91944. * libFLAC has grown larger over time as more functionality has been
  91945. * included, but much of it may be unnecessary for a particular embedded
  91946. * implementation. Unused parts may be pruned by some simple editing of
  91947. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91948. * metadata interface are all independent from each other.
  91949. *
  91950. * It is easiest to just describe the dependencies:
  91951. *
  91952. * - All modules depend on the \link flac_format Format \endlink module.
  91953. * - The decoders and encoders depend on the bitbuffer.
  91954. * - The decoder is independent of the encoder. The encoder uses the
  91955. * decoder because of the verify feature, but this can be removed if
  91956. * not needed.
  91957. * - Parts of the metadata interface require the stream decoder (but not
  91958. * the encoder).
  91959. * - Ogg support is selectable through the compile time macro
  91960. * \c FLAC__HAS_OGG.
  91961. *
  91962. * For example, if your application only requires the stream decoder, no
  91963. * encoder, and no metadata interface, you can remove the stream encoder
  91964. * and the metadata interface, which will greatly reduce the size of the
  91965. * library.
  91966. *
  91967. * Also, there are several places in the libFLAC code with comments marked
  91968. * with "OPT:" where a #define can be changed to enable code that might be
  91969. * faster on a specific platform. Experimenting with these can yield faster
  91970. * binaries.
  91971. */
  91972. /** \defgroup porting Porting Guide for New Versions
  91973. *
  91974. * This module describes differences in the library interfaces from
  91975. * version to version. It assists in the porting of code that uses
  91976. * the libraries to newer versions of FLAC.
  91977. *
  91978. * One simple facility for making porting easier that has been added
  91979. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91980. * library's includes (e.g. \c include/FLAC/export.h). The
  91981. * \c #defines mirror the libraries'
  91982. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91983. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91984. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91985. * These can be used to support multiple versions of an API during the
  91986. * transition phase, e.g.
  91987. *
  91988. * \code
  91989. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91990. * legacy code
  91991. * #else
  91992. * new code
  91993. * #endif
  91994. * \endcode
  91995. *
  91996. * The the source will work for multiple versions and the legacy code can
  91997. * easily be removed when the transition is complete.
  91998. *
  91999. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92000. * include/FLAC/export.h), which can be used to determine whether or not
  92001. * the library has been compiled with support for Ogg FLAC. This is
  92002. * simpler than trying to call an Ogg init function and catching the
  92003. * error.
  92004. */
  92005. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92006. * \ingroup porting
  92007. *
  92008. * \brief
  92009. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92010. *
  92011. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92012. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92013. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92014. * decoding layers and three encoding layers have been merged into a
  92015. * single stream decoder and stream encoder. That is, the functionality
  92016. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92017. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92018. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92019. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92020. * is there is now a single API that can be used to encode or decode
  92021. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92022. * on both seekable and non-seekable streams.
  92023. *
  92024. * Instead of creating an encoder or decoder of a certain layer, now the
  92025. * client will always create a FLAC__StreamEncoder or
  92026. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92027. * initialization function. For example, for the decoder,
  92028. * FLAC__stream_decoder_init() has been replaced by
  92029. * FLAC__stream_decoder_init_stream(). This init function takes
  92030. * callbacks for the I/O, and the seeking callbacks are optional. This
  92031. * allows the client to use the same object for seekable and
  92032. * non-seekable streams. For decoding a FLAC file directly, the client
  92033. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92034. * and fewer callbacks; most of the other callbacks are supplied
  92035. * internally. For situations where fopen()ing by filename is not
  92036. * possible (e.g. Unicode filenames on Windows) the client can instead
  92037. * open the file itself and supply the FILE* to
  92038. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92039. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92040. * Since the callbacks and client data are now passed to the init
  92041. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92042. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92043. * rest of the calls to the decoder are the same as before.
  92044. *
  92045. * There are counterpart init functions for Ogg FLAC, e.g.
  92046. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92047. * and callbacks are the same as for native FLAC.
  92048. *
  92049. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92050. * been set up like so:
  92051. *
  92052. * \code
  92053. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92054. * if(decoder == NULL) do_something;
  92055. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92056. * [... other settings ...]
  92057. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92058. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92059. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92060. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92061. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92062. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92063. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92064. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92065. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92066. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92067. * \endcode
  92068. *
  92069. * In FLAC 1.1.3 it is like this:
  92070. *
  92071. * \code
  92072. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92073. * if(decoder == NULL) do_something;
  92074. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92075. * [... other settings ...]
  92076. * if(FLAC__stream_decoder_init_stream(
  92077. * decoder,
  92078. * my_read_callback,
  92079. * my_seek_callback, // or NULL
  92080. * my_tell_callback, // or NULL
  92081. * my_length_callback, // or NULL
  92082. * my_eof_callback, // or NULL
  92083. * my_write_callback,
  92084. * my_metadata_callback, // or NULL
  92085. * my_error_callback,
  92086. * my_client_data
  92087. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92088. * \endcode
  92089. *
  92090. * or you could do;
  92091. *
  92092. * \code
  92093. * [...]
  92094. * FILE *file = fopen("somefile.flac","rb");
  92095. * if(file == NULL) do_somthing;
  92096. * if(FLAC__stream_decoder_init_FILE(
  92097. * decoder,
  92098. * file,
  92099. * my_write_callback,
  92100. * my_metadata_callback, // or NULL
  92101. * my_error_callback,
  92102. * my_client_data
  92103. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92104. * \endcode
  92105. *
  92106. * or just:
  92107. *
  92108. * \code
  92109. * [...]
  92110. * if(FLAC__stream_decoder_init_file(
  92111. * decoder,
  92112. * "somefile.flac",
  92113. * my_write_callback,
  92114. * my_metadata_callback, // or NULL
  92115. * my_error_callback,
  92116. * my_client_data
  92117. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92118. * \endcode
  92119. *
  92120. * Another small change to the decoder is in how it handles unparseable
  92121. * streams. Before, when the decoder found an unparseable stream
  92122. * (reserved for when the decoder encounters a stream from a future
  92123. * encoder that it can't parse), it changed the state to
  92124. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92125. * drops sync and calls the error callback with a new error code
  92126. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92127. * more robust. If your error callback does not discriminate on the the
  92128. * error state, your code does not need to be changed.
  92129. *
  92130. * The encoder now has a new setting:
  92131. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92132. * method used to window the data before LPC analysis. You only need to
  92133. * add a call to this function if the default is not suitable. There
  92134. * are also two new convenience functions that may be useful:
  92135. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92136. * FLAC__metadata_get_cuesheet().
  92137. *
  92138. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92139. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92140. * is now \c size_t instead of \c unsigned.
  92141. */
  92142. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92143. * \ingroup porting
  92144. *
  92145. * \brief
  92146. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92147. *
  92148. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92149. * There was a slight change in the implementation of
  92150. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92151. * of the \a metadata array of pointers so the client no longer needs
  92152. * to maintain it after the call. The objects themselves that are
  92153. * pointed to by the array are still not copied though and must be
  92154. * maintained until the call to FLAC__stream_encoder_finish().
  92155. */
  92156. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92157. * \ingroup porting
  92158. *
  92159. * \brief
  92160. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92161. *
  92162. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92163. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92164. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92165. *
  92166. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92167. * has changed to reflect the conversion of one of the reserved bits
  92168. * into active use. It used to be \c 2 and now is \c 1. However the
  92169. * FLAC frame header length has not changed, so to skip the proper
  92170. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92171. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92172. */
  92173. /** \defgroup flac FLAC C API
  92174. *
  92175. * The FLAC C API is the interface to libFLAC, a set of structures
  92176. * describing the components of FLAC streams, and functions for
  92177. * encoding and decoding streams, as well as manipulating FLAC
  92178. * metadata in files.
  92179. *
  92180. * You should start with the format components as all other modules
  92181. * are dependent on it.
  92182. */
  92183. #endif
  92184. /*** End of inlined file: all.h ***/
  92185. /*** Start of inlined file: bitmath.c ***/
  92186. /*** Start of inlined file: juce_FlacHeader.h ***/
  92187. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92188. // tasks..
  92189. #define VERSION "1.2.1"
  92190. #define FLAC__NO_DLL 1
  92191. #if JUCE_MSVC
  92192. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92193. #endif
  92194. #if JUCE_MAC
  92195. #define FLAC__SYS_DARWIN 1
  92196. #endif
  92197. /*** End of inlined file: juce_FlacHeader.h ***/
  92198. #if JUCE_USE_FLAC
  92199. #if HAVE_CONFIG_H
  92200. # include <config.h>
  92201. #endif
  92202. /*** Start of inlined file: bitmath.h ***/
  92203. #ifndef FLAC__PRIVATE__BITMATH_H
  92204. #define FLAC__PRIVATE__BITMATH_H
  92205. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92206. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92207. unsigned FLAC__bitmath_silog2(int v);
  92208. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92209. #endif
  92210. /*** End of inlined file: bitmath.h ***/
  92211. /* An example of what FLAC__bitmath_ilog2() computes:
  92212. *
  92213. * ilog2( 0) = assertion failure
  92214. * ilog2( 1) = 0
  92215. * ilog2( 2) = 1
  92216. * ilog2( 3) = 1
  92217. * ilog2( 4) = 2
  92218. * ilog2( 5) = 2
  92219. * ilog2( 6) = 2
  92220. * ilog2( 7) = 2
  92221. * ilog2( 8) = 3
  92222. * ilog2( 9) = 3
  92223. * ilog2(10) = 3
  92224. * ilog2(11) = 3
  92225. * ilog2(12) = 3
  92226. * ilog2(13) = 3
  92227. * ilog2(14) = 3
  92228. * ilog2(15) = 3
  92229. * ilog2(16) = 4
  92230. * ilog2(17) = 4
  92231. * ilog2(18) = 4
  92232. */
  92233. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92234. {
  92235. unsigned l = 0;
  92236. FLAC__ASSERT(v > 0);
  92237. while(v >>= 1)
  92238. l++;
  92239. return l;
  92240. }
  92241. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92242. {
  92243. unsigned l = 0;
  92244. FLAC__ASSERT(v > 0);
  92245. while(v >>= 1)
  92246. l++;
  92247. return l;
  92248. }
  92249. /* An example of what FLAC__bitmath_silog2() computes:
  92250. *
  92251. * silog2(-10) = 5
  92252. * silog2(- 9) = 5
  92253. * silog2(- 8) = 4
  92254. * silog2(- 7) = 4
  92255. * silog2(- 6) = 4
  92256. * silog2(- 5) = 4
  92257. * silog2(- 4) = 3
  92258. * silog2(- 3) = 3
  92259. * silog2(- 2) = 2
  92260. * silog2(- 1) = 2
  92261. * silog2( 0) = 0
  92262. * silog2( 1) = 2
  92263. * silog2( 2) = 3
  92264. * silog2( 3) = 3
  92265. * silog2( 4) = 4
  92266. * silog2( 5) = 4
  92267. * silog2( 6) = 4
  92268. * silog2( 7) = 4
  92269. * silog2( 8) = 5
  92270. * silog2( 9) = 5
  92271. * silog2( 10) = 5
  92272. */
  92273. unsigned FLAC__bitmath_silog2(int v)
  92274. {
  92275. while(1) {
  92276. if(v == 0) {
  92277. return 0;
  92278. }
  92279. else if(v > 0) {
  92280. unsigned l = 0;
  92281. while(v) {
  92282. l++;
  92283. v >>= 1;
  92284. }
  92285. return l+1;
  92286. }
  92287. else if(v == -1) {
  92288. return 2;
  92289. }
  92290. else {
  92291. v++;
  92292. v = -v;
  92293. }
  92294. }
  92295. }
  92296. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92297. {
  92298. while(1) {
  92299. if(v == 0) {
  92300. return 0;
  92301. }
  92302. else if(v > 0) {
  92303. unsigned l = 0;
  92304. while(v) {
  92305. l++;
  92306. v >>= 1;
  92307. }
  92308. return l+1;
  92309. }
  92310. else if(v == -1) {
  92311. return 2;
  92312. }
  92313. else {
  92314. v++;
  92315. v = -v;
  92316. }
  92317. }
  92318. }
  92319. #endif
  92320. /*** End of inlined file: bitmath.c ***/
  92321. /*** Start of inlined file: bitreader.c ***/
  92322. /*** Start of inlined file: juce_FlacHeader.h ***/
  92323. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92324. // tasks..
  92325. #define VERSION "1.2.1"
  92326. #define FLAC__NO_DLL 1
  92327. #if JUCE_MSVC
  92328. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92329. #endif
  92330. #if JUCE_MAC
  92331. #define FLAC__SYS_DARWIN 1
  92332. #endif
  92333. /*** End of inlined file: juce_FlacHeader.h ***/
  92334. #if JUCE_USE_FLAC
  92335. #if HAVE_CONFIG_H
  92336. # include <config.h>
  92337. #endif
  92338. #include <stdlib.h> /* for malloc() */
  92339. #include <string.h> /* for memcpy(), memset() */
  92340. #ifdef _MSC_VER
  92341. #include <winsock.h> /* for ntohl() */
  92342. #elif defined FLAC__SYS_DARWIN
  92343. #include <machine/endian.h> /* for ntohl() */
  92344. #elif defined __MINGW32__
  92345. #include <winsock.h> /* for ntohl() */
  92346. #else
  92347. #include <netinet/in.h> /* for ntohl() */
  92348. #endif
  92349. /*** Start of inlined file: bitreader.h ***/
  92350. #ifndef FLAC__PRIVATE__BITREADER_H
  92351. #define FLAC__PRIVATE__BITREADER_H
  92352. #include <stdio.h> /* for FILE */
  92353. /*** Start of inlined file: cpu.h ***/
  92354. #ifndef FLAC__PRIVATE__CPU_H
  92355. #define FLAC__PRIVATE__CPU_H
  92356. #ifdef HAVE_CONFIG_H
  92357. #include <config.h>
  92358. #endif
  92359. typedef enum {
  92360. FLAC__CPUINFO_TYPE_IA32,
  92361. FLAC__CPUINFO_TYPE_PPC,
  92362. FLAC__CPUINFO_TYPE_UNKNOWN
  92363. } FLAC__CPUInfo_Type;
  92364. typedef struct {
  92365. FLAC__bool cpuid;
  92366. FLAC__bool bswap;
  92367. FLAC__bool cmov;
  92368. FLAC__bool mmx;
  92369. FLAC__bool fxsr;
  92370. FLAC__bool sse;
  92371. FLAC__bool sse2;
  92372. FLAC__bool sse3;
  92373. FLAC__bool ssse3;
  92374. FLAC__bool _3dnow;
  92375. FLAC__bool ext3dnow;
  92376. FLAC__bool extmmx;
  92377. } FLAC__CPUInfo_IA32;
  92378. typedef struct {
  92379. FLAC__bool altivec;
  92380. FLAC__bool ppc64;
  92381. } FLAC__CPUInfo_PPC;
  92382. typedef struct {
  92383. FLAC__bool use_asm;
  92384. FLAC__CPUInfo_Type type;
  92385. union {
  92386. FLAC__CPUInfo_IA32 ia32;
  92387. FLAC__CPUInfo_PPC ppc;
  92388. } data;
  92389. } FLAC__CPUInfo;
  92390. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92391. #ifndef FLAC__NO_ASM
  92392. #ifdef FLAC__CPU_IA32
  92393. #ifdef FLAC__HAS_NASM
  92394. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92395. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92396. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92397. #endif
  92398. #endif
  92399. #endif
  92400. #endif
  92401. /*** End of inlined file: cpu.h ***/
  92402. /*
  92403. * opaque structure definition
  92404. */
  92405. struct FLAC__BitReader;
  92406. typedef struct FLAC__BitReader FLAC__BitReader;
  92407. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92408. /*
  92409. * construction, deletion, initialization, etc functions
  92410. */
  92411. FLAC__BitReader *FLAC__bitreader_new(void);
  92412. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92413. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92414. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92415. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92416. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92417. /*
  92418. * CRC functions
  92419. */
  92420. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92421. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92422. /*
  92423. * info functions
  92424. */
  92425. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92426. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92427. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92428. /*
  92429. * read functions
  92430. */
  92431. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92432. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92433. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92434. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92435. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92436. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92437. 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! */
  92438. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92439. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92440. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92441. #ifndef FLAC__NO_ASM
  92442. # ifdef FLAC__CPU_IA32
  92443. # ifdef FLAC__HAS_NASM
  92444. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92445. # endif
  92446. # endif
  92447. #endif
  92448. #if 0 /* UNUSED */
  92449. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92450. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92451. #endif
  92452. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92453. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92454. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92455. #endif
  92456. /*** End of inlined file: bitreader.h ***/
  92457. /*** Start of inlined file: crc.h ***/
  92458. #ifndef FLAC__PRIVATE__CRC_H
  92459. #define FLAC__PRIVATE__CRC_H
  92460. /* 8 bit CRC generator, MSB shifted first
  92461. ** polynomial = x^8 + x^2 + x^1 + x^0
  92462. ** init = 0
  92463. */
  92464. extern FLAC__byte const FLAC__crc8_table[256];
  92465. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92466. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92467. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92468. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92469. /* 16 bit CRC generator, MSB shifted first
  92470. ** polynomial = x^16 + x^15 + x^2 + x^0
  92471. ** init = 0
  92472. */
  92473. extern unsigned FLAC__crc16_table[256];
  92474. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92475. /* this alternate may be faster on some systems/compilers */
  92476. #if 0
  92477. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92478. #endif
  92479. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92480. #endif
  92481. /*** End of inlined file: crc.h ***/
  92482. /* Things should be fastest when this matches the machine word size */
  92483. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92484. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92485. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92486. typedef FLAC__uint32 brword;
  92487. #define FLAC__BYTES_PER_WORD 4
  92488. #define FLAC__BITS_PER_WORD 32
  92489. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92490. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92491. #if WORDS_BIGENDIAN
  92492. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92493. #else
  92494. #if defined (_MSC_VER) && defined (_X86_)
  92495. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92496. #else
  92497. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92498. #endif
  92499. #endif
  92500. /* counts the # of zero MSBs in a word */
  92501. #define COUNT_ZERO_MSBS(word) ( \
  92502. (word) <= 0xffff ? \
  92503. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92504. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92505. )
  92506. /* this alternate might be slightly faster on some systems/compilers: */
  92507. #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])) )
  92508. /*
  92509. * This should be at least twice as large as the largest number of words
  92510. * required to represent any 'number' (in any encoding) you are going to
  92511. * read. With FLAC this is on the order of maybe a few hundred bits.
  92512. * If the buffer is smaller than that, the decoder won't be able to read
  92513. * in a whole number that is in a variable length encoding (e.g. Rice).
  92514. * But to be practical it should be at least 1K bytes.
  92515. *
  92516. * Increase this number to decrease the number of read callbacks, at the
  92517. * expense of using more memory. Or decrease for the reverse effect,
  92518. * keeping in mind the limit from the first paragraph. The optimal size
  92519. * also depends on the CPU cache size and other factors; some twiddling
  92520. * may be necessary to squeeze out the best performance.
  92521. */
  92522. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92523. static const unsigned char byte_to_unary_table[] = {
  92524. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92525. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92526. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92527. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92528. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92529. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92530. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92531. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92540. };
  92541. #ifdef min
  92542. #undef min
  92543. #endif
  92544. #define min(x,y) ((x)<(y)?(x):(y))
  92545. #ifdef max
  92546. #undef max
  92547. #endif
  92548. #define max(x,y) ((x)>(y)?(x):(y))
  92549. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92550. #ifdef _MSC_VER
  92551. #define FLAC__U64L(x) x
  92552. #else
  92553. #define FLAC__U64L(x) x##LLU
  92554. #endif
  92555. #ifndef FLaC__INLINE
  92556. #define FLaC__INLINE
  92557. #endif
  92558. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92559. struct FLAC__BitReader {
  92560. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92561. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92562. brword *buffer;
  92563. unsigned capacity; /* in words */
  92564. unsigned words; /* # of completed words in buffer */
  92565. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92566. unsigned consumed_words; /* #words ... */
  92567. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92568. unsigned read_crc16; /* the running frame CRC */
  92569. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92570. FLAC__BitReaderReadCallback read_callback;
  92571. void *client_data;
  92572. FLAC__CPUInfo cpu_info;
  92573. };
  92574. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92575. {
  92576. register unsigned crc = br->read_crc16;
  92577. #if FLAC__BYTES_PER_WORD == 4
  92578. switch(br->crc16_align) {
  92579. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92580. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92581. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92582. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92583. }
  92584. #elif FLAC__BYTES_PER_WORD == 8
  92585. switch(br->crc16_align) {
  92586. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92587. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92588. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92589. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92590. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92591. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92592. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92593. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92594. }
  92595. #else
  92596. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92597. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92598. br->read_crc16 = crc;
  92599. #endif
  92600. br->crc16_align = 0;
  92601. }
  92602. /* would be static except it needs to be called by asm routines */
  92603. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92604. {
  92605. unsigned start, end;
  92606. size_t bytes;
  92607. FLAC__byte *target;
  92608. /* first shift the unconsumed buffer data toward the front as much as possible */
  92609. if(br->consumed_words > 0) {
  92610. start = br->consumed_words;
  92611. end = br->words + (br->bytes? 1:0);
  92612. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92613. br->words -= start;
  92614. br->consumed_words = 0;
  92615. }
  92616. /*
  92617. * set the target for reading, taking into account word alignment and endianness
  92618. */
  92619. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92620. if(bytes == 0)
  92621. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92622. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92623. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92624. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92625. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92626. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92627. * ^^-------target, bytes=3
  92628. * on LE machines, have to byteswap the odd tail word so nothing is
  92629. * overwritten:
  92630. */
  92631. #if WORDS_BIGENDIAN
  92632. #else
  92633. if(br->bytes)
  92634. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92635. #endif
  92636. /* now it looks like:
  92637. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92638. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92639. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92640. * ^^-------target, bytes=3
  92641. */
  92642. /* read in the data; note that the callback may return a smaller number of bytes */
  92643. if(!br->read_callback(target, &bytes, br->client_data))
  92644. return false;
  92645. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92646. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92647. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92648. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92649. * now have to byteswap on LE machines:
  92650. */
  92651. #if WORDS_BIGENDIAN
  92652. #else
  92653. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92654. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92655. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92656. start = br->words;
  92657. local_swap32_block_(br->buffer + start, end - start);
  92658. }
  92659. else
  92660. # endif
  92661. for(start = br->words; start < end; start++)
  92662. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92663. #endif
  92664. /* now it looks like:
  92665. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92666. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92667. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92668. * finally we'll update the reader values:
  92669. */
  92670. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92671. br->words = end / FLAC__BYTES_PER_WORD;
  92672. br->bytes = end % FLAC__BYTES_PER_WORD;
  92673. return true;
  92674. }
  92675. /***********************************************************************
  92676. *
  92677. * Class constructor/destructor
  92678. *
  92679. ***********************************************************************/
  92680. FLAC__BitReader *FLAC__bitreader_new(void)
  92681. {
  92682. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92683. /* calloc() implies:
  92684. memset(br, 0, sizeof(FLAC__BitReader));
  92685. br->buffer = 0;
  92686. br->capacity = 0;
  92687. br->words = br->bytes = 0;
  92688. br->consumed_words = br->consumed_bits = 0;
  92689. br->read_callback = 0;
  92690. br->client_data = 0;
  92691. */
  92692. return br;
  92693. }
  92694. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92695. {
  92696. FLAC__ASSERT(0 != br);
  92697. FLAC__bitreader_free(br);
  92698. free(br);
  92699. }
  92700. /***********************************************************************
  92701. *
  92702. * Public class methods
  92703. *
  92704. ***********************************************************************/
  92705. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92706. {
  92707. FLAC__ASSERT(0 != br);
  92708. br->words = br->bytes = 0;
  92709. br->consumed_words = br->consumed_bits = 0;
  92710. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92711. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92712. if(br->buffer == 0)
  92713. return false;
  92714. br->read_callback = rcb;
  92715. br->client_data = cd;
  92716. br->cpu_info = cpu;
  92717. return true;
  92718. }
  92719. void FLAC__bitreader_free(FLAC__BitReader *br)
  92720. {
  92721. FLAC__ASSERT(0 != br);
  92722. if(0 != br->buffer)
  92723. free(br->buffer);
  92724. br->buffer = 0;
  92725. br->capacity = 0;
  92726. br->words = br->bytes = 0;
  92727. br->consumed_words = br->consumed_bits = 0;
  92728. br->read_callback = 0;
  92729. br->client_data = 0;
  92730. }
  92731. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92732. {
  92733. br->words = br->bytes = 0;
  92734. br->consumed_words = br->consumed_bits = 0;
  92735. return true;
  92736. }
  92737. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92738. {
  92739. unsigned i, j;
  92740. if(br == 0) {
  92741. fprintf(out, "bitreader is NULL\n");
  92742. }
  92743. else {
  92744. 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);
  92745. for(i = 0; i < br->words; i++) {
  92746. fprintf(out, "%08X: ", i);
  92747. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92748. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92749. fprintf(out, ".");
  92750. else
  92751. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92752. fprintf(out, "\n");
  92753. }
  92754. if(br->bytes > 0) {
  92755. fprintf(out, "%08X: ", i);
  92756. for(j = 0; j < br->bytes*8; j++)
  92757. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92758. fprintf(out, ".");
  92759. else
  92760. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92761. fprintf(out, "\n");
  92762. }
  92763. }
  92764. }
  92765. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92766. {
  92767. FLAC__ASSERT(0 != br);
  92768. FLAC__ASSERT(0 != br->buffer);
  92769. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92770. br->read_crc16 = (unsigned)seed;
  92771. br->crc16_align = br->consumed_bits;
  92772. }
  92773. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92774. {
  92775. FLAC__ASSERT(0 != br);
  92776. FLAC__ASSERT(0 != br->buffer);
  92777. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92778. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92779. /* CRC any tail bytes in a partially-consumed word */
  92780. if(br->consumed_bits) {
  92781. const brword tail = br->buffer[br->consumed_words];
  92782. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92783. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92784. }
  92785. return br->read_crc16;
  92786. }
  92787. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92788. {
  92789. return ((br->consumed_bits & 7) == 0);
  92790. }
  92791. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92792. {
  92793. return 8 - (br->consumed_bits & 7);
  92794. }
  92795. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92796. {
  92797. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92798. }
  92799. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92800. {
  92801. FLAC__ASSERT(0 != br);
  92802. FLAC__ASSERT(0 != br->buffer);
  92803. FLAC__ASSERT(bits <= 32);
  92804. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92805. FLAC__ASSERT(br->consumed_words <= br->words);
  92806. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92807. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92808. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92809. *val = 0;
  92810. return true;
  92811. }
  92812. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92813. if(!bitreader_read_from_client_(br))
  92814. return false;
  92815. }
  92816. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92817. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92818. if(br->consumed_bits) {
  92819. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92820. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92821. const brword word = br->buffer[br->consumed_words];
  92822. if(bits < n) {
  92823. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92824. br->consumed_bits += bits;
  92825. return true;
  92826. }
  92827. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92828. bits -= n;
  92829. crc16_update_word_(br, word);
  92830. br->consumed_words++;
  92831. br->consumed_bits = 0;
  92832. 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 */
  92833. *val <<= bits;
  92834. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92835. br->consumed_bits = bits;
  92836. }
  92837. return true;
  92838. }
  92839. else {
  92840. const brword word = br->buffer[br->consumed_words];
  92841. if(bits < FLAC__BITS_PER_WORD) {
  92842. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92843. br->consumed_bits = bits;
  92844. return true;
  92845. }
  92846. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92847. *val = word;
  92848. crc16_update_word_(br, word);
  92849. br->consumed_words++;
  92850. return true;
  92851. }
  92852. }
  92853. else {
  92854. /* in this case we're starting our read at a partial tail word;
  92855. * the reader has guaranteed that we have at least 'bits' bits
  92856. * available to read, which makes this case simpler.
  92857. */
  92858. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92859. if(br->consumed_bits) {
  92860. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92861. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92862. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92863. br->consumed_bits += bits;
  92864. return true;
  92865. }
  92866. else {
  92867. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92868. br->consumed_bits += bits;
  92869. return true;
  92870. }
  92871. }
  92872. }
  92873. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92874. {
  92875. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92876. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92877. return false;
  92878. /* sign-extend: */
  92879. *val <<= (32-bits);
  92880. *val >>= (32-bits);
  92881. return true;
  92882. }
  92883. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92884. {
  92885. FLAC__uint32 hi, lo;
  92886. if(bits > 32) {
  92887. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92888. return false;
  92889. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92890. return false;
  92891. *val = hi;
  92892. *val <<= 32;
  92893. *val |= lo;
  92894. }
  92895. else {
  92896. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92897. return false;
  92898. *val = lo;
  92899. }
  92900. return true;
  92901. }
  92902. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92903. {
  92904. FLAC__uint32 x8, x32 = 0;
  92905. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92906. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92907. return false;
  92908. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92909. return false;
  92910. x32 |= (x8 << 8);
  92911. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92912. return false;
  92913. x32 |= (x8 << 16);
  92914. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92915. return false;
  92916. x32 |= (x8 << 24);
  92917. *val = x32;
  92918. return true;
  92919. }
  92920. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92921. {
  92922. /*
  92923. * OPT: a faster implementation is possible but probably not that useful
  92924. * since this is only called a couple of times in the metadata readers.
  92925. */
  92926. FLAC__ASSERT(0 != br);
  92927. FLAC__ASSERT(0 != br->buffer);
  92928. if(bits > 0) {
  92929. const unsigned n = br->consumed_bits & 7;
  92930. unsigned m;
  92931. FLAC__uint32 x;
  92932. if(n != 0) {
  92933. m = min(8-n, bits);
  92934. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92935. return false;
  92936. bits -= m;
  92937. }
  92938. m = bits / 8;
  92939. if(m > 0) {
  92940. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92941. return false;
  92942. bits %= 8;
  92943. }
  92944. if(bits > 0) {
  92945. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92946. return false;
  92947. }
  92948. }
  92949. return true;
  92950. }
  92951. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92952. {
  92953. FLAC__uint32 x;
  92954. FLAC__ASSERT(0 != br);
  92955. FLAC__ASSERT(0 != br->buffer);
  92956. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92957. /* step 1: skip over partial head word to get word aligned */
  92958. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92959. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92960. return false;
  92961. nvals--;
  92962. }
  92963. if(0 == nvals)
  92964. return true;
  92965. /* step 2: skip whole words in chunks */
  92966. while(nvals >= FLAC__BYTES_PER_WORD) {
  92967. if(br->consumed_words < br->words) {
  92968. br->consumed_words++;
  92969. nvals -= FLAC__BYTES_PER_WORD;
  92970. }
  92971. else if(!bitreader_read_from_client_(br))
  92972. return false;
  92973. }
  92974. /* step 3: skip any remainder from partial tail bytes */
  92975. while(nvals) {
  92976. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92977. return false;
  92978. nvals--;
  92979. }
  92980. return true;
  92981. }
  92982. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92983. {
  92984. FLAC__uint32 x;
  92985. FLAC__ASSERT(0 != br);
  92986. FLAC__ASSERT(0 != br->buffer);
  92987. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92988. /* step 1: read from partial head word to get word aligned */
  92989. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92990. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92991. return false;
  92992. *val++ = (FLAC__byte)x;
  92993. nvals--;
  92994. }
  92995. if(0 == nvals)
  92996. return true;
  92997. /* step 2: read whole words in chunks */
  92998. while(nvals >= FLAC__BYTES_PER_WORD) {
  92999. if(br->consumed_words < br->words) {
  93000. const brword word = br->buffer[br->consumed_words++];
  93001. #if FLAC__BYTES_PER_WORD == 4
  93002. val[0] = (FLAC__byte)(word >> 24);
  93003. val[1] = (FLAC__byte)(word >> 16);
  93004. val[2] = (FLAC__byte)(word >> 8);
  93005. val[3] = (FLAC__byte)word;
  93006. #elif FLAC__BYTES_PER_WORD == 8
  93007. val[0] = (FLAC__byte)(word >> 56);
  93008. val[1] = (FLAC__byte)(word >> 48);
  93009. val[2] = (FLAC__byte)(word >> 40);
  93010. val[3] = (FLAC__byte)(word >> 32);
  93011. val[4] = (FLAC__byte)(word >> 24);
  93012. val[5] = (FLAC__byte)(word >> 16);
  93013. val[6] = (FLAC__byte)(word >> 8);
  93014. val[7] = (FLAC__byte)word;
  93015. #else
  93016. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93017. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93018. #endif
  93019. val += FLAC__BYTES_PER_WORD;
  93020. nvals -= FLAC__BYTES_PER_WORD;
  93021. }
  93022. else if(!bitreader_read_from_client_(br))
  93023. return false;
  93024. }
  93025. /* step 3: read any remainder from partial tail bytes */
  93026. while(nvals) {
  93027. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93028. return false;
  93029. *val++ = (FLAC__byte)x;
  93030. nvals--;
  93031. }
  93032. return true;
  93033. }
  93034. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93035. #if 0 /* slow but readable version */
  93036. {
  93037. unsigned bit;
  93038. FLAC__ASSERT(0 != br);
  93039. FLAC__ASSERT(0 != br->buffer);
  93040. *val = 0;
  93041. while(1) {
  93042. if(!FLAC__bitreader_read_bit(br, &bit))
  93043. return false;
  93044. if(bit)
  93045. break;
  93046. else
  93047. *val++;
  93048. }
  93049. return true;
  93050. }
  93051. #else
  93052. {
  93053. unsigned i;
  93054. FLAC__ASSERT(0 != br);
  93055. FLAC__ASSERT(0 != br->buffer);
  93056. *val = 0;
  93057. while(1) {
  93058. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93059. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93060. if(b) {
  93061. i = COUNT_ZERO_MSBS(b);
  93062. *val += i;
  93063. i++;
  93064. br->consumed_bits += i;
  93065. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93066. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93067. br->consumed_words++;
  93068. br->consumed_bits = 0;
  93069. }
  93070. return true;
  93071. }
  93072. else {
  93073. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93074. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93075. br->consumed_words++;
  93076. br->consumed_bits = 0;
  93077. /* didn't find stop bit yet, have to keep going... */
  93078. }
  93079. }
  93080. /* at this point we've eaten up all the whole words; have to try
  93081. * reading through any tail bytes before calling the read callback.
  93082. * this is a repeat of the above logic adjusted for the fact we
  93083. * don't have a whole word. note though if the client is feeding
  93084. * us data a byte at a time (unlikely), br->consumed_bits may not
  93085. * be zero.
  93086. */
  93087. if(br->bytes) {
  93088. const unsigned end = br->bytes * 8;
  93089. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93090. if(b) {
  93091. i = COUNT_ZERO_MSBS(b);
  93092. *val += i;
  93093. i++;
  93094. br->consumed_bits += i;
  93095. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93096. return true;
  93097. }
  93098. else {
  93099. *val += end - br->consumed_bits;
  93100. br->consumed_bits += end;
  93101. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93102. /* didn't find stop bit yet, have to keep going... */
  93103. }
  93104. }
  93105. if(!bitreader_read_from_client_(br))
  93106. return false;
  93107. }
  93108. }
  93109. #endif
  93110. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93111. {
  93112. FLAC__uint32 lsbs = 0, msbs = 0;
  93113. unsigned uval;
  93114. FLAC__ASSERT(0 != br);
  93115. FLAC__ASSERT(0 != br->buffer);
  93116. FLAC__ASSERT(parameter <= 31);
  93117. /* read the unary MSBs and end bit */
  93118. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93119. return false;
  93120. /* read the binary LSBs */
  93121. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93122. return false;
  93123. /* compose the value */
  93124. uval = (msbs << parameter) | lsbs;
  93125. if(uval & 1)
  93126. *val = -((int)(uval >> 1)) - 1;
  93127. else
  93128. *val = (int)(uval >> 1);
  93129. return true;
  93130. }
  93131. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93132. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93133. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93134. /* OPT: possibly faster version for use with MSVC */
  93135. #ifdef _MSC_VER
  93136. {
  93137. unsigned i;
  93138. unsigned uval = 0;
  93139. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93140. /* try and get br->consumed_words and br->consumed_bits into register;
  93141. * must remember to flush them back to *br before calling other
  93142. * bitwriter functions that use them, and before returning */
  93143. register unsigned cwords;
  93144. register unsigned cbits;
  93145. FLAC__ASSERT(0 != br);
  93146. FLAC__ASSERT(0 != br->buffer);
  93147. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93148. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93149. FLAC__ASSERT(parameter < 32);
  93150. /* 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 */
  93151. if(nvals == 0)
  93152. return true;
  93153. cbits = br->consumed_bits;
  93154. cwords = br->consumed_words;
  93155. while(1) {
  93156. /* read unary part */
  93157. while(1) {
  93158. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93159. brword b = br->buffer[cwords] << cbits;
  93160. if(b) {
  93161. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93162. __asm {
  93163. bsr eax, b
  93164. not eax
  93165. and eax, 31
  93166. mov i, eax
  93167. }
  93168. #else
  93169. i = COUNT_ZERO_MSBS(b);
  93170. #endif
  93171. uval += i;
  93172. bits = parameter;
  93173. i++;
  93174. cbits += i;
  93175. if(cbits == FLAC__BITS_PER_WORD) {
  93176. crc16_update_word_(br, br->buffer[cwords]);
  93177. cwords++;
  93178. cbits = 0;
  93179. }
  93180. goto break1;
  93181. }
  93182. else {
  93183. uval += FLAC__BITS_PER_WORD - cbits;
  93184. crc16_update_word_(br, br->buffer[cwords]);
  93185. cwords++;
  93186. cbits = 0;
  93187. /* didn't find stop bit yet, have to keep going... */
  93188. }
  93189. }
  93190. /* at this point we've eaten up all the whole words; have to try
  93191. * reading through any tail bytes before calling the read callback.
  93192. * this is a repeat of the above logic adjusted for the fact we
  93193. * don't have a whole word. note though if the client is feeding
  93194. * us data a byte at a time (unlikely), br->consumed_bits may not
  93195. * be zero.
  93196. */
  93197. if(br->bytes) {
  93198. const unsigned end = br->bytes * 8;
  93199. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93200. if(b) {
  93201. i = COUNT_ZERO_MSBS(b);
  93202. uval += i;
  93203. bits = parameter;
  93204. i++;
  93205. cbits += i;
  93206. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93207. goto break1;
  93208. }
  93209. else {
  93210. uval += end - cbits;
  93211. cbits += end;
  93212. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93213. /* didn't find stop bit yet, have to keep going... */
  93214. }
  93215. }
  93216. /* flush registers and read; bitreader_read_from_client_() does
  93217. * not touch br->consumed_bits at all but we still need to set
  93218. * it in case it fails and we have to return false.
  93219. */
  93220. br->consumed_bits = cbits;
  93221. br->consumed_words = cwords;
  93222. if(!bitreader_read_from_client_(br))
  93223. return false;
  93224. cwords = br->consumed_words;
  93225. }
  93226. break1:
  93227. /* read binary part */
  93228. FLAC__ASSERT(cwords <= br->words);
  93229. if(bits) {
  93230. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93231. /* flush registers and read; bitreader_read_from_client_() does
  93232. * not touch br->consumed_bits at all but we still need to set
  93233. * it in case it fails and we have to return false.
  93234. */
  93235. br->consumed_bits = cbits;
  93236. br->consumed_words = cwords;
  93237. if(!bitreader_read_from_client_(br))
  93238. return false;
  93239. cwords = br->consumed_words;
  93240. }
  93241. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93242. if(cbits) {
  93243. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93244. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93245. const brword word = br->buffer[cwords];
  93246. if(bits < n) {
  93247. uval <<= bits;
  93248. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93249. cbits += bits;
  93250. goto break2;
  93251. }
  93252. uval <<= n;
  93253. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93254. bits -= n;
  93255. crc16_update_word_(br, word);
  93256. cwords++;
  93257. cbits = 0;
  93258. 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 */
  93259. uval <<= bits;
  93260. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93261. cbits = bits;
  93262. }
  93263. goto break2;
  93264. }
  93265. else {
  93266. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93267. uval <<= bits;
  93268. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93269. cbits = bits;
  93270. goto break2;
  93271. }
  93272. }
  93273. else {
  93274. /* in this case we're starting our read at a partial tail word;
  93275. * the reader has guaranteed that we have at least 'bits' bits
  93276. * available to read, which makes this case simpler.
  93277. */
  93278. uval <<= bits;
  93279. if(cbits) {
  93280. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93281. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93282. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93283. cbits += bits;
  93284. goto break2;
  93285. }
  93286. else {
  93287. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93288. cbits += bits;
  93289. goto break2;
  93290. }
  93291. }
  93292. }
  93293. break2:
  93294. /* compose the value */
  93295. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93296. /* are we done? */
  93297. --nvals;
  93298. if(nvals == 0) {
  93299. br->consumed_bits = cbits;
  93300. br->consumed_words = cwords;
  93301. return true;
  93302. }
  93303. uval = 0;
  93304. ++vals;
  93305. }
  93306. }
  93307. #else
  93308. {
  93309. unsigned i;
  93310. unsigned uval = 0;
  93311. /* try and get br->consumed_words and br->consumed_bits into register;
  93312. * must remember to flush them back to *br before calling other
  93313. * bitwriter functions that use them, and before returning */
  93314. register unsigned cwords;
  93315. register unsigned cbits;
  93316. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93317. FLAC__ASSERT(0 != br);
  93318. FLAC__ASSERT(0 != br->buffer);
  93319. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93320. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93321. FLAC__ASSERT(parameter < 32);
  93322. /* 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 */
  93323. if(nvals == 0)
  93324. return true;
  93325. cbits = br->consumed_bits;
  93326. cwords = br->consumed_words;
  93327. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93328. while(1) {
  93329. /* read unary part */
  93330. while(1) {
  93331. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93332. brword b = br->buffer[cwords] << cbits;
  93333. if(b) {
  93334. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93335. asm volatile (
  93336. "bsrl %1, %0;"
  93337. "notl %0;"
  93338. "andl $31, %0;"
  93339. : "=r"(i)
  93340. : "r"(b)
  93341. );
  93342. #else
  93343. i = COUNT_ZERO_MSBS(b);
  93344. #endif
  93345. uval += i;
  93346. cbits += i;
  93347. cbits++; /* skip over stop bit */
  93348. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93349. crc16_update_word_(br, br->buffer[cwords]);
  93350. cwords++;
  93351. cbits = 0;
  93352. }
  93353. goto break1;
  93354. }
  93355. else {
  93356. uval += FLAC__BITS_PER_WORD - cbits;
  93357. crc16_update_word_(br, br->buffer[cwords]);
  93358. cwords++;
  93359. cbits = 0;
  93360. /* didn't find stop bit yet, have to keep going... */
  93361. }
  93362. }
  93363. /* at this point we've eaten up all the whole words; have to try
  93364. * reading through any tail bytes before calling the read callback.
  93365. * this is a repeat of the above logic adjusted for the fact we
  93366. * don't have a whole word. note though if the client is feeding
  93367. * us data a byte at a time (unlikely), br->consumed_bits may not
  93368. * be zero.
  93369. */
  93370. if(br->bytes) {
  93371. const unsigned end = br->bytes * 8;
  93372. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93373. if(b) {
  93374. i = COUNT_ZERO_MSBS(b);
  93375. uval += i;
  93376. cbits += i;
  93377. cbits++; /* skip over stop bit */
  93378. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93379. goto break1;
  93380. }
  93381. else {
  93382. uval += end - cbits;
  93383. cbits += end;
  93384. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93385. /* didn't find stop bit yet, have to keep going... */
  93386. }
  93387. }
  93388. /* flush registers and read; bitreader_read_from_client_() does
  93389. * not touch br->consumed_bits at all but we still need to set
  93390. * it in case it fails and we have to return false.
  93391. */
  93392. br->consumed_bits = cbits;
  93393. br->consumed_words = cwords;
  93394. if(!bitreader_read_from_client_(br))
  93395. return false;
  93396. cwords = br->consumed_words;
  93397. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93398. /* + uval to offset our count by the # of unary bits already
  93399. * consumed before the read, because we will add these back
  93400. * in all at once at break1
  93401. */
  93402. }
  93403. break1:
  93404. ucbits -= uval;
  93405. ucbits--; /* account for stop bit */
  93406. /* read binary part */
  93407. FLAC__ASSERT(cwords <= br->words);
  93408. if(parameter) {
  93409. while(ucbits < parameter) {
  93410. /* flush registers and read; bitreader_read_from_client_() does
  93411. * not touch br->consumed_bits at all but we still need to set
  93412. * it in case it fails and we have to return false.
  93413. */
  93414. br->consumed_bits = cbits;
  93415. br->consumed_words = cwords;
  93416. if(!bitreader_read_from_client_(br))
  93417. return false;
  93418. cwords = br->consumed_words;
  93419. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93420. }
  93421. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93422. if(cbits) {
  93423. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93424. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93425. const brword word = br->buffer[cwords];
  93426. if(parameter < n) {
  93427. uval <<= parameter;
  93428. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93429. cbits += parameter;
  93430. }
  93431. else {
  93432. uval <<= n;
  93433. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93434. crc16_update_word_(br, word);
  93435. cwords++;
  93436. cbits = parameter - n;
  93437. 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 */
  93438. uval <<= cbits;
  93439. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93440. }
  93441. }
  93442. }
  93443. else {
  93444. cbits = parameter;
  93445. uval <<= parameter;
  93446. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93447. }
  93448. }
  93449. else {
  93450. /* in this case we're starting our read at a partial tail word;
  93451. * the reader has guaranteed that we have at least 'parameter'
  93452. * bits available to read, which makes this case simpler.
  93453. */
  93454. uval <<= parameter;
  93455. if(cbits) {
  93456. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93457. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93458. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93459. cbits += parameter;
  93460. }
  93461. else {
  93462. cbits = parameter;
  93463. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93464. }
  93465. }
  93466. }
  93467. ucbits -= parameter;
  93468. /* compose the value */
  93469. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93470. /* are we done? */
  93471. --nvals;
  93472. if(nvals == 0) {
  93473. br->consumed_bits = cbits;
  93474. br->consumed_words = cwords;
  93475. return true;
  93476. }
  93477. uval = 0;
  93478. ++vals;
  93479. }
  93480. }
  93481. #endif
  93482. #if 0 /* UNUSED */
  93483. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93484. {
  93485. FLAC__uint32 lsbs = 0, msbs = 0;
  93486. unsigned bit, uval, k;
  93487. FLAC__ASSERT(0 != br);
  93488. FLAC__ASSERT(0 != br->buffer);
  93489. k = FLAC__bitmath_ilog2(parameter);
  93490. /* read the unary MSBs and end bit */
  93491. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93492. return false;
  93493. /* read the binary LSBs */
  93494. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93495. return false;
  93496. if(parameter == 1u<<k) {
  93497. /* compose the value */
  93498. uval = (msbs << k) | lsbs;
  93499. }
  93500. else {
  93501. unsigned d = (1 << (k+1)) - parameter;
  93502. if(lsbs >= d) {
  93503. if(!FLAC__bitreader_read_bit(br, &bit))
  93504. return false;
  93505. lsbs <<= 1;
  93506. lsbs |= bit;
  93507. lsbs -= d;
  93508. }
  93509. /* compose the value */
  93510. uval = msbs * parameter + lsbs;
  93511. }
  93512. /* unfold unsigned to signed */
  93513. if(uval & 1)
  93514. *val = -((int)(uval >> 1)) - 1;
  93515. else
  93516. *val = (int)(uval >> 1);
  93517. return true;
  93518. }
  93519. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93520. {
  93521. FLAC__uint32 lsbs, msbs = 0;
  93522. unsigned bit, k;
  93523. FLAC__ASSERT(0 != br);
  93524. FLAC__ASSERT(0 != br->buffer);
  93525. k = FLAC__bitmath_ilog2(parameter);
  93526. /* read the unary MSBs and end bit */
  93527. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93528. return false;
  93529. /* read the binary LSBs */
  93530. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93531. return false;
  93532. if(parameter == 1u<<k) {
  93533. /* compose the value */
  93534. *val = (msbs << k) | lsbs;
  93535. }
  93536. else {
  93537. unsigned d = (1 << (k+1)) - parameter;
  93538. if(lsbs >= d) {
  93539. if(!FLAC__bitreader_read_bit(br, &bit))
  93540. return false;
  93541. lsbs <<= 1;
  93542. lsbs |= bit;
  93543. lsbs -= d;
  93544. }
  93545. /* compose the value */
  93546. *val = msbs * parameter + lsbs;
  93547. }
  93548. return true;
  93549. }
  93550. #endif /* UNUSED */
  93551. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93552. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93553. {
  93554. FLAC__uint32 v = 0;
  93555. FLAC__uint32 x;
  93556. unsigned i;
  93557. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93558. return false;
  93559. if(raw)
  93560. raw[(*rawlen)++] = (FLAC__byte)x;
  93561. if(!(x & 0x80)) { /* 0xxxxxxx */
  93562. v = x;
  93563. i = 0;
  93564. }
  93565. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93566. v = x & 0x1F;
  93567. i = 1;
  93568. }
  93569. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93570. v = x & 0x0F;
  93571. i = 2;
  93572. }
  93573. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93574. v = x & 0x07;
  93575. i = 3;
  93576. }
  93577. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93578. v = x & 0x03;
  93579. i = 4;
  93580. }
  93581. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93582. v = x & 0x01;
  93583. i = 5;
  93584. }
  93585. else {
  93586. *val = 0xffffffff;
  93587. return true;
  93588. }
  93589. for( ; i; i--) {
  93590. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93591. return false;
  93592. if(raw)
  93593. raw[(*rawlen)++] = (FLAC__byte)x;
  93594. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93595. *val = 0xffffffff;
  93596. return true;
  93597. }
  93598. v <<= 6;
  93599. v |= (x & 0x3F);
  93600. }
  93601. *val = v;
  93602. return true;
  93603. }
  93604. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93605. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93606. {
  93607. FLAC__uint64 v = 0;
  93608. FLAC__uint32 x;
  93609. unsigned i;
  93610. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93611. return false;
  93612. if(raw)
  93613. raw[(*rawlen)++] = (FLAC__byte)x;
  93614. if(!(x & 0x80)) { /* 0xxxxxxx */
  93615. v = x;
  93616. i = 0;
  93617. }
  93618. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93619. v = x & 0x1F;
  93620. i = 1;
  93621. }
  93622. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93623. v = x & 0x0F;
  93624. i = 2;
  93625. }
  93626. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93627. v = x & 0x07;
  93628. i = 3;
  93629. }
  93630. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93631. v = x & 0x03;
  93632. i = 4;
  93633. }
  93634. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93635. v = x & 0x01;
  93636. i = 5;
  93637. }
  93638. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93639. v = 0;
  93640. i = 6;
  93641. }
  93642. else {
  93643. *val = FLAC__U64L(0xffffffffffffffff);
  93644. return true;
  93645. }
  93646. for( ; i; i--) {
  93647. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93648. return false;
  93649. if(raw)
  93650. raw[(*rawlen)++] = (FLAC__byte)x;
  93651. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93652. *val = FLAC__U64L(0xffffffffffffffff);
  93653. return true;
  93654. }
  93655. v <<= 6;
  93656. v |= (x & 0x3F);
  93657. }
  93658. *val = v;
  93659. return true;
  93660. }
  93661. #endif
  93662. /*** End of inlined file: bitreader.c ***/
  93663. /*** Start of inlined file: bitwriter.c ***/
  93664. /*** Start of inlined file: juce_FlacHeader.h ***/
  93665. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93666. // tasks..
  93667. #define VERSION "1.2.1"
  93668. #define FLAC__NO_DLL 1
  93669. #if JUCE_MSVC
  93670. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93671. #endif
  93672. #if JUCE_MAC
  93673. #define FLAC__SYS_DARWIN 1
  93674. #endif
  93675. /*** End of inlined file: juce_FlacHeader.h ***/
  93676. #if JUCE_USE_FLAC
  93677. #if HAVE_CONFIG_H
  93678. # include <config.h>
  93679. #endif
  93680. #include <stdlib.h> /* for malloc() */
  93681. #include <string.h> /* for memcpy(), memset() */
  93682. #ifdef _MSC_VER
  93683. #include <winsock.h> /* for ntohl() */
  93684. #elif defined FLAC__SYS_DARWIN
  93685. #include <machine/endian.h> /* for ntohl() */
  93686. #elif defined __MINGW32__
  93687. #include <winsock.h> /* for ntohl() */
  93688. #else
  93689. #include <netinet/in.h> /* for ntohl() */
  93690. #endif
  93691. #if 0 /* UNUSED */
  93692. #endif
  93693. /*** Start of inlined file: bitwriter.h ***/
  93694. #ifndef FLAC__PRIVATE__BITWRITER_H
  93695. #define FLAC__PRIVATE__BITWRITER_H
  93696. #include <stdio.h> /* for FILE */
  93697. /*
  93698. * opaque structure definition
  93699. */
  93700. struct FLAC__BitWriter;
  93701. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93702. /*
  93703. * construction, deletion, initialization, etc functions
  93704. */
  93705. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93706. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93707. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93708. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93709. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93710. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93711. /*
  93712. * CRC functions
  93713. *
  93714. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93715. */
  93716. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93717. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93718. /*
  93719. * info functions
  93720. */
  93721. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93722. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93723. /*
  93724. * direct buffer access
  93725. *
  93726. * there may be no calls on the bitwriter between get and release.
  93727. * the bitwriter continues to own the returned buffer.
  93728. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93729. */
  93730. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93731. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93732. /*
  93733. * write functions
  93734. */
  93735. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93736. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93737. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93738. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93739. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93740. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93741. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93742. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93743. #if 0 /* UNUSED */
  93744. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93745. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93746. #endif
  93747. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93748. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93749. #if 0 /* UNUSED */
  93750. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93751. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93752. #endif
  93753. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93754. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93755. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93756. #endif
  93757. /*** End of inlined file: bitwriter.h ***/
  93758. /*** Start of inlined file: alloc.h ***/
  93759. #ifndef FLAC__SHARE__ALLOC_H
  93760. #define FLAC__SHARE__ALLOC_H
  93761. #if HAVE_CONFIG_H
  93762. # include <config.h>
  93763. #endif
  93764. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93765. * before #including this file, otherwise SIZE_MAX might not be defined
  93766. */
  93767. #include <limits.h> /* for SIZE_MAX */
  93768. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93769. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93770. #endif
  93771. #include <stdlib.h> /* for size_t, malloc(), etc */
  93772. #ifndef SIZE_MAX
  93773. # ifndef SIZE_T_MAX
  93774. # ifdef _MSC_VER
  93775. # define SIZE_T_MAX UINT_MAX
  93776. # else
  93777. # error
  93778. # endif
  93779. # endif
  93780. # define SIZE_MAX SIZE_T_MAX
  93781. #endif
  93782. #ifndef FLaC__INLINE
  93783. #define FLaC__INLINE
  93784. #endif
  93785. /* avoid malloc()ing 0 bytes, see:
  93786. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93787. */
  93788. static FLaC__INLINE void *safe_malloc_(size_t size)
  93789. {
  93790. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93791. if(!size)
  93792. size++;
  93793. return malloc(size);
  93794. }
  93795. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93796. {
  93797. if(!nmemb || !size)
  93798. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93799. return calloc(nmemb, size);
  93800. }
  93801. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93802. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93803. {
  93804. size2 += size1;
  93805. if(size2 < size1)
  93806. return 0;
  93807. return safe_malloc_(size2);
  93808. }
  93809. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93810. {
  93811. size2 += size1;
  93812. if(size2 < size1)
  93813. return 0;
  93814. size3 += size2;
  93815. if(size3 < size2)
  93816. return 0;
  93817. return safe_malloc_(size3);
  93818. }
  93819. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93820. {
  93821. size2 += size1;
  93822. if(size2 < size1)
  93823. return 0;
  93824. size3 += size2;
  93825. if(size3 < size2)
  93826. return 0;
  93827. size4 += size3;
  93828. if(size4 < size3)
  93829. return 0;
  93830. return safe_malloc_(size4);
  93831. }
  93832. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93833. #if 0
  93834. needs support for cases where sizeof(size_t) != 4
  93835. {
  93836. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93837. if(sizeof(size_t) == 4) {
  93838. if ((double)size1 * (double)size2 < 4294967296.0)
  93839. return malloc(size1*size2);
  93840. }
  93841. return 0;
  93842. }
  93843. #else
  93844. /* better? */
  93845. {
  93846. if(!size1 || !size2)
  93847. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93848. if(size1 > SIZE_MAX / size2)
  93849. return 0;
  93850. return malloc(size1*size2);
  93851. }
  93852. #endif
  93853. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93854. {
  93855. if(!size1 || !size2 || !size3)
  93856. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93857. if(size1 > SIZE_MAX / size2)
  93858. return 0;
  93859. size1 *= size2;
  93860. if(size1 > SIZE_MAX / size3)
  93861. return 0;
  93862. return malloc(size1*size3);
  93863. }
  93864. /* size1*size2 + size3 */
  93865. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93866. {
  93867. if(!size1 || !size2)
  93868. return safe_malloc_(size3);
  93869. if(size1 > SIZE_MAX / size2)
  93870. return 0;
  93871. return safe_malloc_add_2op_(size1*size2, size3);
  93872. }
  93873. /* size1 * (size2 + size3) */
  93874. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93875. {
  93876. if(!size1 || (!size2 && !size3))
  93877. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93878. size2 += size3;
  93879. if(size2 < size3)
  93880. return 0;
  93881. return safe_malloc_mul_2op_(size1, size2);
  93882. }
  93883. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93884. {
  93885. size2 += size1;
  93886. if(size2 < size1)
  93887. return 0;
  93888. return realloc(ptr, size2);
  93889. }
  93890. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93891. {
  93892. size2 += size1;
  93893. if(size2 < size1)
  93894. return 0;
  93895. size3 += size2;
  93896. if(size3 < size2)
  93897. return 0;
  93898. return realloc(ptr, size3);
  93899. }
  93900. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93901. {
  93902. size2 += size1;
  93903. if(size2 < size1)
  93904. return 0;
  93905. size3 += size2;
  93906. if(size3 < size2)
  93907. return 0;
  93908. size4 += size3;
  93909. if(size4 < size3)
  93910. return 0;
  93911. return realloc(ptr, size4);
  93912. }
  93913. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93914. {
  93915. if(!size1 || !size2)
  93916. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93917. if(size1 > SIZE_MAX / size2)
  93918. return 0;
  93919. return realloc(ptr, size1*size2);
  93920. }
  93921. /* size1 * (size2 + size3) */
  93922. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93923. {
  93924. if(!size1 || (!size2 && !size3))
  93925. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93926. size2 += size3;
  93927. if(size2 < size3)
  93928. return 0;
  93929. return safe_realloc_mul_2op_(ptr, size1, size2);
  93930. }
  93931. #endif
  93932. /*** End of inlined file: alloc.h ***/
  93933. /* Things should be fastest when this matches the machine word size */
  93934. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93935. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93936. typedef FLAC__uint32 bwword;
  93937. #define FLAC__BYTES_PER_WORD 4
  93938. #define FLAC__BITS_PER_WORD 32
  93939. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93940. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93941. #if WORDS_BIGENDIAN
  93942. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93943. #else
  93944. #ifdef _MSC_VER
  93945. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93946. #else
  93947. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93948. #endif
  93949. #endif
  93950. /*
  93951. * The default capacity here doesn't matter too much. The buffer always grows
  93952. * to hold whatever is written to it. Usually the encoder will stop adding at
  93953. * a frame or metadata block, then write that out and clear the buffer for the
  93954. * next one.
  93955. */
  93956. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93957. /* When growing, increment 4K at a time */
  93958. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93959. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93960. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93961. #ifdef min
  93962. #undef min
  93963. #endif
  93964. #define min(x,y) ((x)<(y)?(x):(y))
  93965. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93966. #ifdef _MSC_VER
  93967. #define FLAC__U64L(x) x
  93968. #else
  93969. #define FLAC__U64L(x) x##LLU
  93970. #endif
  93971. #ifndef FLaC__INLINE
  93972. #define FLaC__INLINE
  93973. #endif
  93974. struct FLAC__BitWriter {
  93975. bwword *buffer;
  93976. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93977. unsigned capacity; /* capacity of buffer in words */
  93978. unsigned words; /* # of complete words in buffer */
  93979. unsigned bits; /* # of used bits in accum */
  93980. };
  93981. /* * WATCHOUT: The current implementation only grows the buffer. */
  93982. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93983. {
  93984. unsigned new_capacity;
  93985. bwword *new_buffer;
  93986. FLAC__ASSERT(0 != bw);
  93987. FLAC__ASSERT(0 != bw->buffer);
  93988. /* calculate total words needed to store 'bits_to_add' additional bits */
  93989. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93990. /* it's possible (due to pessimism in the growth estimation that
  93991. * leads to this call) that we don't actually need to grow
  93992. */
  93993. if(bw->capacity >= new_capacity)
  93994. return true;
  93995. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93996. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93997. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93998. /* make sure we got everything right */
  93999. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94000. FLAC__ASSERT(new_capacity > bw->capacity);
  94001. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94002. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94003. if(new_buffer == 0)
  94004. return false;
  94005. bw->buffer = new_buffer;
  94006. bw->capacity = new_capacity;
  94007. return true;
  94008. }
  94009. /***********************************************************************
  94010. *
  94011. * Class constructor/destructor
  94012. *
  94013. ***********************************************************************/
  94014. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94015. {
  94016. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94017. /* note that calloc() sets all members to 0 for us */
  94018. return bw;
  94019. }
  94020. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94021. {
  94022. FLAC__ASSERT(0 != bw);
  94023. FLAC__bitwriter_free(bw);
  94024. free(bw);
  94025. }
  94026. /***********************************************************************
  94027. *
  94028. * Public class methods
  94029. *
  94030. ***********************************************************************/
  94031. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94032. {
  94033. FLAC__ASSERT(0 != bw);
  94034. bw->words = bw->bits = 0;
  94035. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94036. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94037. if(bw->buffer == 0)
  94038. return false;
  94039. return true;
  94040. }
  94041. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94042. {
  94043. FLAC__ASSERT(0 != bw);
  94044. if(0 != bw->buffer)
  94045. free(bw->buffer);
  94046. bw->buffer = 0;
  94047. bw->capacity = 0;
  94048. bw->words = bw->bits = 0;
  94049. }
  94050. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94051. {
  94052. bw->words = bw->bits = 0;
  94053. }
  94054. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94055. {
  94056. unsigned i, j;
  94057. if(bw == 0) {
  94058. fprintf(out, "bitwriter is NULL\n");
  94059. }
  94060. else {
  94061. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94062. for(i = 0; i < bw->words; i++) {
  94063. fprintf(out, "%08X: ", i);
  94064. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94065. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94066. fprintf(out, "\n");
  94067. }
  94068. if(bw->bits > 0) {
  94069. fprintf(out, "%08X: ", i);
  94070. for(j = 0; j < bw->bits; j++)
  94071. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94072. fprintf(out, "\n");
  94073. }
  94074. }
  94075. }
  94076. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94077. {
  94078. const FLAC__byte *buffer;
  94079. size_t bytes;
  94080. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94081. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94082. return false;
  94083. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94084. FLAC__bitwriter_release_buffer(bw);
  94085. return true;
  94086. }
  94087. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94088. {
  94089. const FLAC__byte *buffer;
  94090. size_t bytes;
  94091. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94092. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94093. return false;
  94094. *crc = FLAC__crc8(buffer, bytes);
  94095. FLAC__bitwriter_release_buffer(bw);
  94096. return true;
  94097. }
  94098. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94099. {
  94100. return ((bw->bits & 7) == 0);
  94101. }
  94102. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94103. {
  94104. return FLAC__TOTAL_BITS(bw);
  94105. }
  94106. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94107. {
  94108. FLAC__ASSERT((bw->bits & 7) == 0);
  94109. /* double protection */
  94110. if(bw->bits & 7)
  94111. return false;
  94112. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94113. if(bw->bits) {
  94114. FLAC__ASSERT(bw->words <= bw->capacity);
  94115. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94116. return false;
  94117. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94118. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94119. }
  94120. /* now we can just return what we have */
  94121. *buffer = (FLAC__byte*)bw->buffer;
  94122. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94123. return true;
  94124. }
  94125. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94126. {
  94127. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94128. * get-mode' flag could be added everywhere and then cleared here
  94129. */
  94130. (void)bw;
  94131. }
  94132. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94133. {
  94134. unsigned n;
  94135. FLAC__ASSERT(0 != bw);
  94136. FLAC__ASSERT(0 != bw->buffer);
  94137. if(bits == 0)
  94138. return true;
  94139. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94140. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94141. return false;
  94142. /* first part gets to word alignment */
  94143. if(bw->bits) {
  94144. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94145. bw->accum <<= n;
  94146. bits -= n;
  94147. bw->bits += n;
  94148. if(bw->bits == FLAC__BITS_PER_WORD) {
  94149. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94150. bw->bits = 0;
  94151. }
  94152. else
  94153. return true;
  94154. }
  94155. /* do whole words */
  94156. while(bits >= FLAC__BITS_PER_WORD) {
  94157. bw->buffer[bw->words++] = 0;
  94158. bits -= FLAC__BITS_PER_WORD;
  94159. }
  94160. /* do any leftovers */
  94161. if(bits > 0) {
  94162. bw->accum = 0;
  94163. bw->bits = bits;
  94164. }
  94165. return true;
  94166. }
  94167. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94168. {
  94169. register unsigned left;
  94170. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94171. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94172. FLAC__ASSERT(0 != bw);
  94173. FLAC__ASSERT(0 != bw->buffer);
  94174. FLAC__ASSERT(bits <= 32);
  94175. if(bits == 0)
  94176. return true;
  94177. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94178. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94179. return false;
  94180. left = FLAC__BITS_PER_WORD - bw->bits;
  94181. if(bits < left) {
  94182. bw->accum <<= bits;
  94183. bw->accum |= val;
  94184. bw->bits += bits;
  94185. }
  94186. 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 */
  94187. bw->accum <<= left;
  94188. bw->accum |= val >> (bw->bits = bits - left);
  94189. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94190. bw->accum = val;
  94191. }
  94192. else {
  94193. bw->accum = val;
  94194. bw->bits = 0;
  94195. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94196. }
  94197. return true;
  94198. }
  94199. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94200. {
  94201. /* zero-out unused bits */
  94202. if(bits < 32)
  94203. val &= (~(0xffffffff << bits));
  94204. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94205. }
  94206. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94207. {
  94208. /* this could be a little faster but it's not used for much */
  94209. if(bits > 32) {
  94210. return
  94211. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94212. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94213. }
  94214. else
  94215. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94216. }
  94217. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94218. {
  94219. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94220. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94221. return false;
  94222. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94223. return false;
  94224. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94225. return false;
  94226. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94227. return false;
  94228. return true;
  94229. }
  94230. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94231. {
  94232. unsigned i;
  94233. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94234. for(i = 0; i < nvals; i++) {
  94235. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94236. return false;
  94237. }
  94238. return true;
  94239. }
  94240. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94241. {
  94242. if(val < 32)
  94243. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94244. else
  94245. return
  94246. FLAC__bitwriter_write_zeroes(bw, val) &&
  94247. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94248. }
  94249. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94250. {
  94251. FLAC__uint32 uval;
  94252. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94253. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94254. uval = (val<<1) ^ (val>>31);
  94255. return 1 + parameter + (uval >> parameter);
  94256. }
  94257. #if 0 /* UNUSED */
  94258. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94259. {
  94260. unsigned bits, msbs, uval;
  94261. unsigned k;
  94262. FLAC__ASSERT(parameter > 0);
  94263. /* fold signed to unsigned */
  94264. if(val < 0)
  94265. uval = (unsigned)(((-(++val)) << 1) + 1);
  94266. else
  94267. uval = (unsigned)(val << 1);
  94268. k = FLAC__bitmath_ilog2(parameter);
  94269. if(parameter == 1u<<k) {
  94270. FLAC__ASSERT(k <= 30);
  94271. msbs = uval >> k;
  94272. bits = 1 + k + msbs;
  94273. }
  94274. else {
  94275. unsigned q, r, d;
  94276. d = (1 << (k+1)) - parameter;
  94277. q = uval / parameter;
  94278. r = uval - (q * parameter);
  94279. bits = 1 + q + k;
  94280. if(r >= d)
  94281. bits++;
  94282. }
  94283. return bits;
  94284. }
  94285. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94286. {
  94287. unsigned bits, msbs;
  94288. unsigned k;
  94289. FLAC__ASSERT(parameter > 0);
  94290. k = FLAC__bitmath_ilog2(parameter);
  94291. if(parameter == 1u<<k) {
  94292. FLAC__ASSERT(k <= 30);
  94293. msbs = uval >> k;
  94294. bits = 1 + k + msbs;
  94295. }
  94296. else {
  94297. unsigned q, r, d;
  94298. d = (1 << (k+1)) - parameter;
  94299. q = uval / parameter;
  94300. r = uval - (q * parameter);
  94301. bits = 1 + q + k;
  94302. if(r >= d)
  94303. bits++;
  94304. }
  94305. return bits;
  94306. }
  94307. #endif /* UNUSED */
  94308. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94309. {
  94310. unsigned total_bits, interesting_bits, msbs;
  94311. FLAC__uint32 uval, pattern;
  94312. FLAC__ASSERT(0 != bw);
  94313. FLAC__ASSERT(0 != bw->buffer);
  94314. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94315. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94316. uval = (val<<1) ^ (val>>31);
  94317. msbs = uval >> parameter;
  94318. interesting_bits = 1 + parameter;
  94319. total_bits = interesting_bits + msbs;
  94320. pattern = 1 << parameter; /* the unary end bit */
  94321. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94322. if(total_bits <= 32)
  94323. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94324. else
  94325. return
  94326. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94327. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94328. }
  94329. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94330. {
  94331. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94332. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94333. FLAC__uint32 uval;
  94334. unsigned left;
  94335. const unsigned lsbits = 1 + parameter;
  94336. unsigned msbits;
  94337. FLAC__ASSERT(0 != bw);
  94338. FLAC__ASSERT(0 != bw->buffer);
  94339. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94340. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94341. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94342. while(nvals) {
  94343. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94344. uval = (*vals<<1) ^ (*vals>>31);
  94345. msbits = uval >> parameter;
  94346. #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) */
  94347. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94348. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94349. bw->bits = bw->bits + msbits + lsbits;
  94350. uval |= mask1; /* set stop bit */
  94351. uval &= mask2; /* mask off unused top bits */
  94352. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94353. bw->accum <<= msbits;
  94354. bw->accum <<= lsbits;
  94355. bw->accum |= uval;
  94356. if(bw->bits == FLAC__BITS_PER_WORD) {
  94357. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94358. bw->bits = 0;
  94359. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94360. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94361. FLAC__ASSERT(bw->capacity == bw->words);
  94362. return false;
  94363. }
  94364. }
  94365. }
  94366. else {
  94367. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94368. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94369. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94370. bw->bits = bw->bits + msbits + lsbits;
  94371. uval |= mask1; /* set stop bit */
  94372. uval &= mask2; /* mask off unused top bits */
  94373. bw->accum <<= msbits + lsbits;
  94374. bw->accum |= uval;
  94375. }
  94376. else {
  94377. #endif
  94378. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94379. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94380. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94381. return false;
  94382. if(msbits) {
  94383. /* first part gets to word alignment */
  94384. if(bw->bits) {
  94385. left = FLAC__BITS_PER_WORD - bw->bits;
  94386. if(msbits < left) {
  94387. bw->accum <<= msbits;
  94388. bw->bits += msbits;
  94389. goto break1;
  94390. }
  94391. else {
  94392. bw->accum <<= left;
  94393. msbits -= left;
  94394. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94395. bw->bits = 0;
  94396. }
  94397. }
  94398. /* do whole words */
  94399. while(msbits >= FLAC__BITS_PER_WORD) {
  94400. bw->buffer[bw->words++] = 0;
  94401. msbits -= FLAC__BITS_PER_WORD;
  94402. }
  94403. /* do any leftovers */
  94404. if(msbits > 0) {
  94405. bw->accum = 0;
  94406. bw->bits = msbits;
  94407. }
  94408. }
  94409. break1:
  94410. uval |= mask1; /* set stop bit */
  94411. uval &= mask2; /* mask off unused top bits */
  94412. left = FLAC__BITS_PER_WORD - bw->bits;
  94413. if(lsbits < left) {
  94414. bw->accum <<= lsbits;
  94415. bw->accum |= uval;
  94416. bw->bits += lsbits;
  94417. }
  94418. else {
  94419. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94420. * be > lsbits (because of previous assertions) so it would have
  94421. * triggered the (lsbits<left) case above.
  94422. */
  94423. FLAC__ASSERT(bw->bits);
  94424. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94425. bw->accum <<= left;
  94426. bw->accum |= uval >> (bw->bits = lsbits - left);
  94427. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94428. bw->accum = uval;
  94429. }
  94430. #if 1
  94431. }
  94432. #endif
  94433. vals++;
  94434. nvals--;
  94435. }
  94436. return true;
  94437. }
  94438. #if 0 /* UNUSED */
  94439. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94440. {
  94441. unsigned total_bits, msbs, uval;
  94442. unsigned k;
  94443. FLAC__ASSERT(0 != bw);
  94444. FLAC__ASSERT(0 != bw->buffer);
  94445. FLAC__ASSERT(parameter > 0);
  94446. /* fold signed to unsigned */
  94447. if(val < 0)
  94448. uval = (unsigned)(((-(++val)) << 1) + 1);
  94449. else
  94450. uval = (unsigned)(val << 1);
  94451. k = FLAC__bitmath_ilog2(parameter);
  94452. if(parameter == 1u<<k) {
  94453. unsigned pattern;
  94454. FLAC__ASSERT(k <= 30);
  94455. msbs = uval >> k;
  94456. total_bits = 1 + k + msbs;
  94457. pattern = 1 << k; /* the unary end bit */
  94458. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94459. if(total_bits <= 32) {
  94460. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94461. return false;
  94462. }
  94463. else {
  94464. /* write the unary MSBs */
  94465. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94466. return false;
  94467. /* write the unary end bit and binary LSBs */
  94468. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94469. return false;
  94470. }
  94471. }
  94472. else {
  94473. unsigned q, r, d;
  94474. d = (1 << (k+1)) - parameter;
  94475. q = uval / parameter;
  94476. r = uval - (q * parameter);
  94477. /* write the unary MSBs */
  94478. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94479. return false;
  94480. /* write the unary end bit */
  94481. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94482. return false;
  94483. /* write the binary LSBs */
  94484. if(r >= d) {
  94485. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94486. return false;
  94487. }
  94488. else {
  94489. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94490. return false;
  94491. }
  94492. }
  94493. return true;
  94494. }
  94495. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94496. {
  94497. unsigned total_bits, msbs;
  94498. unsigned k;
  94499. FLAC__ASSERT(0 != bw);
  94500. FLAC__ASSERT(0 != bw->buffer);
  94501. FLAC__ASSERT(parameter > 0);
  94502. k = FLAC__bitmath_ilog2(parameter);
  94503. if(parameter == 1u<<k) {
  94504. unsigned pattern;
  94505. FLAC__ASSERT(k <= 30);
  94506. msbs = uval >> k;
  94507. total_bits = 1 + k + msbs;
  94508. pattern = 1 << k; /* the unary end bit */
  94509. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94510. if(total_bits <= 32) {
  94511. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94512. return false;
  94513. }
  94514. else {
  94515. /* write the unary MSBs */
  94516. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94517. return false;
  94518. /* write the unary end bit and binary LSBs */
  94519. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94520. return false;
  94521. }
  94522. }
  94523. else {
  94524. unsigned q, r, d;
  94525. d = (1 << (k+1)) - parameter;
  94526. q = uval / parameter;
  94527. r = uval - (q * parameter);
  94528. /* write the unary MSBs */
  94529. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94530. return false;
  94531. /* write the unary end bit */
  94532. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94533. return false;
  94534. /* write the binary LSBs */
  94535. if(r >= d) {
  94536. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94537. return false;
  94538. }
  94539. else {
  94540. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94541. return false;
  94542. }
  94543. }
  94544. return true;
  94545. }
  94546. #endif /* UNUSED */
  94547. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94548. {
  94549. FLAC__bool ok = 1;
  94550. FLAC__ASSERT(0 != bw);
  94551. FLAC__ASSERT(0 != bw->buffer);
  94552. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94553. if(val < 0x80) {
  94554. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94555. }
  94556. else if(val < 0x800) {
  94557. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94558. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94559. }
  94560. else if(val < 0x10000) {
  94561. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94562. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94563. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94564. }
  94565. else if(val < 0x200000) {
  94566. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94567. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94568. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94569. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94570. }
  94571. else if(val < 0x4000000) {
  94572. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94573. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94574. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94575. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94576. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94577. }
  94578. else {
  94579. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94580. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94581. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94582. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94583. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94584. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94585. }
  94586. return ok;
  94587. }
  94588. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94589. {
  94590. FLAC__bool ok = 1;
  94591. FLAC__ASSERT(0 != bw);
  94592. FLAC__ASSERT(0 != bw->buffer);
  94593. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94594. if(val < 0x80) {
  94595. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94596. }
  94597. else if(val < 0x800) {
  94598. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94599. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94600. }
  94601. else if(val < 0x10000) {
  94602. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94603. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94604. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94605. }
  94606. else if(val < 0x200000) {
  94607. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94608. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94609. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94610. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94611. }
  94612. else if(val < 0x4000000) {
  94613. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94614. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94615. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94616. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94617. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94618. }
  94619. else if(val < 0x80000000) {
  94620. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94621. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94622. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94623. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94624. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94625. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94626. }
  94627. else {
  94628. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94629. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94630. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94631. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94632. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94633. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94634. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94635. }
  94636. return ok;
  94637. }
  94638. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94639. {
  94640. /* 0-pad to byte boundary */
  94641. if(bw->bits & 7u)
  94642. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94643. else
  94644. return true;
  94645. }
  94646. #endif
  94647. /*** End of inlined file: bitwriter.c ***/
  94648. /*** Start of inlined file: cpu.c ***/
  94649. /*** Start of inlined file: juce_FlacHeader.h ***/
  94650. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94651. // tasks..
  94652. #define VERSION "1.2.1"
  94653. #define FLAC__NO_DLL 1
  94654. #if JUCE_MSVC
  94655. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94656. #endif
  94657. #if JUCE_MAC
  94658. #define FLAC__SYS_DARWIN 1
  94659. #endif
  94660. /*** End of inlined file: juce_FlacHeader.h ***/
  94661. #if JUCE_USE_FLAC
  94662. #if HAVE_CONFIG_H
  94663. # include <config.h>
  94664. #endif
  94665. #include <stdlib.h>
  94666. #include <stdio.h>
  94667. #if defined FLAC__CPU_IA32
  94668. # include <signal.h>
  94669. #elif defined FLAC__CPU_PPC
  94670. # if !defined FLAC__NO_ASM
  94671. # if defined FLAC__SYS_DARWIN
  94672. # include <sys/sysctl.h>
  94673. # include <mach/mach.h>
  94674. # include <mach/mach_host.h>
  94675. # include <mach/host_info.h>
  94676. # include <mach/machine.h>
  94677. # ifndef CPU_SUBTYPE_POWERPC_970
  94678. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94679. # endif
  94680. # else /* FLAC__SYS_DARWIN */
  94681. # include <signal.h>
  94682. # include <setjmp.h>
  94683. static sigjmp_buf jmpbuf;
  94684. static volatile sig_atomic_t canjump = 0;
  94685. static void sigill_handler (int sig)
  94686. {
  94687. if (!canjump) {
  94688. signal (sig, SIG_DFL);
  94689. raise (sig);
  94690. }
  94691. canjump = 0;
  94692. siglongjmp (jmpbuf, 1);
  94693. }
  94694. # endif /* FLAC__SYS_DARWIN */
  94695. # endif /* FLAC__NO_ASM */
  94696. #endif /* FLAC__CPU_PPC */
  94697. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94698. #include <sys/param.h>
  94699. #include <sys/sysctl.h>
  94700. #include <machine/cpu.h>
  94701. #endif
  94702. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94703. #include <sys/types.h>
  94704. #include <sys/sysctl.h>
  94705. #endif
  94706. #if defined(__APPLE__)
  94707. /* how to get sysctlbyname()? */
  94708. #endif
  94709. /* these are flags in EDX of CPUID AX=00000001 */
  94710. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94711. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94712. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94713. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94714. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94715. /* these are flags in ECX of CPUID AX=00000001 */
  94716. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94717. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94718. /* these are flags in EDX of CPUID AX=80000001 */
  94719. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94720. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94721. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94722. /*
  94723. * Extra stuff needed for detection of OS support for SSE on IA-32
  94724. */
  94725. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94726. # if defined(__linux__)
  94727. /*
  94728. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94729. * modify the return address to jump over the offending SSE instruction
  94730. * and also the operation following it that indicates the instruction
  94731. * executed successfully. In this way we use no global variables and
  94732. * stay thread-safe.
  94733. *
  94734. * 3 + 3 + 6:
  94735. * 3 bytes for "xorps xmm0,xmm0"
  94736. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94737. * 6 bytes extra in case our estimate is wrong
  94738. * 12 bytes puts us in the NOP "landing zone"
  94739. */
  94740. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94741. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94742. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94743. {
  94744. (void)signal;
  94745. sc.eip += 3 + 3 + 6;
  94746. }
  94747. # else
  94748. # include <sys/ucontext.h>
  94749. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94750. {
  94751. (void)signal, (void)si;
  94752. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94753. }
  94754. # endif
  94755. # elif defined(_MSC_VER)
  94756. # include <windows.h>
  94757. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94758. # ifdef USE_TRY_CATCH_FLAVOR
  94759. # else
  94760. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94761. {
  94762. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94763. ep->ContextRecord->Eip += 3 + 3 + 6;
  94764. return EXCEPTION_CONTINUE_EXECUTION;
  94765. }
  94766. return EXCEPTION_CONTINUE_SEARCH;
  94767. }
  94768. # endif
  94769. # endif
  94770. #endif
  94771. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94772. {
  94773. /*
  94774. * IA32-specific
  94775. */
  94776. #ifdef FLAC__CPU_IA32
  94777. info->type = FLAC__CPUINFO_TYPE_IA32;
  94778. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94779. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94780. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94781. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94782. info->data.ia32.cmov = false;
  94783. info->data.ia32.mmx = false;
  94784. info->data.ia32.fxsr = false;
  94785. info->data.ia32.sse = false;
  94786. info->data.ia32.sse2 = false;
  94787. info->data.ia32.sse3 = false;
  94788. info->data.ia32.ssse3 = false;
  94789. info->data.ia32._3dnow = false;
  94790. info->data.ia32.ext3dnow = false;
  94791. info->data.ia32.extmmx = false;
  94792. if(info->data.ia32.cpuid) {
  94793. /* http://www.sandpile.org/ia32/cpuid.htm */
  94794. FLAC__uint32 flags_edx, flags_ecx;
  94795. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94796. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94797. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94798. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94799. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94800. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94801. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94802. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94803. #ifdef FLAC__USE_3DNOW
  94804. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94805. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94806. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94807. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94808. #else
  94809. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94810. #endif
  94811. #ifdef DEBUG
  94812. fprintf(stderr, "CPU info (IA-32):\n");
  94813. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94814. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94815. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94816. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94817. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94818. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94819. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94820. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94821. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94822. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94823. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94824. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94825. #endif
  94826. /*
  94827. * now have to check for OS support of SSE/SSE2
  94828. */
  94829. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94830. #if defined FLAC__NO_SSE_OS
  94831. /* assume user knows better than us; turn it off */
  94832. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94833. #elif defined FLAC__SSE_OS
  94834. /* assume user knows better than us; leave as detected above */
  94835. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94836. int sse = 0;
  94837. size_t len;
  94838. /* at least one of these must work: */
  94839. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94840. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94841. if(!sse)
  94842. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94843. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94844. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94845. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94846. size_t len = sizeof(val);
  94847. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94848. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94849. else { /* double-check SSE2 */
  94850. mib[1] = CPU_SSE2;
  94851. len = sizeof(val);
  94852. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94853. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94854. }
  94855. # else
  94856. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94857. # endif
  94858. #elif defined(__linux__)
  94859. int sse = 0;
  94860. struct sigaction sigill_save;
  94861. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94862. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94863. #else
  94864. struct sigaction sigill_sse;
  94865. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94866. __sigemptyset(&sigill_sse.sa_mask);
  94867. 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 */
  94868. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94869. #endif
  94870. {
  94871. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94872. /* see sigill_handler_sse_os() for an explanation of the following: */
  94873. asm volatile (
  94874. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94875. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94876. "incl %0\n\t" /* SIGILL handler will jump over this */
  94877. /* landing zone */
  94878. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94879. "nop\n\t"
  94880. "nop\n\t"
  94881. "nop\n\t"
  94882. "nop\n\t"
  94883. "nop\n\t"
  94884. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94885. "nop\n\t"
  94886. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94887. : "=r"(sse)
  94888. : "r"(sse)
  94889. );
  94890. sigaction(SIGILL, &sigill_save, NULL);
  94891. }
  94892. if(!sse)
  94893. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94894. #elif defined(_MSC_VER)
  94895. # ifdef USE_TRY_CATCH_FLAVOR
  94896. _try {
  94897. __asm {
  94898. # if _MSC_VER <= 1200
  94899. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94900. _emit 0x0F
  94901. _emit 0x57
  94902. _emit 0xC0
  94903. # else
  94904. xorps xmm0,xmm0
  94905. # endif
  94906. }
  94907. }
  94908. _except(EXCEPTION_EXECUTE_HANDLER) {
  94909. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94910. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94911. }
  94912. # else
  94913. int sse = 0;
  94914. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94915. /* see GCC version above for explanation */
  94916. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94917. /* http://www.codeproject.com/cpp/gccasm.asp */
  94918. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94919. __asm {
  94920. # if _MSC_VER <= 1200
  94921. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94922. _emit 0x0F
  94923. _emit 0x57
  94924. _emit 0xC0
  94925. # else
  94926. xorps xmm0,xmm0
  94927. # endif
  94928. inc sse
  94929. nop
  94930. nop
  94931. nop
  94932. nop
  94933. nop
  94934. nop
  94935. nop
  94936. nop
  94937. nop
  94938. }
  94939. SetUnhandledExceptionFilter(save);
  94940. if(!sse)
  94941. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94942. # endif
  94943. #else
  94944. /* no way to test, disable to be safe */
  94945. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94946. #endif
  94947. #ifdef DEBUG
  94948. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94949. #endif
  94950. }
  94951. }
  94952. #else
  94953. info->use_asm = false;
  94954. #endif
  94955. /*
  94956. * PPC-specific
  94957. */
  94958. #elif defined FLAC__CPU_PPC
  94959. info->type = FLAC__CPUINFO_TYPE_PPC;
  94960. # if !defined FLAC__NO_ASM
  94961. info->use_asm = true;
  94962. # ifdef FLAC__USE_ALTIVEC
  94963. # if defined FLAC__SYS_DARWIN
  94964. {
  94965. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94966. size_t len = sizeof(val);
  94967. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94968. }
  94969. {
  94970. host_basic_info_data_t hostInfo;
  94971. mach_msg_type_number_t infoCount;
  94972. infoCount = HOST_BASIC_INFO_COUNT;
  94973. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94974. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94975. }
  94976. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94977. {
  94978. /* no Darwin, do it the brute-force way */
  94979. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94980. info->data.ppc.altivec = 0;
  94981. info->data.ppc.ppc64 = 0;
  94982. signal (SIGILL, sigill_handler);
  94983. canjump = 0;
  94984. if (!sigsetjmp (jmpbuf, 1)) {
  94985. canjump = 1;
  94986. asm volatile (
  94987. "mtspr 256, %0\n\t"
  94988. "vand %%v0, %%v0, %%v0"
  94989. :
  94990. : "r" (-1)
  94991. );
  94992. info->data.ppc.altivec = 1;
  94993. }
  94994. canjump = 0;
  94995. if (!sigsetjmp (jmpbuf, 1)) {
  94996. int x = 0;
  94997. canjump = 1;
  94998. /* PPC64 hardware implements the cntlzd instruction */
  94999. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95000. info->data.ppc.ppc64 = 1;
  95001. }
  95002. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95003. }
  95004. # endif
  95005. # else /* !FLAC__USE_ALTIVEC */
  95006. info->data.ppc.altivec = 0;
  95007. info->data.ppc.ppc64 = 0;
  95008. # endif
  95009. # else
  95010. info->use_asm = false;
  95011. # endif
  95012. /*
  95013. * unknown CPI
  95014. */
  95015. #else
  95016. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95017. info->use_asm = false;
  95018. #endif
  95019. }
  95020. #endif
  95021. /*** End of inlined file: cpu.c ***/
  95022. /*** Start of inlined file: crc.c ***/
  95023. /*** Start of inlined file: juce_FlacHeader.h ***/
  95024. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95025. // tasks..
  95026. #define VERSION "1.2.1"
  95027. #define FLAC__NO_DLL 1
  95028. #if JUCE_MSVC
  95029. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95030. #endif
  95031. #if JUCE_MAC
  95032. #define FLAC__SYS_DARWIN 1
  95033. #endif
  95034. /*** End of inlined file: juce_FlacHeader.h ***/
  95035. #if JUCE_USE_FLAC
  95036. #if HAVE_CONFIG_H
  95037. # include <config.h>
  95038. #endif
  95039. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95040. FLAC__byte const FLAC__crc8_table[256] = {
  95041. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95042. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95043. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95044. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95045. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95046. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95047. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95048. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95049. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95050. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95051. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95052. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95053. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95054. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95055. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95056. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95057. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95058. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95059. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95060. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95061. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95062. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95063. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95064. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95065. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95066. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95067. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95068. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95069. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95070. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95071. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95072. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95073. };
  95074. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95075. unsigned FLAC__crc16_table[256] = {
  95076. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95077. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95078. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95079. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95080. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95081. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95082. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95083. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95084. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95085. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95086. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95087. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95088. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95089. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95090. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95091. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95092. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95093. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95094. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95095. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95096. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95097. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95098. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95099. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95100. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95101. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95102. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95103. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95104. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95105. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95106. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95107. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95108. };
  95109. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95110. {
  95111. *crc = FLAC__crc8_table[*crc ^ data];
  95112. }
  95113. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95114. {
  95115. while(len--)
  95116. *crc = FLAC__crc8_table[*crc ^ *data++];
  95117. }
  95118. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95119. {
  95120. FLAC__uint8 crc = 0;
  95121. while(len--)
  95122. crc = FLAC__crc8_table[crc ^ *data++];
  95123. return crc;
  95124. }
  95125. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95126. {
  95127. unsigned crc = 0;
  95128. while(len--)
  95129. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95130. return crc;
  95131. }
  95132. #endif
  95133. /*** End of inlined file: crc.c ***/
  95134. /*** Start of inlined file: fixed.c ***/
  95135. /*** Start of inlined file: juce_FlacHeader.h ***/
  95136. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95137. // tasks..
  95138. #define VERSION "1.2.1"
  95139. #define FLAC__NO_DLL 1
  95140. #if JUCE_MSVC
  95141. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95142. #endif
  95143. #if JUCE_MAC
  95144. #define FLAC__SYS_DARWIN 1
  95145. #endif
  95146. /*** End of inlined file: juce_FlacHeader.h ***/
  95147. #if JUCE_USE_FLAC
  95148. #if HAVE_CONFIG_H
  95149. # include <config.h>
  95150. #endif
  95151. #include <math.h>
  95152. #include <string.h>
  95153. /*** Start of inlined file: fixed.h ***/
  95154. #ifndef FLAC__PRIVATE__FIXED_H
  95155. #define FLAC__PRIVATE__FIXED_H
  95156. #ifdef HAVE_CONFIG_H
  95157. #include <config.h>
  95158. #endif
  95159. /*** Start of inlined file: float.h ***/
  95160. #ifndef FLAC__PRIVATE__FLOAT_H
  95161. #define FLAC__PRIVATE__FLOAT_H
  95162. #ifdef HAVE_CONFIG_H
  95163. #include <config.h>
  95164. #endif
  95165. /*
  95166. * These typedefs make it easier to ensure that integer versions of
  95167. * the library really only contain integer operations. All the code
  95168. * in libFLAC should use FLAC__float and FLAC__double in place of
  95169. * float and double, and be protected by checks of the macro
  95170. * FLAC__INTEGER_ONLY_LIBRARY.
  95171. *
  95172. * FLAC__real is the basic floating point type used in LPC analysis.
  95173. */
  95174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95175. typedef double FLAC__double;
  95176. typedef float FLAC__float;
  95177. /*
  95178. * WATCHOUT: changing FLAC__real will change the signatures of many
  95179. * functions that have assembly language equivalents and break them.
  95180. */
  95181. typedef float FLAC__real;
  95182. #else
  95183. /*
  95184. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95185. * for the integer part and lower 16 bits for the fractional part.
  95186. */
  95187. typedef FLAC__int32 FLAC__fixedpoint;
  95188. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95189. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95190. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95191. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95192. extern const FLAC__fixedpoint FLAC__FP_E;
  95193. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95194. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95195. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95196. /*
  95197. * FLAC__fixedpoint_log2()
  95198. * --------------------------------------------------------------------
  95199. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95200. * algorithm by Knuth for x >= 1.0
  95201. *
  95202. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95203. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95204. *
  95205. * 'precision' roughly limits the number of iterations that are done;
  95206. * use (unsigned)(-1) for maximum precision.
  95207. *
  95208. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95209. * function will punt and return 0.
  95210. *
  95211. * The return value will also have 'fracbits' fractional bits.
  95212. */
  95213. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95214. #endif
  95215. #endif
  95216. /*** End of inlined file: float.h ***/
  95217. /*** Start of inlined file: format.h ***/
  95218. #ifndef FLAC__PRIVATE__FORMAT_H
  95219. #define FLAC__PRIVATE__FORMAT_H
  95220. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95221. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95222. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95223. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95224. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95225. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95226. #endif
  95227. /*** End of inlined file: format.h ***/
  95228. /*
  95229. * FLAC__fixed_compute_best_predictor()
  95230. * --------------------------------------------------------------------
  95231. * Compute the best fixed predictor and the expected bits-per-sample
  95232. * of the residual signal for each order. The _wide() version uses
  95233. * 64-bit integers which is statistically necessary when bits-per-
  95234. * sample + log2(blocksize) > 30
  95235. *
  95236. * IN data[0,data_len-1]
  95237. * IN data_len
  95238. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95239. */
  95240. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95241. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95242. # ifndef FLAC__NO_ASM
  95243. # ifdef FLAC__CPU_IA32
  95244. # ifdef FLAC__HAS_NASM
  95245. 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]);
  95246. # endif
  95247. # endif
  95248. # endif
  95249. 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]);
  95250. #else
  95251. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95252. 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]);
  95253. #endif
  95254. /*
  95255. * FLAC__fixed_compute_residual()
  95256. * --------------------------------------------------------------------
  95257. * Compute the residual signal obtained from sutracting the predicted
  95258. * signal from the original.
  95259. *
  95260. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95261. * IN data_len length of original signal
  95262. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95263. * OUT residual[0,data_len-1] residual signal
  95264. */
  95265. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95266. /*
  95267. * FLAC__fixed_restore_signal()
  95268. * --------------------------------------------------------------------
  95269. * Restore the original signal by summing the residual and the
  95270. * predictor.
  95271. *
  95272. * IN residual[0,data_len-1] residual signal
  95273. * IN data_len length of original signal
  95274. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95275. * *** IMPORTANT: the caller must pass in the historical samples:
  95276. * IN data[-order,-1] previously-reconstructed historical samples
  95277. * OUT data[0,data_len-1] original signal
  95278. */
  95279. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95280. #endif
  95281. /*** End of inlined file: fixed.h ***/
  95282. #ifndef M_LN2
  95283. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95284. #define M_LN2 0.69314718055994530942
  95285. #endif
  95286. #ifdef min
  95287. #undef min
  95288. #endif
  95289. #define min(x,y) ((x) < (y)? (x) : (y))
  95290. #ifdef local_abs
  95291. #undef local_abs
  95292. #endif
  95293. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95294. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95295. /* rbps stands for residual bits per sample
  95296. *
  95297. * (ln(2) * err)
  95298. * rbps = log (-----------)
  95299. * 2 ( n )
  95300. */
  95301. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95302. {
  95303. FLAC__uint32 rbps;
  95304. unsigned bits; /* the number of bits required to represent a number */
  95305. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95306. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95307. FLAC__ASSERT(err > 0);
  95308. FLAC__ASSERT(n > 0);
  95309. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95310. if(err <= n)
  95311. return 0;
  95312. /*
  95313. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95314. * These allow us later to know we won't lose too much precision in the
  95315. * fixed-point division (err<<fracbits)/n.
  95316. */
  95317. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95318. err <<= fracbits;
  95319. err /= n;
  95320. /* err now holds err/n with fracbits fractional bits */
  95321. /*
  95322. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95323. * our purposes.
  95324. */
  95325. FLAC__ASSERT(err > 0);
  95326. bits = FLAC__bitmath_ilog2(err)+1;
  95327. if(bits > 16) {
  95328. err >>= (bits-16);
  95329. fracbits -= (bits-16);
  95330. }
  95331. rbps = (FLAC__uint32)err;
  95332. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95333. rbps *= FLAC__FP_LN2;
  95334. fracbits += 16;
  95335. FLAC__ASSERT(fracbits >= 0);
  95336. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95337. {
  95338. const int f = fracbits & 3;
  95339. if(f) {
  95340. rbps >>= f;
  95341. fracbits -= f;
  95342. }
  95343. }
  95344. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95345. if(rbps == 0)
  95346. return 0;
  95347. /*
  95348. * The return value must have 16 fractional bits. Since the whole part
  95349. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95350. * must be >= -3, these assertion allows us to be able to shift rbps
  95351. * left if necessary to get 16 fracbits without losing any bits of the
  95352. * whole part of rbps.
  95353. *
  95354. * There is a slight chance due to accumulated error that the whole part
  95355. * will require 6 bits, so we use 6 in the assertion. Really though as
  95356. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95357. */
  95358. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95359. FLAC__ASSERT(fracbits >= -3);
  95360. /* now shift the decimal point into place */
  95361. if(fracbits < 16)
  95362. return rbps << (16-fracbits);
  95363. else if(fracbits > 16)
  95364. return rbps >> (fracbits-16);
  95365. else
  95366. return rbps;
  95367. }
  95368. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95369. {
  95370. FLAC__uint32 rbps;
  95371. unsigned bits; /* the number of bits required to represent a number */
  95372. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95373. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95374. FLAC__ASSERT(err > 0);
  95375. FLAC__ASSERT(n > 0);
  95376. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95377. if(err <= n)
  95378. return 0;
  95379. /*
  95380. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95381. * These allow us later to know we won't lose too much precision in the
  95382. * fixed-point division (err<<fracbits)/n.
  95383. */
  95384. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95385. err <<= fracbits;
  95386. err /= n;
  95387. /* err now holds err/n with fracbits fractional bits */
  95388. /*
  95389. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95390. * our purposes.
  95391. */
  95392. FLAC__ASSERT(err > 0);
  95393. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95394. if(bits > 16) {
  95395. err >>= (bits-16);
  95396. fracbits -= (bits-16);
  95397. }
  95398. rbps = (FLAC__uint32)err;
  95399. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95400. rbps *= FLAC__FP_LN2;
  95401. fracbits += 16;
  95402. FLAC__ASSERT(fracbits >= 0);
  95403. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95404. {
  95405. const int f = fracbits & 3;
  95406. if(f) {
  95407. rbps >>= f;
  95408. fracbits -= f;
  95409. }
  95410. }
  95411. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95412. if(rbps == 0)
  95413. return 0;
  95414. /*
  95415. * The return value must have 16 fractional bits. Since the whole part
  95416. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95417. * must be >= -3, these assertion allows us to be able to shift rbps
  95418. * left if necessary to get 16 fracbits without losing any bits of the
  95419. * whole part of rbps.
  95420. *
  95421. * There is a slight chance due to accumulated error that the whole part
  95422. * will require 6 bits, so we use 6 in the assertion. Really though as
  95423. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95424. */
  95425. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95426. FLAC__ASSERT(fracbits >= -3);
  95427. /* now shift the decimal point into place */
  95428. if(fracbits < 16)
  95429. return rbps << (16-fracbits);
  95430. else if(fracbits > 16)
  95431. return rbps >> (fracbits-16);
  95432. else
  95433. return rbps;
  95434. }
  95435. #endif
  95436. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95437. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95438. #else
  95439. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95440. #endif
  95441. {
  95442. FLAC__int32 last_error_0 = data[-1];
  95443. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95444. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95445. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95446. FLAC__int32 error, save;
  95447. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95448. unsigned i, order;
  95449. for(i = 0; i < data_len; i++) {
  95450. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95451. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95452. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95453. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95454. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95455. }
  95456. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95457. order = 0;
  95458. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95459. order = 1;
  95460. else if(total_error_2 < min(total_error_3, total_error_4))
  95461. order = 2;
  95462. else if(total_error_3 < total_error_4)
  95463. order = 3;
  95464. else
  95465. order = 4;
  95466. /* Estimate the expected number of bits per residual signal sample. */
  95467. /* 'total_error*' is linearly related to the variance of the residual */
  95468. /* signal, so we use it directly to compute E(|x|) */
  95469. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95470. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95471. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95472. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95473. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95474. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95475. 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);
  95476. 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);
  95477. 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);
  95478. 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);
  95479. 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);
  95480. #else
  95481. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95482. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95483. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95484. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95485. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95486. #endif
  95487. return order;
  95488. }
  95489. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95490. 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])
  95491. #else
  95492. 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])
  95493. #endif
  95494. {
  95495. FLAC__int32 last_error_0 = data[-1];
  95496. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95497. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95498. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95499. FLAC__int32 error, save;
  95500. /* total_error_* are 64-bits to avoid overflow when encoding
  95501. * erratic signals when the bits-per-sample and blocksize are
  95502. * large.
  95503. */
  95504. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95505. unsigned i, order;
  95506. for(i = 0; i < data_len; i++) {
  95507. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95508. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95509. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95510. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95511. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95512. }
  95513. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95514. order = 0;
  95515. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95516. order = 1;
  95517. else if(total_error_2 < min(total_error_3, total_error_4))
  95518. order = 2;
  95519. else if(total_error_3 < total_error_4)
  95520. order = 3;
  95521. else
  95522. order = 4;
  95523. /* Estimate the expected number of bits per residual signal sample. */
  95524. /* 'total_error*' is linearly related to the variance of the residual */
  95525. /* signal, so we use it directly to compute E(|x|) */
  95526. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95527. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95528. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95529. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95530. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95531. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95532. #if defined _MSC_VER || defined __MINGW32__
  95533. /* with MSVC you have to spoon feed it the casting */
  95534. 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);
  95535. 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);
  95536. 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);
  95537. 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);
  95538. 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);
  95539. #else
  95540. 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);
  95541. 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);
  95542. 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);
  95543. 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);
  95544. 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);
  95545. #endif
  95546. #else
  95547. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95548. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95549. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95550. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95551. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95552. #endif
  95553. return order;
  95554. }
  95555. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95556. {
  95557. const int idata_len = (int)data_len;
  95558. int i;
  95559. switch(order) {
  95560. case 0:
  95561. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95562. memcpy(residual, data, sizeof(residual[0])*data_len);
  95563. break;
  95564. case 1:
  95565. for(i = 0; i < idata_len; i++)
  95566. residual[i] = data[i] - data[i-1];
  95567. break;
  95568. case 2:
  95569. for(i = 0; i < idata_len; i++)
  95570. #if 1 /* OPT: may be faster with some compilers on some systems */
  95571. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95572. #else
  95573. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95574. #endif
  95575. break;
  95576. case 3:
  95577. for(i = 0; i < idata_len; i++)
  95578. #if 1 /* OPT: may be faster with some compilers on some systems */
  95579. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95580. #else
  95581. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95582. #endif
  95583. break;
  95584. case 4:
  95585. for(i = 0; i < idata_len; i++)
  95586. #if 1 /* OPT: may be faster with some compilers on some systems */
  95587. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95588. #else
  95589. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95590. #endif
  95591. break;
  95592. default:
  95593. FLAC__ASSERT(0);
  95594. }
  95595. }
  95596. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95597. {
  95598. int i, idata_len = (int)data_len;
  95599. switch(order) {
  95600. case 0:
  95601. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95602. memcpy(data, residual, sizeof(residual[0])*data_len);
  95603. break;
  95604. case 1:
  95605. for(i = 0; i < idata_len; i++)
  95606. data[i] = residual[i] + data[i-1];
  95607. break;
  95608. case 2:
  95609. for(i = 0; i < idata_len; i++)
  95610. #if 1 /* OPT: may be faster with some compilers on some systems */
  95611. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95612. #else
  95613. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95614. #endif
  95615. break;
  95616. case 3:
  95617. for(i = 0; i < idata_len; i++)
  95618. #if 1 /* OPT: may be faster with some compilers on some systems */
  95619. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95620. #else
  95621. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95622. #endif
  95623. break;
  95624. case 4:
  95625. for(i = 0; i < idata_len; i++)
  95626. #if 1 /* OPT: may be faster with some compilers on some systems */
  95627. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95628. #else
  95629. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95630. #endif
  95631. break;
  95632. default:
  95633. FLAC__ASSERT(0);
  95634. }
  95635. }
  95636. #endif
  95637. /*** End of inlined file: fixed.c ***/
  95638. /*** Start of inlined file: float.c ***/
  95639. /*** Start of inlined file: juce_FlacHeader.h ***/
  95640. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95641. // tasks..
  95642. #define VERSION "1.2.1"
  95643. #define FLAC__NO_DLL 1
  95644. #if JUCE_MSVC
  95645. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95646. #endif
  95647. #if JUCE_MAC
  95648. #define FLAC__SYS_DARWIN 1
  95649. #endif
  95650. /*** End of inlined file: juce_FlacHeader.h ***/
  95651. #if JUCE_USE_FLAC
  95652. #if HAVE_CONFIG_H
  95653. # include <config.h>
  95654. #endif
  95655. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95656. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95657. #ifdef _MSC_VER
  95658. #define FLAC__U64L(x) x
  95659. #else
  95660. #define FLAC__U64L(x) x##LLU
  95661. #endif
  95662. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95663. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95664. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95665. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95666. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95667. /* Lookup tables for Knuth's logarithm algorithm */
  95668. #define LOG2_LOOKUP_PRECISION 16
  95669. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95670. {
  95671. /*
  95672. * 0 fraction bits
  95673. */
  95674. /* undefined */ 0x00000000,
  95675. /* lg(2/1) = */ 0x00000001,
  95676. /* lg(4/3) = */ 0x00000000,
  95677. /* lg(8/7) = */ 0x00000000,
  95678. /* lg(16/15) = */ 0x00000000,
  95679. /* lg(32/31) = */ 0x00000000,
  95680. /* lg(64/63) = */ 0x00000000,
  95681. /* lg(128/127) = */ 0x00000000,
  95682. /* lg(256/255) = */ 0x00000000,
  95683. /* lg(512/511) = */ 0x00000000,
  95684. /* lg(1024/1023) = */ 0x00000000,
  95685. /* lg(2048/2047) = */ 0x00000000,
  95686. /* lg(4096/4095) = */ 0x00000000,
  95687. /* lg(8192/8191) = */ 0x00000000,
  95688. /* lg(16384/16383) = */ 0x00000000,
  95689. /* lg(32768/32767) = */ 0x00000000
  95690. },
  95691. {
  95692. /*
  95693. * 4 fraction bits
  95694. */
  95695. /* undefined */ 0x00000000,
  95696. /* lg(2/1) = */ 0x00000010,
  95697. /* lg(4/3) = */ 0x00000007,
  95698. /* lg(8/7) = */ 0x00000003,
  95699. /* lg(16/15) = */ 0x00000001,
  95700. /* lg(32/31) = */ 0x00000001,
  95701. /* lg(64/63) = */ 0x00000000,
  95702. /* lg(128/127) = */ 0x00000000,
  95703. /* lg(256/255) = */ 0x00000000,
  95704. /* lg(512/511) = */ 0x00000000,
  95705. /* lg(1024/1023) = */ 0x00000000,
  95706. /* lg(2048/2047) = */ 0x00000000,
  95707. /* lg(4096/4095) = */ 0x00000000,
  95708. /* lg(8192/8191) = */ 0x00000000,
  95709. /* lg(16384/16383) = */ 0x00000000,
  95710. /* lg(32768/32767) = */ 0x00000000
  95711. },
  95712. {
  95713. /*
  95714. * 8 fraction bits
  95715. */
  95716. /* undefined */ 0x00000000,
  95717. /* lg(2/1) = */ 0x00000100,
  95718. /* lg(4/3) = */ 0x0000006a,
  95719. /* lg(8/7) = */ 0x00000031,
  95720. /* lg(16/15) = */ 0x00000018,
  95721. /* lg(32/31) = */ 0x0000000c,
  95722. /* lg(64/63) = */ 0x00000006,
  95723. /* lg(128/127) = */ 0x00000003,
  95724. /* lg(256/255) = */ 0x00000001,
  95725. /* lg(512/511) = */ 0x00000001,
  95726. /* lg(1024/1023) = */ 0x00000000,
  95727. /* lg(2048/2047) = */ 0x00000000,
  95728. /* lg(4096/4095) = */ 0x00000000,
  95729. /* lg(8192/8191) = */ 0x00000000,
  95730. /* lg(16384/16383) = */ 0x00000000,
  95731. /* lg(32768/32767) = */ 0x00000000
  95732. },
  95733. {
  95734. /*
  95735. * 12 fraction bits
  95736. */
  95737. /* undefined */ 0x00000000,
  95738. /* lg(2/1) = */ 0x00001000,
  95739. /* lg(4/3) = */ 0x000006a4,
  95740. /* lg(8/7) = */ 0x00000315,
  95741. /* lg(16/15) = */ 0x0000017d,
  95742. /* lg(32/31) = */ 0x000000bc,
  95743. /* lg(64/63) = */ 0x0000005d,
  95744. /* lg(128/127) = */ 0x0000002e,
  95745. /* lg(256/255) = */ 0x00000017,
  95746. /* lg(512/511) = */ 0x0000000c,
  95747. /* lg(1024/1023) = */ 0x00000006,
  95748. /* lg(2048/2047) = */ 0x00000003,
  95749. /* lg(4096/4095) = */ 0x00000001,
  95750. /* lg(8192/8191) = */ 0x00000001,
  95751. /* lg(16384/16383) = */ 0x00000000,
  95752. /* lg(32768/32767) = */ 0x00000000
  95753. },
  95754. {
  95755. /*
  95756. * 16 fraction bits
  95757. */
  95758. /* undefined */ 0x00000000,
  95759. /* lg(2/1) = */ 0x00010000,
  95760. /* lg(4/3) = */ 0x00006a40,
  95761. /* lg(8/7) = */ 0x00003151,
  95762. /* lg(16/15) = */ 0x000017d6,
  95763. /* lg(32/31) = */ 0x00000bba,
  95764. /* lg(64/63) = */ 0x000005d1,
  95765. /* lg(128/127) = */ 0x000002e6,
  95766. /* lg(256/255) = */ 0x00000172,
  95767. /* lg(512/511) = */ 0x000000b9,
  95768. /* lg(1024/1023) = */ 0x0000005c,
  95769. /* lg(2048/2047) = */ 0x0000002e,
  95770. /* lg(4096/4095) = */ 0x00000017,
  95771. /* lg(8192/8191) = */ 0x0000000c,
  95772. /* lg(16384/16383) = */ 0x00000006,
  95773. /* lg(32768/32767) = */ 0x00000003
  95774. },
  95775. {
  95776. /*
  95777. * 20 fraction bits
  95778. */
  95779. /* undefined */ 0x00000000,
  95780. /* lg(2/1) = */ 0x00100000,
  95781. /* lg(4/3) = */ 0x0006a3fe,
  95782. /* lg(8/7) = */ 0x00031513,
  95783. /* lg(16/15) = */ 0x00017d60,
  95784. /* lg(32/31) = */ 0x0000bb9d,
  95785. /* lg(64/63) = */ 0x00005d10,
  95786. /* lg(128/127) = */ 0x00002e59,
  95787. /* lg(256/255) = */ 0x00001721,
  95788. /* lg(512/511) = */ 0x00000b8e,
  95789. /* lg(1024/1023) = */ 0x000005c6,
  95790. /* lg(2048/2047) = */ 0x000002e3,
  95791. /* lg(4096/4095) = */ 0x00000171,
  95792. /* lg(8192/8191) = */ 0x000000b9,
  95793. /* lg(16384/16383) = */ 0x0000005c,
  95794. /* lg(32768/32767) = */ 0x0000002e
  95795. },
  95796. {
  95797. /*
  95798. * 24 fraction bits
  95799. */
  95800. /* undefined */ 0x00000000,
  95801. /* lg(2/1) = */ 0x01000000,
  95802. /* lg(4/3) = */ 0x006a3fe6,
  95803. /* lg(8/7) = */ 0x00315130,
  95804. /* lg(16/15) = */ 0x0017d605,
  95805. /* lg(32/31) = */ 0x000bb9ca,
  95806. /* lg(64/63) = */ 0x0005d0fc,
  95807. /* lg(128/127) = */ 0x0002e58f,
  95808. /* lg(256/255) = */ 0x0001720e,
  95809. /* lg(512/511) = */ 0x0000b8d8,
  95810. /* lg(1024/1023) = */ 0x00005c61,
  95811. /* lg(2048/2047) = */ 0x00002e2d,
  95812. /* lg(4096/4095) = */ 0x00001716,
  95813. /* lg(8192/8191) = */ 0x00000b8b,
  95814. /* lg(16384/16383) = */ 0x000005c5,
  95815. /* lg(32768/32767) = */ 0x000002e3
  95816. },
  95817. {
  95818. /*
  95819. * 28 fraction bits
  95820. */
  95821. /* undefined */ 0x00000000,
  95822. /* lg(2/1) = */ 0x10000000,
  95823. /* lg(4/3) = */ 0x06a3fe5c,
  95824. /* lg(8/7) = */ 0x03151301,
  95825. /* lg(16/15) = */ 0x017d6049,
  95826. /* lg(32/31) = */ 0x00bb9ca6,
  95827. /* lg(64/63) = */ 0x005d0fba,
  95828. /* lg(128/127) = */ 0x002e58f7,
  95829. /* lg(256/255) = */ 0x001720da,
  95830. /* lg(512/511) = */ 0x000b8d87,
  95831. /* lg(1024/1023) = */ 0x0005c60b,
  95832. /* lg(2048/2047) = */ 0x0002e2d7,
  95833. /* lg(4096/4095) = */ 0x00017160,
  95834. /* lg(8192/8191) = */ 0x0000b8ad,
  95835. /* lg(16384/16383) = */ 0x00005c56,
  95836. /* lg(32768/32767) = */ 0x00002e2b
  95837. }
  95838. };
  95839. #if 0
  95840. static const FLAC__uint64 log2_lookup_wide[] = {
  95841. {
  95842. /*
  95843. * 32 fraction bits
  95844. */
  95845. /* undefined */ 0x00000000,
  95846. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95847. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95848. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95849. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95850. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95851. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95852. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95853. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95854. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95855. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95856. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95857. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95858. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95859. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95860. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95861. },
  95862. {
  95863. /*
  95864. * 48 fraction bits
  95865. */
  95866. /* undefined */ 0x00000000,
  95867. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95868. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95869. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95870. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95871. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95872. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95873. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95874. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95875. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95876. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95877. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95878. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95879. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95880. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95881. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95882. }
  95883. };
  95884. #endif
  95885. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95886. {
  95887. const FLAC__uint32 ONE = (1u << fracbits);
  95888. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95889. FLAC__ASSERT(fracbits < 32);
  95890. FLAC__ASSERT((fracbits & 0x3) == 0);
  95891. if(x < ONE)
  95892. return 0;
  95893. if(precision > LOG2_LOOKUP_PRECISION)
  95894. precision = LOG2_LOOKUP_PRECISION;
  95895. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95896. {
  95897. FLAC__uint32 y = 0;
  95898. FLAC__uint32 z = x >> 1, k = 1;
  95899. while (x > ONE && k < precision) {
  95900. if (x - z >= ONE) {
  95901. x -= z;
  95902. z = x >> k;
  95903. y += table[k];
  95904. }
  95905. else {
  95906. z >>= 1;
  95907. k++;
  95908. }
  95909. }
  95910. return y;
  95911. }
  95912. }
  95913. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95914. #endif
  95915. /*** End of inlined file: float.c ***/
  95916. /*** Start of inlined file: format.c ***/
  95917. /*** Start of inlined file: juce_FlacHeader.h ***/
  95918. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95919. // tasks..
  95920. #define VERSION "1.2.1"
  95921. #define FLAC__NO_DLL 1
  95922. #if JUCE_MSVC
  95923. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95924. #endif
  95925. #if JUCE_MAC
  95926. #define FLAC__SYS_DARWIN 1
  95927. #endif
  95928. /*** End of inlined file: juce_FlacHeader.h ***/
  95929. #if JUCE_USE_FLAC
  95930. #if HAVE_CONFIG_H
  95931. # include <config.h>
  95932. #endif
  95933. #include <stdio.h>
  95934. #include <stdlib.h> /* for qsort() */
  95935. #include <string.h> /* for memset() */
  95936. #ifndef FLaC__INLINE
  95937. #define FLaC__INLINE
  95938. #endif
  95939. #ifdef min
  95940. #undef min
  95941. #endif
  95942. #define min(a,b) ((a)<(b)?(a):(b))
  95943. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95944. #ifdef _MSC_VER
  95945. #define FLAC__U64L(x) x
  95946. #else
  95947. #define FLAC__U64L(x) x##LLU
  95948. #endif
  95949. /* VERSION should come from configure */
  95950. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95951. ;
  95952. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95953. /* yet one more hack because of MSVC6: */
  95954. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95955. #else
  95956. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95957. #endif
  95958. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95959. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95960. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95961. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95962. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95963. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95964. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95965. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95966. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95967. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95968. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95969. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95970. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95971. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95972. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95973. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95974. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95975. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95976. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95977. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95978. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95979. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95980. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95981. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95982. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95983. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95984. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95985. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95986. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95987. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95988. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95989. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95990. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95991. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95992. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95993. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95994. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95995. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95996. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95997. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95998. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95999. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96000. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96001. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96002. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96003. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96004. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96005. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96006. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96007. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96008. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96009. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96010. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96011. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96012. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96013. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96014. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96015. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96016. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96017. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96018. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96019. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96020. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96021. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96022. "PARTITIONED_RICE",
  96023. "PARTITIONED_RICE2"
  96024. };
  96025. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96026. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96027. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96028. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96029. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96030. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96031. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96032. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96033. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96034. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96035. "CONSTANT",
  96036. "VERBATIM",
  96037. "FIXED",
  96038. "LPC"
  96039. };
  96040. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96041. "INDEPENDENT",
  96042. "LEFT_SIDE",
  96043. "RIGHT_SIDE",
  96044. "MID_SIDE"
  96045. };
  96046. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96047. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96048. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96049. };
  96050. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96051. "STREAMINFO",
  96052. "PADDING",
  96053. "APPLICATION",
  96054. "SEEKTABLE",
  96055. "VORBIS_COMMENT",
  96056. "CUESHEET",
  96057. "PICTURE"
  96058. };
  96059. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96060. "Other",
  96061. "32x32 pixels 'file icon' (PNG only)",
  96062. "Other file icon",
  96063. "Cover (front)",
  96064. "Cover (back)",
  96065. "Leaflet page",
  96066. "Media (e.g. label side of CD)",
  96067. "Lead artist/lead performer/soloist",
  96068. "Artist/performer",
  96069. "Conductor",
  96070. "Band/Orchestra",
  96071. "Composer",
  96072. "Lyricist/text writer",
  96073. "Recording Location",
  96074. "During recording",
  96075. "During performance",
  96076. "Movie/video screen capture",
  96077. "A bright coloured fish",
  96078. "Illustration",
  96079. "Band/artist logotype",
  96080. "Publisher/Studio logotype"
  96081. };
  96082. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96083. {
  96084. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96085. return false;
  96086. }
  96087. else
  96088. return true;
  96089. }
  96090. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96091. {
  96092. if(
  96093. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96094. (
  96095. sample_rate >= (1u << 16) &&
  96096. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96097. )
  96098. ) {
  96099. return false;
  96100. }
  96101. else
  96102. return true;
  96103. }
  96104. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96105. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96106. {
  96107. unsigned i;
  96108. FLAC__uint64 prev_sample_number = 0;
  96109. FLAC__bool got_prev = false;
  96110. FLAC__ASSERT(0 != seek_table);
  96111. for(i = 0; i < seek_table->num_points; i++) {
  96112. if(got_prev) {
  96113. if(
  96114. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96115. seek_table->points[i].sample_number <= prev_sample_number
  96116. )
  96117. return false;
  96118. }
  96119. prev_sample_number = seek_table->points[i].sample_number;
  96120. got_prev = true;
  96121. }
  96122. return true;
  96123. }
  96124. /* used as the sort predicate for qsort() */
  96125. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96126. {
  96127. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96128. if(l->sample_number == r->sample_number)
  96129. return 0;
  96130. else if(l->sample_number < r->sample_number)
  96131. return -1;
  96132. else
  96133. return 1;
  96134. }
  96135. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96136. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96137. {
  96138. unsigned i, j;
  96139. FLAC__bool first;
  96140. FLAC__ASSERT(0 != seek_table);
  96141. /* sort the seekpoints */
  96142. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96143. /* uniquify the seekpoints */
  96144. first = true;
  96145. for(i = j = 0; i < seek_table->num_points; i++) {
  96146. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96147. if(!first) {
  96148. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96149. continue;
  96150. }
  96151. }
  96152. first = false;
  96153. seek_table->points[j++] = seek_table->points[i];
  96154. }
  96155. for(i = j; i < seek_table->num_points; i++) {
  96156. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96157. seek_table->points[i].stream_offset = 0;
  96158. seek_table->points[i].frame_samples = 0;
  96159. }
  96160. return j;
  96161. }
  96162. /*
  96163. * also disallows non-shortest-form encodings, c.f.
  96164. * http://www.unicode.org/versions/corrigendum1.html
  96165. * and a more clear explanation at the end of this section:
  96166. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96167. */
  96168. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96169. {
  96170. FLAC__ASSERT(0 != utf8);
  96171. if ((utf8[0] & 0x80) == 0) {
  96172. return 1;
  96173. }
  96174. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96175. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96176. return 0;
  96177. return 2;
  96178. }
  96179. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96180. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96181. return 0;
  96182. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96183. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96184. return 0;
  96185. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96186. return 0;
  96187. return 3;
  96188. }
  96189. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96190. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96191. return 0;
  96192. return 4;
  96193. }
  96194. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96195. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96196. return 0;
  96197. return 5;
  96198. }
  96199. 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) {
  96200. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96201. return 0;
  96202. return 6;
  96203. }
  96204. else {
  96205. return 0;
  96206. }
  96207. }
  96208. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96209. {
  96210. char c;
  96211. for(c = *name; c; c = *(++name))
  96212. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96213. return false;
  96214. return true;
  96215. }
  96216. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96217. {
  96218. if(length == (unsigned)(-1)) {
  96219. while(*value) {
  96220. unsigned n = utf8len_(value);
  96221. if(n == 0)
  96222. return false;
  96223. value += n;
  96224. }
  96225. }
  96226. else {
  96227. const FLAC__byte *end = value + length;
  96228. while(value < end) {
  96229. unsigned n = utf8len_(value);
  96230. if(n == 0)
  96231. return false;
  96232. value += n;
  96233. }
  96234. if(value != end)
  96235. return false;
  96236. }
  96237. return true;
  96238. }
  96239. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96240. {
  96241. const FLAC__byte *s, *end;
  96242. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96243. if(*s < 0x20 || *s > 0x7D)
  96244. return false;
  96245. }
  96246. if(s == end)
  96247. return false;
  96248. s++; /* skip '=' */
  96249. while(s < end) {
  96250. unsigned n = utf8len_(s);
  96251. if(n == 0)
  96252. return false;
  96253. s += n;
  96254. }
  96255. if(s != end)
  96256. return false;
  96257. return true;
  96258. }
  96259. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96260. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96261. {
  96262. unsigned i, j;
  96263. if(check_cd_da_subset) {
  96264. if(cue_sheet->lead_in < 2 * 44100) {
  96265. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96266. return false;
  96267. }
  96268. if(cue_sheet->lead_in % 588 != 0) {
  96269. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96270. return false;
  96271. }
  96272. }
  96273. if(cue_sheet->num_tracks == 0) {
  96274. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96275. return false;
  96276. }
  96277. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96278. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96279. return false;
  96280. }
  96281. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96282. if(cue_sheet->tracks[i].number == 0) {
  96283. if(violation) *violation = "cue sheet may not have a track number 0";
  96284. return false;
  96285. }
  96286. if(check_cd_da_subset) {
  96287. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96288. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96289. return false;
  96290. }
  96291. }
  96292. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96293. if(violation) {
  96294. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96295. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96296. else
  96297. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96298. }
  96299. return false;
  96300. }
  96301. if(i < cue_sheet->num_tracks - 1) {
  96302. if(cue_sheet->tracks[i].num_indices == 0) {
  96303. if(violation) *violation = "cue sheet track must have at least one index point";
  96304. return false;
  96305. }
  96306. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96307. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96308. return false;
  96309. }
  96310. }
  96311. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96312. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96313. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96314. return false;
  96315. }
  96316. if(j > 0) {
  96317. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96318. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96319. return false;
  96320. }
  96321. }
  96322. }
  96323. }
  96324. return true;
  96325. }
  96326. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96327. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96328. {
  96329. char *p;
  96330. FLAC__byte *b;
  96331. for(p = picture->mime_type; *p; p++) {
  96332. if(*p < 0x20 || *p > 0x7e) {
  96333. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96334. return false;
  96335. }
  96336. }
  96337. for(b = picture->description; *b; ) {
  96338. unsigned n = utf8len_(b);
  96339. if(n == 0) {
  96340. if(violation) *violation = "description string must be valid UTF-8";
  96341. return false;
  96342. }
  96343. b += n;
  96344. }
  96345. return true;
  96346. }
  96347. /*
  96348. * These routines are private to libFLAC
  96349. */
  96350. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96351. {
  96352. return
  96353. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96354. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96355. blocksize,
  96356. predictor_order
  96357. );
  96358. }
  96359. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96360. {
  96361. unsigned max_rice_partition_order = 0;
  96362. while(!(blocksize & 1)) {
  96363. max_rice_partition_order++;
  96364. blocksize >>= 1;
  96365. }
  96366. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96367. }
  96368. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96369. {
  96370. unsigned max_rice_partition_order = limit;
  96371. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96372. max_rice_partition_order--;
  96373. FLAC__ASSERT(
  96374. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96375. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96376. );
  96377. return max_rice_partition_order;
  96378. }
  96379. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96380. {
  96381. FLAC__ASSERT(0 != object);
  96382. object->parameters = 0;
  96383. object->raw_bits = 0;
  96384. object->capacity_by_order = 0;
  96385. }
  96386. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96387. {
  96388. FLAC__ASSERT(0 != object);
  96389. if(0 != object->parameters)
  96390. free(object->parameters);
  96391. if(0 != object->raw_bits)
  96392. free(object->raw_bits);
  96393. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96394. }
  96395. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96396. {
  96397. FLAC__ASSERT(0 != object);
  96398. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96399. if(object->capacity_by_order < max_partition_order) {
  96400. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96401. return false;
  96402. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96403. return false;
  96404. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96405. object->capacity_by_order = max_partition_order;
  96406. }
  96407. return true;
  96408. }
  96409. #endif
  96410. /*** End of inlined file: format.c ***/
  96411. /*** Start of inlined file: lpc_flac.c ***/
  96412. /*** Start of inlined file: juce_FlacHeader.h ***/
  96413. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96414. // tasks..
  96415. #define VERSION "1.2.1"
  96416. #define FLAC__NO_DLL 1
  96417. #if JUCE_MSVC
  96418. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96419. #endif
  96420. #if JUCE_MAC
  96421. #define FLAC__SYS_DARWIN 1
  96422. #endif
  96423. /*** End of inlined file: juce_FlacHeader.h ***/
  96424. #if JUCE_USE_FLAC
  96425. #if HAVE_CONFIG_H
  96426. # include <config.h>
  96427. #endif
  96428. #include <math.h>
  96429. /*** Start of inlined file: lpc.h ***/
  96430. #ifndef FLAC__PRIVATE__LPC_H
  96431. #define FLAC__PRIVATE__LPC_H
  96432. #ifdef HAVE_CONFIG_H
  96433. #include <config.h>
  96434. #endif
  96435. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96436. /*
  96437. * FLAC__lpc_window_data()
  96438. * --------------------------------------------------------------------
  96439. * Applies the given window to the data.
  96440. * OPT: asm implementation
  96441. *
  96442. * IN in[0,data_len-1]
  96443. * IN window[0,data_len-1]
  96444. * OUT out[0,lag-1]
  96445. * IN data_len
  96446. */
  96447. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96448. /*
  96449. * FLAC__lpc_compute_autocorrelation()
  96450. * --------------------------------------------------------------------
  96451. * Compute the autocorrelation for lags between 0 and lag-1.
  96452. * Assumes data[] outside of [0,data_len-1] == 0.
  96453. * Asserts that lag > 0.
  96454. *
  96455. * IN data[0,data_len-1]
  96456. * IN data_len
  96457. * IN 0 < lag <= data_len
  96458. * OUT autoc[0,lag-1]
  96459. */
  96460. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96461. #ifndef FLAC__NO_ASM
  96462. # ifdef FLAC__CPU_IA32
  96463. # ifdef FLAC__HAS_NASM
  96464. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96465. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96466. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96467. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96468. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96469. # endif
  96470. # endif
  96471. #endif
  96472. /*
  96473. * FLAC__lpc_compute_lp_coefficients()
  96474. * --------------------------------------------------------------------
  96475. * Computes LP coefficients for orders 1..max_order.
  96476. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96477. * and there is no point in calculating a predictor.
  96478. *
  96479. * IN autoc[0,max_order] autocorrelation values
  96480. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96481. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96482. * *** IMPORTANT:
  96483. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96484. * OUT error[0,max_order-1] error for each order (more
  96485. * specifically, the variance of
  96486. * the error signal times # of
  96487. * samples in the signal)
  96488. *
  96489. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96490. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96491. * in lp_coeff[7][0,7], etc.
  96492. */
  96493. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96494. /*
  96495. * FLAC__lpc_quantize_coefficients()
  96496. * --------------------------------------------------------------------
  96497. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96498. * must be less than 32 (sizeof(FLAC__int32)*8).
  96499. *
  96500. * IN lp_coeff[0,order-1] LP coefficients
  96501. * IN order LP order
  96502. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96503. * desired precision (in bits, including sign
  96504. * bit) of largest coefficient
  96505. * OUT qlp_coeff[0,order-1] quantized coefficients
  96506. * OUT shift # of bits to shift right to get approximated
  96507. * LP coefficients. NOTE: could be negative.
  96508. * RETURN 0 => quantization OK
  96509. * 1 => coefficients require too much shifting for *shift to
  96510. * fit in the LPC subframe header. 'shift' is unset.
  96511. * 2 => coefficients are all zero, which is bad. 'shift' is
  96512. * unset.
  96513. */
  96514. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96515. /*
  96516. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96517. * --------------------------------------------------------------------
  96518. * Compute the residual signal obtained from sutracting the predicted
  96519. * signal from the original.
  96520. *
  96521. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96522. * IN data_len length of original signal
  96523. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96524. * IN order > 0 LP order
  96525. * IN lp_quantization quantization of LP coefficients in bits
  96526. * OUT residual[0,data_len-1] residual signal
  96527. */
  96528. 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[]);
  96529. 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[]);
  96530. #ifndef FLAC__NO_ASM
  96531. # ifdef FLAC__CPU_IA32
  96532. # ifdef FLAC__HAS_NASM
  96533. 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[]);
  96534. 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[]);
  96535. # endif
  96536. # endif
  96537. #endif
  96538. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96539. /*
  96540. * FLAC__lpc_restore_signal()
  96541. * --------------------------------------------------------------------
  96542. * Restore the original signal by summing the residual and the
  96543. * predictor.
  96544. *
  96545. * IN residual[0,data_len-1] residual signal
  96546. * IN data_len length of original signal
  96547. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96548. * IN order > 0 LP order
  96549. * IN lp_quantization quantization of LP coefficients in bits
  96550. * *** IMPORTANT: the caller must pass in the historical samples:
  96551. * IN data[-order,-1] previously-reconstructed historical samples
  96552. * OUT data[0,data_len-1] original signal
  96553. */
  96554. 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[]);
  96555. 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[]);
  96556. #ifndef FLAC__NO_ASM
  96557. # ifdef FLAC__CPU_IA32
  96558. # ifdef FLAC__HAS_NASM
  96559. 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[]);
  96560. 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[]);
  96561. # endif /* FLAC__HAS_NASM */
  96562. # elif defined FLAC__CPU_PPC
  96563. 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[]);
  96564. 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[]);
  96565. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96566. #endif /* FLAC__NO_ASM */
  96567. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96568. /*
  96569. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96570. * --------------------------------------------------------------------
  96571. * Compute the expected number of bits per residual signal sample
  96572. * based on the LP error (which is related to the residual variance).
  96573. *
  96574. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96575. * IN total_samples > 0 # of samples in residual signal
  96576. * RETURN expected bits per sample
  96577. */
  96578. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96579. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96580. /*
  96581. * FLAC__lpc_compute_best_order()
  96582. * --------------------------------------------------------------------
  96583. * Compute the best order from the array of signal errors returned
  96584. * during coefficient computation.
  96585. *
  96586. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96587. * IN max_order > 0 max LP order
  96588. * IN total_samples > 0 # of samples in residual signal
  96589. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96590. * (includes warmup sample size and quantized LP coefficient)
  96591. * RETURN [1,max_order] best order
  96592. */
  96593. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96594. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96595. #endif
  96596. /*** End of inlined file: lpc.h ***/
  96597. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96598. #include <stdio.h>
  96599. #endif
  96600. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96601. #ifndef M_LN2
  96602. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96603. #define M_LN2 0.69314718055994530942
  96604. #endif
  96605. /* OPT: #undef'ing this may improve the speed on some architectures */
  96606. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96607. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96608. {
  96609. unsigned i;
  96610. for(i = 0; i < data_len; i++)
  96611. out[i] = in[i] * window[i];
  96612. }
  96613. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96614. {
  96615. /* a readable, but slower, version */
  96616. #if 0
  96617. FLAC__real d;
  96618. unsigned i;
  96619. FLAC__ASSERT(lag > 0);
  96620. FLAC__ASSERT(lag <= data_len);
  96621. /*
  96622. * Technically we should subtract the mean first like so:
  96623. * for(i = 0; i < data_len; i++)
  96624. * data[i] -= mean;
  96625. * but it appears not to make enough of a difference to matter, and
  96626. * most signals are already closely centered around zero
  96627. */
  96628. while(lag--) {
  96629. for(i = lag, d = 0.0; i < data_len; i++)
  96630. d += data[i] * data[i - lag];
  96631. autoc[lag] = d;
  96632. }
  96633. #endif
  96634. /*
  96635. * this version tends to run faster because of better data locality
  96636. * ('data_len' is usually much larger than 'lag')
  96637. */
  96638. FLAC__real d;
  96639. unsigned sample, coeff;
  96640. const unsigned limit = data_len - lag;
  96641. FLAC__ASSERT(lag > 0);
  96642. FLAC__ASSERT(lag <= data_len);
  96643. for(coeff = 0; coeff < lag; coeff++)
  96644. autoc[coeff] = 0.0;
  96645. for(sample = 0; sample <= limit; sample++) {
  96646. d = data[sample];
  96647. for(coeff = 0; coeff < lag; coeff++)
  96648. autoc[coeff] += d * data[sample+coeff];
  96649. }
  96650. for(; sample < data_len; sample++) {
  96651. d = data[sample];
  96652. for(coeff = 0; coeff < data_len - sample; coeff++)
  96653. autoc[coeff] += d * data[sample+coeff];
  96654. }
  96655. }
  96656. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96657. {
  96658. unsigned i, j;
  96659. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96660. FLAC__ASSERT(0 != max_order);
  96661. FLAC__ASSERT(0 < *max_order);
  96662. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96663. FLAC__ASSERT(autoc[0] != 0.0);
  96664. err = autoc[0];
  96665. for(i = 0; i < *max_order; i++) {
  96666. /* Sum up this iteration's reflection coefficient. */
  96667. r = -autoc[i+1];
  96668. for(j = 0; j < i; j++)
  96669. r -= lpc[j] * autoc[i-j];
  96670. ref[i] = (r/=err);
  96671. /* Update LPC coefficients and total error. */
  96672. lpc[i]=r;
  96673. for(j = 0; j < (i>>1); j++) {
  96674. FLAC__double tmp = lpc[j];
  96675. lpc[j] += r * lpc[i-1-j];
  96676. lpc[i-1-j] += r * tmp;
  96677. }
  96678. if(i & 1)
  96679. lpc[j] += lpc[j] * r;
  96680. err *= (1.0 - r * r);
  96681. /* save this order */
  96682. for(j = 0; j <= i; j++)
  96683. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96684. error[i] = err;
  96685. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96686. if(err == 0.0) {
  96687. *max_order = i+1;
  96688. return;
  96689. }
  96690. }
  96691. }
  96692. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96693. {
  96694. unsigned i;
  96695. FLAC__double cmax;
  96696. FLAC__int32 qmax, qmin;
  96697. FLAC__ASSERT(precision > 0);
  96698. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96699. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96700. precision--;
  96701. qmax = 1 << precision;
  96702. qmin = -qmax;
  96703. qmax--;
  96704. /* calc cmax = max( |lp_coeff[i]| ) */
  96705. cmax = 0.0;
  96706. for(i = 0; i < order; i++) {
  96707. const FLAC__double d = fabs(lp_coeff[i]);
  96708. if(d > cmax)
  96709. cmax = d;
  96710. }
  96711. if(cmax <= 0.0) {
  96712. /* => coefficients are all 0, which means our constant-detect didn't work */
  96713. return 2;
  96714. }
  96715. else {
  96716. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96717. const int min_shiftlimit = -max_shiftlimit - 1;
  96718. int log2cmax;
  96719. (void)frexp(cmax, &log2cmax);
  96720. log2cmax--;
  96721. *shift = (int)precision - log2cmax - 1;
  96722. if(*shift > max_shiftlimit)
  96723. *shift = max_shiftlimit;
  96724. else if(*shift < min_shiftlimit)
  96725. return 1;
  96726. }
  96727. if(*shift >= 0) {
  96728. FLAC__double error = 0.0;
  96729. FLAC__int32 q;
  96730. for(i = 0; i < order; i++) {
  96731. error += lp_coeff[i] * (1 << *shift);
  96732. #if 1 /* unfortunately lround() is C99 */
  96733. if(error >= 0.0)
  96734. q = (FLAC__int32)(error + 0.5);
  96735. else
  96736. q = (FLAC__int32)(error - 0.5);
  96737. #else
  96738. q = lround(error);
  96739. #endif
  96740. #ifdef FLAC__OVERFLOW_DETECT
  96741. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96742. 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]);
  96743. else if(q < qmin)
  96744. 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]);
  96745. #endif
  96746. if(q > qmax)
  96747. q = qmax;
  96748. else if(q < qmin)
  96749. q = qmin;
  96750. error -= q;
  96751. qlp_coeff[i] = q;
  96752. }
  96753. }
  96754. /* negative shift is very rare but due to design flaw, negative shift is
  96755. * a NOP in the decoder, so it must be handled specially by scaling down
  96756. * coeffs
  96757. */
  96758. else {
  96759. const int nshift = -(*shift);
  96760. FLAC__double error = 0.0;
  96761. FLAC__int32 q;
  96762. #ifdef DEBUG
  96763. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96764. #endif
  96765. for(i = 0; i < order; i++) {
  96766. error += lp_coeff[i] / (1 << nshift);
  96767. #if 1 /* unfortunately lround() is C99 */
  96768. if(error >= 0.0)
  96769. q = (FLAC__int32)(error + 0.5);
  96770. else
  96771. q = (FLAC__int32)(error - 0.5);
  96772. #else
  96773. q = lround(error);
  96774. #endif
  96775. #ifdef FLAC__OVERFLOW_DETECT
  96776. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96777. 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]);
  96778. else if(q < qmin)
  96779. 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]);
  96780. #endif
  96781. if(q > qmax)
  96782. q = qmax;
  96783. else if(q < qmin)
  96784. q = qmin;
  96785. error -= q;
  96786. qlp_coeff[i] = q;
  96787. }
  96788. *shift = 0;
  96789. }
  96790. return 0;
  96791. }
  96792. 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[])
  96793. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96794. {
  96795. FLAC__int64 sumo;
  96796. unsigned i, j;
  96797. FLAC__int32 sum;
  96798. const FLAC__int32 *history;
  96799. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96800. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96801. for(i=0;i<order;i++)
  96802. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96803. fprintf(stderr,"\n");
  96804. #endif
  96805. FLAC__ASSERT(order > 0);
  96806. for(i = 0; i < data_len; i++) {
  96807. sumo = 0;
  96808. sum = 0;
  96809. history = data;
  96810. for(j = 0; j < order; j++) {
  96811. sum += qlp_coeff[j] * (*(--history));
  96812. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96813. #if defined _MSC_VER
  96814. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96815. 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);
  96816. #else
  96817. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96818. 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);
  96819. #endif
  96820. }
  96821. *(residual++) = *(data++) - (sum >> lp_quantization);
  96822. }
  96823. /* Here's a slower but clearer version:
  96824. for(i = 0; i < data_len; i++) {
  96825. sum = 0;
  96826. for(j = 0; j < order; j++)
  96827. sum += qlp_coeff[j] * data[i-j-1];
  96828. residual[i] = data[i] - (sum >> lp_quantization);
  96829. }
  96830. */
  96831. }
  96832. #else /* fully unrolled version for normal use */
  96833. {
  96834. int i;
  96835. FLAC__int32 sum;
  96836. FLAC__ASSERT(order > 0);
  96837. FLAC__ASSERT(order <= 32);
  96838. /*
  96839. * We do unique versions up to 12th order since that's the subset limit.
  96840. * Also they are roughly ordered to match frequency of occurrence to
  96841. * minimize branching.
  96842. */
  96843. if(order <= 12) {
  96844. if(order > 8) {
  96845. if(order > 10) {
  96846. if(order == 12) {
  96847. for(i = 0; i < (int)data_len; i++) {
  96848. sum = 0;
  96849. sum += qlp_coeff[11] * data[i-12];
  96850. sum += qlp_coeff[10] * data[i-11];
  96851. sum += qlp_coeff[9] * data[i-10];
  96852. sum += qlp_coeff[8] * data[i-9];
  96853. sum += qlp_coeff[7] * data[i-8];
  96854. sum += qlp_coeff[6] * data[i-7];
  96855. sum += qlp_coeff[5] * data[i-6];
  96856. sum += qlp_coeff[4] * data[i-5];
  96857. sum += qlp_coeff[3] * data[i-4];
  96858. sum += qlp_coeff[2] * data[i-3];
  96859. sum += qlp_coeff[1] * data[i-2];
  96860. sum += qlp_coeff[0] * data[i-1];
  96861. residual[i] = data[i] - (sum >> lp_quantization);
  96862. }
  96863. }
  96864. else { /* order == 11 */
  96865. for(i = 0; i < (int)data_len; i++) {
  96866. sum = 0;
  96867. sum += qlp_coeff[10] * data[i-11];
  96868. sum += qlp_coeff[9] * data[i-10];
  96869. sum += qlp_coeff[8] * data[i-9];
  96870. sum += qlp_coeff[7] * data[i-8];
  96871. sum += qlp_coeff[6] * data[i-7];
  96872. sum += qlp_coeff[5] * data[i-6];
  96873. sum += qlp_coeff[4] * data[i-5];
  96874. sum += qlp_coeff[3] * data[i-4];
  96875. sum += qlp_coeff[2] * data[i-3];
  96876. sum += qlp_coeff[1] * data[i-2];
  96877. sum += qlp_coeff[0] * data[i-1];
  96878. residual[i] = data[i] - (sum >> lp_quantization);
  96879. }
  96880. }
  96881. }
  96882. else {
  96883. if(order == 10) {
  96884. for(i = 0; i < (int)data_len; i++) {
  96885. sum = 0;
  96886. sum += qlp_coeff[9] * data[i-10];
  96887. sum += qlp_coeff[8] * data[i-9];
  96888. sum += qlp_coeff[7] * data[i-8];
  96889. sum += qlp_coeff[6] * data[i-7];
  96890. sum += qlp_coeff[5] * data[i-6];
  96891. sum += qlp_coeff[4] * data[i-5];
  96892. sum += qlp_coeff[3] * data[i-4];
  96893. sum += qlp_coeff[2] * data[i-3];
  96894. sum += qlp_coeff[1] * data[i-2];
  96895. sum += qlp_coeff[0] * data[i-1];
  96896. residual[i] = data[i] - (sum >> lp_quantization);
  96897. }
  96898. }
  96899. else { /* order == 9 */
  96900. for(i = 0; i < (int)data_len; i++) {
  96901. sum = 0;
  96902. sum += qlp_coeff[8] * data[i-9];
  96903. sum += qlp_coeff[7] * data[i-8];
  96904. sum += qlp_coeff[6] * data[i-7];
  96905. sum += qlp_coeff[5] * data[i-6];
  96906. sum += qlp_coeff[4] * data[i-5];
  96907. sum += qlp_coeff[3] * data[i-4];
  96908. sum += qlp_coeff[2] * data[i-3];
  96909. sum += qlp_coeff[1] * data[i-2];
  96910. sum += qlp_coeff[0] * data[i-1];
  96911. residual[i] = data[i] - (sum >> lp_quantization);
  96912. }
  96913. }
  96914. }
  96915. }
  96916. else if(order > 4) {
  96917. if(order > 6) {
  96918. if(order == 8) {
  96919. for(i = 0; i < (int)data_len; i++) {
  96920. sum = 0;
  96921. sum += qlp_coeff[7] * data[i-8];
  96922. sum += qlp_coeff[6] * data[i-7];
  96923. sum += qlp_coeff[5] * data[i-6];
  96924. sum += qlp_coeff[4] * data[i-5];
  96925. sum += qlp_coeff[3] * data[i-4];
  96926. sum += qlp_coeff[2] * data[i-3];
  96927. sum += qlp_coeff[1] * data[i-2];
  96928. sum += qlp_coeff[0] * data[i-1];
  96929. residual[i] = data[i] - (sum >> lp_quantization);
  96930. }
  96931. }
  96932. else { /* order == 7 */
  96933. for(i = 0; i < (int)data_len; i++) {
  96934. sum = 0;
  96935. sum += qlp_coeff[6] * data[i-7];
  96936. sum += qlp_coeff[5] * data[i-6];
  96937. sum += qlp_coeff[4] * data[i-5];
  96938. sum += qlp_coeff[3] * data[i-4];
  96939. sum += qlp_coeff[2] * data[i-3];
  96940. sum += qlp_coeff[1] * data[i-2];
  96941. sum += qlp_coeff[0] * data[i-1];
  96942. residual[i] = data[i] - (sum >> lp_quantization);
  96943. }
  96944. }
  96945. }
  96946. else {
  96947. if(order == 6) {
  96948. for(i = 0; i < (int)data_len; i++) {
  96949. sum = 0;
  96950. sum += qlp_coeff[5] * data[i-6];
  96951. sum += qlp_coeff[4] * data[i-5];
  96952. sum += qlp_coeff[3] * data[i-4];
  96953. sum += qlp_coeff[2] * data[i-3];
  96954. sum += qlp_coeff[1] * data[i-2];
  96955. sum += qlp_coeff[0] * data[i-1];
  96956. residual[i] = data[i] - (sum >> lp_quantization);
  96957. }
  96958. }
  96959. else { /* order == 5 */
  96960. for(i = 0; i < (int)data_len; i++) {
  96961. sum = 0;
  96962. sum += qlp_coeff[4] * data[i-5];
  96963. sum += qlp_coeff[3] * data[i-4];
  96964. sum += qlp_coeff[2] * data[i-3];
  96965. sum += qlp_coeff[1] * data[i-2];
  96966. sum += qlp_coeff[0] * data[i-1];
  96967. residual[i] = data[i] - (sum >> lp_quantization);
  96968. }
  96969. }
  96970. }
  96971. }
  96972. else {
  96973. if(order > 2) {
  96974. if(order == 4) {
  96975. for(i = 0; i < (int)data_len; i++) {
  96976. sum = 0;
  96977. sum += qlp_coeff[3] * data[i-4];
  96978. sum += qlp_coeff[2] * data[i-3];
  96979. sum += qlp_coeff[1] * data[i-2];
  96980. sum += qlp_coeff[0] * data[i-1];
  96981. residual[i] = data[i] - (sum >> lp_quantization);
  96982. }
  96983. }
  96984. else { /* order == 3 */
  96985. for(i = 0; i < (int)data_len; i++) {
  96986. sum = 0;
  96987. sum += qlp_coeff[2] * data[i-3];
  96988. sum += qlp_coeff[1] * data[i-2];
  96989. sum += qlp_coeff[0] * data[i-1];
  96990. residual[i] = data[i] - (sum >> lp_quantization);
  96991. }
  96992. }
  96993. }
  96994. else {
  96995. if(order == 2) {
  96996. for(i = 0; i < (int)data_len; i++) {
  96997. sum = 0;
  96998. sum += qlp_coeff[1] * data[i-2];
  96999. sum += qlp_coeff[0] * data[i-1];
  97000. residual[i] = data[i] - (sum >> lp_quantization);
  97001. }
  97002. }
  97003. else { /* order == 1 */
  97004. for(i = 0; i < (int)data_len; i++)
  97005. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97006. }
  97007. }
  97008. }
  97009. }
  97010. else { /* order > 12 */
  97011. for(i = 0; i < (int)data_len; i++) {
  97012. sum = 0;
  97013. switch(order) {
  97014. case 32: sum += qlp_coeff[31] * data[i-32];
  97015. case 31: sum += qlp_coeff[30] * data[i-31];
  97016. case 30: sum += qlp_coeff[29] * data[i-30];
  97017. case 29: sum += qlp_coeff[28] * data[i-29];
  97018. case 28: sum += qlp_coeff[27] * data[i-28];
  97019. case 27: sum += qlp_coeff[26] * data[i-27];
  97020. case 26: sum += qlp_coeff[25] * data[i-26];
  97021. case 25: sum += qlp_coeff[24] * data[i-25];
  97022. case 24: sum += qlp_coeff[23] * data[i-24];
  97023. case 23: sum += qlp_coeff[22] * data[i-23];
  97024. case 22: sum += qlp_coeff[21] * data[i-22];
  97025. case 21: sum += qlp_coeff[20] * data[i-21];
  97026. case 20: sum += qlp_coeff[19] * data[i-20];
  97027. case 19: sum += qlp_coeff[18] * data[i-19];
  97028. case 18: sum += qlp_coeff[17] * data[i-18];
  97029. case 17: sum += qlp_coeff[16] * data[i-17];
  97030. case 16: sum += qlp_coeff[15] * data[i-16];
  97031. case 15: sum += qlp_coeff[14] * data[i-15];
  97032. case 14: sum += qlp_coeff[13] * data[i-14];
  97033. case 13: sum += qlp_coeff[12] * data[i-13];
  97034. sum += qlp_coeff[11] * data[i-12];
  97035. sum += qlp_coeff[10] * data[i-11];
  97036. sum += qlp_coeff[ 9] * data[i-10];
  97037. sum += qlp_coeff[ 8] * data[i- 9];
  97038. sum += qlp_coeff[ 7] * data[i- 8];
  97039. sum += qlp_coeff[ 6] * data[i- 7];
  97040. sum += qlp_coeff[ 5] * data[i- 6];
  97041. sum += qlp_coeff[ 4] * data[i- 5];
  97042. sum += qlp_coeff[ 3] * data[i- 4];
  97043. sum += qlp_coeff[ 2] * data[i- 3];
  97044. sum += qlp_coeff[ 1] * data[i- 2];
  97045. sum += qlp_coeff[ 0] * data[i- 1];
  97046. }
  97047. residual[i] = data[i] - (sum >> lp_quantization);
  97048. }
  97049. }
  97050. }
  97051. #endif
  97052. 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[])
  97053. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97054. {
  97055. unsigned i, j;
  97056. FLAC__int64 sum;
  97057. const FLAC__int32 *history;
  97058. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97059. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97060. for(i=0;i<order;i++)
  97061. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97062. fprintf(stderr,"\n");
  97063. #endif
  97064. FLAC__ASSERT(order > 0);
  97065. for(i = 0; i < data_len; i++) {
  97066. sum = 0;
  97067. history = data;
  97068. for(j = 0; j < order; j++)
  97069. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97070. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97071. #if defined _MSC_VER
  97072. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97073. #else
  97074. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97075. #endif
  97076. break;
  97077. }
  97078. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97079. #if defined _MSC_VER
  97080. 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));
  97081. #else
  97082. 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)));
  97083. #endif
  97084. break;
  97085. }
  97086. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97087. }
  97088. }
  97089. #else /* fully unrolled version for normal use */
  97090. {
  97091. int i;
  97092. FLAC__int64 sum;
  97093. FLAC__ASSERT(order > 0);
  97094. FLAC__ASSERT(order <= 32);
  97095. /*
  97096. * We do unique versions up to 12th order since that's the subset limit.
  97097. * Also they are roughly ordered to match frequency of occurrence to
  97098. * minimize branching.
  97099. */
  97100. if(order <= 12) {
  97101. if(order > 8) {
  97102. if(order > 10) {
  97103. if(order == 12) {
  97104. for(i = 0; i < (int)data_len; i++) {
  97105. sum = 0;
  97106. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97107. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97108. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97109. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97110. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97111. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97112. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97113. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97114. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97115. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97116. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97117. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97118. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97119. }
  97120. }
  97121. else { /* order == 11 */
  97122. for(i = 0; i < (int)data_len; i++) {
  97123. sum = 0;
  97124. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97125. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97126. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97127. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97128. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97129. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97130. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97131. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97132. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97133. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97134. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97135. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97136. }
  97137. }
  97138. }
  97139. else {
  97140. if(order == 10) {
  97141. for(i = 0; i < (int)data_len; i++) {
  97142. sum = 0;
  97143. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97144. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97145. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97146. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97147. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97148. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97149. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97150. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97151. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97152. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97153. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97154. }
  97155. }
  97156. else { /* order == 9 */
  97157. for(i = 0; i < (int)data_len; i++) {
  97158. sum = 0;
  97159. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97160. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97161. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97162. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97163. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97164. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97165. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97166. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97167. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97168. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97169. }
  97170. }
  97171. }
  97172. }
  97173. else if(order > 4) {
  97174. if(order > 6) {
  97175. if(order == 8) {
  97176. for(i = 0; i < (int)data_len; i++) {
  97177. sum = 0;
  97178. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97179. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97180. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97181. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97182. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97183. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97184. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97185. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97186. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97187. }
  97188. }
  97189. else { /* order == 7 */
  97190. for(i = 0; i < (int)data_len; i++) {
  97191. sum = 0;
  97192. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97193. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97194. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97195. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97196. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97197. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97198. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97199. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97200. }
  97201. }
  97202. }
  97203. else {
  97204. if(order == 6) {
  97205. for(i = 0; i < (int)data_len; i++) {
  97206. sum = 0;
  97207. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97208. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97209. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97210. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97211. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97212. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97213. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97214. }
  97215. }
  97216. else { /* order == 5 */
  97217. for(i = 0; i < (int)data_len; i++) {
  97218. sum = 0;
  97219. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97220. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97221. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97222. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97223. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97224. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97225. }
  97226. }
  97227. }
  97228. }
  97229. else {
  97230. if(order > 2) {
  97231. if(order == 4) {
  97232. for(i = 0; i < (int)data_len; i++) {
  97233. sum = 0;
  97234. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97235. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97236. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97237. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97238. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97239. }
  97240. }
  97241. else { /* order == 3 */
  97242. for(i = 0; i < (int)data_len; i++) {
  97243. sum = 0;
  97244. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97245. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97246. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97247. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97248. }
  97249. }
  97250. }
  97251. else {
  97252. if(order == 2) {
  97253. for(i = 0; i < (int)data_len; i++) {
  97254. sum = 0;
  97255. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97256. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97257. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97258. }
  97259. }
  97260. else { /* order == 1 */
  97261. for(i = 0; i < (int)data_len; i++)
  97262. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97263. }
  97264. }
  97265. }
  97266. }
  97267. else { /* order > 12 */
  97268. for(i = 0; i < (int)data_len; i++) {
  97269. sum = 0;
  97270. switch(order) {
  97271. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97272. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97273. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97274. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97275. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97276. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97277. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97278. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97279. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97280. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97281. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97282. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97283. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97284. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97285. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97286. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97287. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97288. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97289. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97290. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97291. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97292. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97293. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97294. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97295. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97296. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97297. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97298. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97299. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97300. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97301. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97302. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97303. }
  97304. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97305. }
  97306. }
  97307. }
  97308. #endif
  97309. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97310. 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[])
  97311. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97312. {
  97313. FLAC__int64 sumo;
  97314. unsigned i, j;
  97315. FLAC__int32 sum;
  97316. const FLAC__int32 *r = residual, *history;
  97317. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97318. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97319. for(i=0;i<order;i++)
  97320. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97321. fprintf(stderr,"\n");
  97322. #endif
  97323. FLAC__ASSERT(order > 0);
  97324. for(i = 0; i < data_len; i++) {
  97325. sumo = 0;
  97326. sum = 0;
  97327. history = data;
  97328. for(j = 0; j < order; j++) {
  97329. sum += qlp_coeff[j] * (*(--history));
  97330. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97331. #if defined _MSC_VER
  97332. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97333. 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);
  97334. #else
  97335. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97336. 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);
  97337. #endif
  97338. }
  97339. *(data++) = *(r++) + (sum >> lp_quantization);
  97340. }
  97341. /* Here's a slower but clearer version:
  97342. for(i = 0; i < data_len; i++) {
  97343. sum = 0;
  97344. for(j = 0; j < order; j++)
  97345. sum += qlp_coeff[j] * data[i-j-1];
  97346. data[i] = residual[i] + (sum >> lp_quantization);
  97347. }
  97348. */
  97349. }
  97350. #else /* fully unrolled version for normal use */
  97351. {
  97352. int i;
  97353. FLAC__int32 sum;
  97354. FLAC__ASSERT(order > 0);
  97355. FLAC__ASSERT(order <= 32);
  97356. /*
  97357. * We do unique versions up to 12th order since that's the subset limit.
  97358. * Also they are roughly ordered to match frequency of occurrence to
  97359. * minimize branching.
  97360. */
  97361. if(order <= 12) {
  97362. if(order > 8) {
  97363. if(order > 10) {
  97364. if(order == 12) {
  97365. for(i = 0; i < (int)data_len; i++) {
  97366. sum = 0;
  97367. sum += qlp_coeff[11] * data[i-12];
  97368. sum += qlp_coeff[10] * data[i-11];
  97369. sum += qlp_coeff[9] * data[i-10];
  97370. sum += qlp_coeff[8] * data[i-9];
  97371. sum += qlp_coeff[7] * data[i-8];
  97372. sum += qlp_coeff[6] * data[i-7];
  97373. sum += qlp_coeff[5] * data[i-6];
  97374. sum += qlp_coeff[4] * data[i-5];
  97375. sum += qlp_coeff[3] * data[i-4];
  97376. sum += qlp_coeff[2] * data[i-3];
  97377. sum += qlp_coeff[1] * data[i-2];
  97378. sum += qlp_coeff[0] * data[i-1];
  97379. data[i] = residual[i] + (sum >> lp_quantization);
  97380. }
  97381. }
  97382. else { /* order == 11 */
  97383. for(i = 0; i < (int)data_len; i++) {
  97384. sum = 0;
  97385. sum += qlp_coeff[10] * data[i-11];
  97386. sum += qlp_coeff[9] * data[i-10];
  97387. sum += qlp_coeff[8] * data[i-9];
  97388. sum += qlp_coeff[7] * data[i-8];
  97389. sum += qlp_coeff[6] * data[i-7];
  97390. sum += qlp_coeff[5] * data[i-6];
  97391. sum += qlp_coeff[4] * data[i-5];
  97392. sum += qlp_coeff[3] * data[i-4];
  97393. sum += qlp_coeff[2] * data[i-3];
  97394. sum += qlp_coeff[1] * data[i-2];
  97395. sum += qlp_coeff[0] * data[i-1];
  97396. data[i] = residual[i] + (sum >> lp_quantization);
  97397. }
  97398. }
  97399. }
  97400. else {
  97401. if(order == 10) {
  97402. for(i = 0; i < (int)data_len; i++) {
  97403. sum = 0;
  97404. sum += qlp_coeff[9] * data[i-10];
  97405. sum += qlp_coeff[8] * data[i-9];
  97406. sum += qlp_coeff[7] * data[i-8];
  97407. sum += qlp_coeff[6] * data[i-7];
  97408. sum += qlp_coeff[5] * data[i-6];
  97409. sum += qlp_coeff[4] * data[i-5];
  97410. sum += qlp_coeff[3] * data[i-4];
  97411. sum += qlp_coeff[2] * data[i-3];
  97412. sum += qlp_coeff[1] * data[i-2];
  97413. sum += qlp_coeff[0] * data[i-1];
  97414. data[i] = residual[i] + (sum >> lp_quantization);
  97415. }
  97416. }
  97417. else { /* order == 9 */
  97418. for(i = 0; i < (int)data_len; i++) {
  97419. sum = 0;
  97420. sum += qlp_coeff[8] * data[i-9];
  97421. sum += qlp_coeff[7] * data[i-8];
  97422. sum += qlp_coeff[6] * data[i-7];
  97423. sum += qlp_coeff[5] * data[i-6];
  97424. sum += qlp_coeff[4] * data[i-5];
  97425. sum += qlp_coeff[3] * data[i-4];
  97426. sum += qlp_coeff[2] * data[i-3];
  97427. sum += qlp_coeff[1] * data[i-2];
  97428. sum += qlp_coeff[0] * data[i-1];
  97429. data[i] = residual[i] + (sum >> lp_quantization);
  97430. }
  97431. }
  97432. }
  97433. }
  97434. else if(order > 4) {
  97435. if(order > 6) {
  97436. if(order == 8) {
  97437. for(i = 0; i < (int)data_len; i++) {
  97438. sum = 0;
  97439. sum += qlp_coeff[7] * data[i-8];
  97440. sum += qlp_coeff[6] * data[i-7];
  97441. sum += qlp_coeff[5] * data[i-6];
  97442. sum += qlp_coeff[4] * data[i-5];
  97443. sum += qlp_coeff[3] * data[i-4];
  97444. sum += qlp_coeff[2] * data[i-3];
  97445. sum += qlp_coeff[1] * data[i-2];
  97446. sum += qlp_coeff[0] * data[i-1];
  97447. data[i] = residual[i] + (sum >> lp_quantization);
  97448. }
  97449. }
  97450. else { /* order == 7 */
  97451. for(i = 0; i < (int)data_len; i++) {
  97452. sum = 0;
  97453. sum += qlp_coeff[6] * data[i-7];
  97454. sum += qlp_coeff[5] * data[i-6];
  97455. sum += qlp_coeff[4] * data[i-5];
  97456. sum += qlp_coeff[3] * data[i-4];
  97457. sum += qlp_coeff[2] * data[i-3];
  97458. sum += qlp_coeff[1] * data[i-2];
  97459. sum += qlp_coeff[0] * data[i-1];
  97460. data[i] = residual[i] + (sum >> lp_quantization);
  97461. }
  97462. }
  97463. }
  97464. else {
  97465. if(order == 6) {
  97466. for(i = 0; i < (int)data_len; i++) {
  97467. sum = 0;
  97468. sum += qlp_coeff[5] * data[i-6];
  97469. sum += qlp_coeff[4] * data[i-5];
  97470. sum += qlp_coeff[3] * data[i-4];
  97471. sum += qlp_coeff[2] * data[i-3];
  97472. sum += qlp_coeff[1] * data[i-2];
  97473. sum += qlp_coeff[0] * data[i-1];
  97474. data[i] = residual[i] + (sum >> lp_quantization);
  97475. }
  97476. }
  97477. else { /* order == 5 */
  97478. for(i = 0; i < (int)data_len; i++) {
  97479. sum = 0;
  97480. sum += qlp_coeff[4] * data[i-5];
  97481. sum += qlp_coeff[3] * data[i-4];
  97482. sum += qlp_coeff[2] * data[i-3];
  97483. sum += qlp_coeff[1] * data[i-2];
  97484. sum += qlp_coeff[0] * data[i-1];
  97485. data[i] = residual[i] + (sum >> lp_quantization);
  97486. }
  97487. }
  97488. }
  97489. }
  97490. else {
  97491. if(order > 2) {
  97492. if(order == 4) {
  97493. for(i = 0; i < (int)data_len; i++) {
  97494. sum = 0;
  97495. sum += qlp_coeff[3] * data[i-4];
  97496. sum += qlp_coeff[2] * data[i-3];
  97497. sum += qlp_coeff[1] * data[i-2];
  97498. sum += qlp_coeff[0] * data[i-1];
  97499. data[i] = residual[i] + (sum >> lp_quantization);
  97500. }
  97501. }
  97502. else { /* order == 3 */
  97503. for(i = 0; i < (int)data_len; i++) {
  97504. sum = 0;
  97505. sum += qlp_coeff[2] * data[i-3];
  97506. sum += qlp_coeff[1] * data[i-2];
  97507. sum += qlp_coeff[0] * data[i-1];
  97508. data[i] = residual[i] + (sum >> lp_quantization);
  97509. }
  97510. }
  97511. }
  97512. else {
  97513. if(order == 2) {
  97514. for(i = 0; i < (int)data_len; i++) {
  97515. sum = 0;
  97516. sum += qlp_coeff[1] * data[i-2];
  97517. sum += qlp_coeff[0] * data[i-1];
  97518. data[i] = residual[i] + (sum >> lp_quantization);
  97519. }
  97520. }
  97521. else { /* order == 1 */
  97522. for(i = 0; i < (int)data_len; i++)
  97523. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97524. }
  97525. }
  97526. }
  97527. }
  97528. else { /* order > 12 */
  97529. for(i = 0; i < (int)data_len; i++) {
  97530. sum = 0;
  97531. switch(order) {
  97532. case 32: sum += qlp_coeff[31] * data[i-32];
  97533. case 31: sum += qlp_coeff[30] * data[i-31];
  97534. case 30: sum += qlp_coeff[29] * data[i-30];
  97535. case 29: sum += qlp_coeff[28] * data[i-29];
  97536. case 28: sum += qlp_coeff[27] * data[i-28];
  97537. case 27: sum += qlp_coeff[26] * data[i-27];
  97538. case 26: sum += qlp_coeff[25] * data[i-26];
  97539. case 25: sum += qlp_coeff[24] * data[i-25];
  97540. case 24: sum += qlp_coeff[23] * data[i-24];
  97541. case 23: sum += qlp_coeff[22] * data[i-23];
  97542. case 22: sum += qlp_coeff[21] * data[i-22];
  97543. case 21: sum += qlp_coeff[20] * data[i-21];
  97544. case 20: sum += qlp_coeff[19] * data[i-20];
  97545. case 19: sum += qlp_coeff[18] * data[i-19];
  97546. case 18: sum += qlp_coeff[17] * data[i-18];
  97547. case 17: sum += qlp_coeff[16] * data[i-17];
  97548. case 16: sum += qlp_coeff[15] * data[i-16];
  97549. case 15: sum += qlp_coeff[14] * data[i-15];
  97550. case 14: sum += qlp_coeff[13] * data[i-14];
  97551. case 13: sum += qlp_coeff[12] * data[i-13];
  97552. sum += qlp_coeff[11] * data[i-12];
  97553. sum += qlp_coeff[10] * data[i-11];
  97554. sum += qlp_coeff[ 9] * data[i-10];
  97555. sum += qlp_coeff[ 8] * data[i- 9];
  97556. sum += qlp_coeff[ 7] * data[i- 8];
  97557. sum += qlp_coeff[ 6] * data[i- 7];
  97558. sum += qlp_coeff[ 5] * data[i- 6];
  97559. sum += qlp_coeff[ 4] * data[i- 5];
  97560. sum += qlp_coeff[ 3] * data[i- 4];
  97561. sum += qlp_coeff[ 2] * data[i- 3];
  97562. sum += qlp_coeff[ 1] * data[i- 2];
  97563. sum += qlp_coeff[ 0] * data[i- 1];
  97564. }
  97565. data[i] = residual[i] + (sum >> lp_quantization);
  97566. }
  97567. }
  97568. }
  97569. #endif
  97570. 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[])
  97571. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97572. {
  97573. unsigned i, j;
  97574. FLAC__int64 sum;
  97575. const FLAC__int32 *r = residual, *history;
  97576. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97577. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97578. for(i=0;i<order;i++)
  97579. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97580. fprintf(stderr,"\n");
  97581. #endif
  97582. FLAC__ASSERT(order > 0);
  97583. for(i = 0; i < data_len; i++) {
  97584. sum = 0;
  97585. history = data;
  97586. for(j = 0; j < order; j++)
  97587. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97588. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97589. #ifdef _MSC_VER
  97590. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97591. #else
  97592. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97593. #endif
  97594. break;
  97595. }
  97596. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97597. #ifdef _MSC_VER
  97598. 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));
  97599. #else
  97600. 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)));
  97601. #endif
  97602. break;
  97603. }
  97604. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97605. }
  97606. }
  97607. #else /* fully unrolled version for normal use */
  97608. {
  97609. int i;
  97610. FLAC__int64 sum;
  97611. FLAC__ASSERT(order > 0);
  97612. FLAC__ASSERT(order <= 32);
  97613. /*
  97614. * We do unique versions up to 12th order since that's the subset limit.
  97615. * Also they are roughly ordered to match frequency of occurrence to
  97616. * minimize branching.
  97617. */
  97618. if(order <= 12) {
  97619. if(order > 8) {
  97620. if(order > 10) {
  97621. if(order == 12) {
  97622. for(i = 0; i < (int)data_len; i++) {
  97623. sum = 0;
  97624. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97625. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97626. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97627. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97628. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97629. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97630. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97631. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97632. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97633. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97634. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97635. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97636. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97637. }
  97638. }
  97639. else { /* order == 11 */
  97640. for(i = 0; i < (int)data_len; i++) {
  97641. sum = 0;
  97642. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97643. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97644. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97645. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97646. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97647. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97648. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97649. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97650. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97651. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97652. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97653. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97654. }
  97655. }
  97656. }
  97657. else {
  97658. if(order == 10) {
  97659. for(i = 0; i < (int)data_len; i++) {
  97660. sum = 0;
  97661. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97662. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97663. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97664. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97665. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97666. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97667. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97668. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97669. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97670. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97671. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97672. }
  97673. }
  97674. else { /* order == 9 */
  97675. for(i = 0; i < (int)data_len; i++) {
  97676. sum = 0;
  97677. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97678. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97679. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97680. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97681. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97682. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97683. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97684. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97685. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97686. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97687. }
  97688. }
  97689. }
  97690. }
  97691. else if(order > 4) {
  97692. if(order > 6) {
  97693. if(order == 8) {
  97694. for(i = 0; i < (int)data_len; i++) {
  97695. sum = 0;
  97696. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97697. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97698. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97699. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97700. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97701. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97702. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97703. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97704. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97705. }
  97706. }
  97707. else { /* order == 7 */
  97708. for(i = 0; i < (int)data_len; i++) {
  97709. sum = 0;
  97710. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97711. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97712. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97713. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97714. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97715. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97716. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97717. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97718. }
  97719. }
  97720. }
  97721. else {
  97722. if(order == 6) {
  97723. for(i = 0; i < (int)data_len; i++) {
  97724. sum = 0;
  97725. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97726. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97727. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97728. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97729. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97730. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97731. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97732. }
  97733. }
  97734. else { /* order == 5 */
  97735. for(i = 0; i < (int)data_len; i++) {
  97736. sum = 0;
  97737. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97738. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97739. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97740. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97741. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97742. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97743. }
  97744. }
  97745. }
  97746. }
  97747. else {
  97748. if(order > 2) {
  97749. if(order == 4) {
  97750. for(i = 0; i < (int)data_len; i++) {
  97751. sum = 0;
  97752. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97753. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97754. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97755. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97756. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97757. }
  97758. }
  97759. else { /* order == 3 */
  97760. for(i = 0; i < (int)data_len; i++) {
  97761. sum = 0;
  97762. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97763. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97764. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97765. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97766. }
  97767. }
  97768. }
  97769. else {
  97770. if(order == 2) {
  97771. for(i = 0; i < (int)data_len; i++) {
  97772. sum = 0;
  97773. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97774. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97775. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97776. }
  97777. }
  97778. else { /* order == 1 */
  97779. for(i = 0; i < (int)data_len; i++)
  97780. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97781. }
  97782. }
  97783. }
  97784. }
  97785. else { /* order > 12 */
  97786. for(i = 0; i < (int)data_len; i++) {
  97787. sum = 0;
  97788. switch(order) {
  97789. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97790. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97791. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97792. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97793. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97794. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97795. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97796. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97797. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97798. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97799. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97800. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97801. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97802. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97803. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97804. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97805. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97806. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97807. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97808. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97809. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97810. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97811. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97812. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97813. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97814. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97815. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97816. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97817. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97818. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97819. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97820. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97821. }
  97822. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97823. }
  97824. }
  97825. }
  97826. #endif
  97827. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97828. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97829. {
  97830. FLAC__double error_scale;
  97831. FLAC__ASSERT(total_samples > 0);
  97832. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97833. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97834. }
  97835. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97836. {
  97837. if(lpc_error > 0.0) {
  97838. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97839. if(bps >= 0.0)
  97840. return bps;
  97841. else
  97842. return 0.0;
  97843. }
  97844. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97845. return 1e32;
  97846. }
  97847. else {
  97848. return 0.0;
  97849. }
  97850. }
  97851. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97852. {
  97853. 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 */
  97854. FLAC__double bits, best_bits, error_scale;
  97855. FLAC__ASSERT(max_order > 0);
  97856. FLAC__ASSERT(total_samples > 0);
  97857. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97858. best_index = 0;
  97859. best_bits = (unsigned)(-1);
  97860. for(index = 0, order = 1; index < max_order; index++, order++) {
  97861. 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);
  97862. if(bits < best_bits) {
  97863. best_index = index;
  97864. best_bits = bits;
  97865. }
  97866. }
  97867. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97868. }
  97869. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97870. #endif
  97871. /*** End of inlined file: lpc_flac.c ***/
  97872. /*** Start of inlined file: md5.c ***/
  97873. /*** Start of inlined file: juce_FlacHeader.h ***/
  97874. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97875. // tasks..
  97876. #define VERSION "1.2.1"
  97877. #define FLAC__NO_DLL 1
  97878. #if JUCE_MSVC
  97879. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97880. #endif
  97881. #if JUCE_MAC
  97882. #define FLAC__SYS_DARWIN 1
  97883. #endif
  97884. /*** End of inlined file: juce_FlacHeader.h ***/
  97885. #if JUCE_USE_FLAC
  97886. #if HAVE_CONFIG_H
  97887. # include <config.h>
  97888. #endif
  97889. #include <stdlib.h> /* for malloc() */
  97890. #include <string.h> /* for memcpy() */
  97891. /*** Start of inlined file: md5.h ***/
  97892. #ifndef FLAC__PRIVATE__MD5_H
  97893. #define FLAC__PRIVATE__MD5_H
  97894. /*
  97895. * This is the header file for the MD5 message-digest algorithm.
  97896. * The algorithm is due to Ron Rivest. This code was
  97897. * written by Colin Plumb in 1993, no copyright is claimed.
  97898. * This code is in the public domain; do with it what you wish.
  97899. *
  97900. * Equivalent code is available from RSA Data Security, Inc.
  97901. * This code has been tested against that, and is equivalent,
  97902. * except that you don't need to include two pages of legalese
  97903. * with every copy.
  97904. *
  97905. * To compute the message digest of a chunk of bytes, declare an
  97906. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97907. * needed on buffers full of bytes, and then call MD5Final, which
  97908. * will fill a supplied 16-byte array with the digest.
  97909. *
  97910. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97911. * header definitions; now uses stuff from dpkg's config.h
  97912. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97913. * Still in the public domain.
  97914. *
  97915. * Josh Coalson: made some changes to integrate with libFLAC.
  97916. * Still in the public domain, with no warranty.
  97917. */
  97918. typedef struct {
  97919. FLAC__uint32 in[16];
  97920. FLAC__uint32 buf[4];
  97921. FLAC__uint32 bytes[2];
  97922. FLAC__byte *internal_buf;
  97923. size_t capacity;
  97924. } FLAC__MD5Context;
  97925. void FLAC__MD5Init(FLAC__MD5Context *context);
  97926. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97927. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97928. #endif
  97929. /*** End of inlined file: md5.h ***/
  97930. #ifndef FLaC__INLINE
  97931. #define FLaC__INLINE
  97932. #endif
  97933. /*
  97934. * This code implements the MD5 message-digest algorithm.
  97935. * The algorithm is due to Ron Rivest. This code was
  97936. * written by Colin Plumb in 1993, no copyright is claimed.
  97937. * This code is in the public domain; do with it what you wish.
  97938. *
  97939. * Equivalent code is available from RSA Data Security, Inc.
  97940. * This code has been tested against that, and is equivalent,
  97941. * except that you don't need to include two pages of legalese
  97942. * with every copy.
  97943. *
  97944. * To compute the message digest of a chunk of bytes, declare an
  97945. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97946. * needed on buffers full of bytes, and then call MD5Final, which
  97947. * will fill a supplied 16-byte array with the digest.
  97948. *
  97949. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97950. * definitions; now uses stuff from dpkg's config.h.
  97951. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97952. * Still in the public domain.
  97953. *
  97954. * Josh Coalson: made some changes to integrate with libFLAC.
  97955. * Still in the public domain.
  97956. */
  97957. /* The four core functions - F1 is optimized somewhat */
  97958. /* #define F1(x, y, z) (x & y | ~x & z) */
  97959. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97960. #define F2(x, y, z) F1(z, x, y)
  97961. #define F3(x, y, z) (x ^ y ^ z)
  97962. #define F4(x, y, z) (y ^ (x | ~z))
  97963. /* This is the central step in the MD5 algorithm. */
  97964. #define MD5STEP(f,w,x,y,z,in,s) \
  97965. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97966. /*
  97967. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97968. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97969. * the data and converts bytes into longwords for this routine.
  97970. */
  97971. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97972. {
  97973. register FLAC__uint32 a, b, c, d;
  97974. a = buf[0];
  97975. b = buf[1];
  97976. c = buf[2];
  97977. d = buf[3];
  97978. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97979. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97980. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97981. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97982. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97983. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97984. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97985. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97986. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97987. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97988. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97989. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97990. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97991. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97992. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97993. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97994. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97995. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97996. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97997. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97998. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97999. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98000. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98001. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98002. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98003. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98004. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98005. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98006. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98007. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98008. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98009. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98010. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98011. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98012. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98013. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98014. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98015. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98016. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98017. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98018. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98019. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98020. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98021. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98022. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98023. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98024. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98025. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98026. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98027. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98028. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98029. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98030. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98031. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98032. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98033. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98034. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98035. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98036. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98037. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98038. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98039. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98040. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98041. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98042. buf[0] += a;
  98043. buf[1] += b;
  98044. buf[2] += c;
  98045. buf[3] += d;
  98046. }
  98047. #if WORDS_BIGENDIAN
  98048. //@@@@@@ OPT: use bswap/intrinsics
  98049. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98050. {
  98051. register FLAC__uint32 x;
  98052. do {
  98053. x = *buf;
  98054. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98055. *buf++ = (x >> 16) | (x << 16);
  98056. } while (--words);
  98057. }
  98058. static void byteSwapX16(FLAC__uint32 *buf)
  98059. {
  98060. register FLAC__uint32 x;
  98061. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98062. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98063. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98064. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98065. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98066. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98067. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98068. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98069. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98070. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98071. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98072. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98073. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98074. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98075. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98076. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98077. }
  98078. #else
  98079. #define byteSwap(buf, words)
  98080. #define byteSwapX16(buf)
  98081. #endif
  98082. /*
  98083. * Update context to reflect the concatenation of another buffer full
  98084. * of bytes.
  98085. */
  98086. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98087. {
  98088. FLAC__uint32 t;
  98089. /* Update byte count */
  98090. t = ctx->bytes[0];
  98091. if ((ctx->bytes[0] = t + len) < t)
  98092. ctx->bytes[1]++; /* Carry from low to high */
  98093. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98094. if (t > len) {
  98095. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98096. return;
  98097. }
  98098. /* First chunk is an odd size */
  98099. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98100. byteSwapX16(ctx->in);
  98101. FLAC__MD5Transform(ctx->buf, ctx->in);
  98102. buf += t;
  98103. len -= t;
  98104. /* Process data in 64-byte chunks */
  98105. while (len >= 64) {
  98106. memcpy(ctx->in, buf, 64);
  98107. byteSwapX16(ctx->in);
  98108. FLAC__MD5Transform(ctx->buf, ctx->in);
  98109. buf += 64;
  98110. len -= 64;
  98111. }
  98112. /* Handle any remaining bytes of data. */
  98113. memcpy(ctx->in, buf, len);
  98114. }
  98115. /*
  98116. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98117. * initialization constants.
  98118. */
  98119. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98120. {
  98121. ctx->buf[0] = 0x67452301;
  98122. ctx->buf[1] = 0xefcdab89;
  98123. ctx->buf[2] = 0x98badcfe;
  98124. ctx->buf[3] = 0x10325476;
  98125. ctx->bytes[0] = 0;
  98126. ctx->bytes[1] = 0;
  98127. ctx->internal_buf = 0;
  98128. ctx->capacity = 0;
  98129. }
  98130. /*
  98131. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98132. * 1 0* (64-bit count of bits processed, MSB-first)
  98133. */
  98134. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98135. {
  98136. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98137. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98138. /* Set the first char of padding to 0x80. There is always room. */
  98139. *p++ = 0x80;
  98140. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98141. count = 56 - 1 - count;
  98142. if (count < 0) { /* Padding forces an extra block */
  98143. memset(p, 0, count + 8);
  98144. byteSwapX16(ctx->in);
  98145. FLAC__MD5Transform(ctx->buf, ctx->in);
  98146. p = (FLAC__byte *)ctx->in;
  98147. count = 56;
  98148. }
  98149. memset(p, 0, count);
  98150. byteSwap(ctx->in, 14);
  98151. /* Append length in bits and transform */
  98152. ctx->in[14] = ctx->bytes[0] << 3;
  98153. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98154. FLAC__MD5Transform(ctx->buf, ctx->in);
  98155. byteSwap(ctx->buf, 4);
  98156. memcpy(digest, ctx->buf, 16);
  98157. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98158. if(0 != ctx->internal_buf) {
  98159. free(ctx->internal_buf);
  98160. ctx->internal_buf = 0;
  98161. ctx->capacity = 0;
  98162. }
  98163. }
  98164. /*
  98165. * Convert the incoming audio signal to a byte stream
  98166. */
  98167. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98168. {
  98169. unsigned channel, sample;
  98170. register FLAC__int32 a_word;
  98171. register FLAC__byte *buf_ = buf;
  98172. #if WORDS_BIGENDIAN
  98173. #else
  98174. if(channels == 2 && bytes_per_sample == 2) {
  98175. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98176. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98177. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98178. *buf1_ = (FLAC__int16)signal[1][sample];
  98179. }
  98180. else if(channels == 1 && bytes_per_sample == 2) {
  98181. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98182. for(sample = 0; sample < samples; sample++)
  98183. *buf1_++ = (FLAC__int16)signal[0][sample];
  98184. }
  98185. else
  98186. #endif
  98187. if(bytes_per_sample == 2) {
  98188. if(channels == 2) {
  98189. for(sample = 0; sample < samples; sample++) {
  98190. a_word = signal[0][sample];
  98191. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98192. *buf_++ = (FLAC__byte)a_word;
  98193. a_word = signal[1][sample];
  98194. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98195. *buf_++ = (FLAC__byte)a_word;
  98196. }
  98197. }
  98198. else if(channels == 1) {
  98199. for(sample = 0; sample < samples; sample++) {
  98200. a_word = signal[0][sample];
  98201. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98202. *buf_++ = (FLAC__byte)a_word;
  98203. }
  98204. }
  98205. else {
  98206. for(sample = 0; sample < samples; sample++) {
  98207. for(channel = 0; channel < channels; channel++) {
  98208. a_word = signal[channel][sample];
  98209. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98210. *buf_++ = (FLAC__byte)a_word;
  98211. }
  98212. }
  98213. }
  98214. }
  98215. else if(bytes_per_sample == 3) {
  98216. if(channels == 2) {
  98217. for(sample = 0; sample < samples; sample++) {
  98218. a_word = signal[0][sample];
  98219. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98220. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98221. *buf_++ = (FLAC__byte)a_word;
  98222. a_word = signal[1][sample];
  98223. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98224. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98225. *buf_++ = (FLAC__byte)a_word;
  98226. }
  98227. }
  98228. else if(channels == 1) {
  98229. for(sample = 0; sample < samples; sample++) {
  98230. a_word = signal[0][sample];
  98231. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98232. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98233. *buf_++ = (FLAC__byte)a_word;
  98234. }
  98235. }
  98236. else {
  98237. for(sample = 0; sample < samples; sample++) {
  98238. for(channel = 0; channel < channels; channel++) {
  98239. a_word = signal[channel][sample];
  98240. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98241. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98242. *buf_++ = (FLAC__byte)a_word;
  98243. }
  98244. }
  98245. }
  98246. }
  98247. else if(bytes_per_sample == 1) {
  98248. if(channels == 2) {
  98249. for(sample = 0; sample < samples; sample++) {
  98250. a_word = signal[0][sample];
  98251. *buf_++ = (FLAC__byte)a_word;
  98252. a_word = signal[1][sample];
  98253. *buf_++ = (FLAC__byte)a_word;
  98254. }
  98255. }
  98256. else if(channels == 1) {
  98257. for(sample = 0; sample < samples; sample++) {
  98258. a_word = signal[0][sample];
  98259. *buf_++ = (FLAC__byte)a_word;
  98260. }
  98261. }
  98262. else {
  98263. for(sample = 0; sample < samples; sample++) {
  98264. for(channel = 0; channel < channels; channel++) {
  98265. a_word = signal[channel][sample];
  98266. *buf_++ = (FLAC__byte)a_word;
  98267. }
  98268. }
  98269. }
  98270. }
  98271. else { /* bytes_per_sample == 4, maybe optimize more later */
  98272. for(sample = 0; sample < samples; sample++) {
  98273. for(channel = 0; channel < channels; channel++) {
  98274. a_word = signal[channel][sample];
  98275. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98276. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98277. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98278. *buf_++ = (FLAC__byte)a_word;
  98279. }
  98280. }
  98281. }
  98282. }
  98283. /*
  98284. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98285. */
  98286. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98287. {
  98288. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98289. /* overflow check */
  98290. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98291. return false;
  98292. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98293. return false;
  98294. if(ctx->capacity < bytes_needed) {
  98295. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98296. if(0 == tmp) {
  98297. free(ctx->internal_buf);
  98298. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98299. return false;
  98300. }
  98301. ctx->internal_buf = tmp;
  98302. ctx->capacity = bytes_needed;
  98303. }
  98304. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98305. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98306. return true;
  98307. }
  98308. #endif
  98309. /*** End of inlined file: md5.c ***/
  98310. /*** Start of inlined file: memory.c ***/
  98311. /*** Start of inlined file: juce_FlacHeader.h ***/
  98312. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98313. // tasks..
  98314. #define VERSION "1.2.1"
  98315. #define FLAC__NO_DLL 1
  98316. #if JUCE_MSVC
  98317. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98318. #endif
  98319. #if JUCE_MAC
  98320. #define FLAC__SYS_DARWIN 1
  98321. #endif
  98322. /*** End of inlined file: juce_FlacHeader.h ***/
  98323. #if JUCE_USE_FLAC
  98324. #if HAVE_CONFIG_H
  98325. # include <config.h>
  98326. #endif
  98327. /*** Start of inlined file: memory.h ***/
  98328. #ifndef FLAC__PRIVATE__MEMORY_H
  98329. #define FLAC__PRIVATE__MEMORY_H
  98330. #ifdef HAVE_CONFIG_H
  98331. #include <config.h>
  98332. #endif
  98333. #include <stdlib.h> /* for size_t */
  98334. /* Returns the unaligned address returned by malloc.
  98335. * Use free() on this address to deallocate.
  98336. */
  98337. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98338. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98339. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98340. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98341. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98342. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98343. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98344. #endif
  98345. #endif
  98346. /*** End of inlined file: memory.h ***/
  98347. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98348. {
  98349. void *x;
  98350. FLAC__ASSERT(0 != aligned_address);
  98351. #ifdef FLAC__ALIGN_MALLOC_DATA
  98352. /* align on 32-byte (256-bit) boundary */
  98353. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98354. #ifdef SIZEOF_VOIDP
  98355. #if SIZEOF_VOIDP == 4
  98356. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98357. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98358. #elif SIZEOF_VOIDP == 8
  98359. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98360. #else
  98361. # error Unsupported sizeof(void*)
  98362. #endif
  98363. #else
  98364. /* there's got to be a better way to do this right for all archs */
  98365. if(sizeof(void*) == sizeof(unsigned))
  98366. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98367. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98368. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98369. else
  98370. return 0;
  98371. #endif
  98372. #else
  98373. x = safe_malloc_(bytes);
  98374. *aligned_address = x;
  98375. #endif
  98376. return x;
  98377. }
  98378. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98379. {
  98380. FLAC__int32 *pu; /* unaligned pointer */
  98381. union { /* union needed to comply with C99 pointer aliasing rules */
  98382. FLAC__int32 *pa; /* aligned pointer */
  98383. void *pv; /* aligned pointer alias */
  98384. } u;
  98385. FLAC__ASSERT(elements > 0);
  98386. FLAC__ASSERT(0 != unaligned_pointer);
  98387. FLAC__ASSERT(0 != aligned_pointer);
  98388. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98389. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98390. if(0 == pu) {
  98391. return false;
  98392. }
  98393. else {
  98394. if(*unaligned_pointer != 0)
  98395. free(*unaligned_pointer);
  98396. *unaligned_pointer = pu;
  98397. *aligned_pointer = u.pa;
  98398. return true;
  98399. }
  98400. }
  98401. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98402. {
  98403. FLAC__uint32 *pu; /* unaligned pointer */
  98404. union { /* union needed to comply with C99 pointer aliasing rules */
  98405. FLAC__uint32 *pa; /* aligned pointer */
  98406. void *pv; /* aligned pointer alias */
  98407. } u;
  98408. FLAC__ASSERT(elements > 0);
  98409. FLAC__ASSERT(0 != unaligned_pointer);
  98410. FLAC__ASSERT(0 != aligned_pointer);
  98411. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98412. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98413. if(0 == pu) {
  98414. return false;
  98415. }
  98416. else {
  98417. if(*unaligned_pointer != 0)
  98418. free(*unaligned_pointer);
  98419. *unaligned_pointer = pu;
  98420. *aligned_pointer = u.pa;
  98421. return true;
  98422. }
  98423. }
  98424. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98425. {
  98426. FLAC__uint64 *pu; /* unaligned pointer */
  98427. union { /* union needed to comply with C99 pointer aliasing rules */
  98428. FLAC__uint64 *pa; /* aligned pointer */
  98429. void *pv; /* aligned pointer alias */
  98430. } u;
  98431. FLAC__ASSERT(elements > 0);
  98432. FLAC__ASSERT(0 != unaligned_pointer);
  98433. FLAC__ASSERT(0 != aligned_pointer);
  98434. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98435. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98436. if(0 == pu) {
  98437. return false;
  98438. }
  98439. else {
  98440. if(*unaligned_pointer != 0)
  98441. free(*unaligned_pointer);
  98442. *unaligned_pointer = pu;
  98443. *aligned_pointer = u.pa;
  98444. return true;
  98445. }
  98446. }
  98447. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98448. {
  98449. unsigned *pu; /* unaligned pointer */
  98450. union { /* union needed to comply with C99 pointer aliasing rules */
  98451. unsigned *pa; /* aligned pointer */
  98452. void *pv; /* aligned pointer alias */
  98453. } u;
  98454. FLAC__ASSERT(elements > 0);
  98455. FLAC__ASSERT(0 != unaligned_pointer);
  98456. FLAC__ASSERT(0 != aligned_pointer);
  98457. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98458. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98459. if(0 == pu) {
  98460. return false;
  98461. }
  98462. else {
  98463. if(*unaligned_pointer != 0)
  98464. free(*unaligned_pointer);
  98465. *unaligned_pointer = pu;
  98466. *aligned_pointer = u.pa;
  98467. return true;
  98468. }
  98469. }
  98470. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98471. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98472. {
  98473. FLAC__real *pu; /* unaligned pointer */
  98474. union { /* union needed to comply with C99 pointer aliasing rules */
  98475. FLAC__real *pa; /* aligned pointer */
  98476. void *pv; /* aligned pointer alias */
  98477. } u;
  98478. FLAC__ASSERT(elements > 0);
  98479. FLAC__ASSERT(0 != unaligned_pointer);
  98480. FLAC__ASSERT(0 != aligned_pointer);
  98481. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98482. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98483. if(0 == pu) {
  98484. return false;
  98485. }
  98486. else {
  98487. if(*unaligned_pointer != 0)
  98488. free(*unaligned_pointer);
  98489. *unaligned_pointer = pu;
  98490. *aligned_pointer = u.pa;
  98491. return true;
  98492. }
  98493. }
  98494. #endif
  98495. #endif
  98496. /*** End of inlined file: memory.c ***/
  98497. /*** Start of inlined file: stream_decoder.c ***/
  98498. /*** Start of inlined file: juce_FlacHeader.h ***/
  98499. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98500. // tasks..
  98501. #define VERSION "1.2.1"
  98502. #define FLAC__NO_DLL 1
  98503. #if JUCE_MSVC
  98504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98505. #endif
  98506. #if JUCE_MAC
  98507. #define FLAC__SYS_DARWIN 1
  98508. #endif
  98509. /*** End of inlined file: juce_FlacHeader.h ***/
  98510. #if JUCE_USE_FLAC
  98511. #if HAVE_CONFIG_H
  98512. # include <config.h>
  98513. #endif
  98514. #if defined _MSC_VER || defined __MINGW32__
  98515. #include <io.h> /* for _setmode() */
  98516. #include <fcntl.h> /* for _O_BINARY */
  98517. #endif
  98518. #if defined __CYGWIN__ || defined __EMX__
  98519. #include <io.h> /* for setmode(), O_BINARY */
  98520. #include <fcntl.h> /* for _O_BINARY */
  98521. #endif
  98522. #include <stdio.h>
  98523. #include <stdlib.h> /* for malloc() */
  98524. #include <string.h> /* for memset/memcpy() */
  98525. #include <sys/stat.h> /* for stat() */
  98526. #include <sys/types.h> /* for off_t */
  98527. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98528. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98529. #define fseeko fseek
  98530. #define ftello ftell
  98531. #endif
  98532. #endif
  98533. /*** Start of inlined file: stream_decoder.h ***/
  98534. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98535. #define FLAC__PROTECTED__STREAM_DECODER_H
  98536. #if FLAC__HAS_OGG
  98537. #include "include/private/ogg_decoder_aspect.h"
  98538. #endif
  98539. typedef struct FLAC__StreamDecoderProtected {
  98540. FLAC__StreamDecoderState state;
  98541. unsigned channels;
  98542. FLAC__ChannelAssignment channel_assignment;
  98543. unsigned bits_per_sample;
  98544. unsigned sample_rate; /* in Hz */
  98545. unsigned blocksize; /* in samples (per channel) */
  98546. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98547. #if FLAC__HAS_OGG
  98548. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98549. #endif
  98550. } FLAC__StreamDecoderProtected;
  98551. /*
  98552. * return the number of input bytes consumed
  98553. */
  98554. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98555. #endif
  98556. /*** End of inlined file: stream_decoder.h ***/
  98557. #ifdef max
  98558. #undef max
  98559. #endif
  98560. #define max(a,b) ((a)>(b)?(a):(b))
  98561. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98562. #ifdef _MSC_VER
  98563. #define FLAC__U64L(x) x
  98564. #else
  98565. #define FLAC__U64L(x) x##LLU
  98566. #endif
  98567. /* technically this should be in an "export.c" but this is convenient enough */
  98568. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98569. #if FLAC__HAS_OGG
  98570. 1
  98571. #else
  98572. 0
  98573. #endif
  98574. ;
  98575. /***********************************************************************
  98576. *
  98577. * Private static data
  98578. *
  98579. ***********************************************************************/
  98580. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98581. /***********************************************************************
  98582. *
  98583. * Private class method prototypes
  98584. *
  98585. ***********************************************************************/
  98586. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98587. static FILE *get_binary_stdin_(void);
  98588. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98589. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98590. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98591. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98592. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98593. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98594. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98595. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98596. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98597. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98598. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98599. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98600. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98601. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98602. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98603. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98604. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98605. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98606. 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);
  98607. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98608. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98609. #if FLAC__HAS_OGG
  98610. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98611. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98612. #endif
  98613. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98614. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98615. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98616. #if FLAC__HAS_OGG
  98617. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98618. #endif
  98619. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98620. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98621. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98622. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98623. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98624. /***********************************************************************
  98625. *
  98626. * Private class data
  98627. *
  98628. ***********************************************************************/
  98629. typedef struct FLAC__StreamDecoderPrivate {
  98630. #if FLAC__HAS_OGG
  98631. FLAC__bool is_ogg;
  98632. #endif
  98633. FLAC__StreamDecoderReadCallback read_callback;
  98634. FLAC__StreamDecoderSeekCallback seek_callback;
  98635. FLAC__StreamDecoderTellCallback tell_callback;
  98636. FLAC__StreamDecoderLengthCallback length_callback;
  98637. FLAC__StreamDecoderEofCallback eof_callback;
  98638. FLAC__StreamDecoderWriteCallback write_callback;
  98639. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98640. FLAC__StreamDecoderErrorCallback error_callback;
  98641. /* generic 32-bit datapath: */
  98642. 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[]);
  98643. /* generic 64-bit datapath: */
  98644. 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[]);
  98645. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98646. 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[]);
  98647. /* 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: */
  98648. 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[]);
  98649. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98650. void *client_data;
  98651. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98652. FLAC__BitReader *input;
  98653. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98654. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98655. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98656. unsigned output_capacity, output_channels;
  98657. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98658. FLAC__uint64 samples_decoded;
  98659. FLAC__bool has_stream_info, has_seek_table;
  98660. FLAC__StreamMetadata stream_info;
  98661. FLAC__StreamMetadata seek_table;
  98662. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98663. FLAC__byte *metadata_filter_ids;
  98664. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98665. FLAC__Frame frame;
  98666. FLAC__bool cached; /* true if there is a byte in lookahead */
  98667. FLAC__CPUInfo cpuinfo;
  98668. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98669. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98670. /* unaligned (original) pointers to allocated data */
  98671. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98672. 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 */
  98673. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98674. FLAC__bool is_seeking;
  98675. FLAC__MD5Context md5context;
  98676. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98677. /* (the rest of these are only used for seeking) */
  98678. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98679. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98680. FLAC__uint64 target_sample;
  98681. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98682. #if FLAC__HAS_OGG
  98683. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98684. #endif
  98685. } FLAC__StreamDecoderPrivate;
  98686. /***********************************************************************
  98687. *
  98688. * Public static class data
  98689. *
  98690. ***********************************************************************/
  98691. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98692. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98693. "FLAC__STREAM_DECODER_READ_METADATA",
  98694. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98695. "FLAC__STREAM_DECODER_READ_FRAME",
  98696. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98697. "FLAC__STREAM_DECODER_OGG_ERROR",
  98698. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98699. "FLAC__STREAM_DECODER_ABORTED",
  98700. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98701. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98702. };
  98703. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98704. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98705. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98706. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98707. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98708. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98709. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98710. };
  98711. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98712. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98713. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98714. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98715. };
  98716. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98717. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98718. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98719. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98720. };
  98721. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98722. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98723. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98724. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98725. };
  98726. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98727. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98728. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98729. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98730. };
  98731. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98732. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98733. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98734. };
  98735. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98736. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98737. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98738. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98739. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98740. };
  98741. /***********************************************************************
  98742. *
  98743. * Class constructor/destructor
  98744. *
  98745. ***********************************************************************/
  98746. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98747. {
  98748. FLAC__StreamDecoder *decoder;
  98749. unsigned i;
  98750. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98751. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98752. if(decoder == 0) {
  98753. return 0;
  98754. }
  98755. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98756. if(decoder->protected_ == 0) {
  98757. free(decoder);
  98758. return 0;
  98759. }
  98760. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98761. if(decoder->private_ == 0) {
  98762. free(decoder->protected_);
  98763. free(decoder);
  98764. return 0;
  98765. }
  98766. decoder->private_->input = FLAC__bitreader_new();
  98767. if(decoder->private_->input == 0) {
  98768. free(decoder->private_);
  98769. free(decoder->protected_);
  98770. free(decoder);
  98771. return 0;
  98772. }
  98773. decoder->private_->metadata_filter_ids_capacity = 16;
  98774. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98775. FLAC__bitreader_delete(decoder->private_->input);
  98776. free(decoder->private_);
  98777. free(decoder->protected_);
  98778. free(decoder);
  98779. return 0;
  98780. }
  98781. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98782. decoder->private_->output[i] = 0;
  98783. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98784. }
  98785. decoder->private_->output_capacity = 0;
  98786. decoder->private_->output_channels = 0;
  98787. decoder->private_->has_seek_table = false;
  98788. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98789. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98790. decoder->private_->file = 0;
  98791. set_defaults_dec(decoder);
  98792. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98793. return decoder;
  98794. }
  98795. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98796. {
  98797. unsigned i;
  98798. FLAC__ASSERT(0 != decoder);
  98799. FLAC__ASSERT(0 != decoder->protected_);
  98800. FLAC__ASSERT(0 != decoder->private_);
  98801. FLAC__ASSERT(0 != decoder->private_->input);
  98802. (void)FLAC__stream_decoder_finish(decoder);
  98803. if(0 != decoder->private_->metadata_filter_ids)
  98804. free(decoder->private_->metadata_filter_ids);
  98805. FLAC__bitreader_delete(decoder->private_->input);
  98806. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98807. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98808. free(decoder->private_);
  98809. free(decoder->protected_);
  98810. free(decoder);
  98811. }
  98812. /***********************************************************************
  98813. *
  98814. * Public class methods
  98815. *
  98816. ***********************************************************************/
  98817. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98818. FLAC__StreamDecoder *decoder,
  98819. FLAC__StreamDecoderReadCallback read_callback,
  98820. FLAC__StreamDecoderSeekCallback seek_callback,
  98821. FLAC__StreamDecoderTellCallback tell_callback,
  98822. FLAC__StreamDecoderLengthCallback length_callback,
  98823. FLAC__StreamDecoderEofCallback eof_callback,
  98824. FLAC__StreamDecoderWriteCallback write_callback,
  98825. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98826. FLAC__StreamDecoderErrorCallback error_callback,
  98827. void *client_data,
  98828. FLAC__bool is_ogg
  98829. )
  98830. {
  98831. FLAC__ASSERT(0 != decoder);
  98832. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98833. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98834. #if !FLAC__HAS_OGG
  98835. if(is_ogg)
  98836. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98837. #endif
  98838. if(
  98839. 0 == read_callback ||
  98840. 0 == write_callback ||
  98841. 0 == error_callback ||
  98842. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98843. )
  98844. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98845. #if FLAC__HAS_OGG
  98846. decoder->private_->is_ogg = is_ogg;
  98847. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98848. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98849. #endif
  98850. /*
  98851. * get the CPU info and set the function pointers
  98852. */
  98853. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98854. /* first default to the non-asm routines */
  98855. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98856. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98857. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98858. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98859. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98860. /* now override with asm where appropriate */
  98861. #ifndef FLAC__NO_ASM
  98862. if(decoder->private_->cpuinfo.use_asm) {
  98863. #ifdef FLAC__CPU_IA32
  98864. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98865. #ifdef FLAC__HAS_NASM
  98866. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98867. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98868. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98869. #endif
  98870. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98871. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98872. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98873. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98874. }
  98875. else {
  98876. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98877. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98878. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98879. }
  98880. #endif
  98881. #elif defined FLAC__CPU_PPC
  98882. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98883. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98884. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98885. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98886. }
  98887. #endif
  98888. }
  98889. #endif
  98890. /* from here on, errors are fatal */
  98891. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98892. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98893. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98894. }
  98895. decoder->private_->read_callback = read_callback;
  98896. decoder->private_->seek_callback = seek_callback;
  98897. decoder->private_->tell_callback = tell_callback;
  98898. decoder->private_->length_callback = length_callback;
  98899. decoder->private_->eof_callback = eof_callback;
  98900. decoder->private_->write_callback = write_callback;
  98901. decoder->private_->metadata_callback = metadata_callback;
  98902. decoder->private_->error_callback = error_callback;
  98903. decoder->private_->client_data = client_data;
  98904. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98905. decoder->private_->samples_decoded = 0;
  98906. decoder->private_->has_stream_info = false;
  98907. decoder->private_->cached = false;
  98908. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98909. decoder->private_->is_seeking = false;
  98910. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98911. if(!FLAC__stream_decoder_reset(decoder)) {
  98912. /* above call sets the state for us */
  98913. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98914. }
  98915. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98916. }
  98917. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98918. FLAC__StreamDecoder *decoder,
  98919. FLAC__StreamDecoderReadCallback read_callback,
  98920. FLAC__StreamDecoderSeekCallback seek_callback,
  98921. FLAC__StreamDecoderTellCallback tell_callback,
  98922. FLAC__StreamDecoderLengthCallback length_callback,
  98923. FLAC__StreamDecoderEofCallback eof_callback,
  98924. FLAC__StreamDecoderWriteCallback write_callback,
  98925. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98926. FLAC__StreamDecoderErrorCallback error_callback,
  98927. void *client_data
  98928. )
  98929. {
  98930. return init_stream_internal_dec(
  98931. decoder,
  98932. read_callback,
  98933. seek_callback,
  98934. tell_callback,
  98935. length_callback,
  98936. eof_callback,
  98937. write_callback,
  98938. metadata_callback,
  98939. error_callback,
  98940. client_data,
  98941. /*is_ogg=*/false
  98942. );
  98943. }
  98944. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98945. FLAC__StreamDecoder *decoder,
  98946. FLAC__StreamDecoderReadCallback read_callback,
  98947. FLAC__StreamDecoderSeekCallback seek_callback,
  98948. FLAC__StreamDecoderTellCallback tell_callback,
  98949. FLAC__StreamDecoderLengthCallback length_callback,
  98950. FLAC__StreamDecoderEofCallback eof_callback,
  98951. FLAC__StreamDecoderWriteCallback write_callback,
  98952. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98953. FLAC__StreamDecoderErrorCallback error_callback,
  98954. void *client_data
  98955. )
  98956. {
  98957. return init_stream_internal_dec(
  98958. decoder,
  98959. read_callback,
  98960. seek_callback,
  98961. tell_callback,
  98962. length_callback,
  98963. eof_callback,
  98964. write_callback,
  98965. metadata_callback,
  98966. error_callback,
  98967. client_data,
  98968. /*is_ogg=*/true
  98969. );
  98970. }
  98971. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98972. FLAC__StreamDecoder *decoder,
  98973. FILE *file,
  98974. FLAC__StreamDecoderWriteCallback write_callback,
  98975. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98976. FLAC__StreamDecoderErrorCallback error_callback,
  98977. void *client_data,
  98978. FLAC__bool is_ogg
  98979. )
  98980. {
  98981. FLAC__ASSERT(0 != decoder);
  98982. FLAC__ASSERT(0 != file);
  98983. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98984. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98985. if(0 == write_callback || 0 == error_callback)
  98986. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98987. /*
  98988. * To make sure that our file does not go unclosed after an error, we
  98989. * must assign the FILE pointer before any further error can occur in
  98990. * this routine.
  98991. */
  98992. if(file == stdin)
  98993. file = get_binary_stdin_(); /* just to be safe */
  98994. decoder->private_->file = file;
  98995. return init_stream_internal_dec(
  98996. decoder,
  98997. file_read_callback_dec,
  98998. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98999. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99000. decoder->private_->file == stdin? 0: file_length_callback_,
  99001. file_eof_callback_,
  99002. write_callback,
  99003. metadata_callback,
  99004. error_callback,
  99005. client_data,
  99006. is_ogg
  99007. );
  99008. }
  99009. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99010. FLAC__StreamDecoder *decoder,
  99011. FILE *file,
  99012. FLAC__StreamDecoderWriteCallback write_callback,
  99013. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99014. FLAC__StreamDecoderErrorCallback error_callback,
  99015. void *client_data
  99016. )
  99017. {
  99018. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99019. }
  99020. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99021. FLAC__StreamDecoder *decoder,
  99022. FILE *file,
  99023. FLAC__StreamDecoderWriteCallback write_callback,
  99024. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99025. FLAC__StreamDecoderErrorCallback error_callback,
  99026. void *client_data
  99027. )
  99028. {
  99029. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99030. }
  99031. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99032. FLAC__StreamDecoder *decoder,
  99033. const char *filename,
  99034. FLAC__StreamDecoderWriteCallback write_callback,
  99035. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99036. FLAC__StreamDecoderErrorCallback error_callback,
  99037. void *client_data,
  99038. FLAC__bool is_ogg
  99039. )
  99040. {
  99041. FILE *file;
  99042. FLAC__ASSERT(0 != decoder);
  99043. /*
  99044. * To make sure that our file does not go unclosed after an error, we
  99045. * have to do the same entrance checks here that are later performed
  99046. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99047. */
  99048. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99049. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99050. if(0 == write_callback || 0 == error_callback)
  99051. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99052. file = filename? fopen(filename, "rb") : stdin;
  99053. if(0 == file)
  99054. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99055. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99056. }
  99057. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99058. FLAC__StreamDecoder *decoder,
  99059. const char *filename,
  99060. FLAC__StreamDecoderWriteCallback write_callback,
  99061. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99062. FLAC__StreamDecoderErrorCallback error_callback,
  99063. void *client_data
  99064. )
  99065. {
  99066. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99067. }
  99068. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99069. FLAC__StreamDecoder *decoder,
  99070. const char *filename,
  99071. FLAC__StreamDecoderWriteCallback write_callback,
  99072. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99073. FLAC__StreamDecoderErrorCallback error_callback,
  99074. void *client_data
  99075. )
  99076. {
  99077. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99078. }
  99079. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99080. {
  99081. FLAC__bool md5_failed = false;
  99082. unsigned i;
  99083. FLAC__ASSERT(0 != decoder);
  99084. FLAC__ASSERT(0 != decoder->private_);
  99085. FLAC__ASSERT(0 != decoder->protected_);
  99086. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99087. return true;
  99088. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99089. * always call FLAC__MD5Final()
  99090. */
  99091. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99092. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99093. free(decoder->private_->seek_table.data.seek_table.points);
  99094. decoder->private_->seek_table.data.seek_table.points = 0;
  99095. decoder->private_->has_seek_table = false;
  99096. }
  99097. FLAC__bitreader_free(decoder->private_->input);
  99098. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99099. /* WATCHOUT:
  99100. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99101. * output arrays have a buffer of up to 3 zeroes in front
  99102. * (at negative indices) for alignment purposes; we use 4
  99103. * to keep the data well-aligned.
  99104. */
  99105. if(0 != decoder->private_->output[i]) {
  99106. free(decoder->private_->output[i]-4);
  99107. decoder->private_->output[i] = 0;
  99108. }
  99109. if(0 != decoder->private_->residual_unaligned[i]) {
  99110. free(decoder->private_->residual_unaligned[i]);
  99111. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99112. }
  99113. }
  99114. decoder->private_->output_capacity = 0;
  99115. decoder->private_->output_channels = 0;
  99116. #if FLAC__HAS_OGG
  99117. if(decoder->private_->is_ogg)
  99118. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99119. #endif
  99120. if(0 != decoder->private_->file) {
  99121. if(decoder->private_->file != stdin)
  99122. fclose(decoder->private_->file);
  99123. decoder->private_->file = 0;
  99124. }
  99125. if(decoder->private_->do_md5_checking) {
  99126. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99127. md5_failed = true;
  99128. }
  99129. decoder->private_->is_seeking = false;
  99130. set_defaults_dec(decoder);
  99131. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99132. return !md5_failed;
  99133. }
  99134. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99135. {
  99136. FLAC__ASSERT(0 != decoder);
  99137. FLAC__ASSERT(0 != decoder->private_);
  99138. FLAC__ASSERT(0 != decoder->protected_);
  99139. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99140. return false;
  99141. #if FLAC__HAS_OGG
  99142. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99143. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99144. return true;
  99145. #else
  99146. (void)value;
  99147. return false;
  99148. #endif
  99149. }
  99150. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99151. {
  99152. FLAC__ASSERT(0 != decoder);
  99153. FLAC__ASSERT(0 != decoder->protected_);
  99154. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99155. return false;
  99156. decoder->protected_->md5_checking = value;
  99157. return true;
  99158. }
  99159. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99160. {
  99161. FLAC__ASSERT(0 != decoder);
  99162. FLAC__ASSERT(0 != decoder->private_);
  99163. FLAC__ASSERT(0 != decoder->protected_);
  99164. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99165. /* double protection */
  99166. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99167. return false;
  99168. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99169. return false;
  99170. decoder->private_->metadata_filter[type] = true;
  99171. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99172. decoder->private_->metadata_filter_ids_count = 0;
  99173. return true;
  99174. }
  99175. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99176. {
  99177. FLAC__ASSERT(0 != decoder);
  99178. FLAC__ASSERT(0 != decoder->private_);
  99179. FLAC__ASSERT(0 != decoder->protected_);
  99180. FLAC__ASSERT(0 != id);
  99181. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99182. return false;
  99183. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99184. return true;
  99185. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99186. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99187. 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))) {
  99188. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99189. return false;
  99190. }
  99191. decoder->private_->metadata_filter_ids_capacity *= 2;
  99192. }
  99193. 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));
  99194. decoder->private_->metadata_filter_ids_count++;
  99195. return true;
  99196. }
  99197. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99198. {
  99199. unsigned i;
  99200. FLAC__ASSERT(0 != decoder);
  99201. FLAC__ASSERT(0 != decoder->private_);
  99202. FLAC__ASSERT(0 != decoder->protected_);
  99203. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99204. return false;
  99205. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99206. decoder->private_->metadata_filter[i] = true;
  99207. decoder->private_->metadata_filter_ids_count = 0;
  99208. return true;
  99209. }
  99210. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99211. {
  99212. FLAC__ASSERT(0 != decoder);
  99213. FLAC__ASSERT(0 != decoder->private_);
  99214. FLAC__ASSERT(0 != decoder->protected_);
  99215. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99216. /* double protection */
  99217. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99218. return false;
  99219. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99220. return false;
  99221. decoder->private_->metadata_filter[type] = false;
  99222. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99223. decoder->private_->metadata_filter_ids_count = 0;
  99224. return true;
  99225. }
  99226. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99227. {
  99228. FLAC__ASSERT(0 != decoder);
  99229. FLAC__ASSERT(0 != decoder->private_);
  99230. FLAC__ASSERT(0 != decoder->protected_);
  99231. FLAC__ASSERT(0 != id);
  99232. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99233. return false;
  99234. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99235. return true;
  99236. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99237. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99238. 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))) {
  99239. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99240. return false;
  99241. }
  99242. decoder->private_->metadata_filter_ids_capacity *= 2;
  99243. }
  99244. 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));
  99245. decoder->private_->metadata_filter_ids_count++;
  99246. return true;
  99247. }
  99248. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99249. {
  99250. FLAC__ASSERT(0 != decoder);
  99251. FLAC__ASSERT(0 != decoder->private_);
  99252. FLAC__ASSERT(0 != decoder->protected_);
  99253. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99254. return false;
  99255. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99256. decoder->private_->metadata_filter_ids_count = 0;
  99257. return true;
  99258. }
  99259. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99260. {
  99261. FLAC__ASSERT(0 != decoder);
  99262. FLAC__ASSERT(0 != decoder->protected_);
  99263. return decoder->protected_->state;
  99264. }
  99265. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99266. {
  99267. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99268. }
  99269. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99270. {
  99271. FLAC__ASSERT(0 != decoder);
  99272. FLAC__ASSERT(0 != decoder->protected_);
  99273. return decoder->protected_->md5_checking;
  99274. }
  99275. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99276. {
  99277. FLAC__ASSERT(0 != decoder);
  99278. FLAC__ASSERT(0 != decoder->protected_);
  99279. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99280. }
  99281. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99282. {
  99283. FLAC__ASSERT(0 != decoder);
  99284. FLAC__ASSERT(0 != decoder->protected_);
  99285. return decoder->protected_->channels;
  99286. }
  99287. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99288. {
  99289. FLAC__ASSERT(0 != decoder);
  99290. FLAC__ASSERT(0 != decoder->protected_);
  99291. return decoder->protected_->channel_assignment;
  99292. }
  99293. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99294. {
  99295. FLAC__ASSERT(0 != decoder);
  99296. FLAC__ASSERT(0 != decoder->protected_);
  99297. return decoder->protected_->bits_per_sample;
  99298. }
  99299. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99300. {
  99301. FLAC__ASSERT(0 != decoder);
  99302. FLAC__ASSERT(0 != decoder->protected_);
  99303. return decoder->protected_->sample_rate;
  99304. }
  99305. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99306. {
  99307. FLAC__ASSERT(0 != decoder);
  99308. FLAC__ASSERT(0 != decoder->protected_);
  99309. return decoder->protected_->blocksize;
  99310. }
  99311. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99312. {
  99313. FLAC__ASSERT(0 != decoder);
  99314. FLAC__ASSERT(0 != decoder->private_);
  99315. FLAC__ASSERT(0 != position);
  99316. #if FLAC__HAS_OGG
  99317. if(decoder->private_->is_ogg)
  99318. return false;
  99319. #endif
  99320. if(0 == decoder->private_->tell_callback)
  99321. return false;
  99322. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99323. return false;
  99324. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99325. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99326. return false;
  99327. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99328. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99329. return true;
  99330. }
  99331. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99332. {
  99333. FLAC__ASSERT(0 != decoder);
  99334. FLAC__ASSERT(0 != decoder->private_);
  99335. FLAC__ASSERT(0 != decoder->protected_);
  99336. decoder->private_->samples_decoded = 0;
  99337. decoder->private_->do_md5_checking = false;
  99338. #if FLAC__HAS_OGG
  99339. if(decoder->private_->is_ogg)
  99340. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99341. #endif
  99342. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99343. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99344. return false;
  99345. }
  99346. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99347. return true;
  99348. }
  99349. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99350. {
  99351. FLAC__ASSERT(0 != decoder);
  99352. FLAC__ASSERT(0 != decoder->private_);
  99353. FLAC__ASSERT(0 != decoder->protected_);
  99354. if(!FLAC__stream_decoder_flush(decoder)) {
  99355. /* above call sets the state for us */
  99356. return false;
  99357. }
  99358. #if FLAC__HAS_OGG
  99359. /*@@@ could go in !internal_reset_hack block below */
  99360. if(decoder->private_->is_ogg)
  99361. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99362. #endif
  99363. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99364. * (internal_reset_hack) don't try to rewind since we are already at
  99365. * the beginning of the stream and don't want to fail if the input is
  99366. * not seekable.
  99367. */
  99368. if(!decoder->private_->internal_reset_hack) {
  99369. if(decoder->private_->file == stdin)
  99370. return false; /* can't rewind stdin, reset fails */
  99371. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99372. return false; /* seekable and seek fails, reset fails */
  99373. }
  99374. else
  99375. decoder->private_->internal_reset_hack = false;
  99376. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99377. decoder->private_->has_stream_info = false;
  99378. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99379. free(decoder->private_->seek_table.data.seek_table.points);
  99380. decoder->private_->seek_table.data.seek_table.points = 0;
  99381. decoder->private_->has_seek_table = false;
  99382. }
  99383. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99384. /*
  99385. * This goes in reset() and not flush() because according to the spec, a
  99386. * fixed-blocksize stream must stay that way through the whole stream.
  99387. */
  99388. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99389. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99390. * is because md5 checking may be turned on to start and then turned off if
  99391. * a seek occurs. So we init the context here and finalize it in
  99392. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99393. * properly.
  99394. */
  99395. FLAC__MD5Init(&decoder->private_->md5context);
  99396. decoder->private_->first_frame_offset = 0;
  99397. decoder->private_->unparseable_frame_count = 0;
  99398. return true;
  99399. }
  99400. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99401. {
  99402. FLAC__bool got_a_frame;
  99403. FLAC__ASSERT(0 != decoder);
  99404. FLAC__ASSERT(0 != decoder->protected_);
  99405. while(1) {
  99406. switch(decoder->protected_->state) {
  99407. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99408. if(!find_metadata_(decoder))
  99409. return false; /* above function sets the status for us */
  99410. break;
  99411. case FLAC__STREAM_DECODER_READ_METADATA:
  99412. if(!read_metadata_(decoder))
  99413. return false; /* above function sets the status for us */
  99414. else
  99415. return true;
  99416. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99417. if(!frame_sync_(decoder))
  99418. return true; /* above function sets the status for us */
  99419. break;
  99420. case FLAC__STREAM_DECODER_READ_FRAME:
  99421. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99422. return false; /* above function sets the status for us */
  99423. if(got_a_frame)
  99424. return true; /* above function sets the status for us */
  99425. break;
  99426. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99427. case FLAC__STREAM_DECODER_ABORTED:
  99428. return true;
  99429. default:
  99430. FLAC__ASSERT(0);
  99431. return false;
  99432. }
  99433. }
  99434. }
  99435. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99436. {
  99437. FLAC__ASSERT(0 != decoder);
  99438. FLAC__ASSERT(0 != decoder->protected_);
  99439. while(1) {
  99440. switch(decoder->protected_->state) {
  99441. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99442. if(!find_metadata_(decoder))
  99443. return false; /* above function sets the status for us */
  99444. break;
  99445. case FLAC__STREAM_DECODER_READ_METADATA:
  99446. if(!read_metadata_(decoder))
  99447. return false; /* above function sets the status for us */
  99448. break;
  99449. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99450. case FLAC__STREAM_DECODER_READ_FRAME:
  99451. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99452. case FLAC__STREAM_DECODER_ABORTED:
  99453. return true;
  99454. default:
  99455. FLAC__ASSERT(0);
  99456. return false;
  99457. }
  99458. }
  99459. }
  99460. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99461. {
  99462. FLAC__bool dummy;
  99463. FLAC__ASSERT(0 != decoder);
  99464. FLAC__ASSERT(0 != decoder->protected_);
  99465. while(1) {
  99466. switch(decoder->protected_->state) {
  99467. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99468. if(!find_metadata_(decoder))
  99469. return false; /* above function sets the status for us */
  99470. break;
  99471. case FLAC__STREAM_DECODER_READ_METADATA:
  99472. if(!read_metadata_(decoder))
  99473. return false; /* above function sets the status for us */
  99474. break;
  99475. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99476. if(!frame_sync_(decoder))
  99477. return true; /* above function sets the status for us */
  99478. break;
  99479. case FLAC__STREAM_DECODER_READ_FRAME:
  99480. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99481. return false; /* above function sets the status for us */
  99482. break;
  99483. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99484. case FLAC__STREAM_DECODER_ABORTED:
  99485. return true;
  99486. default:
  99487. FLAC__ASSERT(0);
  99488. return false;
  99489. }
  99490. }
  99491. }
  99492. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99493. {
  99494. FLAC__bool got_a_frame;
  99495. FLAC__ASSERT(0 != decoder);
  99496. FLAC__ASSERT(0 != decoder->protected_);
  99497. while(1) {
  99498. switch(decoder->protected_->state) {
  99499. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99500. case FLAC__STREAM_DECODER_READ_METADATA:
  99501. return false; /* above function sets the status for us */
  99502. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99503. if(!frame_sync_(decoder))
  99504. return true; /* above function sets the status for us */
  99505. break;
  99506. case FLAC__STREAM_DECODER_READ_FRAME:
  99507. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99508. return false; /* above function sets the status for us */
  99509. if(got_a_frame)
  99510. return true; /* above function sets the status for us */
  99511. break;
  99512. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99513. case FLAC__STREAM_DECODER_ABORTED:
  99514. return true;
  99515. default:
  99516. FLAC__ASSERT(0);
  99517. return false;
  99518. }
  99519. }
  99520. }
  99521. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99522. {
  99523. FLAC__uint64 length;
  99524. FLAC__ASSERT(0 != decoder);
  99525. if(
  99526. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99527. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99528. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99529. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99530. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99531. )
  99532. return false;
  99533. if(0 == decoder->private_->seek_callback)
  99534. return false;
  99535. FLAC__ASSERT(decoder->private_->seek_callback);
  99536. FLAC__ASSERT(decoder->private_->tell_callback);
  99537. FLAC__ASSERT(decoder->private_->length_callback);
  99538. FLAC__ASSERT(decoder->private_->eof_callback);
  99539. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99540. return false;
  99541. decoder->private_->is_seeking = true;
  99542. /* turn off md5 checking if a seek is attempted */
  99543. decoder->private_->do_md5_checking = false;
  99544. /* 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) */
  99545. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99546. decoder->private_->is_seeking = false;
  99547. return false;
  99548. }
  99549. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99550. if(
  99551. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99552. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99553. ) {
  99554. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99555. /* above call sets the state for us */
  99556. decoder->private_->is_seeking = false;
  99557. return false;
  99558. }
  99559. /* check this again in case we didn't know total_samples the first time */
  99560. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99561. decoder->private_->is_seeking = false;
  99562. return false;
  99563. }
  99564. }
  99565. {
  99566. const FLAC__bool ok =
  99567. #if FLAC__HAS_OGG
  99568. decoder->private_->is_ogg?
  99569. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99570. #endif
  99571. seek_to_absolute_sample_(decoder, length, sample)
  99572. ;
  99573. decoder->private_->is_seeking = false;
  99574. return ok;
  99575. }
  99576. }
  99577. /***********************************************************************
  99578. *
  99579. * Protected class methods
  99580. *
  99581. ***********************************************************************/
  99582. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99583. {
  99584. FLAC__ASSERT(0 != decoder);
  99585. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99586. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99587. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99588. }
  99589. /***********************************************************************
  99590. *
  99591. * Private class methods
  99592. *
  99593. ***********************************************************************/
  99594. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99595. {
  99596. #if FLAC__HAS_OGG
  99597. decoder->private_->is_ogg = false;
  99598. #endif
  99599. decoder->private_->read_callback = 0;
  99600. decoder->private_->seek_callback = 0;
  99601. decoder->private_->tell_callback = 0;
  99602. decoder->private_->length_callback = 0;
  99603. decoder->private_->eof_callback = 0;
  99604. decoder->private_->write_callback = 0;
  99605. decoder->private_->metadata_callback = 0;
  99606. decoder->private_->error_callback = 0;
  99607. decoder->private_->client_data = 0;
  99608. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99609. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99610. decoder->private_->metadata_filter_ids_count = 0;
  99611. decoder->protected_->md5_checking = false;
  99612. #if FLAC__HAS_OGG
  99613. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99614. #endif
  99615. }
  99616. /*
  99617. * This will forcibly set stdin to binary mode (for OSes that require it)
  99618. */
  99619. FILE *get_binary_stdin_(void)
  99620. {
  99621. /* if something breaks here it is probably due to the presence or
  99622. * absence of an underscore before the identifiers 'setmode',
  99623. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99624. */
  99625. #if defined _MSC_VER || defined __MINGW32__
  99626. _setmode(_fileno(stdin), _O_BINARY);
  99627. #elif defined __CYGWIN__
  99628. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99629. setmode(_fileno(stdin), _O_BINARY);
  99630. #elif defined __EMX__
  99631. setmode(fileno(stdin), O_BINARY);
  99632. #endif
  99633. return stdin;
  99634. }
  99635. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99636. {
  99637. unsigned i;
  99638. FLAC__int32 *tmp;
  99639. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99640. return true;
  99641. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99642. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99643. if(0 != decoder->private_->output[i]) {
  99644. free(decoder->private_->output[i]-4);
  99645. decoder->private_->output[i] = 0;
  99646. }
  99647. if(0 != decoder->private_->residual_unaligned[i]) {
  99648. free(decoder->private_->residual_unaligned[i]);
  99649. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99650. }
  99651. }
  99652. for(i = 0; i < channels; i++) {
  99653. /* WATCHOUT:
  99654. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99655. * output arrays have a buffer of up to 3 zeroes in front
  99656. * (at negative indices) for alignment purposes; we use 4
  99657. * to keep the data well-aligned.
  99658. */
  99659. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99660. if(tmp == 0) {
  99661. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99662. return false;
  99663. }
  99664. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99665. decoder->private_->output[i] = tmp + 4;
  99666. /* WATCHOUT:
  99667. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99668. */
  99669. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99670. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99671. return false;
  99672. }
  99673. }
  99674. decoder->private_->output_capacity = size;
  99675. decoder->private_->output_channels = channels;
  99676. return true;
  99677. }
  99678. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99679. {
  99680. size_t i;
  99681. FLAC__ASSERT(0 != decoder);
  99682. FLAC__ASSERT(0 != decoder->private_);
  99683. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99684. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99685. return true;
  99686. return false;
  99687. }
  99688. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99689. {
  99690. FLAC__uint32 x;
  99691. unsigned i, id_;
  99692. FLAC__bool first = true;
  99693. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99694. for(i = id_ = 0; i < 4; ) {
  99695. if(decoder->private_->cached) {
  99696. x = (FLAC__uint32)decoder->private_->lookahead;
  99697. decoder->private_->cached = false;
  99698. }
  99699. else {
  99700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99701. return false; /* read_callback_ sets the state for us */
  99702. }
  99703. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99704. first = true;
  99705. i++;
  99706. id_ = 0;
  99707. continue;
  99708. }
  99709. if(x == ID3V2_TAG_[id_]) {
  99710. id_++;
  99711. i = 0;
  99712. if(id_ == 3) {
  99713. if(!skip_id3v2_tag_(decoder))
  99714. return false; /* skip_id3v2_tag_ sets the state for us */
  99715. }
  99716. continue;
  99717. }
  99718. id_ = 0;
  99719. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99720. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99722. return false; /* read_callback_ sets the state for us */
  99723. /* 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 */
  99724. /* else we have to check if the second byte is the end of a sync code */
  99725. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99726. decoder->private_->lookahead = (FLAC__byte)x;
  99727. decoder->private_->cached = true;
  99728. }
  99729. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99730. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99731. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99732. return true;
  99733. }
  99734. }
  99735. i = 0;
  99736. if(first) {
  99737. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99738. first = false;
  99739. }
  99740. }
  99741. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99742. return true;
  99743. }
  99744. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99745. {
  99746. FLAC__bool is_last;
  99747. FLAC__uint32 i, x, type, length;
  99748. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99749. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99750. return false; /* read_callback_ sets the state for us */
  99751. is_last = x? true : false;
  99752. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99753. return false; /* read_callback_ sets the state for us */
  99754. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99755. return false; /* read_callback_ sets the state for us */
  99756. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99757. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99758. return false;
  99759. decoder->private_->has_stream_info = true;
  99760. 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))
  99761. decoder->private_->do_md5_checking = false;
  99762. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99763. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99764. }
  99765. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99766. if(!read_metadata_seektable_(decoder, is_last, length))
  99767. return false;
  99768. decoder->private_->has_seek_table = true;
  99769. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99770. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99771. }
  99772. else {
  99773. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99774. unsigned real_length = length;
  99775. FLAC__StreamMetadata block;
  99776. block.is_last = is_last;
  99777. block.type = (FLAC__MetadataType)type;
  99778. block.length = length;
  99779. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99780. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99781. return false; /* read_callback_ sets the state for us */
  99782. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99783. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99784. return false;
  99785. }
  99786. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99787. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99788. skip_it = !skip_it;
  99789. }
  99790. if(skip_it) {
  99791. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99792. return false; /* read_callback_ sets the state for us */
  99793. }
  99794. else {
  99795. switch(type) {
  99796. case FLAC__METADATA_TYPE_PADDING:
  99797. /* skip the padding bytes */
  99798. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99799. return false; /* read_callback_ sets the state for us */
  99800. break;
  99801. case FLAC__METADATA_TYPE_APPLICATION:
  99802. /* remember, we read the ID already */
  99803. if(real_length > 0) {
  99804. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99805. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99806. return false;
  99807. }
  99808. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99809. return false; /* read_callback_ sets the state for us */
  99810. }
  99811. else
  99812. block.data.application.data = 0;
  99813. break;
  99814. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99815. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99816. return false;
  99817. break;
  99818. case FLAC__METADATA_TYPE_CUESHEET:
  99819. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99820. return false;
  99821. break;
  99822. case FLAC__METADATA_TYPE_PICTURE:
  99823. if(!read_metadata_picture_(decoder, &block.data.picture))
  99824. return false;
  99825. break;
  99826. case FLAC__METADATA_TYPE_STREAMINFO:
  99827. case FLAC__METADATA_TYPE_SEEKTABLE:
  99828. FLAC__ASSERT(0);
  99829. break;
  99830. default:
  99831. if(real_length > 0) {
  99832. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99833. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99834. return false;
  99835. }
  99836. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99837. return false; /* read_callback_ sets the state for us */
  99838. }
  99839. else
  99840. block.data.unknown.data = 0;
  99841. break;
  99842. }
  99843. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99844. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99845. /* now we have to free any malloc()ed data in the block */
  99846. switch(type) {
  99847. case FLAC__METADATA_TYPE_PADDING:
  99848. break;
  99849. case FLAC__METADATA_TYPE_APPLICATION:
  99850. if(0 != block.data.application.data)
  99851. free(block.data.application.data);
  99852. break;
  99853. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99854. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99855. free(block.data.vorbis_comment.vendor_string.entry);
  99856. if(block.data.vorbis_comment.num_comments > 0)
  99857. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99858. if(0 != block.data.vorbis_comment.comments[i].entry)
  99859. free(block.data.vorbis_comment.comments[i].entry);
  99860. if(0 != block.data.vorbis_comment.comments)
  99861. free(block.data.vorbis_comment.comments);
  99862. break;
  99863. case FLAC__METADATA_TYPE_CUESHEET:
  99864. if(block.data.cue_sheet.num_tracks > 0)
  99865. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99866. if(0 != block.data.cue_sheet.tracks[i].indices)
  99867. free(block.data.cue_sheet.tracks[i].indices);
  99868. if(0 != block.data.cue_sheet.tracks)
  99869. free(block.data.cue_sheet.tracks);
  99870. break;
  99871. case FLAC__METADATA_TYPE_PICTURE:
  99872. if(0 != block.data.picture.mime_type)
  99873. free(block.data.picture.mime_type);
  99874. if(0 != block.data.picture.description)
  99875. free(block.data.picture.description);
  99876. if(0 != block.data.picture.data)
  99877. free(block.data.picture.data);
  99878. break;
  99879. case FLAC__METADATA_TYPE_STREAMINFO:
  99880. case FLAC__METADATA_TYPE_SEEKTABLE:
  99881. FLAC__ASSERT(0);
  99882. default:
  99883. if(0 != block.data.unknown.data)
  99884. free(block.data.unknown.data);
  99885. break;
  99886. }
  99887. }
  99888. }
  99889. if(is_last) {
  99890. /* if this fails, it's OK, it's just a hint for the seek routine */
  99891. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99892. decoder->private_->first_frame_offset = 0;
  99893. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99894. }
  99895. return true;
  99896. }
  99897. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99898. {
  99899. FLAC__uint32 x;
  99900. unsigned bits, used_bits = 0;
  99901. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99902. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99903. decoder->private_->stream_info.is_last = is_last;
  99904. decoder->private_->stream_info.length = length;
  99905. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99906. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99907. return false; /* read_callback_ sets the state for us */
  99908. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99909. used_bits += bits;
  99910. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99911. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99912. return false; /* read_callback_ sets the state for us */
  99913. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99914. used_bits += bits;
  99915. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99916. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99917. return false; /* read_callback_ sets the state for us */
  99918. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99919. used_bits += bits;
  99920. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99921. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99922. return false; /* read_callback_ sets the state for us */
  99923. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99924. used_bits += bits;
  99925. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99926. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99927. return false; /* read_callback_ sets the state for us */
  99928. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99929. used_bits += bits;
  99930. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99931. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99932. return false; /* read_callback_ sets the state for us */
  99933. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99934. used_bits += bits;
  99935. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99936. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99937. return false; /* read_callback_ sets the state for us */
  99938. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99939. used_bits += bits;
  99940. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99941. 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))
  99942. return false; /* read_callback_ sets the state for us */
  99943. used_bits += bits;
  99944. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99945. return false; /* read_callback_ sets the state for us */
  99946. used_bits += 16*8;
  99947. /* skip the rest of the block */
  99948. FLAC__ASSERT(used_bits % 8 == 0);
  99949. length -= (used_bits / 8);
  99950. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99951. return false; /* read_callback_ sets the state for us */
  99952. return true;
  99953. }
  99954. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99955. {
  99956. FLAC__uint32 i, x;
  99957. FLAC__uint64 xx;
  99958. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99959. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99960. decoder->private_->seek_table.is_last = is_last;
  99961. decoder->private_->seek_table.length = length;
  99962. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99963. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99964. 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)))) {
  99965. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99966. return false;
  99967. }
  99968. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99969. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99970. return false; /* read_callback_ sets the state for us */
  99971. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99972. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99973. return false; /* read_callback_ sets the state for us */
  99974. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99975. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99976. return false; /* read_callback_ sets the state for us */
  99977. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99978. }
  99979. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99980. /* if there is a partial point left, skip over it */
  99981. if(length > 0) {
  99982. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99983. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99984. return false; /* read_callback_ sets the state for us */
  99985. }
  99986. return true;
  99987. }
  99988. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99989. {
  99990. FLAC__uint32 i;
  99991. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99992. /* read vendor string */
  99993. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99994. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99995. return false; /* read_callback_ sets the state for us */
  99996. if(obj->vendor_string.length > 0) {
  99997. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99998. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99999. return false;
  100000. }
  100001. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100002. return false; /* read_callback_ sets the state for us */
  100003. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100004. }
  100005. else
  100006. obj->vendor_string.entry = 0;
  100007. /* read num comments */
  100008. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100009. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100010. return false; /* read_callback_ sets the state for us */
  100011. /* read comments */
  100012. if(obj->num_comments > 0) {
  100013. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100014. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100015. return false;
  100016. }
  100017. for(i = 0; i < obj->num_comments; i++) {
  100018. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100019. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100020. return false; /* read_callback_ sets the state for us */
  100021. if(obj->comments[i].length > 0) {
  100022. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100023. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100024. return false;
  100025. }
  100026. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100027. return false; /* read_callback_ sets the state for us */
  100028. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100029. }
  100030. else
  100031. obj->comments[i].entry = 0;
  100032. }
  100033. }
  100034. else {
  100035. obj->comments = 0;
  100036. }
  100037. return true;
  100038. }
  100039. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100040. {
  100041. FLAC__uint32 i, j, x;
  100042. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100043. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100044. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100045. 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))
  100046. return false; /* read_callback_ sets the state for us */
  100047. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100048. return false; /* read_callback_ sets the state for us */
  100049. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100050. return false; /* read_callback_ sets the state for us */
  100051. obj->is_cd = x? true : false;
  100052. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100053. return false; /* read_callback_ sets the state for us */
  100054. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100055. return false; /* read_callback_ sets the state for us */
  100056. obj->num_tracks = x;
  100057. if(obj->num_tracks > 0) {
  100058. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100059. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100060. return false;
  100061. }
  100062. for(i = 0; i < obj->num_tracks; i++) {
  100063. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100064. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100065. return false; /* read_callback_ sets the state for us */
  100066. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100067. return false; /* read_callback_ sets the state for us */
  100068. track->number = (FLAC__byte)x;
  100069. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100070. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100071. return false; /* read_callback_ sets the state for us */
  100072. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100073. return false; /* read_callback_ sets the state for us */
  100074. track->type = x;
  100075. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100076. return false; /* read_callback_ sets the state for us */
  100077. track->pre_emphasis = x;
  100078. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100079. return false; /* read_callback_ sets the state for us */
  100080. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100081. return false; /* read_callback_ sets the state for us */
  100082. track->num_indices = (FLAC__byte)x;
  100083. if(track->num_indices > 0) {
  100084. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100085. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100086. return false;
  100087. }
  100088. for(j = 0; j < track->num_indices; j++) {
  100089. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100090. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100091. return false; /* read_callback_ sets the state for us */
  100092. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100093. return false; /* read_callback_ sets the state for us */
  100094. index->number = (FLAC__byte)x;
  100095. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100096. return false; /* read_callback_ sets the state for us */
  100097. }
  100098. }
  100099. }
  100100. }
  100101. return true;
  100102. }
  100103. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100104. {
  100105. FLAC__uint32 x;
  100106. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100107. /* read type */
  100108. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100109. return false; /* read_callback_ sets the state for us */
  100110. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100111. /* read MIME type */
  100112. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100113. return false; /* read_callback_ sets the state for us */
  100114. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100115. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100116. return false;
  100117. }
  100118. if(x > 0) {
  100119. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100120. return false; /* read_callback_ sets the state for us */
  100121. }
  100122. obj->mime_type[x] = '\0';
  100123. /* read description */
  100124. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100125. return false; /* read_callback_ sets the state for us */
  100126. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100127. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100128. return false;
  100129. }
  100130. if(x > 0) {
  100131. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100132. return false; /* read_callback_ sets the state for us */
  100133. }
  100134. obj->description[x] = '\0';
  100135. /* read width */
  100136. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100137. return false; /* read_callback_ sets the state for us */
  100138. /* read height */
  100139. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100140. return false; /* read_callback_ sets the state for us */
  100141. /* read depth */
  100142. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100143. return false; /* read_callback_ sets the state for us */
  100144. /* read colors */
  100145. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100146. return false; /* read_callback_ sets the state for us */
  100147. /* read data */
  100148. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100149. return false; /* read_callback_ sets the state for us */
  100150. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100151. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100152. return false;
  100153. }
  100154. if(obj->data_length > 0) {
  100155. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100156. return false; /* read_callback_ sets the state for us */
  100157. }
  100158. return true;
  100159. }
  100160. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100161. {
  100162. FLAC__uint32 x;
  100163. unsigned i, skip;
  100164. /* skip the version and flags bytes */
  100165. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100166. return false; /* read_callback_ sets the state for us */
  100167. /* get the size (in bytes) to skip */
  100168. skip = 0;
  100169. for(i = 0; i < 4; i++) {
  100170. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100171. return false; /* read_callback_ sets the state for us */
  100172. skip <<= 7;
  100173. skip |= (x & 0x7f);
  100174. }
  100175. /* skip the rest of the tag */
  100176. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100177. return false; /* read_callback_ sets the state for us */
  100178. return true;
  100179. }
  100180. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100181. {
  100182. FLAC__uint32 x;
  100183. FLAC__bool first = true;
  100184. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100185. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100186. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100187. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100188. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100189. return true;
  100190. }
  100191. }
  100192. /* make sure we're byte aligned */
  100193. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100194. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100195. return false; /* read_callback_ sets the state for us */
  100196. }
  100197. while(1) {
  100198. if(decoder->private_->cached) {
  100199. x = (FLAC__uint32)decoder->private_->lookahead;
  100200. decoder->private_->cached = false;
  100201. }
  100202. else {
  100203. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100204. return false; /* read_callback_ sets the state for us */
  100205. }
  100206. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100207. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100208. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100209. return false; /* read_callback_ sets the state for us */
  100210. /* 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 */
  100211. /* else we have to check if the second byte is the end of a sync code */
  100212. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100213. decoder->private_->lookahead = (FLAC__byte)x;
  100214. decoder->private_->cached = true;
  100215. }
  100216. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100217. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100218. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100219. return true;
  100220. }
  100221. }
  100222. if(first) {
  100223. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100224. first = false;
  100225. }
  100226. }
  100227. return true;
  100228. }
  100229. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100230. {
  100231. unsigned channel;
  100232. unsigned i;
  100233. FLAC__int32 mid, side;
  100234. unsigned frame_crc; /* the one we calculate from the input stream */
  100235. FLAC__uint32 x;
  100236. *got_a_frame = false;
  100237. /* init the CRC */
  100238. frame_crc = 0;
  100239. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100240. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100241. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100242. if(!read_frame_header_(decoder))
  100243. return false;
  100244. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100245. return true;
  100246. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100247. return false;
  100248. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100249. /*
  100250. * first figure the correct bits-per-sample of the subframe
  100251. */
  100252. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100253. switch(decoder->private_->frame.header.channel_assignment) {
  100254. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100255. /* no adjustment needed */
  100256. break;
  100257. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100258. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100259. if(channel == 1)
  100260. bps++;
  100261. break;
  100262. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100263. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100264. if(channel == 0)
  100265. bps++;
  100266. break;
  100267. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100268. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100269. if(channel == 1)
  100270. bps++;
  100271. break;
  100272. default:
  100273. FLAC__ASSERT(0);
  100274. }
  100275. /*
  100276. * now read it
  100277. */
  100278. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100279. return false;
  100280. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100281. return true;
  100282. }
  100283. if(!read_zero_padding_(decoder))
  100284. return false;
  100285. 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) */
  100286. return true;
  100287. /*
  100288. * Read the frame CRC-16 from the footer and check
  100289. */
  100290. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100291. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100292. return false; /* read_callback_ sets the state for us */
  100293. if(frame_crc == x) {
  100294. if(do_full_decode) {
  100295. /* Undo any special channel coding */
  100296. switch(decoder->private_->frame.header.channel_assignment) {
  100297. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100298. /* do nothing */
  100299. break;
  100300. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100301. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100302. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100303. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100304. break;
  100305. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100306. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100307. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100308. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100309. break;
  100310. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100311. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100312. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100313. #if 1
  100314. mid = decoder->private_->output[0][i];
  100315. side = decoder->private_->output[1][i];
  100316. mid <<= 1;
  100317. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100318. decoder->private_->output[0][i] = (mid + side) >> 1;
  100319. decoder->private_->output[1][i] = (mid - side) >> 1;
  100320. #else
  100321. /* OPT: without 'side' temp variable */
  100322. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100323. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100324. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100325. #endif
  100326. }
  100327. break;
  100328. default:
  100329. FLAC__ASSERT(0);
  100330. break;
  100331. }
  100332. }
  100333. }
  100334. else {
  100335. /* Bad frame, emit error and zero the output signal */
  100336. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100337. if(do_full_decode) {
  100338. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100339. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100340. }
  100341. }
  100342. }
  100343. *got_a_frame = true;
  100344. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100345. if(decoder->private_->next_fixed_block_size)
  100346. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100347. /* put the latest values into the public section of the decoder instance */
  100348. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100349. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100350. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100351. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100352. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100353. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100354. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100355. /* write it */
  100356. if(do_full_decode) {
  100357. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100358. return false;
  100359. }
  100360. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100361. return true;
  100362. }
  100363. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100364. {
  100365. FLAC__uint32 x;
  100366. FLAC__uint64 xx;
  100367. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100368. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100369. unsigned raw_header_len;
  100370. FLAC__bool is_unparseable = false;
  100371. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100372. /* init the raw header with the saved bits from synchronization */
  100373. raw_header[0] = decoder->private_->header_warmup[0];
  100374. raw_header[1] = decoder->private_->header_warmup[1];
  100375. raw_header_len = 2;
  100376. /* check to make sure that reserved bit is 0 */
  100377. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100378. is_unparseable = true;
  100379. /*
  100380. * Note that along the way as we read the header, we look for a sync
  100381. * code inside. If we find one it would indicate that our original
  100382. * sync was bad since there cannot be a sync code in a valid header.
  100383. *
  100384. * Three kinds of things can go wrong when reading the frame header:
  100385. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100386. * If we don't find a sync code, it can end up looking like we read
  100387. * a valid but unparseable header, until getting to the frame header
  100388. * CRC. Even then we could get a false positive on the CRC.
  100389. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100390. * future encoder).
  100391. * 3) We may be on a damaged frame which appears valid but unparseable.
  100392. *
  100393. * For all these reasons, we try and read a complete frame header as
  100394. * long as it seems valid, even if unparseable, up until the frame
  100395. * header CRC.
  100396. */
  100397. /*
  100398. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100399. */
  100400. for(i = 0; i < 2; i++) {
  100401. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100402. return false; /* read_callback_ sets the state for us */
  100403. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100404. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100405. decoder->private_->lookahead = (FLAC__byte)x;
  100406. decoder->private_->cached = true;
  100407. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100408. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100409. return true;
  100410. }
  100411. raw_header[raw_header_len++] = (FLAC__byte)x;
  100412. }
  100413. switch(x = raw_header[2] >> 4) {
  100414. case 0:
  100415. is_unparseable = true;
  100416. break;
  100417. case 1:
  100418. decoder->private_->frame.header.blocksize = 192;
  100419. break;
  100420. case 2:
  100421. case 3:
  100422. case 4:
  100423. case 5:
  100424. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100425. break;
  100426. case 6:
  100427. case 7:
  100428. blocksize_hint = x;
  100429. break;
  100430. case 8:
  100431. case 9:
  100432. case 10:
  100433. case 11:
  100434. case 12:
  100435. case 13:
  100436. case 14:
  100437. case 15:
  100438. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100439. break;
  100440. default:
  100441. FLAC__ASSERT(0);
  100442. break;
  100443. }
  100444. switch(x = raw_header[2] & 0x0f) {
  100445. case 0:
  100446. if(decoder->private_->has_stream_info)
  100447. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100448. else
  100449. is_unparseable = true;
  100450. break;
  100451. case 1:
  100452. decoder->private_->frame.header.sample_rate = 88200;
  100453. break;
  100454. case 2:
  100455. decoder->private_->frame.header.sample_rate = 176400;
  100456. break;
  100457. case 3:
  100458. decoder->private_->frame.header.sample_rate = 192000;
  100459. break;
  100460. case 4:
  100461. decoder->private_->frame.header.sample_rate = 8000;
  100462. break;
  100463. case 5:
  100464. decoder->private_->frame.header.sample_rate = 16000;
  100465. break;
  100466. case 6:
  100467. decoder->private_->frame.header.sample_rate = 22050;
  100468. break;
  100469. case 7:
  100470. decoder->private_->frame.header.sample_rate = 24000;
  100471. break;
  100472. case 8:
  100473. decoder->private_->frame.header.sample_rate = 32000;
  100474. break;
  100475. case 9:
  100476. decoder->private_->frame.header.sample_rate = 44100;
  100477. break;
  100478. case 10:
  100479. decoder->private_->frame.header.sample_rate = 48000;
  100480. break;
  100481. case 11:
  100482. decoder->private_->frame.header.sample_rate = 96000;
  100483. break;
  100484. case 12:
  100485. case 13:
  100486. case 14:
  100487. sample_rate_hint = x;
  100488. break;
  100489. case 15:
  100490. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100491. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100492. return true;
  100493. default:
  100494. FLAC__ASSERT(0);
  100495. }
  100496. x = (unsigned)(raw_header[3] >> 4);
  100497. if(x & 8) {
  100498. decoder->private_->frame.header.channels = 2;
  100499. switch(x & 7) {
  100500. case 0:
  100501. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100502. break;
  100503. case 1:
  100504. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100505. break;
  100506. case 2:
  100507. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100508. break;
  100509. default:
  100510. is_unparseable = true;
  100511. break;
  100512. }
  100513. }
  100514. else {
  100515. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100516. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100517. }
  100518. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100519. case 0:
  100520. if(decoder->private_->has_stream_info)
  100521. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100522. else
  100523. is_unparseable = true;
  100524. break;
  100525. case 1:
  100526. decoder->private_->frame.header.bits_per_sample = 8;
  100527. break;
  100528. case 2:
  100529. decoder->private_->frame.header.bits_per_sample = 12;
  100530. break;
  100531. case 4:
  100532. decoder->private_->frame.header.bits_per_sample = 16;
  100533. break;
  100534. case 5:
  100535. decoder->private_->frame.header.bits_per_sample = 20;
  100536. break;
  100537. case 6:
  100538. decoder->private_->frame.header.bits_per_sample = 24;
  100539. break;
  100540. case 3:
  100541. case 7:
  100542. is_unparseable = true;
  100543. break;
  100544. default:
  100545. FLAC__ASSERT(0);
  100546. break;
  100547. }
  100548. /* check to make sure that reserved bit is 0 */
  100549. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100550. is_unparseable = true;
  100551. /* read the frame's starting sample number (or frame number as the case may be) */
  100552. if(
  100553. raw_header[1] & 0x01 ||
  100554. /*@@@ 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 */
  100555. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100556. ) { /* variable blocksize */
  100557. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100558. return false; /* read_callback_ sets the state for us */
  100559. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100560. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100561. decoder->private_->cached = true;
  100562. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100563. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100564. return true;
  100565. }
  100566. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100567. decoder->private_->frame.header.number.sample_number = xx;
  100568. }
  100569. else { /* fixed blocksize */
  100570. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100571. return false; /* read_callback_ sets the state for us */
  100572. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100573. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100574. decoder->private_->cached = true;
  100575. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100576. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100577. return true;
  100578. }
  100579. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100580. decoder->private_->frame.header.number.frame_number = x;
  100581. }
  100582. if(blocksize_hint) {
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100584. return false; /* read_callback_ sets the state for us */
  100585. raw_header[raw_header_len++] = (FLAC__byte)x;
  100586. if(blocksize_hint == 7) {
  100587. FLAC__uint32 _x;
  100588. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100589. return false; /* read_callback_ sets the state for us */
  100590. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100591. x = (x << 8) | _x;
  100592. }
  100593. decoder->private_->frame.header.blocksize = x+1;
  100594. }
  100595. if(sample_rate_hint) {
  100596. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100597. return false; /* read_callback_ sets the state for us */
  100598. raw_header[raw_header_len++] = (FLAC__byte)x;
  100599. if(sample_rate_hint != 12) {
  100600. FLAC__uint32 _x;
  100601. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100602. return false; /* read_callback_ sets the state for us */
  100603. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100604. x = (x << 8) | _x;
  100605. }
  100606. if(sample_rate_hint == 12)
  100607. decoder->private_->frame.header.sample_rate = x*1000;
  100608. else if(sample_rate_hint == 13)
  100609. decoder->private_->frame.header.sample_rate = x;
  100610. else
  100611. decoder->private_->frame.header.sample_rate = x*10;
  100612. }
  100613. /* read the CRC-8 byte */
  100614. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100615. return false; /* read_callback_ sets the state for us */
  100616. crc8 = (FLAC__byte)x;
  100617. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100618. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100619. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100620. return true;
  100621. }
  100622. /* calculate the sample number from the frame number if needed */
  100623. decoder->private_->next_fixed_block_size = 0;
  100624. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100625. x = decoder->private_->frame.header.number.frame_number;
  100626. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100627. if(decoder->private_->fixed_block_size)
  100628. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100629. else if(decoder->private_->has_stream_info) {
  100630. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100631. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100632. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100633. }
  100634. else
  100635. is_unparseable = true;
  100636. }
  100637. else if(x == 0) {
  100638. decoder->private_->frame.header.number.sample_number = 0;
  100639. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100640. }
  100641. else {
  100642. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100643. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100644. }
  100645. }
  100646. if(is_unparseable) {
  100647. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100648. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100649. return true;
  100650. }
  100651. return true;
  100652. }
  100653. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100654. {
  100655. FLAC__uint32 x;
  100656. FLAC__bool wasted_bits;
  100657. unsigned i;
  100658. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100659. return false; /* read_callback_ sets the state for us */
  100660. wasted_bits = (x & 1);
  100661. x &= 0xfe;
  100662. if(wasted_bits) {
  100663. unsigned u;
  100664. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100665. return false; /* read_callback_ sets the state for us */
  100666. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100667. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100668. }
  100669. else
  100670. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100671. /*
  100672. * Lots of magic numbers here
  100673. */
  100674. if(x & 0x80) {
  100675. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100676. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100677. return true;
  100678. }
  100679. else if(x == 0) {
  100680. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100681. return false;
  100682. }
  100683. else if(x == 2) {
  100684. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100685. return false;
  100686. }
  100687. else if(x < 16) {
  100688. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100689. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100690. return true;
  100691. }
  100692. else if(x <= 24) {
  100693. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100694. return false;
  100695. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100696. return true;
  100697. }
  100698. else if(x < 64) {
  100699. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100700. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100701. return true;
  100702. }
  100703. else {
  100704. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100705. return false;
  100706. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100707. return true;
  100708. }
  100709. if(wasted_bits && do_full_decode) {
  100710. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100711. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100712. decoder->private_->output[channel][i] <<= x;
  100713. }
  100714. return true;
  100715. }
  100716. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100717. {
  100718. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100719. FLAC__int32 x;
  100720. unsigned i;
  100721. FLAC__int32 *output = decoder->private_->output[channel];
  100722. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100723. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100724. return false; /* read_callback_ sets the state for us */
  100725. subframe->value = x;
  100726. /* decode the subframe */
  100727. if(do_full_decode) {
  100728. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100729. output[i] = x;
  100730. }
  100731. return true;
  100732. }
  100733. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100734. {
  100735. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100736. FLAC__int32 i32;
  100737. FLAC__uint32 u32;
  100738. unsigned u;
  100739. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100740. subframe->residual = decoder->private_->residual[channel];
  100741. subframe->order = order;
  100742. /* read warm-up samples */
  100743. for(u = 0; u < order; u++) {
  100744. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100745. return false; /* read_callback_ sets the state for us */
  100746. subframe->warmup[u] = i32;
  100747. }
  100748. /* read entropy coding method info */
  100749. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100750. return false; /* read_callback_ sets the state for us */
  100751. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100752. switch(subframe->entropy_coding_method.type) {
  100753. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100754. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100755. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100756. return false; /* read_callback_ sets the state for us */
  100757. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100758. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100759. break;
  100760. default:
  100761. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100762. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100763. return true;
  100764. }
  100765. /* read residual */
  100766. switch(subframe->entropy_coding_method.type) {
  100767. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100768. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100769. 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))
  100770. return false;
  100771. break;
  100772. default:
  100773. FLAC__ASSERT(0);
  100774. }
  100775. /* decode the subframe */
  100776. if(do_full_decode) {
  100777. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100778. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100779. }
  100780. return true;
  100781. }
  100782. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100783. {
  100784. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100785. FLAC__int32 i32;
  100786. FLAC__uint32 u32;
  100787. unsigned u;
  100788. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100789. subframe->residual = decoder->private_->residual[channel];
  100790. subframe->order = order;
  100791. /* read warm-up samples */
  100792. for(u = 0; u < order; u++) {
  100793. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100794. return false; /* read_callback_ sets the state for us */
  100795. subframe->warmup[u] = i32;
  100796. }
  100797. /* read qlp coeff precision */
  100798. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100799. return false; /* read_callback_ sets the state for us */
  100800. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100801. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100802. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100803. return true;
  100804. }
  100805. subframe->qlp_coeff_precision = u32+1;
  100806. /* read qlp shift */
  100807. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100808. return false; /* read_callback_ sets the state for us */
  100809. subframe->quantization_level = i32;
  100810. /* read quantized lp coefficiencts */
  100811. for(u = 0; u < order; u++) {
  100812. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100813. return false; /* read_callback_ sets the state for us */
  100814. subframe->qlp_coeff[u] = i32;
  100815. }
  100816. /* read entropy coding method info */
  100817. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100818. return false; /* read_callback_ sets the state for us */
  100819. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100820. switch(subframe->entropy_coding_method.type) {
  100821. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100822. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100823. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100824. return false; /* read_callback_ sets the state for us */
  100825. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100826. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100827. break;
  100828. default:
  100829. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100830. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100831. return true;
  100832. }
  100833. /* read residual */
  100834. switch(subframe->entropy_coding_method.type) {
  100835. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100836. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100837. 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))
  100838. return false;
  100839. break;
  100840. default:
  100841. FLAC__ASSERT(0);
  100842. }
  100843. /* decode the subframe */
  100844. if(do_full_decode) {
  100845. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100846. /*@@@@@@ technically not pessimistic enough, should be more like
  100847. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100848. */
  100849. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100850. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100851. if(order <= 8)
  100852. 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);
  100853. else
  100854. 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);
  100855. }
  100856. else
  100857. 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);
  100858. else
  100859. 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);
  100860. }
  100861. return true;
  100862. }
  100863. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100864. {
  100865. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100866. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100867. unsigned i;
  100868. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100869. subframe->data = residual;
  100870. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100871. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100872. return false; /* read_callback_ sets the state for us */
  100873. residual[i] = x;
  100874. }
  100875. /* decode the subframe */
  100876. if(do_full_decode)
  100877. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100878. return true;
  100879. }
  100880. 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)
  100881. {
  100882. FLAC__uint32 rice_parameter;
  100883. int i;
  100884. unsigned partition, sample, u;
  100885. const unsigned partitions = 1u << partition_order;
  100886. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100887. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100888. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100889. /* sanity checks */
  100890. if(partition_order == 0) {
  100891. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100892. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100893. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100894. return true;
  100895. }
  100896. }
  100897. else {
  100898. if(partition_samples < predictor_order) {
  100899. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100900. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100901. return true;
  100902. }
  100903. }
  100904. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100905. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100906. return false;
  100907. }
  100908. sample = 0;
  100909. for(partition = 0; partition < partitions; partition++) {
  100910. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100911. return false; /* read_callback_ sets the state for us */
  100912. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100913. if(rice_parameter < pesc) {
  100914. partitioned_rice_contents->raw_bits[partition] = 0;
  100915. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100916. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100917. return false; /* read_callback_ sets the state for us */
  100918. sample += u;
  100919. }
  100920. else {
  100921. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100922. return false; /* read_callback_ sets the state for us */
  100923. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100924. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100925. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100926. return false; /* read_callback_ sets the state for us */
  100927. residual[sample] = i;
  100928. }
  100929. }
  100930. }
  100931. return true;
  100932. }
  100933. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100934. {
  100935. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100936. FLAC__uint32 zero = 0;
  100937. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100938. return false; /* read_callback_ sets the state for us */
  100939. if(zero != 0) {
  100940. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100941. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100942. }
  100943. }
  100944. return true;
  100945. }
  100946. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100947. {
  100948. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100949. if(
  100950. #if FLAC__HAS_OGG
  100951. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100952. !decoder->private_->is_ogg &&
  100953. #endif
  100954. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100955. ) {
  100956. *bytes = 0;
  100957. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100958. return false;
  100959. }
  100960. else if(*bytes > 0) {
  100961. /* While seeking, it is possible for our seek to land in the
  100962. * middle of audio data that looks exactly like a frame header
  100963. * from a future version of an encoder. When that happens, our
  100964. * error callback will get an
  100965. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100966. * unparseable_frame_count. But there is a remote possibility
  100967. * that it is properly synced at such a "future-codec frame",
  100968. * so to make sure, we wait to see many "unparseable" errors in
  100969. * a row before bailing out.
  100970. */
  100971. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100972. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100973. return false;
  100974. }
  100975. else {
  100976. const FLAC__StreamDecoderReadStatus status =
  100977. #if FLAC__HAS_OGG
  100978. decoder->private_->is_ogg?
  100979. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100980. #endif
  100981. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100982. ;
  100983. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100984. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100985. return false;
  100986. }
  100987. else if(*bytes == 0) {
  100988. if(
  100989. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100990. (
  100991. #if FLAC__HAS_OGG
  100992. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100993. !decoder->private_->is_ogg &&
  100994. #endif
  100995. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100996. )
  100997. ) {
  100998. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100999. return false;
  101000. }
  101001. else
  101002. return true;
  101003. }
  101004. else
  101005. return true;
  101006. }
  101007. }
  101008. else {
  101009. /* abort to avoid a deadlock */
  101010. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101011. return false;
  101012. }
  101013. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101014. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101015. * and at the same time hit the end of the stream (for example, seeking
  101016. * to a point that is after the beginning of the last Ogg page). There
  101017. * is no way to report an Ogg sync loss through the callbacks (see note
  101018. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101019. * So to keep the decoder from stopping at this point we gate the call
  101020. * to the eof_callback and let the Ogg decoder aspect set the
  101021. * end-of-stream state when it is needed.
  101022. */
  101023. }
  101024. #if FLAC__HAS_OGG
  101025. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101026. {
  101027. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101028. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101029. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101030. /* we don't really have a way to handle lost sync via read
  101031. * callback so we'll let it pass and let the underlying
  101032. * FLAC decoder catch the error
  101033. */
  101034. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101035. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101036. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101037. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101038. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101039. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101040. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101041. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101042. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101043. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101044. default:
  101045. FLAC__ASSERT(0);
  101046. /* double protection */
  101047. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101048. }
  101049. }
  101050. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101051. {
  101052. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101053. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101054. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101055. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101056. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101057. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101058. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101059. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101060. default:
  101061. /* double protection: */
  101062. FLAC__ASSERT(0);
  101063. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101064. }
  101065. }
  101066. #endif
  101067. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101068. {
  101069. if(decoder->private_->is_seeking) {
  101070. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101071. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101072. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101073. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101074. #if FLAC__HAS_OGG
  101075. decoder->private_->got_a_frame = true;
  101076. #endif
  101077. decoder->private_->last_frame = *frame; /* save the frame */
  101078. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101079. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101080. /* kick out of seek mode */
  101081. decoder->private_->is_seeking = false;
  101082. /* shift out the samples before target_sample */
  101083. if(delta > 0) {
  101084. unsigned channel;
  101085. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101086. for(channel = 0; channel < frame->header.channels; channel++)
  101087. newbuffer[channel] = buffer[channel] + delta;
  101088. decoder->private_->last_frame.header.blocksize -= delta;
  101089. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101090. /* write the relevant samples */
  101091. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101092. }
  101093. else {
  101094. /* write the relevant samples */
  101095. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101096. }
  101097. }
  101098. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101099. }
  101100. /*
  101101. * If we never got STREAMINFO, turn off MD5 checking to save
  101102. * cycles since we don't have a sum to compare to anyway
  101103. */
  101104. if(!decoder->private_->has_stream_info)
  101105. decoder->private_->do_md5_checking = false;
  101106. if(decoder->private_->do_md5_checking) {
  101107. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101108. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101109. }
  101110. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101111. }
  101112. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101113. {
  101114. if(!decoder->private_->is_seeking)
  101115. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101116. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101117. decoder->private_->unparseable_frame_count++;
  101118. }
  101119. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101120. {
  101121. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101122. FLAC__int64 pos = -1;
  101123. int i;
  101124. unsigned approx_bytes_per_frame;
  101125. FLAC__bool first_seek = true;
  101126. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101127. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101128. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101129. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101130. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101131. /* take these from the current frame in case they've changed mid-stream */
  101132. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101133. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101134. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101135. /* use values from stream info if we didn't decode a frame */
  101136. if(channels == 0)
  101137. channels = decoder->private_->stream_info.data.stream_info.channels;
  101138. if(bps == 0)
  101139. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101140. /* we are just guessing here */
  101141. if(max_framesize > 0)
  101142. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101143. /*
  101144. * Check if it's a known fixed-blocksize stream. Note that though
  101145. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101146. * never get a STREAMINFO block when decoding so the value of
  101147. * min_blocksize might be zero.
  101148. */
  101149. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101150. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101151. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101152. }
  101153. else
  101154. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101155. /*
  101156. * First, we set an upper and lower bound on where in the
  101157. * stream we will search. For now we assume the worst case
  101158. * scenario, which is our best guess at the beginning of
  101159. * the first frame and end of the stream.
  101160. */
  101161. lower_bound = first_frame_offset;
  101162. lower_bound_sample = 0;
  101163. upper_bound = stream_length;
  101164. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101165. /*
  101166. * Now we refine the bounds if we have a seektable with
  101167. * suitable points. Note that according to the spec they
  101168. * must be ordered by ascending sample number.
  101169. *
  101170. * Note: to protect against invalid seek tables we will ignore points
  101171. * that have frame_samples==0 or sample_number>=total_samples
  101172. */
  101173. if(seek_table) {
  101174. FLAC__uint64 new_lower_bound = lower_bound;
  101175. FLAC__uint64 new_upper_bound = upper_bound;
  101176. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101177. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101178. /* find the closest seek point <= target_sample, if it exists */
  101179. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101180. if(
  101181. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101182. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101183. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101184. seek_table->points[i].sample_number <= target_sample
  101185. )
  101186. break;
  101187. }
  101188. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101189. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101190. new_lower_bound_sample = seek_table->points[i].sample_number;
  101191. }
  101192. /* find the closest seek point > target_sample, if it exists */
  101193. for(i = 0; i < (int)seek_table->num_points; i++) {
  101194. if(
  101195. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101196. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101197. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101198. seek_table->points[i].sample_number > target_sample
  101199. )
  101200. break;
  101201. }
  101202. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101203. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101204. new_upper_bound_sample = seek_table->points[i].sample_number;
  101205. }
  101206. /* final protection against unsorted seek tables; keep original values if bogus */
  101207. if(new_upper_bound >= new_lower_bound) {
  101208. lower_bound = new_lower_bound;
  101209. upper_bound = new_upper_bound;
  101210. lower_bound_sample = new_lower_bound_sample;
  101211. upper_bound_sample = new_upper_bound_sample;
  101212. }
  101213. }
  101214. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101215. /* there are 2 insidious ways that the following equality occurs, which
  101216. * we need to fix:
  101217. * 1) total_samples is 0 (unknown) and target_sample is 0
  101218. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101219. * exactly equal to the last seek point in the seek table; this
  101220. * means there is no seek point above it, and upper_bound_samples
  101221. * remains equal to the estimate (of target_samples) we made above
  101222. * in either case it does not hurt to move upper_bound_sample up by 1
  101223. */
  101224. if(upper_bound_sample == lower_bound_sample)
  101225. upper_bound_sample++;
  101226. decoder->private_->target_sample = target_sample;
  101227. while(1) {
  101228. /* check if the bounds are still ok */
  101229. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101230. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101231. return false;
  101232. }
  101233. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101234. #if defined _MSC_VER || defined __MINGW32__
  101235. /* with VC++ you have to spoon feed it the casting */
  101236. 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;
  101237. #else
  101238. 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;
  101239. #endif
  101240. #else
  101241. /* a little less accurate: */
  101242. if(upper_bound - lower_bound < 0xffffffff)
  101243. 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;
  101244. else /* @@@ WATCHOUT, ~2TB limit */
  101245. 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;
  101246. #endif
  101247. if(pos >= (FLAC__int64)upper_bound)
  101248. pos = (FLAC__int64)upper_bound - 1;
  101249. if(pos < (FLAC__int64)lower_bound)
  101250. pos = (FLAC__int64)lower_bound;
  101251. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101252. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101253. return false;
  101254. }
  101255. if(!FLAC__stream_decoder_flush(decoder)) {
  101256. /* above call sets the state for us */
  101257. return false;
  101258. }
  101259. /* Now we need to get a frame. First we need to reset our
  101260. * unparseable_frame_count; if we get too many unparseable
  101261. * frames in a row, the read callback will return
  101262. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101263. * FLAC__stream_decoder_process_single() to return false.
  101264. */
  101265. decoder->private_->unparseable_frame_count = 0;
  101266. if(!FLAC__stream_decoder_process_single(decoder)) {
  101267. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101268. return false;
  101269. }
  101270. /* our write callback will change the state when it gets to the target frame */
  101271. /* 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 */
  101272. #if 0
  101273. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101274. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101275. break;
  101276. #endif
  101277. if(!decoder->private_->is_seeking)
  101278. break;
  101279. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101280. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101281. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101282. if (pos == (FLAC__int64)lower_bound) {
  101283. /* can't move back any more than the first frame, something is fatally wrong */
  101284. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101285. return false;
  101286. }
  101287. /* our last move backwards wasn't big enough, try again */
  101288. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101289. continue;
  101290. }
  101291. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101292. first_seek = false;
  101293. /* make sure we are not seeking in corrupted stream */
  101294. if (this_frame_sample < lower_bound_sample) {
  101295. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101296. return false;
  101297. }
  101298. /* we need to narrow the search */
  101299. if(target_sample < this_frame_sample) {
  101300. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101301. /*@@@@@@ what will decode position be if at end of stream? */
  101302. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101303. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101304. return false;
  101305. }
  101306. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101307. }
  101308. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101309. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101310. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101311. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101312. return false;
  101313. }
  101314. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101315. }
  101316. }
  101317. return true;
  101318. }
  101319. #if FLAC__HAS_OGG
  101320. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101321. {
  101322. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101323. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101324. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101325. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101326. FLAC__bool did_a_seek;
  101327. unsigned iteration = 0;
  101328. /* In the first iterations, we will calculate the target byte position
  101329. * by the distance from the target sample to left_sample and
  101330. * right_sample (let's call it "proportional search"). After that, we
  101331. * will switch to binary search.
  101332. */
  101333. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101334. /* We will switch to a linear search once our current sample is less
  101335. * than this number of samples ahead of the target sample
  101336. */
  101337. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101338. /* If the total number of samples is unknown, use a large value, and
  101339. * force binary search immediately.
  101340. */
  101341. if(right_sample == 0) {
  101342. right_sample = (FLAC__uint64)(-1);
  101343. BINARY_SEARCH_AFTER_ITERATION = 0;
  101344. }
  101345. decoder->private_->target_sample = target_sample;
  101346. for( ; ; iteration++) {
  101347. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101348. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101349. pos = (right_pos + left_pos) / 2;
  101350. }
  101351. else {
  101352. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101353. #if defined _MSC_VER || defined __MINGW32__
  101354. /* with MSVC you have to spoon feed it the casting */
  101355. 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));
  101356. #else
  101357. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101358. #endif
  101359. #else
  101360. /* a little less accurate: */
  101361. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101362. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101363. else /* @@@ WATCHOUT, ~2TB limit */
  101364. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101365. #endif
  101366. /* @@@ TODO: might want to limit pos to some distance
  101367. * before EOF, to make sure we land before the last frame,
  101368. * thereby getting a this_frame_sample and so having a better
  101369. * estimate.
  101370. */
  101371. }
  101372. /* physical seek */
  101373. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101374. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101375. return false;
  101376. }
  101377. if(!FLAC__stream_decoder_flush(decoder)) {
  101378. /* above call sets the state for us */
  101379. return false;
  101380. }
  101381. did_a_seek = true;
  101382. }
  101383. else
  101384. did_a_seek = false;
  101385. decoder->private_->got_a_frame = false;
  101386. if(!FLAC__stream_decoder_process_single(decoder)) {
  101387. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101388. return false;
  101389. }
  101390. if(!decoder->private_->got_a_frame) {
  101391. if(did_a_seek) {
  101392. /* this can happen if we seek to a point after the last frame; we drop
  101393. * to binary search right away in this case to avoid any wasted
  101394. * iterations of proportional search.
  101395. */
  101396. right_pos = pos;
  101397. BINARY_SEARCH_AFTER_ITERATION = 0;
  101398. }
  101399. else {
  101400. /* this can probably only happen if total_samples is unknown and the
  101401. * target_sample is past the end of the stream
  101402. */
  101403. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101404. return false;
  101405. }
  101406. }
  101407. /* our write callback will change the state when it gets to the target frame */
  101408. else if(!decoder->private_->is_seeking) {
  101409. break;
  101410. }
  101411. else {
  101412. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101413. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101414. if (did_a_seek) {
  101415. if (this_frame_sample <= target_sample) {
  101416. /* The 'equal' case should not happen, since
  101417. * FLAC__stream_decoder_process_single()
  101418. * should recognize that it has hit the
  101419. * target sample and we would exit through
  101420. * the 'break' above.
  101421. */
  101422. FLAC__ASSERT(this_frame_sample != target_sample);
  101423. left_sample = this_frame_sample;
  101424. /* sanity check to avoid infinite loop */
  101425. if (left_pos == pos) {
  101426. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101427. return false;
  101428. }
  101429. left_pos = pos;
  101430. }
  101431. else if(this_frame_sample > target_sample) {
  101432. right_sample = this_frame_sample;
  101433. /* sanity check to avoid infinite loop */
  101434. if (right_pos == pos) {
  101435. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101436. return false;
  101437. }
  101438. right_pos = pos;
  101439. }
  101440. }
  101441. }
  101442. }
  101443. return true;
  101444. }
  101445. #endif
  101446. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101447. {
  101448. (void)client_data;
  101449. if(*bytes > 0) {
  101450. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101451. if(ferror(decoder->private_->file))
  101452. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101453. else if(*bytes == 0)
  101454. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101455. else
  101456. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101457. }
  101458. else
  101459. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101460. }
  101461. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101462. {
  101463. (void)client_data;
  101464. if(decoder->private_->file == stdin)
  101465. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101466. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101467. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101468. else
  101469. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101470. }
  101471. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101472. {
  101473. off_t pos;
  101474. (void)client_data;
  101475. if(decoder->private_->file == stdin)
  101476. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101477. else if((pos = ftello(decoder->private_->file)) < 0)
  101478. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101479. else {
  101480. *absolute_byte_offset = (FLAC__uint64)pos;
  101481. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101482. }
  101483. }
  101484. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101485. {
  101486. struct stat filestats;
  101487. (void)client_data;
  101488. if(decoder->private_->file == stdin)
  101489. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101490. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101491. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101492. else {
  101493. *stream_length = (FLAC__uint64)filestats.st_size;
  101494. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101495. }
  101496. }
  101497. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101498. {
  101499. (void)client_data;
  101500. return feof(decoder->private_->file)? true : false;
  101501. }
  101502. #endif
  101503. /*** End of inlined file: stream_decoder.c ***/
  101504. /*** Start of inlined file: stream_encoder.c ***/
  101505. /*** Start of inlined file: juce_FlacHeader.h ***/
  101506. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101507. // tasks..
  101508. #define VERSION "1.2.1"
  101509. #define FLAC__NO_DLL 1
  101510. #if JUCE_MSVC
  101511. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101512. #endif
  101513. #if JUCE_MAC
  101514. #define FLAC__SYS_DARWIN 1
  101515. #endif
  101516. /*** End of inlined file: juce_FlacHeader.h ***/
  101517. #if JUCE_USE_FLAC
  101518. #if HAVE_CONFIG_H
  101519. # include <config.h>
  101520. #endif
  101521. #if defined _MSC_VER || defined __MINGW32__
  101522. #include <io.h> /* for _setmode() */
  101523. #include <fcntl.h> /* for _O_BINARY */
  101524. #endif
  101525. #if defined __CYGWIN__ || defined __EMX__
  101526. #include <io.h> /* for setmode(), O_BINARY */
  101527. #include <fcntl.h> /* for _O_BINARY */
  101528. #endif
  101529. #include <limits.h>
  101530. #include <stdio.h>
  101531. #include <stdlib.h> /* for malloc() */
  101532. #include <string.h> /* for memcpy() */
  101533. #include <sys/types.h> /* for off_t */
  101534. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101535. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101536. #define fseeko fseek
  101537. #define ftello ftell
  101538. #endif
  101539. #endif
  101540. /*** Start of inlined file: stream_encoder.h ***/
  101541. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101542. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101543. #if FLAC__HAS_OGG
  101544. #include "private/ogg_encoder_aspect.h"
  101545. #endif
  101546. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101547. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101548. typedef enum {
  101549. FLAC__APODIZATION_BARTLETT,
  101550. FLAC__APODIZATION_BARTLETT_HANN,
  101551. FLAC__APODIZATION_BLACKMAN,
  101552. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101553. FLAC__APODIZATION_CONNES,
  101554. FLAC__APODIZATION_FLATTOP,
  101555. FLAC__APODIZATION_GAUSS,
  101556. FLAC__APODIZATION_HAMMING,
  101557. FLAC__APODIZATION_HANN,
  101558. FLAC__APODIZATION_KAISER_BESSEL,
  101559. FLAC__APODIZATION_NUTTALL,
  101560. FLAC__APODIZATION_RECTANGLE,
  101561. FLAC__APODIZATION_TRIANGLE,
  101562. FLAC__APODIZATION_TUKEY,
  101563. FLAC__APODIZATION_WELCH
  101564. } FLAC__ApodizationFunction;
  101565. typedef struct {
  101566. FLAC__ApodizationFunction type;
  101567. union {
  101568. struct {
  101569. FLAC__real stddev;
  101570. } gauss;
  101571. struct {
  101572. FLAC__real p;
  101573. } tukey;
  101574. } parameters;
  101575. } FLAC__ApodizationSpecification;
  101576. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101577. typedef struct FLAC__StreamEncoderProtected {
  101578. FLAC__StreamEncoderState state;
  101579. FLAC__bool verify;
  101580. FLAC__bool streamable_subset;
  101581. FLAC__bool do_md5;
  101582. FLAC__bool do_mid_side_stereo;
  101583. FLAC__bool loose_mid_side_stereo;
  101584. unsigned channels;
  101585. unsigned bits_per_sample;
  101586. unsigned sample_rate;
  101587. unsigned blocksize;
  101588. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101589. unsigned num_apodizations;
  101590. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101591. #endif
  101592. unsigned max_lpc_order;
  101593. unsigned qlp_coeff_precision;
  101594. FLAC__bool do_qlp_coeff_prec_search;
  101595. FLAC__bool do_exhaustive_model_search;
  101596. FLAC__bool do_escape_coding;
  101597. unsigned min_residual_partition_order;
  101598. unsigned max_residual_partition_order;
  101599. unsigned rice_parameter_search_dist;
  101600. FLAC__uint64 total_samples_estimate;
  101601. FLAC__StreamMetadata **metadata;
  101602. unsigned num_metadata_blocks;
  101603. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101604. #if FLAC__HAS_OGG
  101605. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101606. #endif
  101607. } FLAC__StreamEncoderProtected;
  101608. #endif
  101609. /*** End of inlined file: stream_encoder.h ***/
  101610. #if FLAC__HAS_OGG
  101611. #include "include/private/ogg_helper.h"
  101612. #include "include/private/ogg_mapping.h"
  101613. #endif
  101614. /*** Start of inlined file: stream_encoder_framing.h ***/
  101615. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101616. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101617. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101618. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101619. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101620. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101621. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101622. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101623. #endif
  101624. /*** End of inlined file: stream_encoder_framing.h ***/
  101625. /*** Start of inlined file: window.h ***/
  101626. #ifndef FLAC__PRIVATE__WINDOW_H
  101627. #define FLAC__PRIVATE__WINDOW_H
  101628. #ifdef HAVE_CONFIG_H
  101629. #include <config.h>
  101630. #endif
  101631. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101632. /*
  101633. * FLAC__window_*()
  101634. * --------------------------------------------------------------------
  101635. * Calculates window coefficients according to different apodization
  101636. * functions.
  101637. *
  101638. * OUT window[0,L-1]
  101639. * IN L (number of points in window)
  101640. */
  101641. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101642. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101643. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101644. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101645. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101646. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101647. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101648. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101649. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101650. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101651. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101652. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101653. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101654. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101655. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101656. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101657. #endif
  101658. /*** End of inlined file: window.h ***/
  101659. #ifndef FLaC__INLINE
  101660. #define FLaC__INLINE
  101661. #endif
  101662. #ifdef min
  101663. #undef min
  101664. #endif
  101665. #define min(x,y) ((x)<(y)?(x):(y))
  101666. #ifdef max
  101667. #undef max
  101668. #endif
  101669. #define max(x,y) ((x)>(y)?(x):(y))
  101670. /* Exact Rice codeword length calculation is off by default. The simple
  101671. * (and fast) estimation (of how many bits a residual value will be
  101672. * encoded with) in this encoder is very good, almost always yielding
  101673. * compression within 0.1% of exact calculation.
  101674. */
  101675. #undef EXACT_RICE_BITS_CALCULATION
  101676. /* Rice parameter searching is off by default. The simple (and fast)
  101677. * parameter estimation in this encoder is very good, almost always
  101678. * yielding compression within 0.1% of the optimal parameters.
  101679. */
  101680. #undef ENABLE_RICE_PARAMETER_SEARCH
  101681. typedef struct {
  101682. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101683. unsigned size; /* of each data[] in samples */
  101684. unsigned tail;
  101685. } verify_input_fifo;
  101686. typedef struct {
  101687. const FLAC__byte *data;
  101688. unsigned capacity;
  101689. unsigned bytes;
  101690. } verify_output;
  101691. typedef enum {
  101692. ENCODER_IN_MAGIC = 0,
  101693. ENCODER_IN_METADATA = 1,
  101694. ENCODER_IN_AUDIO = 2
  101695. } EncoderStateHint;
  101696. static struct CompressionLevels {
  101697. FLAC__bool do_mid_side_stereo;
  101698. FLAC__bool loose_mid_side_stereo;
  101699. unsigned max_lpc_order;
  101700. unsigned qlp_coeff_precision;
  101701. FLAC__bool do_qlp_coeff_prec_search;
  101702. FLAC__bool do_escape_coding;
  101703. FLAC__bool do_exhaustive_model_search;
  101704. unsigned min_residual_partition_order;
  101705. unsigned max_residual_partition_order;
  101706. unsigned rice_parameter_search_dist;
  101707. } compression_levels_[] = {
  101708. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101709. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101710. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101711. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101712. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101713. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101714. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101715. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101716. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101717. };
  101718. /***********************************************************************
  101719. *
  101720. * Private class method prototypes
  101721. *
  101722. ***********************************************************************/
  101723. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101724. static void free_(FLAC__StreamEncoder *encoder);
  101725. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101726. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101727. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101728. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101729. #if FLAC__HAS_OGG
  101730. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101731. #endif
  101732. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101733. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101734. static FLAC__bool process_subframe_(
  101735. FLAC__StreamEncoder *encoder,
  101736. unsigned min_partition_order,
  101737. unsigned max_partition_order,
  101738. const FLAC__FrameHeader *frame_header,
  101739. unsigned subframe_bps,
  101740. const FLAC__int32 integer_signal[],
  101741. FLAC__Subframe *subframe[2],
  101742. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101743. FLAC__int32 *residual[2],
  101744. unsigned *best_subframe,
  101745. unsigned *best_bits
  101746. );
  101747. static FLAC__bool add_subframe_(
  101748. FLAC__StreamEncoder *encoder,
  101749. unsigned blocksize,
  101750. unsigned subframe_bps,
  101751. const FLAC__Subframe *subframe,
  101752. FLAC__BitWriter *frame
  101753. );
  101754. static unsigned evaluate_constant_subframe_(
  101755. FLAC__StreamEncoder *encoder,
  101756. const FLAC__int32 signal,
  101757. unsigned blocksize,
  101758. unsigned subframe_bps,
  101759. FLAC__Subframe *subframe
  101760. );
  101761. static unsigned evaluate_fixed_subframe_(
  101762. FLAC__StreamEncoder *encoder,
  101763. const FLAC__int32 signal[],
  101764. FLAC__int32 residual[],
  101765. FLAC__uint64 abs_residual_partition_sums[],
  101766. unsigned raw_bits_per_partition[],
  101767. unsigned blocksize,
  101768. unsigned subframe_bps,
  101769. unsigned order,
  101770. unsigned rice_parameter,
  101771. unsigned rice_parameter_limit,
  101772. unsigned min_partition_order,
  101773. unsigned max_partition_order,
  101774. FLAC__bool do_escape_coding,
  101775. unsigned rice_parameter_search_dist,
  101776. FLAC__Subframe *subframe,
  101777. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101778. );
  101779. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101780. static unsigned evaluate_lpc_subframe_(
  101781. FLAC__StreamEncoder *encoder,
  101782. const FLAC__int32 signal[],
  101783. FLAC__int32 residual[],
  101784. FLAC__uint64 abs_residual_partition_sums[],
  101785. unsigned raw_bits_per_partition[],
  101786. const FLAC__real lp_coeff[],
  101787. unsigned blocksize,
  101788. unsigned subframe_bps,
  101789. unsigned order,
  101790. unsigned qlp_coeff_precision,
  101791. unsigned rice_parameter,
  101792. unsigned rice_parameter_limit,
  101793. unsigned min_partition_order,
  101794. unsigned max_partition_order,
  101795. FLAC__bool do_escape_coding,
  101796. unsigned rice_parameter_search_dist,
  101797. FLAC__Subframe *subframe,
  101798. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101799. );
  101800. #endif
  101801. static unsigned evaluate_verbatim_subframe_(
  101802. FLAC__StreamEncoder *encoder,
  101803. const FLAC__int32 signal[],
  101804. unsigned blocksize,
  101805. unsigned subframe_bps,
  101806. FLAC__Subframe *subframe
  101807. );
  101808. static unsigned find_best_partition_order_(
  101809. struct FLAC__StreamEncoderPrivate *private_,
  101810. const FLAC__int32 residual[],
  101811. FLAC__uint64 abs_residual_partition_sums[],
  101812. unsigned raw_bits_per_partition[],
  101813. unsigned residual_samples,
  101814. unsigned predictor_order,
  101815. unsigned rice_parameter,
  101816. unsigned rice_parameter_limit,
  101817. unsigned min_partition_order,
  101818. unsigned max_partition_order,
  101819. unsigned bps,
  101820. FLAC__bool do_escape_coding,
  101821. unsigned rice_parameter_search_dist,
  101822. FLAC__EntropyCodingMethod *best_ecm
  101823. );
  101824. static void precompute_partition_info_sums_(
  101825. const FLAC__int32 residual[],
  101826. FLAC__uint64 abs_residual_partition_sums[],
  101827. unsigned residual_samples,
  101828. unsigned predictor_order,
  101829. unsigned min_partition_order,
  101830. unsigned max_partition_order,
  101831. unsigned bps
  101832. );
  101833. static void precompute_partition_info_escapes_(
  101834. const FLAC__int32 residual[],
  101835. unsigned raw_bits_per_partition[],
  101836. unsigned residual_samples,
  101837. unsigned predictor_order,
  101838. unsigned min_partition_order,
  101839. unsigned max_partition_order
  101840. );
  101841. static FLAC__bool set_partitioned_rice_(
  101842. #ifdef EXACT_RICE_BITS_CALCULATION
  101843. const FLAC__int32 residual[],
  101844. #endif
  101845. const FLAC__uint64 abs_residual_partition_sums[],
  101846. const unsigned raw_bits_per_partition[],
  101847. const unsigned residual_samples,
  101848. const unsigned predictor_order,
  101849. const unsigned suggested_rice_parameter,
  101850. const unsigned rice_parameter_limit,
  101851. const unsigned rice_parameter_search_dist,
  101852. const unsigned partition_order,
  101853. const FLAC__bool search_for_escapes,
  101854. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101855. unsigned *bits
  101856. );
  101857. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101858. /* verify-related routines: */
  101859. static void append_to_verify_fifo_(
  101860. verify_input_fifo *fifo,
  101861. const FLAC__int32 * const input[],
  101862. unsigned input_offset,
  101863. unsigned channels,
  101864. unsigned wide_samples
  101865. );
  101866. static void append_to_verify_fifo_interleaved_(
  101867. verify_input_fifo *fifo,
  101868. const FLAC__int32 input[],
  101869. unsigned input_offset,
  101870. unsigned channels,
  101871. unsigned wide_samples
  101872. );
  101873. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101874. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101875. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101876. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101877. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101878. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101879. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101880. 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);
  101881. static FILE *get_binary_stdout_(void);
  101882. /***********************************************************************
  101883. *
  101884. * Private class data
  101885. *
  101886. ***********************************************************************/
  101887. typedef struct FLAC__StreamEncoderPrivate {
  101888. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101889. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101890. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101891. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101892. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101893. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101894. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101895. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101896. #endif
  101897. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101898. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101899. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101900. FLAC__int32 *residual_workspace_mid_side[2][2];
  101901. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101902. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101903. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101904. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101905. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101906. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101907. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101908. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101909. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101910. unsigned best_subframe_mid_side[2];
  101911. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101912. unsigned best_subframe_bits_mid_side[2];
  101913. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101914. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101915. FLAC__BitWriter *frame; /* the current frame being worked on */
  101916. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101917. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101918. FLAC__ChannelAssignment last_channel_assignment;
  101919. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101920. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101921. unsigned current_sample_number;
  101922. unsigned current_frame_number;
  101923. FLAC__MD5Context md5context;
  101924. FLAC__CPUInfo cpuinfo;
  101925. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101926. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101927. #else
  101928. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101929. #endif
  101930. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101931. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101932. 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[]);
  101933. 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[]);
  101934. 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[]);
  101935. #endif
  101936. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101937. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101938. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101939. FLAC__bool disable_constant_subframes;
  101940. FLAC__bool disable_fixed_subframes;
  101941. FLAC__bool disable_verbatim_subframes;
  101942. #if FLAC__HAS_OGG
  101943. FLAC__bool is_ogg;
  101944. #endif
  101945. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101946. FLAC__StreamEncoderSeekCallback seek_callback;
  101947. FLAC__StreamEncoderTellCallback tell_callback;
  101948. FLAC__StreamEncoderWriteCallback write_callback;
  101949. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101950. FLAC__StreamEncoderProgressCallback progress_callback;
  101951. void *client_data;
  101952. unsigned first_seekpoint_to_check;
  101953. FILE *file; /* only used when encoding to a file */
  101954. FLAC__uint64 bytes_written;
  101955. FLAC__uint64 samples_written;
  101956. unsigned frames_written;
  101957. unsigned total_frames_estimate;
  101958. /* unaligned (original) pointers to allocated data */
  101959. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101960. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101961. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101962. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101963. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101964. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101965. FLAC__real *windowed_signal_unaligned;
  101966. #endif
  101967. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101968. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101969. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101970. unsigned *raw_bits_per_partition_unaligned;
  101971. /*
  101972. * These fields have been moved here from private function local
  101973. * declarations merely to save stack space during encoding.
  101974. */
  101975. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101976. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101977. #endif
  101978. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101979. /*
  101980. * The data for the verify section
  101981. */
  101982. struct {
  101983. FLAC__StreamDecoder *decoder;
  101984. EncoderStateHint state_hint;
  101985. FLAC__bool needs_magic_hack;
  101986. verify_input_fifo input_fifo;
  101987. verify_output output;
  101988. struct {
  101989. FLAC__uint64 absolute_sample;
  101990. unsigned frame_number;
  101991. unsigned channel;
  101992. unsigned sample;
  101993. FLAC__int32 expected;
  101994. FLAC__int32 got;
  101995. } error_stats;
  101996. } verify;
  101997. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101998. } FLAC__StreamEncoderPrivate;
  101999. /***********************************************************************
  102000. *
  102001. * Public static class data
  102002. *
  102003. ***********************************************************************/
  102004. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102005. "FLAC__STREAM_ENCODER_OK",
  102006. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102007. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102008. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102009. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102010. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102011. "FLAC__STREAM_ENCODER_IO_ERROR",
  102012. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102013. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102014. };
  102015. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102016. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102017. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102018. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102019. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102020. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102021. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102022. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102023. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102024. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102025. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102026. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102027. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102028. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102029. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102030. };
  102031. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102032. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102033. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102034. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102035. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102036. };
  102037. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102038. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102039. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102040. };
  102041. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102042. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102043. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102044. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102045. };
  102046. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102047. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102048. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102049. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102050. };
  102051. /* Number of samples that will be overread to watch for end of stream. By
  102052. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102053. * always try to read blocksize+1 samples before encoding a block, so that
  102054. * even if the stream has a total sample count that is an integral multiple
  102055. * of the blocksize, we will still notice when we are encoding the last
  102056. * block. This is needed, for example, to correctly set the end-of-stream
  102057. * marker in Ogg FLAC.
  102058. *
  102059. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102060. * not really any reason to change it.
  102061. */
  102062. static const unsigned OVERREAD_ = 1;
  102063. /***********************************************************************
  102064. *
  102065. * Class constructor/destructor
  102066. *
  102067. */
  102068. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102069. {
  102070. FLAC__StreamEncoder *encoder;
  102071. unsigned i;
  102072. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102073. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102074. if(encoder == 0) {
  102075. return 0;
  102076. }
  102077. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102078. if(encoder->protected_ == 0) {
  102079. free(encoder);
  102080. return 0;
  102081. }
  102082. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102083. if(encoder->private_ == 0) {
  102084. free(encoder->protected_);
  102085. free(encoder);
  102086. return 0;
  102087. }
  102088. encoder->private_->frame = FLAC__bitwriter_new();
  102089. if(encoder->private_->frame == 0) {
  102090. free(encoder->private_);
  102091. free(encoder->protected_);
  102092. free(encoder);
  102093. return 0;
  102094. }
  102095. encoder->private_->file = 0;
  102096. set_defaults_enc(encoder);
  102097. encoder->private_->is_being_deleted = false;
  102098. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102099. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102100. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102101. }
  102102. for(i = 0; i < 2; i++) {
  102103. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102104. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102105. }
  102106. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102107. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102108. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102109. }
  102110. for(i = 0; i < 2; i++) {
  102111. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102112. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102113. }
  102114. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102115. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102116. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102117. }
  102118. for(i = 0; i < 2; i++) {
  102119. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102120. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102121. }
  102122. for(i = 0; i < 2; i++)
  102123. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102124. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102125. return encoder;
  102126. }
  102127. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102128. {
  102129. unsigned i;
  102130. FLAC__ASSERT(0 != encoder);
  102131. FLAC__ASSERT(0 != encoder->protected_);
  102132. FLAC__ASSERT(0 != encoder->private_);
  102133. FLAC__ASSERT(0 != encoder->private_->frame);
  102134. encoder->private_->is_being_deleted = true;
  102135. (void)FLAC__stream_encoder_finish(encoder);
  102136. if(0 != encoder->private_->verify.decoder)
  102137. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102138. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102139. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102140. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102141. }
  102142. for(i = 0; i < 2; i++) {
  102143. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102144. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102145. }
  102146. for(i = 0; i < 2; i++)
  102147. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102148. FLAC__bitwriter_delete(encoder->private_->frame);
  102149. free(encoder->private_);
  102150. free(encoder->protected_);
  102151. free(encoder);
  102152. }
  102153. /***********************************************************************
  102154. *
  102155. * Public class methods
  102156. *
  102157. ***********************************************************************/
  102158. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102159. FLAC__StreamEncoder *encoder,
  102160. FLAC__StreamEncoderReadCallback read_callback,
  102161. FLAC__StreamEncoderWriteCallback write_callback,
  102162. FLAC__StreamEncoderSeekCallback seek_callback,
  102163. FLAC__StreamEncoderTellCallback tell_callback,
  102164. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102165. void *client_data,
  102166. FLAC__bool is_ogg
  102167. )
  102168. {
  102169. unsigned i;
  102170. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102171. FLAC__ASSERT(0 != encoder);
  102172. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102173. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102174. #if !FLAC__HAS_OGG
  102175. if(is_ogg)
  102176. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102177. #endif
  102178. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102179. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102180. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102181. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102182. if(encoder->protected_->channels != 2) {
  102183. encoder->protected_->do_mid_side_stereo = false;
  102184. encoder->protected_->loose_mid_side_stereo = false;
  102185. }
  102186. else if(!encoder->protected_->do_mid_side_stereo)
  102187. encoder->protected_->loose_mid_side_stereo = false;
  102188. if(encoder->protected_->bits_per_sample >= 32)
  102189. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102190. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102191. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102192. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102193. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102194. if(encoder->protected_->blocksize == 0) {
  102195. if(encoder->protected_->max_lpc_order == 0)
  102196. encoder->protected_->blocksize = 1152;
  102197. else
  102198. encoder->protected_->blocksize = 4096;
  102199. }
  102200. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102201. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102202. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102203. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102204. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102205. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102206. if(encoder->protected_->qlp_coeff_precision == 0) {
  102207. if(encoder->protected_->bits_per_sample < 16) {
  102208. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102209. /* @@@ until then we'll make a guess */
  102210. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102211. }
  102212. else if(encoder->protected_->bits_per_sample == 16) {
  102213. if(encoder->protected_->blocksize <= 192)
  102214. encoder->protected_->qlp_coeff_precision = 7;
  102215. else if(encoder->protected_->blocksize <= 384)
  102216. encoder->protected_->qlp_coeff_precision = 8;
  102217. else if(encoder->protected_->blocksize <= 576)
  102218. encoder->protected_->qlp_coeff_precision = 9;
  102219. else if(encoder->protected_->blocksize <= 1152)
  102220. encoder->protected_->qlp_coeff_precision = 10;
  102221. else if(encoder->protected_->blocksize <= 2304)
  102222. encoder->protected_->qlp_coeff_precision = 11;
  102223. else if(encoder->protected_->blocksize <= 4608)
  102224. encoder->protected_->qlp_coeff_precision = 12;
  102225. else
  102226. encoder->protected_->qlp_coeff_precision = 13;
  102227. }
  102228. else {
  102229. if(encoder->protected_->blocksize <= 384)
  102230. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102231. else if(encoder->protected_->blocksize <= 1152)
  102232. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102233. else
  102234. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102235. }
  102236. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102237. }
  102238. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102239. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102240. if(encoder->protected_->streamable_subset) {
  102241. if(
  102242. encoder->protected_->blocksize != 192 &&
  102243. encoder->protected_->blocksize != 576 &&
  102244. encoder->protected_->blocksize != 1152 &&
  102245. encoder->protected_->blocksize != 2304 &&
  102246. encoder->protected_->blocksize != 4608 &&
  102247. encoder->protected_->blocksize != 256 &&
  102248. encoder->protected_->blocksize != 512 &&
  102249. encoder->protected_->blocksize != 1024 &&
  102250. encoder->protected_->blocksize != 2048 &&
  102251. encoder->protected_->blocksize != 4096 &&
  102252. encoder->protected_->blocksize != 8192 &&
  102253. encoder->protected_->blocksize != 16384
  102254. )
  102255. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102256. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102257. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102258. if(
  102259. encoder->protected_->bits_per_sample != 8 &&
  102260. encoder->protected_->bits_per_sample != 12 &&
  102261. encoder->protected_->bits_per_sample != 16 &&
  102262. encoder->protected_->bits_per_sample != 20 &&
  102263. encoder->protected_->bits_per_sample != 24
  102264. )
  102265. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102266. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102267. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102268. if(
  102269. encoder->protected_->sample_rate <= 48000 &&
  102270. (
  102271. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102272. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102273. )
  102274. ) {
  102275. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102276. }
  102277. }
  102278. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102279. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102280. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102281. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102282. #if FLAC__HAS_OGG
  102283. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102284. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102285. unsigned i;
  102286. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102287. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102288. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102289. for( ; i > 0; i--)
  102290. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102291. encoder->protected_->metadata[0] = vc;
  102292. break;
  102293. }
  102294. }
  102295. }
  102296. #endif
  102297. /* keep track of any SEEKTABLE block */
  102298. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102299. unsigned i;
  102300. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102301. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102302. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102303. break; /* take only the first one */
  102304. }
  102305. }
  102306. }
  102307. /* validate metadata */
  102308. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102309. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102310. metadata_has_seektable = false;
  102311. metadata_has_vorbis_comment = false;
  102312. metadata_picture_has_type1 = false;
  102313. metadata_picture_has_type2 = false;
  102314. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102315. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102316. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102317. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102318. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102319. if(metadata_has_seektable) /* only one is allowed */
  102320. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102321. metadata_has_seektable = true;
  102322. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102323. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102324. }
  102325. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102326. if(metadata_has_vorbis_comment) /* only one is allowed */
  102327. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102328. metadata_has_vorbis_comment = true;
  102329. }
  102330. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102331. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102332. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102333. }
  102334. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102335. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102336. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102337. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102338. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102339. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102340. metadata_picture_has_type1 = true;
  102341. /* standard icon must be 32x32 pixel PNG */
  102342. if(
  102343. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102344. (
  102345. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102346. m->data.picture.width != 32 ||
  102347. m->data.picture.height != 32
  102348. )
  102349. )
  102350. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102351. }
  102352. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102353. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102354. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102355. metadata_picture_has_type2 = true;
  102356. }
  102357. }
  102358. }
  102359. encoder->private_->input_capacity = 0;
  102360. for(i = 0; i < encoder->protected_->channels; i++) {
  102361. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102362. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102363. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102364. #endif
  102365. }
  102366. for(i = 0; i < 2; i++) {
  102367. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102368. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102369. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102370. #endif
  102371. }
  102372. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102373. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102374. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102375. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102376. #endif
  102377. for(i = 0; i < encoder->protected_->channels; i++) {
  102378. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102379. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102380. encoder->private_->best_subframe[i] = 0;
  102381. }
  102382. for(i = 0; i < 2; i++) {
  102383. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102384. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102385. encoder->private_->best_subframe_mid_side[i] = 0;
  102386. }
  102387. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102388. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102389. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102390. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102391. #else
  102392. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102393. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102394. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102395. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102396. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102397. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102398. 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);
  102399. #endif
  102400. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102401. encoder->private_->loose_mid_side_stereo_frames = 1;
  102402. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102403. encoder->private_->current_sample_number = 0;
  102404. encoder->private_->current_frame_number = 0;
  102405. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102406. 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? */
  102407. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102408. /*
  102409. * get the CPU info and set the function pointers
  102410. */
  102411. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102412. /* first default to the non-asm routines */
  102413. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102414. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102415. #endif
  102416. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102417. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102418. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102419. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102420. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102421. #endif
  102422. /* now override with asm where appropriate */
  102423. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102424. # ifndef FLAC__NO_ASM
  102425. if(encoder->private_->cpuinfo.use_asm) {
  102426. # ifdef FLAC__CPU_IA32
  102427. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102428. # ifdef FLAC__HAS_NASM
  102429. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102430. if(encoder->protected_->max_lpc_order < 4)
  102431. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102432. else if(encoder->protected_->max_lpc_order < 8)
  102433. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102434. else if(encoder->protected_->max_lpc_order < 12)
  102435. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102436. else
  102437. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102438. }
  102439. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102440. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102441. else
  102442. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102443. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102444. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102445. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102446. }
  102447. else {
  102448. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102449. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102450. }
  102451. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102452. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102453. # endif /* FLAC__HAS_NASM */
  102454. # endif /* FLAC__CPU_IA32 */
  102455. }
  102456. # endif /* !FLAC__NO_ASM */
  102457. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102458. /* finally override based on wide-ness if necessary */
  102459. if(encoder->private_->use_wide_by_block) {
  102460. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102461. }
  102462. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102463. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102464. #if FLAC__HAS_OGG
  102465. encoder->private_->is_ogg = is_ogg;
  102466. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102467. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102468. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102469. }
  102470. #endif
  102471. encoder->private_->read_callback = read_callback;
  102472. encoder->private_->write_callback = write_callback;
  102473. encoder->private_->seek_callback = seek_callback;
  102474. encoder->private_->tell_callback = tell_callback;
  102475. encoder->private_->metadata_callback = metadata_callback;
  102476. encoder->private_->client_data = client_data;
  102477. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102478. /* the above function sets the state for us in case of an error */
  102479. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102480. }
  102481. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102482. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102483. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102484. }
  102485. /*
  102486. * Set up the verify stuff if necessary
  102487. */
  102488. if(encoder->protected_->verify) {
  102489. /*
  102490. * First, set up the fifo which will hold the
  102491. * original signal to compare against
  102492. */
  102493. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102494. for(i = 0; i < encoder->protected_->channels; i++) {
  102495. 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))) {
  102496. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102497. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102498. }
  102499. }
  102500. encoder->private_->verify.input_fifo.tail = 0;
  102501. /*
  102502. * Now set up a stream decoder for verification
  102503. */
  102504. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102505. if(0 == encoder->private_->verify.decoder) {
  102506. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102507. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102508. }
  102509. 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) {
  102510. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102511. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102512. }
  102513. }
  102514. encoder->private_->verify.error_stats.absolute_sample = 0;
  102515. encoder->private_->verify.error_stats.frame_number = 0;
  102516. encoder->private_->verify.error_stats.channel = 0;
  102517. encoder->private_->verify.error_stats.sample = 0;
  102518. encoder->private_->verify.error_stats.expected = 0;
  102519. encoder->private_->verify.error_stats.got = 0;
  102520. /*
  102521. * These must be done before we write any metadata, because that
  102522. * calls the write_callback, which uses these values.
  102523. */
  102524. encoder->private_->first_seekpoint_to_check = 0;
  102525. encoder->private_->samples_written = 0;
  102526. encoder->protected_->streaminfo_offset = 0;
  102527. encoder->protected_->seektable_offset = 0;
  102528. encoder->protected_->audio_offset = 0;
  102529. /*
  102530. * write the stream header
  102531. */
  102532. if(encoder->protected_->verify)
  102533. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102534. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102535. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102536. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102537. }
  102538. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102539. /* the above function sets the state for us in case of an error */
  102540. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102541. }
  102542. /*
  102543. * write the STREAMINFO metadata block
  102544. */
  102545. if(encoder->protected_->verify)
  102546. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102547. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102548. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102549. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102550. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102551. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102552. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102553. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102554. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102555. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102556. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102557. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102558. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102559. if(encoder->protected_->do_md5)
  102560. FLAC__MD5Init(&encoder->private_->md5context);
  102561. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102562. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102563. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102564. }
  102565. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102566. /* the above function sets the state for us in case of an error */
  102567. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102568. }
  102569. /*
  102570. * Now that the STREAMINFO block is written, we can init this to an
  102571. * absurdly-high value...
  102572. */
  102573. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102574. /* ... and clear this to 0 */
  102575. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102576. /*
  102577. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102578. * if not, we will write an empty one (FLAC__add_metadata_block()
  102579. * automatically supplies the vendor string).
  102580. *
  102581. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102582. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102583. * true it will have already insured that the metadata list is properly
  102584. * ordered.)
  102585. */
  102586. if(!metadata_has_vorbis_comment) {
  102587. FLAC__StreamMetadata vorbis_comment;
  102588. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102589. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102590. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102591. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102592. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102593. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102594. vorbis_comment.data.vorbis_comment.comments = 0;
  102595. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102596. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102597. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102598. }
  102599. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102600. /* the above function sets the state for us in case of an error */
  102601. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102602. }
  102603. }
  102604. /*
  102605. * write the user's metadata blocks
  102606. */
  102607. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102608. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102609. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102610. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102611. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102612. }
  102613. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102614. /* the above function sets the state for us in case of an error */
  102615. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102616. }
  102617. }
  102618. /* now that all the metadata is written, we save the stream offset */
  102619. 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 */
  102620. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102621. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102622. }
  102623. if(encoder->protected_->verify)
  102624. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102625. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102626. }
  102627. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102628. FLAC__StreamEncoder *encoder,
  102629. FLAC__StreamEncoderWriteCallback write_callback,
  102630. FLAC__StreamEncoderSeekCallback seek_callback,
  102631. FLAC__StreamEncoderTellCallback tell_callback,
  102632. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102633. void *client_data
  102634. )
  102635. {
  102636. return init_stream_internal_enc(
  102637. encoder,
  102638. /*read_callback=*/0,
  102639. write_callback,
  102640. seek_callback,
  102641. tell_callback,
  102642. metadata_callback,
  102643. client_data,
  102644. /*is_ogg=*/false
  102645. );
  102646. }
  102647. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102648. FLAC__StreamEncoder *encoder,
  102649. FLAC__StreamEncoderReadCallback read_callback,
  102650. FLAC__StreamEncoderWriteCallback write_callback,
  102651. FLAC__StreamEncoderSeekCallback seek_callback,
  102652. FLAC__StreamEncoderTellCallback tell_callback,
  102653. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102654. void *client_data
  102655. )
  102656. {
  102657. return init_stream_internal_enc(
  102658. encoder,
  102659. read_callback,
  102660. write_callback,
  102661. seek_callback,
  102662. tell_callback,
  102663. metadata_callback,
  102664. client_data,
  102665. /*is_ogg=*/true
  102666. );
  102667. }
  102668. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102669. FLAC__StreamEncoder *encoder,
  102670. FILE *file,
  102671. FLAC__StreamEncoderProgressCallback progress_callback,
  102672. void *client_data,
  102673. FLAC__bool is_ogg
  102674. )
  102675. {
  102676. FLAC__StreamEncoderInitStatus init_status;
  102677. FLAC__ASSERT(0 != encoder);
  102678. FLAC__ASSERT(0 != file);
  102679. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102680. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102681. /* double protection */
  102682. if(file == 0) {
  102683. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102684. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102685. }
  102686. /*
  102687. * To make sure that our file does not go unclosed after an error, we
  102688. * must assign the FILE pointer before any further error can occur in
  102689. * this routine.
  102690. */
  102691. if(file == stdout)
  102692. file = get_binary_stdout_(); /* just to be safe */
  102693. encoder->private_->file = file;
  102694. encoder->private_->progress_callback = progress_callback;
  102695. encoder->private_->bytes_written = 0;
  102696. encoder->private_->samples_written = 0;
  102697. encoder->private_->frames_written = 0;
  102698. init_status = init_stream_internal_enc(
  102699. encoder,
  102700. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102701. file_write_callback_,
  102702. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102703. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102704. /*metadata_callback=*/0,
  102705. client_data,
  102706. is_ogg
  102707. );
  102708. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102709. /* the above function sets the state for us in case of an error */
  102710. return init_status;
  102711. }
  102712. {
  102713. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102714. FLAC__ASSERT(blocksize != 0);
  102715. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102716. }
  102717. return init_status;
  102718. }
  102719. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102720. FLAC__StreamEncoder *encoder,
  102721. FILE *file,
  102722. FLAC__StreamEncoderProgressCallback progress_callback,
  102723. void *client_data
  102724. )
  102725. {
  102726. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102727. }
  102728. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102729. FLAC__StreamEncoder *encoder,
  102730. FILE *file,
  102731. FLAC__StreamEncoderProgressCallback progress_callback,
  102732. void *client_data
  102733. )
  102734. {
  102735. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102736. }
  102737. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102738. FLAC__StreamEncoder *encoder,
  102739. const char *filename,
  102740. FLAC__StreamEncoderProgressCallback progress_callback,
  102741. void *client_data,
  102742. FLAC__bool is_ogg
  102743. )
  102744. {
  102745. FILE *file;
  102746. FLAC__ASSERT(0 != encoder);
  102747. /*
  102748. * To make sure that our file does not go unclosed after an error, we
  102749. * have to do the same entrance checks here that are later performed
  102750. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102751. */
  102752. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102753. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102754. file = filename? fopen(filename, "w+b") : stdout;
  102755. if(file == 0) {
  102756. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102757. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102758. }
  102759. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102760. }
  102761. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102762. FLAC__StreamEncoder *encoder,
  102763. const char *filename,
  102764. FLAC__StreamEncoderProgressCallback progress_callback,
  102765. void *client_data
  102766. )
  102767. {
  102768. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102769. }
  102770. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102771. FLAC__StreamEncoder *encoder,
  102772. const char *filename,
  102773. FLAC__StreamEncoderProgressCallback progress_callback,
  102774. void *client_data
  102775. )
  102776. {
  102777. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102778. }
  102779. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102780. {
  102781. FLAC__bool error = false;
  102782. FLAC__ASSERT(0 != encoder);
  102783. FLAC__ASSERT(0 != encoder->private_);
  102784. FLAC__ASSERT(0 != encoder->protected_);
  102785. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102786. return true;
  102787. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102788. if(encoder->private_->current_sample_number != 0) {
  102789. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102790. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102791. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102792. error = true;
  102793. }
  102794. }
  102795. if(encoder->protected_->do_md5)
  102796. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102797. if(!encoder->private_->is_being_deleted) {
  102798. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102799. if(encoder->private_->seek_callback) {
  102800. #if FLAC__HAS_OGG
  102801. if(encoder->private_->is_ogg)
  102802. update_ogg_metadata_(encoder);
  102803. else
  102804. #endif
  102805. update_metadata_(encoder);
  102806. /* check if an error occurred while updating metadata */
  102807. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102808. error = true;
  102809. }
  102810. if(encoder->private_->metadata_callback)
  102811. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102812. }
  102813. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102814. if(!error)
  102815. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102816. error = true;
  102817. }
  102818. }
  102819. if(0 != encoder->private_->file) {
  102820. if(encoder->private_->file != stdout)
  102821. fclose(encoder->private_->file);
  102822. encoder->private_->file = 0;
  102823. }
  102824. #if FLAC__HAS_OGG
  102825. if(encoder->private_->is_ogg)
  102826. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102827. #endif
  102828. free_(encoder);
  102829. set_defaults_enc(encoder);
  102830. if(!error)
  102831. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102832. return !error;
  102833. }
  102834. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102835. {
  102836. FLAC__ASSERT(0 != encoder);
  102837. FLAC__ASSERT(0 != encoder->private_);
  102838. FLAC__ASSERT(0 != encoder->protected_);
  102839. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102840. return false;
  102841. #if FLAC__HAS_OGG
  102842. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102843. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102844. return true;
  102845. #else
  102846. (void)value;
  102847. return false;
  102848. #endif
  102849. }
  102850. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102851. {
  102852. FLAC__ASSERT(0 != encoder);
  102853. FLAC__ASSERT(0 != encoder->private_);
  102854. FLAC__ASSERT(0 != encoder->protected_);
  102855. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102856. return false;
  102857. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102858. encoder->protected_->verify = value;
  102859. #endif
  102860. return true;
  102861. }
  102862. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102863. {
  102864. FLAC__ASSERT(0 != encoder);
  102865. FLAC__ASSERT(0 != encoder->private_);
  102866. FLAC__ASSERT(0 != encoder->protected_);
  102867. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102868. return false;
  102869. encoder->protected_->streamable_subset = value;
  102870. return true;
  102871. }
  102872. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102873. {
  102874. FLAC__ASSERT(0 != encoder);
  102875. FLAC__ASSERT(0 != encoder->private_);
  102876. FLAC__ASSERT(0 != encoder->protected_);
  102877. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102878. return false;
  102879. encoder->protected_->do_md5 = value;
  102880. return true;
  102881. }
  102882. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102883. {
  102884. FLAC__ASSERT(0 != encoder);
  102885. FLAC__ASSERT(0 != encoder->private_);
  102886. FLAC__ASSERT(0 != encoder->protected_);
  102887. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102888. return false;
  102889. encoder->protected_->channels = value;
  102890. return true;
  102891. }
  102892. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102893. {
  102894. FLAC__ASSERT(0 != encoder);
  102895. FLAC__ASSERT(0 != encoder->private_);
  102896. FLAC__ASSERT(0 != encoder->protected_);
  102897. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102898. return false;
  102899. encoder->protected_->bits_per_sample = value;
  102900. return true;
  102901. }
  102902. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102903. {
  102904. FLAC__ASSERT(0 != encoder);
  102905. FLAC__ASSERT(0 != encoder->private_);
  102906. FLAC__ASSERT(0 != encoder->protected_);
  102907. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102908. return false;
  102909. encoder->protected_->sample_rate = value;
  102910. return true;
  102911. }
  102912. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102913. {
  102914. FLAC__bool ok = true;
  102915. FLAC__ASSERT(0 != encoder);
  102916. FLAC__ASSERT(0 != encoder->private_);
  102917. FLAC__ASSERT(0 != encoder->protected_);
  102918. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102919. return false;
  102920. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102921. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102922. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102923. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102924. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102925. #if 0
  102926. /* was: */
  102927. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102928. /* but it's too hard to specify the string in a locale-specific way */
  102929. #else
  102930. encoder->protected_->num_apodizations = 1;
  102931. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102932. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102933. #endif
  102934. #endif
  102935. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102936. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102937. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102938. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102939. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102940. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102941. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102942. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102943. return ok;
  102944. }
  102945. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102946. {
  102947. FLAC__ASSERT(0 != encoder);
  102948. FLAC__ASSERT(0 != encoder->private_);
  102949. FLAC__ASSERT(0 != encoder->protected_);
  102950. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102951. return false;
  102952. encoder->protected_->blocksize = value;
  102953. return true;
  102954. }
  102955. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102956. {
  102957. FLAC__ASSERT(0 != encoder);
  102958. FLAC__ASSERT(0 != encoder->private_);
  102959. FLAC__ASSERT(0 != encoder->protected_);
  102960. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102961. return false;
  102962. encoder->protected_->do_mid_side_stereo = value;
  102963. return true;
  102964. }
  102965. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102966. {
  102967. FLAC__ASSERT(0 != encoder);
  102968. FLAC__ASSERT(0 != encoder->private_);
  102969. FLAC__ASSERT(0 != encoder->protected_);
  102970. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102971. return false;
  102972. encoder->protected_->loose_mid_side_stereo = value;
  102973. return true;
  102974. }
  102975. /*@@@@add to tests*/
  102976. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102977. {
  102978. FLAC__ASSERT(0 != encoder);
  102979. FLAC__ASSERT(0 != encoder->private_);
  102980. FLAC__ASSERT(0 != encoder->protected_);
  102981. FLAC__ASSERT(0 != specification);
  102982. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102983. return false;
  102984. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102985. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102986. #else
  102987. encoder->protected_->num_apodizations = 0;
  102988. while(1) {
  102989. const char *s = strchr(specification, ';');
  102990. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102991. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102992. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102993. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102994. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102995. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102996. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102997. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102998. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102999. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103000. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103001. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103002. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103003. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103004. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103005. if (stddev > 0.0 && stddev <= 0.5) {
  103006. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103007. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103008. }
  103009. }
  103010. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103011. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103012. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103013. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103014. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103015. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103016. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103017. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103018. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103019. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103020. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103021. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103022. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103023. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103024. if (p >= 0.0 && p <= 1.0) {
  103025. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103026. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103027. }
  103028. }
  103029. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103030. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103031. if (encoder->protected_->num_apodizations == 32)
  103032. break;
  103033. if (s)
  103034. specification = s+1;
  103035. else
  103036. break;
  103037. }
  103038. if(encoder->protected_->num_apodizations == 0) {
  103039. encoder->protected_->num_apodizations = 1;
  103040. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103041. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103042. }
  103043. #endif
  103044. return true;
  103045. }
  103046. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103047. {
  103048. FLAC__ASSERT(0 != encoder);
  103049. FLAC__ASSERT(0 != encoder->private_);
  103050. FLAC__ASSERT(0 != encoder->protected_);
  103051. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103052. return false;
  103053. encoder->protected_->max_lpc_order = value;
  103054. return true;
  103055. }
  103056. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103057. {
  103058. FLAC__ASSERT(0 != encoder);
  103059. FLAC__ASSERT(0 != encoder->private_);
  103060. FLAC__ASSERT(0 != encoder->protected_);
  103061. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103062. return false;
  103063. encoder->protected_->qlp_coeff_precision = value;
  103064. return true;
  103065. }
  103066. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103067. {
  103068. FLAC__ASSERT(0 != encoder);
  103069. FLAC__ASSERT(0 != encoder->private_);
  103070. FLAC__ASSERT(0 != encoder->protected_);
  103071. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103072. return false;
  103073. encoder->protected_->do_qlp_coeff_prec_search = value;
  103074. return true;
  103075. }
  103076. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103077. {
  103078. FLAC__ASSERT(0 != encoder);
  103079. FLAC__ASSERT(0 != encoder->private_);
  103080. FLAC__ASSERT(0 != encoder->protected_);
  103081. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103082. return false;
  103083. #if 0
  103084. /*@@@ deprecated: */
  103085. encoder->protected_->do_escape_coding = value;
  103086. #else
  103087. (void)value;
  103088. #endif
  103089. return true;
  103090. }
  103091. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103092. {
  103093. FLAC__ASSERT(0 != encoder);
  103094. FLAC__ASSERT(0 != encoder->private_);
  103095. FLAC__ASSERT(0 != encoder->protected_);
  103096. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103097. return false;
  103098. encoder->protected_->do_exhaustive_model_search = value;
  103099. return true;
  103100. }
  103101. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103102. {
  103103. FLAC__ASSERT(0 != encoder);
  103104. FLAC__ASSERT(0 != encoder->private_);
  103105. FLAC__ASSERT(0 != encoder->protected_);
  103106. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103107. return false;
  103108. encoder->protected_->min_residual_partition_order = value;
  103109. return true;
  103110. }
  103111. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103112. {
  103113. FLAC__ASSERT(0 != encoder);
  103114. FLAC__ASSERT(0 != encoder->private_);
  103115. FLAC__ASSERT(0 != encoder->protected_);
  103116. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103117. return false;
  103118. encoder->protected_->max_residual_partition_order = value;
  103119. return true;
  103120. }
  103121. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103122. {
  103123. FLAC__ASSERT(0 != encoder);
  103124. FLAC__ASSERT(0 != encoder->private_);
  103125. FLAC__ASSERT(0 != encoder->protected_);
  103126. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103127. return false;
  103128. #if 0
  103129. /*@@@ deprecated: */
  103130. encoder->protected_->rice_parameter_search_dist = value;
  103131. #else
  103132. (void)value;
  103133. #endif
  103134. return true;
  103135. }
  103136. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103137. {
  103138. FLAC__ASSERT(0 != encoder);
  103139. FLAC__ASSERT(0 != encoder->private_);
  103140. FLAC__ASSERT(0 != encoder->protected_);
  103141. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103142. return false;
  103143. encoder->protected_->total_samples_estimate = value;
  103144. return true;
  103145. }
  103146. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103147. {
  103148. FLAC__ASSERT(0 != encoder);
  103149. FLAC__ASSERT(0 != encoder->private_);
  103150. FLAC__ASSERT(0 != encoder->protected_);
  103151. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103152. return false;
  103153. if(0 == metadata)
  103154. num_blocks = 0;
  103155. if(0 == num_blocks)
  103156. metadata = 0;
  103157. /* realloc() does not do exactly what we want so... */
  103158. if(encoder->protected_->metadata) {
  103159. free(encoder->protected_->metadata);
  103160. encoder->protected_->metadata = 0;
  103161. encoder->protected_->num_metadata_blocks = 0;
  103162. }
  103163. if(num_blocks) {
  103164. FLAC__StreamMetadata **m;
  103165. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103166. return false;
  103167. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103168. encoder->protected_->metadata = m;
  103169. encoder->protected_->num_metadata_blocks = num_blocks;
  103170. }
  103171. #if FLAC__HAS_OGG
  103172. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103173. return false;
  103174. #endif
  103175. return true;
  103176. }
  103177. /*
  103178. * These three functions are not static, but not publically exposed in
  103179. * include/FLAC/ either. They are used by the test suite.
  103180. */
  103181. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103182. {
  103183. FLAC__ASSERT(0 != encoder);
  103184. FLAC__ASSERT(0 != encoder->private_);
  103185. FLAC__ASSERT(0 != encoder->protected_);
  103186. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103187. return false;
  103188. encoder->private_->disable_constant_subframes = value;
  103189. return true;
  103190. }
  103191. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103192. {
  103193. FLAC__ASSERT(0 != encoder);
  103194. FLAC__ASSERT(0 != encoder->private_);
  103195. FLAC__ASSERT(0 != encoder->protected_);
  103196. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103197. return false;
  103198. encoder->private_->disable_fixed_subframes = value;
  103199. return true;
  103200. }
  103201. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103202. {
  103203. FLAC__ASSERT(0 != encoder);
  103204. FLAC__ASSERT(0 != encoder->private_);
  103205. FLAC__ASSERT(0 != encoder->protected_);
  103206. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103207. return false;
  103208. encoder->private_->disable_verbatim_subframes = value;
  103209. return true;
  103210. }
  103211. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103212. {
  103213. FLAC__ASSERT(0 != encoder);
  103214. FLAC__ASSERT(0 != encoder->private_);
  103215. FLAC__ASSERT(0 != encoder->protected_);
  103216. return encoder->protected_->state;
  103217. }
  103218. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103219. {
  103220. FLAC__ASSERT(0 != encoder);
  103221. FLAC__ASSERT(0 != encoder->private_);
  103222. FLAC__ASSERT(0 != encoder->protected_);
  103223. if(encoder->protected_->verify)
  103224. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103225. else
  103226. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103227. }
  103228. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103229. {
  103230. FLAC__ASSERT(0 != encoder);
  103231. FLAC__ASSERT(0 != encoder->private_);
  103232. FLAC__ASSERT(0 != encoder->protected_);
  103233. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103234. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103235. else
  103236. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103237. }
  103238. 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)
  103239. {
  103240. FLAC__ASSERT(0 != encoder);
  103241. FLAC__ASSERT(0 != encoder->private_);
  103242. FLAC__ASSERT(0 != encoder->protected_);
  103243. if(0 != absolute_sample)
  103244. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103245. if(0 != frame_number)
  103246. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103247. if(0 != channel)
  103248. *channel = encoder->private_->verify.error_stats.channel;
  103249. if(0 != sample)
  103250. *sample = encoder->private_->verify.error_stats.sample;
  103251. if(0 != expected)
  103252. *expected = encoder->private_->verify.error_stats.expected;
  103253. if(0 != got)
  103254. *got = encoder->private_->verify.error_stats.got;
  103255. }
  103256. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103257. {
  103258. FLAC__ASSERT(0 != encoder);
  103259. FLAC__ASSERT(0 != encoder->private_);
  103260. FLAC__ASSERT(0 != encoder->protected_);
  103261. return encoder->protected_->verify;
  103262. }
  103263. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103264. {
  103265. FLAC__ASSERT(0 != encoder);
  103266. FLAC__ASSERT(0 != encoder->private_);
  103267. FLAC__ASSERT(0 != encoder->protected_);
  103268. return encoder->protected_->streamable_subset;
  103269. }
  103270. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103271. {
  103272. FLAC__ASSERT(0 != encoder);
  103273. FLAC__ASSERT(0 != encoder->private_);
  103274. FLAC__ASSERT(0 != encoder->protected_);
  103275. return encoder->protected_->do_md5;
  103276. }
  103277. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103278. {
  103279. FLAC__ASSERT(0 != encoder);
  103280. FLAC__ASSERT(0 != encoder->private_);
  103281. FLAC__ASSERT(0 != encoder->protected_);
  103282. return encoder->protected_->channels;
  103283. }
  103284. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103285. {
  103286. FLAC__ASSERT(0 != encoder);
  103287. FLAC__ASSERT(0 != encoder->private_);
  103288. FLAC__ASSERT(0 != encoder->protected_);
  103289. return encoder->protected_->bits_per_sample;
  103290. }
  103291. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103292. {
  103293. FLAC__ASSERT(0 != encoder);
  103294. FLAC__ASSERT(0 != encoder->private_);
  103295. FLAC__ASSERT(0 != encoder->protected_);
  103296. return encoder->protected_->sample_rate;
  103297. }
  103298. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103299. {
  103300. FLAC__ASSERT(0 != encoder);
  103301. FLAC__ASSERT(0 != encoder->private_);
  103302. FLAC__ASSERT(0 != encoder->protected_);
  103303. return encoder->protected_->blocksize;
  103304. }
  103305. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103306. {
  103307. FLAC__ASSERT(0 != encoder);
  103308. FLAC__ASSERT(0 != encoder->private_);
  103309. FLAC__ASSERT(0 != encoder->protected_);
  103310. return encoder->protected_->do_mid_side_stereo;
  103311. }
  103312. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103313. {
  103314. FLAC__ASSERT(0 != encoder);
  103315. FLAC__ASSERT(0 != encoder->private_);
  103316. FLAC__ASSERT(0 != encoder->protected_);
  103317. return encoder->protected_->loose_mid_side_stereo;
  103318. }
  103319. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103320. {
  103321. FLAC__ASSERT(0 != encoder);
  103322. FLAC__ASSERT(0 != encoder->private_);
  103323. FLAC__ASSERT(0 != encoder->protected_);
  103324. return encoder->protected_->max_lpc_order;
  103325. }
  103326. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103327. {
  103328. FLAC__ASSERT(0 != encoder);
  103329. FLAC__ASSERT(0 != encoder->private_);
  103330. FLAC__ASSERT(0 != encoder->protected_);
  103331. return encoder->protected_->qlp_coeff_precision;
  103332. }
  103333. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103334. {
  103335. FLAC__ASSERT(0 != encoder);
  103336. FLAC__ASSERT(0 != encoder->private_);
  103337. FLAC__ASSERT(0 != encoder->protected_);
  103338. return encoder->protected_->do_qlp_coeff_prec_search;
  103339. }
  103340. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103341. {
  103342. FLAC__ASSERT(0 != encoder);
  103343. FLAC__ASSERT(0 != encoder->private_);
  103344. FLAC__ASSERT(0 != encoder->protected_);
  103345. return encoder->protected_->do_escape_coding;
  103346. }
  103347. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103348. {
  103349. FLAC__ASSERT(0 != encoder);
  103350. FLAC__ASSERT(0 != encoder->private_);
  103351. FLAC__ASSERT(0 != encoder->protected_);
  103352. return encoder->protected_->do_exhaustive_model_search;
  103353. }
  103354. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103355. {
  103356. FLAC__ASSERT(0 != encoder);
  103357. FLAC__ASSERT(0 != encoder->private_);
  103358. FLAC__ASSERT(0 != encoder->protected_);
  103359. return encoder->protected_->min_residual_partition_order;
  103360. }
  103361. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103362. {
  103363. FLAC__ASSERT(0 != encoder);
  103364. FLAC__ASSERT(0 != encoder->private_);
  103365. FLAC__ASSERT(0 != encoder->protected_);
  103366. return encoder->protected_->max_residual_partition_order;
  103367. }
  103368. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103369. {
  103370. FLAC__ASSERT(0 != encoder);
  103371. FLAC__ASSERT(0 != encoder->private_);
  103372. FLAC__ASSERT(0 != encoder->protected_);
  103373. return encoder->protected_->rice_parameter_search_dist;
  103374. }
  103375. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103376. {
  103377. FLAC__ASSERT(0 != encoder);
  103378. FLAC__ASSERT(0 != encoder->private_);
  103379. FLAC__ASSERT(0 != encoder->protected_);
  103380. return encoder->protected_->total_samples_estimate;
  103381. }
  103382. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103383. {
  103384. unsigned i, j = 0, channel;
  103385. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103386. FLAC__ASSERT(0 != encoder);
  103387. FLAC__ASSERT(0 != encoder->private_);
  103388. FLAC__ASSERT(0 != encoder->protected_);
  103389. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103390. do {
  103391. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103392. if(encoder->protected_->verify)
  103393. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103394. for(channel = 0; channel < channels; channel++)
  103395. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103396. if(encoder->protected_->do_mid_side_stereo) {
  103397. FLAC__ASSERT(channels == 2);
  103398. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103399. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103400. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103401. 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' ! */
  103402. }
  103403. }
  103404. else
  103405. j += n;
  103406. encoder->private_->current_sample_number += n;
  103407. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103408. if(encoder->private_->current_sample_number > blocksize) {
  103409. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103410. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103411. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103412. return false;
  103413. /* move unprocessed overread samples to beginnings of arrays */
  103414. for(channel = 0; channel < channels; channel++)
  103415. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103416. if(encoder->protected_->do_mid_side_stereo) {
  103417. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103418. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103419. }
  103420. encoder->private_->current_sample_number = 1;
  103421. }
  103422. } while(j < samples);
  103423. return true;
  103424. }
  103425. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103426. {
  103427. unsigned i, j, k, channel;
  103428. FLAC__int32 x, mid, side;
  103429. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103430. FLAC__ASSERT(0 != encoder);
  103431. FLAC__ASSERT(0 != encoder->private_);
  103432. FLAC__ASSERT(0 != encoder->protected_);
  103433. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103434. j = k = 0;
  103435. /*
  103436. * we have several flavors of the same basic loop, optimized for
  103437. * different conditions:
  103438. */
  103439. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103440. /*
  103441. * stereo coding: unroll channel loop
  103442. */
  103443. do {
  103444. if(encoder->protected_->verify)
  103445. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103446. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103447. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103448. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103449. x = buffer[k++];
  103450. encoder->private_->integer_signal[1][i] = x;
  103451. mid += x;
  103452. side -= x;
  103453. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103454. encoder->private_->integer_signal_mid_side[1][i] = side;
  103455. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103456. }
  103457. encoder->private_->current_sample_number = i;
  103458. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103459. if(i > blocksize) {
  103460. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103461. return false;
  103462. /* move unprocessed overread samples to beginnings of arrays */
  103463. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103464. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103465. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103466. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103467. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103468. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103469. encoder->private_->current_sample_number = 1;
  103470. }
  103471. } while(j < samples);
  103472. }
  103473. else {
  103474. /*
  103475. * independent channel coding: buffer each channel in inner loop
  103476. */
  103477. do {
  103478. if(encoder->protected_->verify)
  103479. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103480. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103481. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103482. for(channel = 0; channel < channels; channel++)
  103483. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103484. }
  103485. encoder->private_->current_sample_number = i;
  103486. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103487. if(i > blocksize) {
  103488. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103489. return false;
  103490. /* move unprocessed overread samples to beginnings of arrays */
  103491. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103492. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103493. for(channel = 0; channel < channels; channel++)
  103494. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103495. encoder->private_->current_sample_number = 1;
  103496. }
  103497. } while(j < samples);
  103498. }
  103499. return true;
  103500. }
  103501. /***********************************************************************
  103502. *
  103503. * Private class methods
  103504. *
  103505. ***********************************************************************/
  103506. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103507. {
  103508. FLAC__ASSERT(0 != encoder);
  103509. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103510. encoder->protected_->verify = true;
  103511. #else
  103512. encoder->protected_->verify = false;
  103513. #endif
  103514. encoder->protected_->streamable_subset = true;
  103515. encoder->protected_->do_md5 = true;
  103516. encoder->protected_->do_mid_side_stereo = false;
  103517. encoder->protected_->loose_mid_side_stereo = false;
  103518. encoder->protected_->channels = 2;
  103519. encoder->protected_->bits_per_sample = 16;
  103520. encoder->protected_->sample_rate = 44100;
  103521. encoder->protected_->blocksize = 0;
  103522. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103523. encoder->protected_->num_apodizations = 1;
  103524. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103525. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103526. #endif
  103527. encoder->protected_->max_lpc_order = 0;
  103528. encoder->protected_->qlp_coeff_precision = 0;
  103529. encoder->protected_->do_qlp_coeff_prec_search = false;
  103530. encoder->protected_->do_exhaustive_model_search = false;
  103531. encoder->protected_->do_escape_coding = false;
  103532. encoder->protected_->min_residual_partition_order = 0;
  103533. encoder->protected_->max_residual_partition_order = 0;
  103534. encoder->protected_->rice_parameter_search_dist = 0;
  103535. encoder->protected_->total_samples_estimate = 0;
  103536. encoder->protected_->metadata = 0;
  103537. encoder->protected_->num_metadata_blocks = 0;
  103538. encoder->private_->seek_table = 0;
  103539. encoder->private_->disable_constant_subframes = false;
  103540. encoder->private_->disable_fixed_subframes = false;
  103541. encoder->private_->disable_verbatim_subframes = false;
  103542. #if FLAC__HAS_OGG
  103543. encoder->private_->is_ogg = false;
  103544. #endif
  103545. encoder->private_->read_callback = 0;
  103546. encoder->private_->write_callback = 0;
  103547. encoder->private_->seek_callback = 0;
  103548. encoder->private_->tell_callback = 0;
  103549. encoder->private_->metadata_callback = 0;
  103550. encoder->private_->progress_callback = 0;
  103551. encoder->private_->client_data = 0;
  103552. #if FLAC__HAS_OGG
  103553. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103554. #endif
  103555. }
  103556. void free_(FLAC__StreamEncoder *encoder)
  103557. {
  103558. unsigned i, channel;
  103559. FLAC__ASSERT(0 != encoder);
  103560. if(encoder->protected_->metadata) {
  103561. free(encoder->protected_->metadata);
  103562. encoder->protected_->metadata = 0;
  103563. encoder->protected_->num_metadata_blocks = 0;
  103564. }
  103565. for(i = 0; i < encoder->protected_->channels; i++) {
  103566. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103567. free(encoder->private_->integer_signal_unaligned[i]);
  103568. encoder->private_->integer_signal_unaligned[i] = 0;
  103569. }
  103570. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103571. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103572. free(encoder->private_->real_signal_unaligned[i]);
  103573. encoder->private_->real_signal_unaligned[i] = 0;
  103574. }
  103575. #endif
  103576. }
  103577. for(i = 0; i < 2; i++) {
  103578. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103579. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103580. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103581. }
  103582. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103583. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103584. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103585. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103586. }
  103587. #endif
  103588. }
  103589. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103590. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103591. if(0 != encoder->private_->window_unaligned[i]) {
  103592. free(encoder->private_->window_unaligned[i]);
  103593. encoder->private_->window_unaligned[i] = 0;
  103594. }
  103595. }
  103596. if(0 != encoder->private_->windowed_signal_unaligned) {
  103597. free(encoder->private_->windowed_signal_unaligned);
  103598. encoder->private_->windowed_signal_unaligned = 0;
  103599. }
  103600. #endif
  103601. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103602. for(i = 0; i < 2; i++) {
  103603. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103604. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103605. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103606. }
  103607. }
  103608. }
  103609. for(channel = 0; channel < 2; channel++) {
  103610. for(i = 0; i < 2; i++) {
  103611. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103612. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103613. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103614. }
  103615. }
  103616. }
  103617. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103618. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103619. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103620. }
  103621. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103622. free(encoder->private_->raw_bits_per_partition_unaligned);
  103623. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103624. }
  103625. if(encoder->protected_->verify) {
  103626. for(i = 0; i < encoder->protected_->channels; i++) {
  103627. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103628. free(encoder->private_->verify.input_fifo.data[i]);
  103629. encoder->private_->verify.input_fifo.data[i] = 0;
  103630. }
  103631. }
  103632. }
  103633. FLAC__bitwriter_free(encoder->private_->frame);
  103634. }
  103635. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103636. {
  103637. FLAC__bool ok;
  103638. unsigned i, channel;
  103639. FLAC__ASSERT(new_blocksize > 0);
  103640. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103641. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103642. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103643. if(new_blocksize <= encoder->private_->input_capacity)
  103644. return true;
  103645. ok = true;
  103646. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103647. * requires that the input arrays (in our case the integer signals)
  103648. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103649. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103650. */
  103651. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103652. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103653. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103654. encoder->private_->integer_signal[i] += 4;
  103655. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103656. #if 0 /* @@@ currently unused */
  103657. if(encoder->protected_->max_lpc_order > 0)
  103658. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103659. #endif
  103660. #endif
  103661. }
  103662. for(i = 0; ok && i < 2; i++) {
  103663. 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]);
  103664. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103665. encoder->private_->integer_signal_mid_side[i] += 4;
  103666. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103667. #if 0 /* @@@ currently unused */
  103668. if(encoder->protected_->max_lpc_order > 0)
  103669. 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]);
  103670. #endif
  103671. #endif
  103672. }
  103673. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103674. if(ok && encoder->protected_->max_lpc_order > 0) {
  103675. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103676. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103677. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103678. }
  103679. #endif
  103680. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103681. for(i = 0; ok && i < 2; i++) {
  103682. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103683. }
  103684. }
  103685. for(channel = 0; ok && channel < 2; channel++) {
  103686. for(i = 0; ok && i < 2; i++) {
  103687. 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]);
  103688. }
  103689. }
  103690. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103691. /*@@@ 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) */
  103692. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103693. if(encoder->protected_->do_escape_coding)
  103694. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103695. /* now adjust the windows if the blocksize has changed */
  103696. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103697. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103698. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103699. switch(encoder->protected_->apodizations[i].type) {
  103700. case FLAC__APODIZATION_BARTLETT:
  103701. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103702. break;
  103703. case FLAC__APODIZATION_BARTLETT_HANN:
  103704. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103705. break;
  103706. case FLAC__APODIZATION_BLACKMAN:
  103707. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103708. break;
  103709. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103710. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103711. break;
  103712. case FLAC__APODIZATION_CONNES:
  103713. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103714. break;
  103715. case FLAC__APODIZATION_FLATTOP:
  103716. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103717. break;
  103718. case FLAC__APODIZATION_GAUSS:
  103719. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103720. break;
  103721. case FLAC__APODIZATION_HAMMING:
  103722. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103723. break;
  103724. case FLAC__APODIZATION_HANN:
  103725. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103726. break;
  103727. case FLAC__APODIZATION_KAISER_BESSEL:
  103728. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103729. break;
  103730. case FLAC__APODIZATION_NUTTALL:
  103731. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103732. break;
  103733. case FLAC__APODIZATION_RECTANGLE:
  103734. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103735. break;
  103736. case FLAC__APODIZATION_TRIANGLE:
  103737. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103738. break;
  103739. case FLAC__APODIZATION_TUKEY:
  103740. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103741. break;
  103742. case FLAC__APODIZATION_WELCH:
  103743. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103744. break;
  103745. default:
  103746. FLAC__ASSERT(0);
  103747. /* double protection */
  103748. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103749. break;
  103750. }
  103751. }
  103752. }
  103753. #endif
  103754. if(ok)
  103755. encoder->private_->input_capacity = new_blocksize;
  103756. else
  103757. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103758. return ok;
  103759. }
  103760. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103761. {
  103762. const FLAC__byte *buffer;
  103763. size_t bytes;
  103764. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103765. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103766. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103767. return false;
  103768. }
  103769. if(encoder->protected_->verify) {
  103770. encoder->private_->verify.output.data = buffer;
  103771. encoder->private_->verify.output.bytes = bytes;
  103772. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103773. encoder->private_->verify.needs_magic_hack = true;
  103774. }
  103775. else {
  103776. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103777. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103778. FLAC__bitwriter_clear(encoder->private_->frame);
  103779. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103780. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103781. return false;
  103782. }
  103783. }
  103784. }
  103785. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103786. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103787. FLAC__bitwriter_clear(encoder->private_->frame);
  103788. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103789. return false;
  103790. }
  103791. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103792. FLAC__bitwriter_clear(encoder->private_->frame);
  103793. if(samples > 0) {
  103794. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103795. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103796. }
  103797. return true;
  103798. }
  103799. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103800. {
  103801. FLAC__StreamEncoderWriteStatus status;
  103802. FLAC__uint64 output_position = 0;
  103803. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103804. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103805. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103806. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103807. }
  103808. /*
  103809. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103810. */
  103811. if(samples == 0) {
  103812. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103813. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103814. encoder->protected_->streaminfo_offset = output_position;
  103815. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103816. encoder->protected_->seektable_offset = output_position;
  103817. }
  103818. /*
  103819. * Mark the current seek point if hit (if audio_offset == 0 that
  103820. * means we're still writing metadata and haven't hit the first
  103821. * frame yet)
  103822. */
  103823. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103824. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103825. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103826. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103827. FLAC__uint64 test_sample;
  103828. unsigned i;
  103829. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103830. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103831. if(test_sample > frame_last_sample) {
  103832. break;
  103833. }
  103834. else if(test_sample >= frame_first_sample) {
  103835. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103836. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103837. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103838. encoder->private_->first_seekpoint_to_check++;
  103839. /* DO NOT: "break;" and here's why:
  103840. * The seektable template may contain more than one target
  103841. * sample for any given frame; we will keep looping, generating
  103842. * duplicate seekpoints for them, and we'll clean it up later,
  103843. * just before writing the seektable back to the metadata.
  103844. */
  103845. }
  103846. else {
  103847. encoder->private_->first_seekpoint_to_check++;
  103848. }
  103849. }
  103850. }
  103851. #if FLAC__HAS_OGG
  103852. if(encoder->private_->is_ogg) {
  103853. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103854. &encoder->protected_->ogg_encoder_aspect,
  103855. buffer,
  103856. bytes,
  103857. samples,
  103858. encoder->private_->current_frame_number,
  103859. is_last_block,
  103860. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103861. encoder,
  103862. encoder->private_->client_data
  103863. );
  103864. }
  103865. else
  103866. #endif
  103867. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103868. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103869. encoder->private_->bytes_written += bytes;
  103870. encoder->private_->samples_written += samples;
  103871. /* we keep a high watermark on the number of frames written because
  103872. * when the encoder goes back to write metadata, 'current_frame'
  103873. * will drop back to 0.
  103874. */
  103875. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103876. }
  103877. else
  103878. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103879. return status;
  103880. }
  103881. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103882. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103883. {
  103884. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103885. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103886. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103887. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103888. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103889. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103890. FLAC__StreamEncoderSeekStatus seek_status;
  103891. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103892. /* All this is based on intimate knowledge of the stream header
  103893. * layout, but a change to the header format that would break this
  103894. * would also break all streams encoded in the previous format.
  103895. */
  103896. /*
  103897. * Write MD5 signature
  103898. */
  103899. {
  103900. const unsigned md5_offset =
  103901. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103902. (
  103903. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103904. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103905. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103906. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103907. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103908. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103909. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103910. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103911. ) / 8;
  103912. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103913. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103914. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103915. return;
  103916. }
  103917. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103918. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103919. return;
  103920. }
  103921. }
  103922. /*
  103923. * Write total samples
  103924. */
  103925. {
  103926. const unsigned total_samples_byte_offset =
  103927. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103928. (
  103929. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103930. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103931. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103932. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103933. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103934. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103935. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103936. - 4
  103937. ) / 8;
  103938. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103939. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103940. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103941. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103942. b[4] = (FLAC__byte)(samples & 0xFF);
  103943. 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) {
  103944. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103945. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103946. return;
  103947. }
  103948. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103949. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103950. return;
  103951. }
  103952. }
  103953. /*
  103954. * Write min/max framesize
  103955. */
  103956. {
  103957. const unsigned min_framesize_offset =
  103958. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103959. (
  103960. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103961. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103962. ) / 8;
  103963. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103964. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103965. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103966. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103967. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103968. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103969. 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) {
  103970. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103971. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103972. return;
  103973. }
  103974. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103975. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103976. return;
  103977. }
  103978. }
  103979. /*
  103980. * Write seektable
  103981. */
  103982. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103983. unsigned i;
  103984. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103985. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103986. 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) {
  103987. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103988. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103989. return;
  103990. }
  103991. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103992. FLAC__uint64 xx;
  103993. unsigned x;
  103994. xx = encoder->private_->seek_table->points[i].sample_number;
  103995. b[7] = (FLAC__byte)xx; xx >>= 8;
  103996. b[6] = (FLAC__byte)xx; xx >>= 8;
  103997. b[5] = (FLAC__byte)xx; xx >>= 8;
  103998. b[4] = (FLAC__byte)xx; xx >>= 8;
  103999. b[3] = (FLAC__byte)xx; xx >>= 8;
  104000. b[2] = (FLAC__byte)xx; xx >>= 8;
  104001. b[1] = (FLAC__byte)xx; xx >>= 8;
  104002. b[0] = (FLAC__byte)xx; xx >>= 8;
  104003. xx = encoder->private_->seek_table->points[i].stream_offset;
  104004. b[15] = (FLAC__byte)xx; xx >>= 8;
  104005. b[14] = (FLAC__byte)xx; xx >>= 8;
  104006. b[13] = (FLAC__byte)xx; xx >>= 8;
  104007. b[12] = (FLAC__byte)xx; xx >>= 8;
  104008. b[11] = (FLAC__byte)xx; xx >>= 8;
  104009. b[10] = (FLAC__byte)xx; xx >>= 8;
  104010. b[9] = (FLAC__byte)xx; xx >>= 8;
  104011. b[8] = (FLAC__byte)xx; xx >>= 8;
  104012. x = encoder->private_->seek_table->points[i].frame_samples;
  104013. b[17] = (FLAC__byte)x; x >>= 8;
  104014. b[16] = (FLAC__byte)x; x >>= 8;
  104015. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104016. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104017. return;
  104018. }
  104019. }
  104020. }
  104021. }
  104022. #if FLAC__HAS_OGG
  104023. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104024. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104025. {
  104026. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104027. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104028. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104029. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104030. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104031. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104032. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104033. FLAC__STREAM_SYNC_LENGTH
  104034. ;
  104035. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104036. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104037. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104038. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104039. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104040. ogg_page page;
  104041. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104042. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104043. /* Pre-check that client supports seeking, since we don't want the
  104044. * ogg_helper code to ever have to deal with this condition.
  104045. */
  104046. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104047. return;
  104048. /* All this is based on intimate knowledge of the stream header
  104049. * layout, but a change to the header format that would break this
  104050. * would also break all streams encoded in the previous format.
  104051. */
  104052. /**
  104053. ** Write STREAMINFO stats
  104054. **/
  104055. simple_ogg_page__init(&page);
  104056. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104057. simple_ogg_page__clear(&page);
  104058. return; /* state already set */
  104059. }
  104060. /*
  104061. * Write MD5 signature
  104062. */
  104063. {
  104064. const unsigned md5_offset =
  104065. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104066. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104067. (
  104068. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104069. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104070. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104071. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104072. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104073. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104074. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104075. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104076. ) / 8;
  104077. if(md5_offset + 16 > (unsigned)page.body_len) {
  104078. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104079. simple_ogg_page__clear(&page);
  104080. return;
  104081. }
  104082. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104083. }
  104084. /*
  104085. * Write total samples
  104086. */
  104087. {
  104088. const unsigned total_samples_byte_offset =
  104089. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104090. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104091. (
  104092. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104093. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104094. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104095. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104096. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104097. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104098. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104099. - 4
  104100. ) / 8;
  104101. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104102. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104103. simple_ogg_page__clear(&page);
  104104. return;
  104105. }
  104106. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104107. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104108. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104109. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104110. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104111. b[4] = (FLAC__byte)(samples & 0xFF);
  104112. memcpy(page.body + total_samples_byte_offset, b, 5);
  104113. }
  104114. /*
  104115. * Write min/max framesize
  104116. */
  104117. {
  104118. const unsigned min_framesize_offset =
  104119. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104120. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104121. (
  104122. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104123. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104124. ) / 8;
  104125. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104126. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104127. simple_ogg_page__clear(&page);
  104128. return;
  104129. }
  104130. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104131. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104132. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104133. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104134. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104135. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104136. memcpy(page.body + min_framesize_offset, b, 6);
  104137. }
  104138. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104139. simple_ogg_page__clear(&page);
  104140. return; /* state already set */
  104141. }
  104142. simple_ogg_page__clear(&page);
  104143. /*
  104144. * Write seektable
  104145. */
  104146. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104147. unsigned i;
  104148. FLAC__byte *p;
  104149. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104150. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104151. simple_ogg_page__init(&page);
  104152. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104153. simple_ogg_page__clear(&page);
  104154. return; /* state already set */
  104155. }
  104156. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104157. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104158. simple_ogg_page__clear(&page);
  104159. return;
  104160. }
  104161. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104162. FLAC__uint64 xx;
  104163. unsigned x;
  104164. xx = encoder->private_->seek_table->points[i].sample_number;
  104165. b[7] = (FLAC__byte)xx; xx >>= 8;
  104166. b[6] = (FLAC__byte)xx; xx >>= 8;
  104167. b[5] = (FLAC__byte)xx; xx >>= 8;
  104168. b[4] = (FLAC__byte)xx; xx >>= 8;
  104169. b[3] = (FLAC__byte)xx; xx >>= 8;
  104170. b[2] = (FLAC__byte)xx; xx >>= 8;
  104171. b[1] = (FLAC__byte)xx; xx >>= 8;
  104172. b[0] = (FLAC__byte)xx; xx >>= 8;
  104173. xx = encoder->private_->seek_table->points[i].stream_offset;
  104174. b[15] = (FLAC__byte)xx; xx >>= 8;
  104175. b[14] = (FLAC__byte)xx; xx >>= 8;
  104176. b[13] = (FLAC__byte)xx; xx >>= 8;
  104177. b[12] = (FLAC__byte)xx; xx >>= 8;
  104178. b[11] = (FLAC__byte)xx; xx >>= 8;
  104179. b[10] = (FLAC__byte)xx; xx >>= 8;
  104180. b[9] = (FLAC__byte)xx; xx >>= 8;
  104181. b[8] = (FLAC__byte)xx; xx >>= 8;
  104182. x = encoder->private_->seek_table->points[i].frame_samples;
  104183. b[17] = (FLAC__byte)x; x >>= 8;
  104184. b[16] = (FLAC__byte)x; x >>= 8;
  104185. memcpy(p, b, 18);
  104186. }
  104187. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104188. simple_ogg_page__clear(&page);
  104189. return; /* state already set */
  104190. }
  104191. simple_ogg_page__clear(&page);
  104192. }
  104193. }
  104194. #endif
  104195. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104196. {
  104197. FLAC__uint16 crc;
  104198. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104199. /*
  104200. * Accumulate raw signal to the MD5 signature
  104201. */
  104202. 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)) {
  104203. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104204. return false;
  104205. }
  104206. /*
  104207. * Process the frame header and subframes into the frame bitbuffer
  104208. */
  104209. if(!process_subframes_(encoder, is_fractional_block)) {
  104210. /* the above function sets the state for us in case of an error */
  104211. return false;
  104212. }
  104213. /*
  104214. * Zero-pad the frame to a byte_boundary
  104215. */
  104216. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104217. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104218. return false;
  104219. }
  104220. /*
  104221. * CRC-16 the whole thing
  104222. */
  104223. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104224. if(
  104225. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104226. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104227. ) {
  104228. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104229. return false;
  104230. }
  104231. /*
  104232. * Write it
  104233. */
  104234. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104235. /* the above function sets the state for us in case of an error */
  104236. return false;
  104237. }
  104238. /*
  104239. * Get ready for the next frame
  104240. */
  104241. encoder->private_->current_sample_number = 0;
  104242. encoder->private_->current_frame_number++;
  104243. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104244. return true;
  104245. }
  104246. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104247. {
  104248. FLAC__FrameHeader frame_header;
  104249. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104250. FLAC__bool do_independent, do_mid_side;
  104251. /*
  104252. * Calculate the min,max Rice partition orders
  104253. */
  104254. if(is_fractional_block) {
  104255. max_partition_order = 0;
  104256. }
  104257. else {
  104258. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104259. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104260. }
  104261. min_partition_order = min(min_partition_order, max_partition_order);
  104262. /*
  104263. * Setup the frame
  104264. */
  104265. frame_header.blocksize = encoder->protected_->blocksize;
  104266. frame_header.sample_rate = encoder->protected_->sample_rate;
  104267. frame_header.channels = encoder->protected_->channels;
  104268. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104269. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104270. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104271. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104272. /*
  104273. * Figure out what channel assignments to try
  104274. */
  104275. if(encoder->protected_->do_mid_side_stereo) {
  104276. if(encoder->protected_->loose_mid_side_stereo) {
  104277. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104278. do_independent = true;
  104279. do_mid_side = true;
  104280. }
  104281. else {
  104282. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104283. do_mid_side = !do_independent;
  104284. }
  104285. }
  104286. else {
  104287. do_independent = true;
  104288. do_mid_side = true;
  104289. }
  104290. }
  104291. else {
  104292. do_independent = true;
  104293. do_mid_side = false;
  104294. }
  104295. FLAC__ASSERT(do_independent || do_mid_side);
  104296. /*
  104297. * Check for wasted bits; set effective bps for each subframe
  104298. */
  104299. if(do_independent) {
  104300. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104301. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104302. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104303. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104304. }
  104305. }
  104306. if(do_mid_side) {
  104307. FLAC__ASSERT(encoder->protected_->channels == 2);
  104308. for(channel = 0; channel < 2; channel++) {
  104309. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104310. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104311. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104312. }
  104313. }
  104314. /*
  104315. * First do a normal encoding pass of each independent channel
  104316. */
  104317. if(do_independent) {
  104318. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104319. if(!
  104320. process_subframe_(
  104321. encoder,
  104322. min_partition_order,
  104323. max_partition_order,
  104324. &frame_header,
  104325. encoder->private_->subframe_bps[channel],
  104326. encoder->private_->integer_signal[channel],
  104327. encoder->private_->subframe_workspace_ptr[channel],
  104328. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104329. encoder->private_->residual_workspace[channel],
  104330. encoder->private_->best_subframe+channel,
  104331. encoder->private_->best_subframe_bits+channel
  104332. )
  104333. )
  104334. return false;
  104335. }
  104336. }
  104337. /*
  104338. * Now do mid and side channels if requested
  104339. */
  104340. if(do_mid_side) {
  104341. FLAC__ASSERT(encoder->protected_->channels == 2);
  104342. for(channel = 0; channel < 2; channel++) {
  104343. if(!
  104344. process_subframe_(
  104345. encoder,
  104346. min_partition_order,
  104347. max_partition_order,
  104348. &frame_header,
  104349. encoder->private_->subframe_bps_mid_side[channel],
  104350. encoder->private_->integer_signal_mid_side[channel],
  104351. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104352. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104353. encoder->private_->residual_workspace_mid_side[channel],
  104354. encoder->private_->best_subframe_mid_side+channel,
  104355. encoder->private_->best_subframe_bits_mid_side+channel
  104356. )
  104357. )
  104358. return false;
  104359. }
  104360. }
  104361. /*
  104362. * Compose the frame bitbuffer
  104363. */
  104364. if(do_mid_side) {
  104365. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104366. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104367. FLAC__ChannelAssignment channel_assignment;
  104368. FLAC__ASSERT(encoder->protected_->channels == 2);
  104369. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104370. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104371. }
  104372. else {
  104373. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104374. unsigned min_bits;
  104375. int ca;
  104376. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104377. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104378. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104379. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104380. FLAC__ASSERT(do_independent && do_mid_side);
  104381. /* We have to figure out which channel assignent results in the smallest frame */
  104382. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104383. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104384. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104385. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104386. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104387. min_bits = bits[channel_assignment];
  104388. for(ca = 1; ca <= 3; ca++) {
  104389. if(bits[ca] < min_bits) {
  104390. min_bits = bits[ca];
  104391. channel_assignment = (FLAC__ChannelAssignment)ca;
  104392. }
  104393. }
  104394. }
  104395. frame_header.channel_assignment = channel_assignment;
  104396. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104397. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104398. return false;
  104399. }
  104400. switch(channel_assignment) {
  104401. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104402. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104403. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104404. break;
  104405. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104406. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104407. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104408. break;
  104409. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104410. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104411. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104412. break;
  104413. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104414. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104415. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104416. break;
  104417. default:
  104418. FLAC__ASSERT(0);
  104419. }
  104420. switch(channel_assignment) {
  104421. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104422. left_bps = encoder->private_->subframe_bps [0];
  104423. right_bps = encoder->private_->subframe_bps [1];
  104424. break;
  104425. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104426. left_bps = encoder->private_->subframe_bps [0];
  104427. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104428. break;
  104429. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104430. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104431. right_bps = encoder->private_->subframe_bps [1];
  104432. break;
  104433. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104434. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104435. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104436. break;
  104437. default:
  104438. FLAC__ASSERT(0);
  104439. }
  104440. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104441. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104442. return false;
  104443. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104444. return false;
  104445. }
  104446. else {
  104447. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104448. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104449. return false;
  104450. }
  104451. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104452. 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)) {
  104453. /* the above function sets the state for us in case of an error */
  104454. return false;
  104455. }
  104456. }
  104457. }
  104458. if(encoder->protected_->loose_mid_side_stereo) {
  104459. encoder->private_->loose_mid_side_stereo_frame_count++;
  104460. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104461. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104462. }
  104463. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104464. return true;
  104465. }
  104466. FLAC__bool process_subframe_(
  104467. FLAC__StreamEncoder *encoder,
  104468. unsigned min_partition_order,
  104469. unsigned max_partition_order,
  104470. const FLAC__FrameHeader *frame_header,
  104471. unsigned subframe_bps,
  104472. const FLAC__int32 integer_signal[],
  104473. FLAC__Subframe *subframe[2],
  104474. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104475. FLAC__int32 *residual[2],
  104476. unsigned *best_subframe,
  104477. unsigned *best_bits
  104478. )
  104479. {
  104480. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104481. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104482. #else
  104483. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104484. #endif
  104485. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104486. FLAC__double lpc_residual_bits_per_sample;
  104487. 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 */
  104488. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104489. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104490. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104491. #endif
  104492. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104493. unsigned rice_parameter;
  104494. unsigned _candidate_bits, _best_bits;
  104495. unsigned _best_subframe;
  104496. /* only use RICE2 partitions if stream bps > 16 */
  104497. 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;
  104498. FLAC__ASSERT(frame_header->blocksize > 0);
  104499. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104500. _best_subframe = 0;
  104501. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104502. _best_bits = UINT_MAX;
  104503. else
  104504. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104505. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104506. unsigned signal_is_constant = false;
  104507. 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);
  104508. /* check for constant subframe */
  104509. if(
  104510. !encoder->private_->disable_constant_subframes &&
  104511. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104512. fixed_residual_bits_per_sample[1] == 0.0
  104513. #else
  104514. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104515. #endif
  104516. ) {
  104517. /* the above means it's possible all samples are the same value; now double-check it: */
  104518. unsigned i;
  104519. signal_is_constant = true;
  104520. for(i = 1; i < frame_header->blocksize; i++) {
  104521. if(integer_signal[0] != integer_signal[i]) {
  104522. signal_is_constant = false;
  104523. break;
  104524. }
  104525. }
  104526. }
  104527. if(signal_is_constant) {
  104528. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104529. if(_candidate_bits < _best_bits) {
  104530. _best_subframe = !_best_subframe;
  104531. _best_bits = _candidate_bits;
  104532. }
  104533. }
  104534. else {
  104535. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104536. /* encode fixed */
  104537. if(encoder->protected_->do_exhaustive_model_search) {
  104538. min_fixed_order = 0;
  104539. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104540. }
  104541. else {
  104542. min_fixed_order = max_fixed_order = guess_fixed_order;
  104543. }
  104544. if(max_fixed_order >= frame_header->blocksize)
  104545. max_fixed_order = frame_header->blocksize - 1;
  104546. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104547. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104548. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104549. continue; /* don't even try */
  104550. 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 */
  104551. #else
  104552. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104553. continue; /* don't even try */
  104554. 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 */
  104555. #endif
  104556. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104557. if(rice_parameter >= rice_parameter_limit) {
  104558. #ifdef DEBUG_VERBOSE
  104559. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104560. #endif
  104561. rice_parameter = rice_parameter_limit - 1;
  104562. }
  104563. _candidate_bits =
  104564. evaluate_fixed_subframe_(
  104565. encoder,
  104566. integer_signal,
  104567. residual[!_best_subframe],
  104568. encoder->private_->abs_residual_partition_sums,
  104569. encoder->private_->raw_bits_per_partition,
  104570. frame_header->blocksize,
  104571. subframe_bps,
  104572. fixed_order,
  104573. rice_parameter,
  104574. rice_parameter_limit,
  104575. min_partition_order,
  104576. max_partition_order,
  104577. encoder->protected_->do_escape_coding,
  104578. encoder->protected_->rice_parameter_search_dist,
  104579. subframe[!_best_subframe],
  104580. partitioned_rice_contents[!_best_subframe]
  104581. );
  104582. if(_candidate_bits < _best_bits) {
  104583. _best_subframe = !_best_subframe;
  104584. _best_bits = _candidate_bits;
  104585. }
  104586. }
  104587. }
  104588. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104589. /* encode lpc */
  104590. if(encoder->protected_->max_lpc_order > 0) {
  104591. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104592. max_lpc_order = frame_header->blocksize-1;
  104593. else
  104594. max_lpc_order = encoder->protected_->max_lpc_order;
  104595. if(max_lpc_order > 0) {
  104596. unsigned a;
  104597. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104598. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104599. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104600. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104601. if(autoc[0] != 0.0) {
  104602. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104603. if(encoder->protected_->do_exhaustive_model_search) {
  104604. min_lpc_order = 1;
  104605. }
  104606. else {
  104607. const unsigned guess_lpc_order =
  104608. FLAC__lpc_compute_best_order(
  104609. lpc_error,
  104610. max_lpc_order,
  104611. frame_header->blocksize,
  104612. subframe_bps + (
  104613. encoder->protected_->do_qlp_coeff_prec_search?
  104614. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104615. encoder->protected_->qlp_coeff_precision
  104616. )
  104617. );
  104618. min_lpc_order = max_lpc_order = guess_lpc_order;
  104619. }
  104620. if(max_lpc_order >= frame_header->blocksize)
  104621. max_lpc_order = frame_header->blocksize - 1;
  104622. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104623. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104624. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104625. continue; /* don't even try */
  104626. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104627. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104628. if(rice_parameter >= rice_parameter_limit) {
  104629. #ifdef DEBUG_VERBOSE
  104630. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104631. #endif
  104632. rice_parameter = rice_parameter_limit - 1;
  104633. }
  104634. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104635. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104636. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104637. if(subframe_bps <= 17) {
  104638. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104639. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104640. }
  104641. else
  104642. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104643. }
  104644. else {
  104645. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104646. }
  104647. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104648. _candidate_bits =
  104649. evaluate_lpc_subframe_(
  104650. encoder,
  104651. integer_signal,
  104652. residual[!_best_subframe],
  104653. encoder->private_->abs_residual_partition_sums,
  104654. encoder->private_->raw_bits_per_partition,
  104655. encoder->private_->lp_coeff[lpc_order-1],
  104656. frame_header->blocksize,
  104657. subframe_bps,
  104658. lpc_order,
  104659. qlp_coeff_precision,
  104660. rice_parameter,
  104661. rice_parameter_limit,
  104662. min_partition_order,
  104663. max_partition_order,
  104664. encoder->protected_->do_escape_coding,
  104665. encoder->protected_->rice_parameter_search_dist,
  104666. subframe[!_best_subframe],
  104667. partitioned_rice_contents[!_best_subframe]
  104668. );
  104669. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104670. if(_candidate_bits < _best_bits) {
  104671. _best_subframe = !_best_subframe;
  104672. _best_bits = _candidate_bits;
  104673. }
  104674. }
  104675. }
  104676. }
  104677. }
  104678. }
  104679. }
  104680. }
  104681. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104682. }
  104683. }
  104684. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104685. if(_best_bits == UINT_MAX) {
  104686. FLAC__ASSERT(_best_subframe == 0);
  104687. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104688. }
  104689. *best_subframe = _best_subframe;
  104690. *best_bits = _best_bits;
  104691. return true;
  104692. }
  104693. FLAC__bool add_subframe_(
  104694. FLAC__StreamEncoder *encoder,
  104695. unsigned blocksize,
  104696. unsigned subframe_bps,
  104697. const FLAC__Subframe *subframe,
  104698. FLAC__BitWriter *frame
  104699. )
  104700. {
  104701. switch(subframe->type) {
  104702. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104703. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104704. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104705. return false;
  104706. }
  104707. break;
  104708. case FLAC__SUBFRAME_TYPE_FIXED:
  104709. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104710. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104711. return false;
  104712. }
  104713. break;
  104714. case FLAC__SUBFRAME_TYPE_LPC:
  104715. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104716. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104717. return false;
  104718. }
  104719. break;
  104720. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104721. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104722. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104723. return false;
  104724. }
  104725. break;
  104726. default:
  104727. FLAC__ASSERT(0);
  104728. }
  104729. return true;
  104730. }
  104731. #define SPOTCHECK_ESTIMATE 0
  104732. #if SPOTCHECK_ESTIMATE
  104733. static void spotcheck_subframe_estimate_(
  104734. FLAC__StreamEncoder *encoder,
  104735. unsigned blocksize,
  104736. unsigned subframe_bps,
  104737. const FLAC__Subframe *subframe,
  104738. unsigned estimate
  104739. )
  104740. {
  104741. FLAC__bool ret;
  104742. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104743. if(frame == 0) {
  104744. fprintf(stderr, "EST: can't allocate frame\n");
  104745. return;
  104746. }
  104747. if(!FLAC__bitwriter_init(frame)) {
  104748. fprintf(stderr, "EST: can't init frame\n");
  104749. return;
  104750. }
  104751. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104752. FLAC__ASSERT(ret);
  104753. {
  104754. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104755. if(estimate != actual)
  104756. 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);
  104757. }
  104758. FLAC__bitwriter_delete(frame);
  104759. }
  104760. #endif
  104761. unsigned evaluate_constant_subframe_(
  104762. FLAC__StreamEncoder *encoder,
  104763. const FLAC__int32 signal,
  104764. unsigned blocksize,
  104765. unsigned subframe_bps,
  104766. FLAC__Subframe *subframe
  104767. )
  104768. {
  104769. unsigned estimate;
  104770. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104771. subframe->data.constant.value = signal;
  104772. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104773. #if SPOTCHECK_ESTIMATE
  104774. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104775. #else
  104776. (void)encoder, (void)blocksize;
  104777. #endif
  104778. return estimate;
  104779. }
  104780. unsigned evaluate_fixed_subframe_(
  104781. FLAC__StreamEncoder *encoder,
  104782. const FLAC__int32 signal[],
  104783. FLAC__int32 residual[],
  104784. FLAC__uint64 abs_residual_partition_sums[],
  104785. unsigned raw_bits_per_partition[],
  104786. unsigned blocksize,
  104787. unsigned subframe_bps,
  104788. unsigned order,
  104789. unsigned rice_parameter,
  104790. unsigned rice_parameter_limit,
  104791. unsigned min_partition_order,
  104792. unsigned max_partition_order,
  104793. FLAC__bool do_escape_coding,
  104794. unsigned rice_parameter_search_dist,
  104795. FLAC__Subframe *subframe,
  104796. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104797. )
  104798. {
  104799. unsigned i, residual_bits, estimate;
  104800. const unsigned residual_samples = blocksize - order;
  104801. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104802. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104803. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104804. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104805. subframe->data.fixed.residual = residual;
  104806. residual_bits =
  104807. find_best_partition_order_(
  104808. encoder->private_,
  104809. residual,
  104810. abs_residual_partition_sums,
  104811. raw_bits_per_partition,
  104812. residual_samples,
  104813. order,
  104814. rice_parameter,
  104815. rice_parameter_limit,
  104816. min_partition_order,
  104817. max_partition_order,
  104818. subframe_bps,
  104819. do_escape_coding,
  104820. rice_parameter_search_dist,
  104821. &subframe->data.fixed.entropy_coding_method
  104822. );
  104823. subframe->data.fixed.order = order;
  104824. for(i = 0; i < order; i++)
  104825. subframe->data.fixed.warmup[i] = signal[i];
  104826. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104827. #if SPOTCHECK_ESTIMATE
  104828. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104829. #endif
  104830. return estimate;
  104831. }
  104832. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104833. unsigned evaluate_lpc_subframe_(
  104834. FLAC__StreamEncoder *encoder,
  104835. const FLAC__int32 signal[],
  104836. FLAC__int32 residual[],
  104837. FLAC__uint64 abs_residual_partition_sums[],
  104838. unsigned raw_bits_per_partition[],
  104839. const FLAC__real lp_coeff[],
  104840. unsigned blocksize,
  104841. unsigned subframe_bps,
  104842. unsigned order,
  104843. unsigned qlp_coeff_precision,
  104844. unsigned rice_parameter,
  104845. unsigned rice_parameter_limit,
  104846. unsigned min_partition_order,
  104847. unsigned max_partition_order,
  104848. FLAC__bool do_escape_coding,
  104849. unsigned rice_parameter_search_dist,
  104850. FLAC__Subframe *subframe,
  104851. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104852. )
  104853. {
  104854. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104855. unsigned i, residual_bits, estimate;
  104856. int quantization, ret;
  104857. const unsigned residual_samples = blocksize - order;
  104858. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104859. if(subframe_bps <= 16) {
  104860. FLAC__ASSERT(order > 0);
  104861. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104862. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104863. }
  104864. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104865. if(ret != 0)
  104866. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104867. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104868. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104869. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104870. else
  104871. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104872. else
  104873. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104874. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104875. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104876. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104877. subframe->data.lpc.residual = residual;
  104878. residual_bits =
  104879. find_best_partition_order_(
  104880. encoder->private_,
  104881. residual,
  104882. abs_residual_partition_sums,
  104883. raw_bits_per_partition,
  104884. residual_samples,
  104885. order,
  104886. rice_parameter,
  104887. rice_parameter_limit,
  104888. min_partition_order,
  104889. max_partition_order,
  104890. subframe_bps,
  104891. do_escape_coding,
  104892. rice_parameter_search_dist,
  104893. &subframe->data.lpc.entropy_coding_method
  104894. );
  104895. subframe->data.lpc.order = order;
  104896. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104897. subframe->data.lpc.quantization_level = quantization;
  104898. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104899. for(i = 0; i < order; i++)
  104900. subframe->data.lpc.warmup[i] = signal[i];
  104901. 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;
  104902. #if SPOTCHECK_ESTIMATE
  104903. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104904. #endif
  104905. return estimate;
  104906. }
  104907. #endif
  104908. unsigned evaluate_verbatim_subframe_(
  104909. FLAC__StreamEncoder *encoder,
  104910. const FLAC__int32 signal[],
  104911. unsigned blocksize,
  104912. unsigned subframe_bps,
  104913. FLAC__Subframe *subframe
  104914. )
  104915. {
  104916. unsigned estimate;
  104917. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104918. subframe->data.verbatim.data = signal;
  104919. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104920. #if SPOTCHECK_ESTIMATE
  104921. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104922. #else
  104923. (void)encoder;
  104924. #endif
  104925. return estimate;
  104926. }
  104927. unsigned find_best_partition_order_(
  104928. FLAC__StreamEncoderPrivate *private_,
  104929. const FLAC__int32 residual[],
  104930. FLAC__uint64 abs_residual_partition_sums[],
  104931. unsigned raw_bits_per_partition[],
  104932. unsigned residual_samples,
  104933. unsigned predictor_order,
  104934. unsigned rice_parameter,
  104935. unsigned rice_parameter_limit,
  104936. unsigned min_partition_order,
  104937. unsigned max_partition_order,
  104938. unsigned bps,
  104939. FLAC__bool do_escape_coding,
  104940. unsigned rice_parameter_search_dist,
  104941. FLAC__EntropyCodingMethod *best_ecm
  104942. )
  104943. {
  104944. unsigned residual_bits, best_residual_bits = 0;
  104945. unsigned best_parameters_index = 0;
  104946. unsigned best_partition_order = 0;
  104947. const unsigned blocksize = residual_samples + predictor_order;
  104948. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104949. min_partition_order = min(min_partition_order, max_partition_order);
  104950. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104951. if(do_escape_coding)
  104952. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104953. {
  104954. int partition_order;
  104955. unsigned sum;
  104956. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104957. if(!
  104958. set_partitioned_rice_(
  104959. #ifdef EXACT_RICE_BITS_CALCULATION
  104960. residual,
  104961. #endif
  104962. abs_residual_partition_sums+sum,
  104963. raw_bits_per_partition+sum,
  104964. residual_samples,
  104965. predictor_order,
  104966. rice_parameter,
  104967. rice_parameter_limit,
  104968. rice_parameter_search_dist,
  104969. (unsigned)partition_order,
  104970. do_escape_coding,
  104971. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104972. &residual_bits
  104973. )
  104974. )
  104975. {
  104976. FLAC__ASSERT(best_residual_bits != 0);
  104977. break;
  104978. }
  104979. sum += 1u << partition_order;
  104980. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104981. best_residual_bits = residual_bits;
  104982. best_parameters_index = !best_parameters_index;
  104983. best_partition_order = partition_order;
  104984. }
  104985. }
  104986. }
  104987. best_ecm->data.partitioned_rice.order = best_partition_order;
  104988. {
  104989. /*
  104990. * We are allowed to de-const the pointer based on our special
  104991. * knowledge; it is const to the outside world.
  104992. */
  104993. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104994. unsigned partition;
  104995. /* save best parameters and raw_bits */
  104996. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104997. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104998. if(do_escape_coding)
  104999. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105000. /*
  105001. * Now need to check if the type should be changed to
  105002. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105003. * size of the rice parameters.
  105004. */
  105005. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105006. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105007. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105008. break;
  105009. }
  105010. }
  105011. }
  105012. return best_residual_bits;
  105013. }
  105014. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105015. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105016. const FLAC__int32 residual[],
  105017. FLAC__uint64 abs_residual_partition_sums[],
  105018. unsigned blocksize,
  105019. unsigned predictor_order,
  105020. unsigned min_partition_order,
  105021. unsigned max_partition_order
  105022. );
  105023. #endif
  105024. void precompute_partition_info_sums_(
  105025. const FLAC__int32 residual[],
  105026. FLAC__uint64 abs_residual_partition_sums[],
  105027. unsigned residual_samples,
  105028. unsigned predictor_order,
  105029. unsigned min_partition_order,
  105030. unsigned max_partition_order,
  105031. unsigned bps
  105032. )
  105033. {
  105034. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105035. unsigned partitions = 1u << max_partition_order;
  105036. FLAC__ASSERT(default_partition_samples > predictor_order);
  105037. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105038. /* slightly pessimistic but still catches all common cases */
  105039. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105040. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105041. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105042. return;
  105043. }
  105044. #endif
  105045. /* first do max_partition_order */
  105046. {
  105047. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105048. /* slightly pessimistic but still catches all common cases */
  105049. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105050. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105051. FLAC__uint32 abs_residual_partition_sum;
  105052. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105053. end += default_partition_samples;
  105054. abs_residual_partition_sum = 0;
  105055. for( ; residual_sample < end; residual_sample++)
  105056. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105057. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105058. }
  105059. }
  105060. else { /* have to pessimistically use 64 bits for accumulator */
  105061. FLAC__uint64 abs_residual_partition_sum;
  105062. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105063. end += default_partition_samples;
  105064. abs_residual_partition_sum = 0;
  105065. for( ; residual_sample < end; residual_sample++)
  105066. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105067. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105068. }
  105069. }
  105070. }
  105071. /* now merge partitions for lower orders */
  105072. {
  105073. unsigned from_partition = 0, to_partition = partitions;
  105074. int partition_order;
  105075. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105076. unsigned i;
  105077. partitions >>= 1;
  105078. for(i = 0; i < partitions; i++) {
  105079. abs_residual_partition_sums[to_partition++] =
  105080. abs_residual_partition_sums[from_partition ] +
  105081. abs_residual_partition_sums[from_partition+1];
  105082. from_partition += 2;
  105083. }
  105084. }
  105085. }
  105086. }
  105087. void precompute_partition_info_escapes_(
  105088. const FLAC__int32 residual[],
  105089. unsigned raw_bits_per_partition[],
  105090. unsigned residual_samples,
  105091. unsigned predictor_order,
  105092. unsigned min_partition_order,
  105093. unsigned max_partition_order
  105094. )
  105095. {
  105096. int partition_order;
  105097. unsigned from_partition, to_partition = 0;
  105098. const unsigned blocksize = residual_samples + predictor_order;
  105099. /* first do max_partition_order */
  105100. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105101. FLAC__int32 r;
  105102. FLAC__uint32 rmax;
  105103. unsigned partition, partition_sample, partition_samples, residual_sample;
  105104. const unsigned partitions = 1u << partition_order;
  105105. const unsigned default_partition_samples = blocksize >> partition_order;
  105106. FLAC__ASSERT(default_partition_samples > predictor_order);
  105107. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105108. partition_samples = default_partition_samples;
  105109. if(partition == 0)
  105110. partition_samples -= predictor_order;
  105111. rmax = 0;
  105112. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105113. r = residual[residual_sample++];
  105114. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105115. if(r < 0)
  105116. rmax |= ~r;
  105117. else
  105118. rmax |= r;
  105119. }
  105120. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105121. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105122. }
  105123. to_partition = partitions;
  105124. break; /*@@@ yuck, should remove the 'for' loop instead */
  105125. }
  105126. /* now merge partitions for lower orders */
  105127. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105128. unsigned m;
  105129. unsigned i;
  105130. const unsigned partitions = 1u << partition_order;
  105131. for(i = 0; i < partitions; i++) {
  105132. m = raw_bits_per_partition[from_partition];
  105133. from_partition++;
  105134. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105135. from_partition++;
  105136. to_partition++;
  105137. }
  105138. }
  105139. }
  105140. #ifdef EXACT_RICE_BITS_CALCULATION
  105141. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105142. const unsigned rice_parameter,
  105143. const unsigned partition_samples,
  105144. const FLAC__int32 *residual
  105145. )
  105146. {
  105147. unsigned i, partition_bits =
  105148. 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 */
  105149. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105150. ;
  105151. for(i = 0; i < partition_samples; i++)
  105152. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105153. return partition_bits;
  105154. }
  105155. #else
  105156. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105157. const unsigned rice_parameter,
  105158. const unsigned partition_samples,
  105159. const FLAC__uint64 abs_residual_partition_sum
  105160. )
  105161. {
  105162. return
  105163. 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 */
  105164. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105165. (
  105166. rice_parameter?
  105167. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105168. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105169. )
  105170. - (partition_samples >> 1)
  105171. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105172. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105173. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105174. * So the subtraction term tries to guess how many extra bits were contributed.
  105175. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105176. */
  105177. ;
  105178. }
  105179. #endif
  105180. FLAC__bool set_partitioned_rice_(
  105181. #ifdef EXACT_RICE_BITS_CALCULATION
  105182. const FLAC__int32 residual[],
  105183. #endif
  105184. const FLAC__uint64 abs_residual_partition_sums[],
  105185. const unsigned raw_bits_per_partition[],
  105186. const unsigned residual_samples,
  105187. const unsigned predictor_order,
  105188. const unsigned suggested_rice_parameter,
  105189. const unsigned rice_parameter_limit,
  105190. const unsigned rice_parameter_search_dist,
  105191. const unsigned partition_order,
  105192. const FLAC__bool search_for_escapes,
  105193. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105194. unsigned *bits
  105195. )
  105196. {
  105197. unsigned rice_parameter, partition_bits;
  105198. unsigned best_partition_bits, best_rice_parameter = 0;
  105199. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105200. unsigned *parameters, *raw_bits;
  105201. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105202. unsigned min_rice_parameter, max_rice_parameter;
  105203. #else
  105204. (void)rice_parameter_search_dist;
  105205. #endif
  105206. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105207. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105208. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105209. parameters = partitioned_rice_contents->parameters;
  105210. raw_bits = partitioned_rice_contents->raw_bits;
  105211. if(partition_order == 0) {
  105212. best_partition_bits = (unsigned)(-1);
  105213. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105214. if(rice_parameter_search_dist) {
  105215. if(suggested_rice_parameter < rice_parameter_search_dist)
  105216. min_rice_parameter = 0;
  105217. else
  105218. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105219. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105220. if(max_rice_parameter >= rice_parameter_limit) {
  105221. #ifdef DEBUG_VERBOSE
  105222. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105223. #endif
  105224. max_rice_parameter = rice_parameter_limit - 1;
  105225. }
  105226. }
  105227. else
  105228. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105229. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105230. #else
  105231. rice_parameter = suggested_rice_parameter;
  105232. #endif
  105233. #ifdef EXACT_RICE_BITS_CALCULATION
  105234. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105235. #else
  105236. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105237. #endif
  105238. if(partition_bits < best_partition_bits) {
  105239. best_rice_parameter = rice_parameter;
  105240. best_partition_bits = partition_bits;
  105241. }
  105242. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105243. }
  105244. #endif
  105245. if(search_for_escapes) {
  105246. 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;
  105247. if(partition_bits <= best_partition_bits) {
  105248. raw_bits[0] = raw_bits_per_partition[0];
  105249. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105250. best_partition_bits = partition_bits;
  105251. }
  105252. else
  105253. raw_bits[0] = 0;
  105254. }
  105255. parameters[0] = best_rice_parameter;
  105256. bits_ += best_partition_bits;
  105257. }
  105258. else {
  105259. unsigned partition, residual_sample;
  105260. unsigned partition_samples;
  105261. FLAC__uint64 mean, k;
  105262. const unsigned partitions = 1u << partition_order;
  105263. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105264. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105265. if(partition == 0) {
  105266. if(partition_samples <= predictor_order)
  105267. return false;
  105268. else
  105269. partition_samples -= predictor_order;
  105270. }
  105271. mean = abs_residual_partition_sums[partition];
  105272. /* we are basically calculating the size in bits of the
  105273. * average residual magnitude in the partition:
  105274. * rice_parameter = floor(log2(mean/partition_samples))
  105275. * 'mean' is not a good name for the variable, it is
  105276. * actually the sum of magnitudes of all residual values
  105277. * in the partition, so the actual mean is
  105278. * mean/partition_samples
  105279. */
  105280. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105281. ;
  105282. if(rice_parameter >= rice_parameter_limit) {
  105283. #ifdef DEBUG_VERBOSE
  105284. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105285. #endif
  105286. rice_parameter = rice_parameter_limit - 1;
  105287. }
  105288. best_partition_bits = (unsigned)(-1);
  105289. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105290. if(rice_parameter_search_dist) {
  105291. if(rice_parameter < rice_parameter_search_dist)
  105292. min_rice_parameter = 0;
  105293. else
  105294. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105295. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105296. if(max_rice_parameter >= rice_parameter_limit) {
  105297. #ifdef DEBUG_VERBOSE
  105298. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105299. #endif
  105300. max_rice_parameter = rice_parameter_limit - 1;
  105301. }
  105302. }
  105303. else
  105304. min_rice_parameter = max_rice_parameter = rice_parameter;
  105305. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105306. #endif
  105307. #ifdef EXACT_RICE_BITS_CALCULATION
  105308. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105309. #else
  105310. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105311. #endif
  105312. if(partition_bits < best_partition_bits) {
  105313. best_rice_parameter = rice_parameter;
  105314. best_partition_bits = partition_bits;
  105315. }
  105316. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105317. }
  105318. #endif
  105319. if(search_for_escapes) {
  105320. 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;
  105321. if(partition_bits <= best_partition_bits) {
  105322. raw_bits[partition] = raw_bits_per_partition[partition];
  105323. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105324. best_partition_bits = partition_bits;
  105325. }
  105326. else
  105327. raw_bits[partition] = 0;
  105328. }
  105329. parameters[partition] = best_rice_parameter;
  105330. bits_ += best_partition_bits;
  105331. residual_sample += partition_samples;
  105332. }
  105333. }
  105334. *bits = bits_;
  105335. return true;
  105336. }
  105337. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105338. {
  105339. unsigned i, shift;
  105340. FLAC__int32 x = 0;
  105341. for(i = 0; i < samples && !(x&1); i++)
  105342. x |= signal[i];
  105343. if(x == 0) {
  105344. shift = 0;
  105345. }
  105346. else {
  105347. for(shift = 0; !(x&1); shift++)
  105348. x >>= 1;
  105349. }
  105350. if(shift > 0) {
  105351. for(i = 0; i < samples; i++)
  105352. signal[i] >>= shift;
  105353. }
  105354. return shift;
  105355. }
  105356. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105357. {
  105358. unsigned channel;
  105359. for(channel = 0; channel < channels; channel++)
  105360. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105361. fifo->tail += wide_samples;
  105362. FLAC__ASSERT(fifo->tail <= fifo->size);
  105363. }
  105364. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105365. {
  105366. unsigned channel;
  105367. unsigned sample, wide_sample;
  105368. unsigned tail = fifo->tail;
  105369. sample = input_offset * channels;
  105370. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105371. for(channel = 0; channel < channels; channel++)
  105372. fifo->data[channel][tail] = input[sample++];
  105373. tail++;
  105374. }
  105375. fifo->tail = tail;
  105376. FLAC__ASSERT(fifo->tail <= fifo->size);
  105377. }
  105378. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105379. {
  105380. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105381. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105382. (void)decoder;
  105383. if(encoder->private_->verify.needs_magic_hack) {
  105384. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105385. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105386. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105387. encoder->private_->verify.needs_magic_hack = false;
  105388. }
  105389. else {
  105390. if(encoded_bytes == 0) {
  105391. /*
  105392. * If we get here, a FIFO underflow has occurred,
  105393. * which means there is a bug somewhere.
  105394. */
  105395. FLAC__ASSERT(0);
  105396. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105397. }
  105398. else if(encoded_bytes < *bytes)
  105399. *bytes = encoded_bytes;
  105400. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105401. encoder->private_->verify.output.data += *bytes;
  105402. encoder->private_->verify.output.bytes -= *bytes;
  105403. }
  105404. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105405. }
  105406. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105407. {
  105408. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105409. unsigned channel;
  105410. const unsigned channels = frame->header.channels;
  105411. const unsigned blocksize = frame->header.blocksize;
  105412. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105413. (void)decoder;
  105414. for(channel = 0; channel < channels; channel++) {
  105415. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105416. unsigned i, sample = 0;
  105417. FLAC__int32 expect = 0, got = 0;
  105418. for(i = 0; i < blocksize; i++) {
  105419. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105420. sample = i;
  105421. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105422. got = (FLAC__int32)buffer[channel][i];
  105423. break;
  105424. }
  105425. }
  105426. FLAC__ASSERT(i < blocksize);
  105427. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105428. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105429. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105430. encoder->private_->verify.error_stats.channel = channel;
  105431. encoder->private_->verify.error_stats.sample = sample;
  105432. encoder->private_->verify.error_stats.expected = expect;
  105433. encoder->private_->verify.error_stats.got = got;
  105434. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105435. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105436. }
  105437. }
  105438. /* dequeue the frame from the fifo */
  105439. encoder->private_->verify.input_fifo.tail -= blocksize;
  105440. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105441. for(channel = 0; channel < channels; channel++)
  105442. 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]));
  105443. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105444. }
  105445. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105446. {
  105447. (void)decoder, (void)metadata, (void)client_data;
  105448. }
  105449. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105450. {
  105451. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105452. (void)decoder, (void)status;
  105453. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105454. }
  105455. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105456. {
  105457. (void)client_data;
  105458. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105459. if (*bytes == 0) {
  105460. if (feof(encoder->private_->file))
  105461. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105462. else if (ferror(encoder->private_->file))
  105463. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105464. }
  105465. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105466. }
  105467. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105468. {
  105469. (void)client_data;
  105470. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105471. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105472. else
  105473. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105474. }
  105475. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105476. {
  105477. off_t offset;
  105478. (void)client_data;
  105479. offset = ftello(encoder->private_->file);
  105480. if(offset < 0) {
  105481. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105482. }
  105483. else {
  105484. *absolute_byte_offset = (FLAC__uint64)offset;
  105485. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105486. }
  105487. }
  105488. #ifdef FLAC__VALGRIND_TESTING
  105489. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105490. {
  105491. size_t ret = fwrite(ptr, size, nmemb, stream);
  105492. if(!ferror(stream))
  105493. fflush(stream);
  105494. return ret;
  105495. }
  105496. #else
  105497. #define local__fwrite fwrite
  105498. #endif
  105499. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105500. {
  105501. (void)client_data, (void)current_frame;
  105502. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105503. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105504. #if FLAC__HAS_OGG
  105505. /* We would like to be able to use 'samples > 0' in the
  105506. * clause here but currently because of the nature of our
  105507. * Ogg writing implementation, 'samples' is always 0 (see
  105508. * ogg_encoder_aspect.c). The downside is extra progress
  105509. * callbacks.
  105510. */
  105511. encoder->private_->is_ogg? true :
  105512. #endif
  105513. samples > 0
  105514. );
  105515. if(call_it) {
  105516. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105517. * because at this point in the callback chain, the stats
  105518. * have not been updated. Only after we return and control
  105519. * gets back to write_frame_() are the stats updated
  105520. */
  105521. 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);
  105522. }
  105523. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105524. }
  105525. else
  105526. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105527. }
  105528. /*
  105529. * This will forcibly set stdout to binary mode (for OSes that require it)
  105530. */
  105531. FILE *get_binary_stdout_(void)
  105532. {
  105533. /* if something breaks here it is probably due to the presence or
  105534. * absence of an underscore before the identifiers 'setmode',
  105535. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105536. */
  105537. #if defined _MSC_VER || defined __MINGW32__
  105538. _setmode(_fileno(stdout), _O_BINARY);
  105539. #elif defined __CYGWIN__
  105540. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105541. setmode(_fileno(stdout), _O_BINARY);
  105542. #elif defined __EMX__
  105543. setmode(fileno(stdout), O_BINARY);
  105544. #endif
  105545. return stdout;
  105546. }
  105547. #endif
  105548. /*** End of inlined file: stream_encoder.c ***/
  105549. /*** Start of inlined file: stream_encoder_framing.c ***/
  105550. /*** Start of inlined file: juce_FlacHeader.h ***/
  105551. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105552. // tasks..
  105553. #define VERSION "1.2.1"
  105554. #define FLAC__NO_DLL 1
  105555. #if JUCE_MSVC
  105556. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105557. #endif
  105558. #if JUCE_MAC
  105559. #define FLAC__SYS_DARWIN 1
  105560. #endif
  105561. /*** End of inlined file: juce_FlacHeader.h ***/
  105562. #if JUCE_USE_FLAC
  105563. #if HAVE_CONFIG_H
  105564. # include <config.h>
  105565. #endif
  105566. #include <stdio.h>
  105567. #include <string.h> /* for strlen() */
  105568. #ifdef max
  105569. #undef max
  105570. #endif
  105571. #define max(x,y) ((x)>(y)?(x):(y))
  105572. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105573. 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);
  105574. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105575. {
  105576. unsigned i, j;
  105577. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105578. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105579. return false;
  105580. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105581. return false;
  105582. /*
  105583. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105584. */
  105585. i = metadata->length;
  105586. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105587. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105588. i -= metadata->data.vorbis_comment.vendor_string.length;
  105589. i += vendor_string_length;
  105590. }
  105591. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105592. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105593. return false;
  105594. switch(metadata->type) {
  105595. case FLAC__METADATA_TYPE_STREAMINFO:
  105596. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105597. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105598. return false;
  105599. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105600. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105601. return false;
  105602. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105603. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105604. return false;
  105605. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105606. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105607. return false;
  105608. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105609. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105610. return false;
  105611. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105612. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105613. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105614. return false;
  105615. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105616. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105617. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105618. return false;
  105619. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105620. return false;
  105621. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105622. return false;
  105623. break;
  105624. case FLAC__METADATA_TYPE_PADDING:
  105625. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105626. return false;
  105627. break;
  105628. case FLAC__METADATA_TYPE_APPLICATION:
  105629. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105630. return false;
  105631. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105632. return false;
  105633. break;
  105634. case FLAC__METADATA_TYPE_SEEKTABLE:
  105635. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105636. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105637. return false;
  105638. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105639. return false;
  105640. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105641. return false;
  105642. }
  105643. break;
  105644. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105645. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105646. return false;
  105647. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105648. return false;
  105649. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105650. return false;
  105651. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105652. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105653. return false;
  105654. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105655. return false;
  105656. }
  105657. break;
  105658. case FLAC__METADATA_TYPE_CUESHEET:
  105659. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105660. 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))
  105661. return false;
  105662. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105663. return false;
  105664. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105665. return false;
  105666. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105667. return false;
  105668. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105669. return false;
  105670. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105671. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105672. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105673. return false;
  105674. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105675. return false;
  105676. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105677. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105678. return false;
  105679. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105680. return false;
  105681. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105682. return false;
  105683. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105684. return false;
  105685. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105686. return false;
  105687. for(j = 0; j < track->num_indices; j++) {
  105688. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105689. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105690. return false;
  105691. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105692. return false;
  105693. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105694. return false;
  105695. }
  105696. }
  105697. break;
  105698. case FLAC__METADATA_TYPE_PICTURE:
  105699. {
  105700. size_t len;
  105701. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105702. return false;
  105703. len = strlen(metadata->data.picture.mime_type);
  105704. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105705. return false;
  105706. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105707. return false;
  105708. len = strlen((const char *)metadata->data.picture.description);
  105709. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105710. return false;
  105711. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105712. return false;
  105713. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105714. return false;
  105715. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105716. return false;
  105717. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105718. return false;
  105719. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105720. return false;
  105721. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105722. return false;
  105723. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105724. return false;
  105725. }
  105726. break;
  105727. default:
  105728. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105729. return false;
  105730. break;
  105731. }
  105732. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105733. return true;
  105734. }
  105735. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105736. {
  105737. unsigned u, blocksize_hint, sample_rate_hint;
  105738. FLAC__byte crc;
  105739. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105740. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105741. return false;
  105742. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105743. return false;
  105744. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105745. return false;
  105746. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105747. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105748. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105749. blocksize_hint = 0;
  105750. switch(header->blocksize) {
  105751. case 192: u = 1; break;
  105752. case 576: u = 2; break;
  105753. case 1152: u = 3; break;
  105754. case 2304: u = 4; break;
  105755. case 4608: u = 5; break;
  105756. case 256: u = 8; break;
  105757. case 512: u = 9; break;
  105758. case 1024: u = 10; break;
  105759. case 2048: u = 11; break;
  105760. case 4096: u = 12; break;
  105761. case 8192: u = 13; break;
  105762. case 16384: u = 14; break;
  105763. case 32768: u = 15; break;
  105764. default:
  105765. if(header->blocksize <= 0x100)
  105766. blocksize_hint = u = 6;
  105767. else
  105768. blocksize_hint = u = 7;
  105769. break;
  105770. }
  105771. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105772. return false;
  105773. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105774. sample_rate_hint = 0;
  105775. switch(header->sample_rate) {
  105776. case 88200: u = 1; break;
  105777. case 176400: u = 2; break;
  105778. case 192000: u = 3; break;
  105779. case 8000: u = 4; break;
  105780. case 16000: u = 5; break;
  105781. case 22050: u = 6; break;
  105782. case 24000: u = 7; break;
  105783. case 32000: u = 8; break;
  105784. case 44100: u = 9; break;
  105785. case 48000: u = 10; break;
  105786. case 96000: u = 11; break;
  105787. default:
  105788. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105789. sample_rate_hint = u = 12;
  105790. else if(header->sample_rate % 10 == 0)
  105791. sample_rate_hint = u = 14;
  105792. else if(header->sample_rate <= 0xffff)
  105793. sample_rate_hint = u = 13;
  105794. else
  105795. u = 0;
  105796. break;
  105797. }
  105798. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105799. return false;
  105800. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105801. switch(header->channel_assignment) {
  105802. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105803. u = header->channels - 1;
  105804. break;
  105805. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105806. FLAC__ASSERT(header->channels == 2);
  105807. u = 8;
  105808. break;
  105809. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105810. FLAC__ASSERT(header->channels == 2);
  105811. u = 9;
  105812. break;
  105813. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105814. FLAC__ASSERT(header->channels == 2);
  105815. u = 10;
  105816. break;
  105817. default:
  105818. FLAC__ASSERT(0);
  105819. }
  105820. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105821. return false;
  105822. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105823. switch(header->bits_per_sample) {
  105824. case 8 : u = 1; break;
  105825. case 12: u = 2; break;
  105826. case 16: u = 4; break;
  105827. case 20: u = 5; break;
  105828. case 24: u = 6; break;
  105829. default: u = 0; break;
  105830. }
  105831. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105832. return false;
  105833. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105834. return false;
  105835. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105836. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105837. return false;
  105838. }
  105839. else {
  105840. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105841. return false;
  105842. }
  105843. if(blocksize_hint)
  105844. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105845. return false;
  105846. switch(sample_rate_hint) {
  105847. case 12:
  105848. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105849. return false;
  105850. break;
  105851. case 13:
  105852. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105853. return false;
  105854. break;
  105855. case 14:
  105856. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105857. return false;
  105858. break;
  105859. }
  105860. /* write the CRC */
  105861. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105862. return false;
  105863. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105864. return false;
  105865. return true;
  105866. }
  105867. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105868. {
  105869. FLAC__bool ok;
  105870. ok =
  105871. 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) &&
  105872. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105873. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105874. ;
  105875. return ok;
  105876. }
  105877. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105878. {
  105879. unsigned i;
  105880. 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))
  105881. return false;
  105882. if(wasted_bits)
  105883. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105884. return false;
  105885. for(i = 0; i < subframe->order; i++)
  105886. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105887. return false;
  105888. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105889. return false;
  105890. switch(subframe->entropy_coding_method.type) {
  105891. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105892. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105893. if(!add_residual_partitioned_rice_(
  105894. bw,
  105895. subframe->residual,
  105896. residual_samples,
  105897. subframe->order,
  105898. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105899. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105900. subframe->entropy_coding_method.data.partitioned_rice.order,
  105901. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105902. ))
  105903. return false;
  105904. break;
  105905. default:
  105906. FLAC__ASSERT(0);
  105907. }
  105908. return true;
  105909. }
  105910. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105911. {
  105912. unsigned i;
  105913. 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))
  105914. return false;
  105915. if(wasted_bits)
  105916. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105917. return false;
  105918. for(i = 0; i < subframe->order; i++)
  105919. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105920. return false;
  105921. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105922. return false;
  105923. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105924. return false;
  105925. for(i = 0; i < subframe->order; i++)
  105926. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105927. return false;
  105928. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105929. return false;
  105930. switch(subframe->entropy_coding_method.type) {
  105931. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105932. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105933. if(!add_residual_partitioned_rice_(
  105934. bw,
  105935. subframe->residual,
  105936. residual_samples,
  105937. subframe->order,
  105938. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105939. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105940. subframe->entropy_coding_method.data.partitioned_rice.order,
  105941. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105942. ))
  105943. return false;
  105944. break;
  105945. default:
  105946. FLAC__ASSERT(0);
  105947. }
  105948. return true;
  105949. }
  105950. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105951. {
  105952. unsigned i;
  105953. const FLAC__int32 *signal = subframe->data;
  105954. 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))
  105955. return false;
  105956. if(wasted_bits)
  105957. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105958. return false;
  105959. for(i = 0; i < samples; i++)
  105960. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105961. return false;
  105962. return true;
  105963. }
  105964. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105965. {
  105966. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105967. return false;
  105968. switch(method->type) {
  105969. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105970. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105971. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105972. return false;
  105973. break;
  105974. default:
  105975. FLAC__ASSERT(0);
  105976. }
  105977. return true;
  105978. }
  105979. 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)
  105980. {
  105981. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105982. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105983. if(partition_order == 0) {
  105984. unsigned i;
  105985. if(raw_bits[0] == 0) {
  105986. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105987. return false;
  105988. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105989. return false;
  105990. }
  105991. else {
  105992. FLAC__ASSERT(rice_parameters[0] == 0);
  105993. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105994. return false;
  105995. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105996. return false;
  105997. for(i = 0; i < residual_samples; i++) {
  105998. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105999. return false;
  106000. }
  106001. }
  106002. return true;
  106003. }
  106004. else {
  106005. unsigned i, j, k = 0, k_last = 0;
  106006. unsigned partition_samples;
  106007. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106008. for(i = 0; i < (1u<<partition_order); i++) {
  106009. partition_samples = default_partition_samples;
  106010. if(i == 0)
  106011. partition_samples -= predictor_order;
  106012. k += partition_samples;
  106013. if(raw_bits[i] == 0) {
  106014. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106015. return false;
  106016. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106017. return false;
  106018. }
  106019. else {
  106020. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106021. return false;
  106022. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106023. return false;
  106024. for(j = k_last; j < k; j++) {
  106025. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106026. return false;
  106027. }
  106028. }
  106029. k_last = k;
  106030. }
  106031. return true;
  106032. }
  106033. }
  106034. #endif
  106035. /*** End of inlined file: stream_encoder_framing.c ***/
  106036. /*** Start of inlined file: window_flac.c ***/
  106037. /*** Start of inlined file: juce_FlacHeader.h ***/
  106038. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106039. // tasks..
  106040. #define VERSION "1.2.1"
  106041. #define FLAC__NO_DLL 1
  106042. #if JUCE_MSVC
  106043. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106044. #endif
  106045. #if JUCE_MAC
  106046. #define FLAC__SYS_DARWIN 1
  106047. #endif
  106048. /*** End of inlined file: juce_FlacHeader.h ***/
  106049. #if JUCE_USE_FLAC
  106050. #if HAVE_CONFIG_H
  106051. # include <config.h>
  106052. #endif
  106053. #include <math.h>
  106054. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106055. #ifndef M_PI
  106056. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106057. #define M_PI 3.14159265358979323846
  106058. #endif
  106059. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106060. {
  106061. const FLAC__int32 N = L - 1;
  106062. FLAC__int32 n;
  106063. if (L & 1) {
  106064. for (n = 0; n <= N/2; n++)
  106065. window[n] = 2.0f * n / (float)N;
  106066. for (; n <= N; n++)
  106067. window[n] = 2.0f - 2.0f * n / (float)N;
  106068. }
  106069. else {
  106070. for (n = 0; n <= L/2-1; n++)
  106071. window[n] = 2.0f * n / (float)N;
  106072. for (; n <= N; n++)
  106073. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106074. }
  106075. }
  106076. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106077. {
  106078. const FLAC__int32 N = L - 1;
  106079. FLAC__int32 n;
  106080. for (n = 0; n < L; n++)
  106081. 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)));
  106082. }
  106083. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106084. {
  106085. const FLAC__int32 N = L - 1;
  106086. FLAC__int32 n;
  106087. for (n = 0; n < L; n++)
  106088. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106089. }
  106090. /* 4-term -92dB side-lobe */
  106091. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106092. {
  106093. const FLAC__int32 N = L - 1;
  106094. FLAC__int32 n;
  106095. for (n = 0; n <= N; n++)
  106096. 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));
  106097. }
  106098. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106099. {
  106100. const FLAC__int32 N = L - 1;
  106101. const double N2 = (double)N / 2.;
  106102. FLAC__int32 n;
  106103. for (n = 0; n <= N; n++) {
  106104. double k = ((double)n - N2) / N2;
  106105. k = 1.0f - k * k;
  106106. window[n] = (FLAC__real)(k * k);
  106107. }
  106108. }
  106109. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106110. {
  106111. const FLAC__int32 N = L - 1;
  106112. FLAC__int32 n;
  106113. for (n = 0; n < L; n++)
  106114. 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));
  106115. }
  106116. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106117. {
  106118. const FLAC__int32 N = L - 1;
  106119. const double N2 = (double)N / 2.;
  106120. FLAC__int32 n;
  106121. for (n = 0; n <= N; n++) {
  106122. const double k = ((double)n - N2) / (stddev * N2);
  106123. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106124. }
  106125. }
  106126. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106127. {
  106128. const FLAC__int32 N = L - 1;
  106129. FLAC__int32 n;
  106130. for (n = 0; n < L; n++)
  106131. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106132. }
  106133. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106134. {
  106135. const FLAC__int32 N = L - 1;
  106136. FLAC__int32 n;
  106137. for (n = 0; n < L; n++)
  106138. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106139. }
  106140. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106141. {
  106142. const FLAC__int32 N = L - 1;
  106143. FLAC__int32 n;
  106144. for (n = 0; n < L; n++)
  106145. 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));
  106146. }
  106147. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106148. {
  106149. const FLAC__int32 N = L - 1;
  106150. FLAC__int32 n;
  106151. for (n = 0; n < L; n++)
  106152. 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));
  106153. }
  106154. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106155. {
  106156. FLAC__int32 n;
  106157. for (n = 0; n < L; n++)
  106158. window[n] = 1.0f;
  106159. }
  106160. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106161. {
  106162. FLAC__int32 n;
  106163. if (L & 1) {
  106164. for (n = 1; n <= L+1/2; n++)
  106165. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106166. for (; n <= L; n++)
  106167. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106168. }
  106169. else {
  106170. for (n = 1; n <= L/2; n++)
  106171. window[n-1] = 2.0f * n / (float)L;
  106172. for (; n <= L; n++)
  106173. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106174. }
  106175. }
  106176. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106177. {
  106178. if (p <= 0.0)
  106179. FLAC__window_rectangle(window, L);
  106180. else if (p >= 1.0)
  106181. FLAC__window_hann(window, L);
  106182. else {
  106183. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106184. FLAC__int32 n;
  106185. /* start with rectangle... */
  106186. FLAC__window_rectangle(window, L);
  106187. /* ...replace ends with hann */
  106188. if (Np > 0) {
  106189. for (n = 0; n <= Np; n++) {
  106190. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106191. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106192. }
  106193. }
  106194. }
  106195. }
  106196. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106197. {
  106198. const FLAC__int32 N = L - 1;
  106199. const double N2 = (double)N / 2.;
  106200. FLAC__int32 n;
  106201. for (n = 0; n <= N; n++) {
  106202. const double k = ((double)n - N2) / N2;
  106203. window[n] = (FLAC__real)(1.0f - k * k);
  106204. }
  106205. }
  106206. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106207. #endif
  106208. /*** End of inlined file: window_flac.c ***/
  106209. #else
  106210. #include <FLAC/all.h>
  106211. #endif
  106212. }
  106213. #undef max
  106214. #undef min
  106215. BEGIN_JUCE_NAMESPACE
  106216. static const char* const flacFormatName = "FLAC file";
  106217. static const char* const flacExtensions[] = { ".flac", 0 };
  106218. class FlacReader : public AudioFormatReader
  106219. {
  106220. public:
  106221. FlacReader (InputStream* const in)
  106222. : AudioFormatReader (in, TRANS (flacFormatName)),
  106223. reservoir (2, 0),
  106224. reservoirStart (0),
  106225. samplesInReservoir (0),
  106226. scanningForLength (false)
  106227. {
  106228. using namespace FlacNamespace;
  106229. lengthInSamples = 0;
  106230. decoder = FLAC__stream_decoder_new();
  106231. ok = FLAC__stream_decoder_init_stream (decoder,
  106232. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106233. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106234. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106235. if (ok)
  106236. {
  106237. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106238. if (lengthInSamples == 0 && sampleRate > 0)
  106239. {
  106240. // the length hasn't been stored in the metadata, so we'll need to
  106241. // work it out the length the hard way, by scanning the whole file..
  106242. scanningForLength = true;
  106243. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106244. scanningForLength = false;
  106245. const int64 tempLength = lengthInSamples;
  106246. FLAC__stream_decoder_reset (decoder);
  106247. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106248. lengthInSamples = tempLength;
  106249. }
  106250. }
  106251. }
  106252. ~FlacReader()
  106253. {
  106254. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106255. }
  106256. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106257. {
  106258. sampleRate = info.sample_rate;
  106259. bitsPerSample = info.bits_per_sample;
  106260. lengthInSamples = (unsigned int) info.total_samples;
  106261. numChannels = info.channels;
  106262. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106263. }
  106264. // returns the number of samples read
  106265. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106266. int64 startSampleInFile, int numSamples)
  106267. {
  106268. using namespace FlacNamespace;
  106269. if (! ok)
  106270. return false;
  106271. while (numSamples > 0)
  106272. {
  106273. if (startSampleInFile >= reservoirStart
  106274. && startSampleInFile < reservoirStart + samplesInReservoir)
  106275. {
  106276. const int num = (int) jmin ((int64) numSamples,
  106277. reservoirStart + samplesInReservoir - startSampleInFile);
  106278. jassert (num > 0);
  106279. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106280. if (destSamples[i] != 0)
  106281. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106282. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106283. sizeof (int) * num);
  106284. startOffsetInDestBuffer += num;
  106285. startSampleInFile += num;
  106286. numSamples -= num;
  106287. }
  106288. else
  106289. {
  106290. if (startSampleInFile >= (int) lengthInSamples)
  106291. {
  106292. samplesInReservoir = 0;
  106293. }
  106294. else if (startSampleInFile < reservoirStart
  106295. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106296. {
  106297. // had some problems with flac crashing if the read pos is aligned more
  106298. // accurately than this. Probably fixed in newer versions of the library, though.
  106299. reservoirStart = (int) (startSampleInFile & ~511);
  106300. samplesInReservoir = 0;
  106301. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106302. }
  106303. else
  106304. {
  106305. reservoirStart += samplesInReservoir;
  106306. samplesInReservoir = 0;
  106307. FLAC__stream_decoder_process_single (decoder);
  106308. }
  106309. if (samplesInReservoir == 0)
  106310. break;
  106311. }
  106312. }
  106313. if (numSamples > 0)
  106314. {
  106315. for (int i = numDestChannels; --i >= 0;)
  106316. if (destSamples[i] != 0)
  106317. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106318. sizeof (int) * numSamples);
  106319. }
  106320. return true;
  106321. }
  106322. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106323. {
  106324. if (scanningForLength)
  106325. {
  106326. lengthInSamples += numSamples;
  106327. }
  106328. else
  106329. {
  106330. if (numSamples > reservoir.getNumSamples())
  106331. reservoir.setSize (numChannels, numSamples, false, false, true);
  106332. const int bitsToShift = 32 - bitsPerSample;
  106333. for (int i = 0; i < (int) numChannels; ++i)
  106334. {
  106335. const FlacNamespace::FLAC__int32* src = buffer[i];
  106336. int n = i;
  106337. while (src == 0 && n > 0)
  106338. src = buffer [--n];
  106339. if (src != 0)
  106340. {
  106341. int* dest = (int*) reservoir.getSampleData(i);
  106342. for (int j = 0; j < numSamples; ++j)
  106343. dest[j] = src[j] << bitsToShift;
  106344. }
  106345. }
  106346. samplesInReservoir = numSamples;
  106347. }
  106348. }
  106349. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106350. {
  106351. using namespace FlacNamespace;
  106352. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106353. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106354. }
  106355. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106356. {
  106357. using namespace FlacNamespace;
  106358. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106359. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106360. }
  106361. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106362. {
  106363. using namespace FlacNamespace;
  106364. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106365. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106366. }
  106367. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106368. {
  106369. using namespace FlacNamespace;
  106370. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106371. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106372. }
  106373. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106374. {
  106375. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106376. }
  106377. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106378. const FlacNamespace::FLAC__Frame* frame,
  106379. const FlacNamespace::FLAC__int32* const buffer[],
  106380. void* client_data)
  106381. {
  106382. using namespace FlacNamespace;
  106383. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106384. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106385. }
  106386. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106387. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106388. void* client_data)
  106389. {
  106390. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106391. }
  106392. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106393. {
  106394. }
  106395. juce_UseDebuggingNewOperator
  106396. private:
  106397. FlacNamespace::FLAC__StreamDecoder* decoder;
  106398. AudioSampleBuffer reservoir;
  106399. int reservoirStart, samplesInReservoir;
  106400. bool ok, scanningForLength;
  106401. FlacReader (const FlacReader&);
  106402. FlacReader& operator= (const FlacReader&);
  106403. };
  106404. class FlacWriter : public AudioFormatWriter
  106405. {
  106406. public:
  106407. FlacWriter (OutputStream* const out,
  106408. const double sampleRate_,
  106409. const int numChannels_,
  106410. const int bitsPerSample_)
  106411. : AudioFormatWriter (out, TRANS (flacFormatName),
  106412. sampleRate_,
  106413. numChannels_,
  106414. bitsPerSample_)
  106415. {
  106416. using namespace FlacNamespace;
  106417. encoder = FLAC__stream_encoder_new();
  106418. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106419. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106420. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106421. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106422. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106423. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106424. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106425. ok = FLAC__stream_encoder_init_stream (encoder,
  106426. encodeWriteCallback, encodeSeekCallback,
  106427. encodeTellCallback, encodeMetadataCallback,
  106428. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106429. }
  106430. ~FlacWriter()
  106431. {
  106432. if (ok)
  106433. {
  106434. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106435. output->flush();
  106436. }
  106437. else
  106438. {
  106439. output = 0; // to stop the base class deleting this, as it needs to be returned
  106440. // to the caller of createWriter()
  106441. }
  106442. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106443. }
  106444. bool write (const int** samplesToWrite, int numSamples)
  106445. {
  106446. using namespace FlacNamespace;
  106447. if (! ok)
  106448. return false;
  106449. int* buf[3];
  106450. const int bitsToShift = 32 - bitsPerSample;
  106451. if (bitsToShift > 0)
  106452. {
  106453. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106454. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106455. buf[0] = (int*) temp.getData();
  106456. buf[1] = buf[0] + numSamples;
  106457. buf[2] = 0;
  106458. for (int i = numChannelsToWrite; --i >= 0;)
  106459. {
  106460. if (samplesToWrite[i] != 0)
  106461. {
  106462. for (int j = 0; j < numSamples; ++j)
  106463. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106464. }
  106465. }
  106466. samplesToWrite = (const int**) buf;
  106467. }
  106468. return FLAC__stream_encoder_process (encoder,
  106469. (const FLAC__int32**) samplesToWrite,
  106470. numSamples) != 0;
  106471. }
  106472. bool writeData (const void* const data, const int size) const
  106473. {
  106474. return output->write (data, size);
  106475. }
  106476. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106477. {
  106478. using namespace FlacNamespace;
  106479. b += bytes;
  106480. for (int i = 0; i < bytes; ++i)
  106481. {
  106482. *(--b) = (FLAC__byte) (val & 0xff);
  106483. val >>= 8;
  106484. }
  106485. }
  106486. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106487. {
  106488. using namespace FlacNamespace;
  106489. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106490. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106491. const unsigned int channelsMinus1 = info.channels - 1;
  106492. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106493. packUint32 (info.min_blocksize, buffer, 2);
  106494. packUint32 (info.max_blocksize, buffer + 2, 2);
  106495. packUint32 (info.min_framesize, buffer + 4, 3);
  106496. packUint32 (info.max_framesize, buffer + 7, 3);
  106497. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106498. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106499. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106500. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106501. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106502. memcpy (buffer + 18, info.md5sum, 16);
  106503. const bool seekOk = output->setPosition (4);
  106504. (void) seekOk;
  106505. // if this fails, you've given it an output stream that can't seek! It needs
  106506. // to be able to seek back to write the header
  106507. jassert (seekOk);
  106508. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106509. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106510. }
  106511. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106512. const FlacNamespace::FLAC__byte buffer[],
  106513. size_t bytes,
  106514. unsigned int /*samples*/,
  106515. unsigned int /*current_frame*/,
  106516. void* client_data)
  106517. {
  106518. using namespace FlacNamespace;
  106519. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106520. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106521. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106522. }
  106523. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106524. {
  106525. using namespace FlacNamespace;
  106526. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106527. }
  106528. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106529. {
  106530. using namespace FlacNamespace;
  106531. if (client_data == 0)
  106532. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106533. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106534. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106535. }
  106536. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106537. {
  106538. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106539. }
  106540. juce_UseDebuggingNewOperator
  106541. bool ok;
  106542. private:
  106543. FlacNamespace::FLAC__StreamEncoder* encoder;
  106544. MemoryBlock temp;
  106545. FlacWriter (const FlacWriter&);
  106546. FlacWriter& operator= (const FlacWriter&);
  106547. };
  106548. FlacAudioFormat::FlacAudioFormat()
  106549. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106550. {
  106551. }
  106552. FlacAudioFormat::~FlacAudioFormat()
  106553. {
  106554. }
  106555. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106556. {
  106557. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106558. return Array <int> (rates);
  106559. }
  106560. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106561. {
  106562. const int depths[] = { 16, 24, 0 };
  106563. return Array <int> (depths);
  106564. }
  106565. bool FlacAudioFormat::canDoStereo()
  106566. {
  106567. return true;
  106568. }
  106569. bool FlacAudioFormat::canDoMono()
  106570. {
  106571. return true;
  106572. }
  106573. bool FlacAudioFormat::isCompressed()
  106574. {
  106575. return true;
  106576. }
  106577. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106578. const bool deleteStreamIfOpeningFails)
  106579. {
  106580. ScopedPointer<FlacReader> r (new FlacReader (in));
  106581. if (r->sampleRate != 0)
  106582. return r.release();
  106583. if (! deleteStreamIfOpeningFails)
  106584. r->input = 0;
  106585. return 0;
  106586. }
  106587. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106588. double sampleRate,
  106589. unsigned int numberOfChannels,
  106590. int bitsPerSample,
  106591. const StringPairArray& /*metadataValues*/,
  106592. int /*qualityOptionIndex*/)
  106593. {
  106594. if (getPossibleBitDepths().contains (bitsPerSample))
  106595. {
  106596. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106597. if (w->ok)
  106598. return w.release();
  106599. }
  106600. return 0;
  106601. }
  106602. END_JUCE_NAMESPACE
  106603. #endif
  106604. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106605. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106606. #if JUCE_USE_OGGVORBIS
  106607. #if JUCE_MAC
  106608. #define __MACOSX__ 1
  106609. #endif
  106610. namespace OggVorbisNamespace
  106611. {
  106612. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106613. /*** Start of inlined file: vorbisenc.h ***/
  106614. #ifndef _OV_ENC_H_
  106615. #define _OV_ENC_H_
  106616. #ifdef __cplusplus
  106617. extern "C"
  106618. {
  106619. #endif /* __cplusplus */
  106620. /*** Start of inlined file: codec.h ***/
  106621. #ifndef _vorbis_codec_h_
  106622. #define _vorbis_codec_h_
  106623. #ifdef __cplusplus
  106624. extern "C"
  106625. {
  106626. #endif /* __cplusplus */
  106627. /*** Start of inlined file: ogg.h ***/
  106628. #ifndef _OGG_H
  106629. #define _OGG_H
  106630. #ifdef __cplusplus
  106631. extern "C" {
  106632. #endif
  106633. /*** Start of inlined file: os_types.h ***/
  106634. #ifndef _OS_TYPES_H
  106635. #define _OS_TYPES_H
  106636. /* make it easy on the folks that want to compile the libs with a
  106637. different malloc than stdlib */
  106638. #define _ogg_malloc malloc
  106639. #define _ogg_calloc calloc
  106640. #define _ogg_realloc realloc
  106641. #define _ogg_free free
  106642. #if defined(_WIN32)
  106643. # if defined(__CYGWIN__)
  106644. # include <_G_config.h>
  106645. typedef _G_int64_t ogg_int64_t;
  106646. typedef _G_int32_t ogg_int32_t;
  106647. typedef _G_uint32_t ogg_uint32_t;
  106648. typedef _G_int16_t ogg_int16_t;
  106649. typedef _G_uint16_t ogg_uint16_t;
  106650. # elif defined(__MINGW32__)
  106651. typedef short ogg_int16_t;
  106652. typedef unsigned short ogg_uint16_t;
  106653. typedef int ogg_int32_t;
  106654. typedef unsigned int ogg_uint32_t;
  106655. typedef long long ogg_int64_t;
  106656. typedef unsigned long long ogg_uint64_t;
  106657. # elif defined(__MWERKS__)
  106658. typedef long long ogg_int64_t;
  106659. typedef int ogg_int32_t;
  106660. typedef unsigned int ogg_uint32_t;
  106661. typedef short ogg_int16_t;
  106662. typedef unsigned short ogg_uint16_t;
  106663. # else
  106664. /* MSVC/Borland */
  106665. typedef __int64 ogg_int64_t;
  106666. typedef __int32 ogg_int32_t;
  106667. typedef unsigned __int32 ogg_uint32_t;
  106668. typedef __int16 ogg_int16_t;
  106669. typedef unsigned __int16 ogg_uint16_t;
  106670. # endif
  106671. #elif defined(__MACOS__)
  106672. # include <sys/types.h>
  106673. typedef SInt16 ogg_int16_t;
  106674. typedef UInt16 ogg_uint16_t;
  106675. typedef SInt32 ogg_int32_t;
  106676. typedef UInt32 ogg_uint32_t;
  106677. typedef SInt64 ogg_int64_t;
  106678. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106679. # include <sys/types.h>
  106680. typedef int16_t ogg_int16_t;
  106681. typedef u_int16_t ogg_uint16_t;
  106682. typedef int32_t ogg_int32_t;
  106683. typedef u_int32_t ogg_uint32_t;
  106684. typedef int64_t ogg_int64_t;
  106685. #elif defined(__BEOS__)
  106686. /* Be */
  106687. # include <inttypes.h>
  106688. typedef int16_t ogg_int16_t;
  106689. typedef u_int16_t ogg_uint16_t;
  106690. typedef int32_t ogg_int32_t;
  106691. typedef u_int32_t ogg_uint32_t;
  106692. typedef int64_t ogg_int64_t;
  106693. #elif defined (__EMX__)
  106694. /* OS/2 GCC */
  106695. typedef short ogg_int16_t;
  106696. typedef unsigned short ogg_uint16_t;
  106697. typedef int ogg_int32_t;
  106698. typedef unsigned int ogg_uint32_t;
  106699. typedef long long ogg_int64_t;
  106700. #elif defined (DJGPP)
  106701. /* DJGPP */
  106702. typedef short ogg_int16_t;
  106703. typedef int ogg_int32_t;
  106704. typedef unsigned int ogg_uint32_t;
  106705. typedef long long ogg_int64_t;
  106706. #elif defined(R5900)
  106707. /* PS2 EE */
  106708. typedef long ogg_int64_t;
  106709. typedef int ogg_int32_t;
  106710. typedef unsigned ogg_uint32_t;
  106711. typedef short ogg_int16_t;
  106712. #elif defined(__SYMBIAN32__)
  106713. /* Symbian GCC */
  106714. typedef signed short ogg_int16_t;
  106715. typedef unsigned short ogg_uint16_t;
  106716. typedef signed int ogg_int32_t;
  106717. typedef unsigned int ogg_uint32_t;
  106718. typedef long long int ogg_int64_t;
  106719. #else
  106720. # include <sys/types.h>
  106721. /*** Start of inlined file: config_types.h ***/
  106722. #ifndef __CONFIG_TYPES_H__
  106723. #define __CONFIG_TYPES_H__
  106724. typedef int16_t ogg_int16_t;
  106725. typedef unsigned short ogg_uint16_t;
  106726. typedef int32_t ogg_int32_t;
  106727. typedef unsigned int ogg_uint32_t;
  106728. typedef int64_t ogg_int64_t;
  106729. #endif
  106730. /*** End of inlined file: config_types.h ***/
  106731. #endif
  106732. #endif /* _OS_TYPES_H */
  106733. /*** End of inlined file: os_types.h ***/
  106734. typedef struct {
  106735. long endbyte;
  106736. int endbit;
  106737. unsigned char *buffer;
  106738. unsigned char *ptr;
  106739. long storage;
  106740. } oggpack_buffer;
  106741. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106742. typedef struct {
  106743. unsigned char *header;
  106744. long header_len;
  106745. unsigned char *body;
  106746. long body_len;
  106747. } ogg_page;
  106748. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106749. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106750. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106751. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106752. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106753. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106754. }
  106755. /* ogg_stream_state contains the current encode/decode state of a logical
  106756. Ogg bitstream **********************************************************/
  106757. typedef struct {
  106758. unsigned char *body_data; /* bytes from packet bodies */
  106759. long body_storage; /* storage elements allocated */
  106760. long body_fill; /* elements stored; fill mark */
  106761. long body_returned; /* elements of fill returned */
  106762. int *lacing_vals; /* The values that will go to the segment table */
  106763. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106764. this way, but it is simple coupled to the
  106765. lacing fifo */
  106766. long lacing_storage;
  106767. long lacing_fill;
  106768. long lacing_packet;
  106769. long lacing_returned;
  106770. unsigned char header[282]; /* working space for header encode */
  106771. int header_fill;
  106772. int e_o_s; /* set when we have buffered the last packet in the
  106773. logical bitstream */
  106774. int b_o_s; /* set after we've written the initial page
  106775. of a logical bitstream */
  106776. long serialno;
  106777. long pageno;
  106778. ogg_int64_t packetno; /* sequence number for decode; the framing
  106779. knows where there's a hole in the data,
  106780. but we need coupling so that the codec
  106781. (which is in a seperate abstraction
  106782. layer) also knows about the gap */
  106783. ogg_int64_t granulepos;
  106784. } ogg_stream_state;
  106785. /* ogg_packet is used to encapsulate the data and metadata belonging
  106786. to a single raw Ogg/Vorbis packet *************************************/
  106787. typedef struct {
  106788. unsigned char *packet;
  106789. long bytes;
  106790. long b_o_s;
  106791. long e_o_s;
  106792. ogg_int64_t granulepos;
  106793. ogg_int64_t packetno; /* sequence number for decode; the framing
  106794. knows where there's a hole in the data,
  106795. but we need coupling so that the codec
  106796. (which is in a seperate abstraction
  106797. layer) also knows about the gap */
  106798. } ogg_packet;
  106799. typedef struct {
  106800. unsigned char *data;
  106801. int storage;
  106802. int fill;
  106803. int returned;
  106804. int unsynced;
  106805. int headerbytes;
  106806. int bodybytes;
  106807. } ogg_sync_state;
  106808. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106809. extern void oggpack_writeinit(oggpack_buffer *b);
  106810. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106811. extern void oggpack_writealign(oggpack_buffer *b);
  106812. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106813. extern void oggpack_reset(oggpack_buffer *b);
  106814. extern void oggpack_writeclear(oggpack_buffer *b);
  106815. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106816. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106817. extern long oggpack_look(oggpack_buffer *b,int bits);
  106818. extern long oggpack_look1(oggpack_buffer *b);
  106819. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106820. extern void oggpack_adv1(oggpack_buffer *b);
  106821. extern long oggpack_read(oggpack_buffer *b,int bits);
  106822. extern long oggpack_read1(oggpack_buffer *b);
  106823. extern long oggpack_bytes(oggpack_buffer *b);
  106824. extern long oggpack_bits(oggpack_buffer *b);
  106825. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106826. extern void oggpackB_writeinit(oggpack_buffer *b);
  106827. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106828. extern void oggpackB_writealign(oggpack_buffer *b);
  106829. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106830. extern void oggpackB_reset(oggpack_buffer *b);
  106831. extern void oggpackB_writeclear(oggpack_buffer *b);
  106832. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106833. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106834. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106835. extern long oggpackB_look1(oggpack_buffer *b);
  106836. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106837. extern void oggpackB_adv1(oggpack_buffer *b);
  106838. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106839. extern long oggpackB_read1(oggpack_buffer *b);
  106840. extern long oggpackB_bytes(oggpack_buffer *b);
  106841. extern long oggpackB_bits(oggpack_buffer *b);
  106842. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106843. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106844. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106845. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106846. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106847. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106848. extern int ogg_sync_init(ogg_sync_state *oy);
  106849. extern int ogg_sync_clear(ogg_sync_state *oy);
  106850. extern int ogg_sync_reset(ogg_sync_state *oy);
  106851. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106852. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106853. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106854. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106855. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106856. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106857. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106858. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106859. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106860. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106861. extern int ogg_stream_clear(ogg_stream_state *os);
  106862. extern int ogg_stream_reset(ogg_stream_state *os);
  106863. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106864. extern int ogg_stream_destroy(ogg_stream_state *os);
  106865. extern int ogg_stream_eos(ogg_stream_state *os);
  106866. extern void ogg_page_checksum_set(ogg_page *og);
  106867. extern int ogg_page_version(ogg_page *og);
  106868. extern int ogg_page_continued(ogg_page *og);
  106869. extern int ogg_page_bos(ogg_page *og);
  106870. extern int ogg_page_eos(ogg_page *og);
  106871. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106872. extern int ogg_page_serialno(ogg_page *og);
  106873. extern long ogg_page_pageno(ogg_page *og);
  106874. extern int ogg_page_packets(ogg_page *og);
  106875. extern void ogg_packet_clear(ogg_packet *op);
  106876. #ifdef __cplusplus
  106877. }
  106878. #endif
  106879. #endif /* _OGG_H */
  106880. /*** End of inlined file: ogg.h ***/
  106881. typedef struct vorbis_info{
  106882. int version;
  106883. int channels;
  106884. long rate;
  106885. /* The below bitrate declarations are *hints*.
  106886. Combinations of the three values carry the following implications:
  106887. all three set to the same value:
  106888. implies a fixed rate bitstream
  106889. only nominal set:
  106890. implies a VBR stream that averages the nominal bitrate. No hard
  106891. upper/lower limit
  106892. upper and or lower set:
  106893. implies a VBR bitstream that obeys the bitrate limits. nominal
  106894. may also be set to give a nominal rate.
  106895. none set:
  106896. the coder does not care to speculate.
  106897. */
  106898. long bitrate_upper;
  106899. long bitrate_nominal;
  106900. long bitrate_lower;
  106901. long bitrate_window;
  106902. void *codec_setup;
  106903. } vorbis_info;
  106904. /* vorbis_dsp_state buffers the current vorbis audio
  106905. analysis/synthesis state. The DSP state belongs to a specific
  106906. logical bitstream ****************************************************/
  106907. typedef struct vorbis_dsp_state{
  106908. int analysisp;
  106909. vorbis_info *vi;
  106910. float **pcm;
  106911. float **pcmret;
  106912. int pcm_storage;
  106913. int pcm_current;
  106914. int pcm_returned;
  106915. int preextrapolate;
  106916. int eofflag;
  106917. long lW;
  106918. long W;
  106919. long nW;
  106920. long centerW;
  106921. ogg_int64_t granulepos;
  106922. ogg_int64_t sequence;
  106923. ogg_int64_t glue_bits;
  106924. ogg_int64_t time_bits;
  106925. ogg_int64_t floor_bits;
  106926. ogg_int64_t res_bits;
  106927. void *backend_state;
  106928. } vorbis_dsp_state;
  106929. typedef struct vorbis_block{
  106930. /* necessary stream state for linking to the framing abstraction */
  106931. float **pcm; /* this is a pointer into local storage */
  106932. oggpack_buffer opb;
  106933. long lW;
  106934. long W;
  106935. long nW;
  106936. int pcmend;
  106937. int mode;
  106938. int eofflag;
  106939. ogg_int64_t granulepos;
  106940. ogg_int64_t sequence;
  106941. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106942. /* local storage to avoid remallocing; it's up to the mapping to
  106943. structure it */
  106944. void *localstore;
  106945. long localtop;
  106946. long localalloc;
  106947. long totaluse;
  106948. struct alloc_chain *reap;
  106949. /* bitmetrics for the frame */
  106950. long glue_bits;
  106951. long time_bits;
  106952. long floor_bits;
  106953. long res_bits;
  106954. void *internal;
  106955. } vorbis_block;
  106956. /* vorbis_block is a single block of data to be processed as part of
  106957. the analysis/synthesis stream; it belongs to a specific logical
  106958. bitstream, but is independant from other vorbis_blocks belonging to
  106959. that logical bitstream. *************************************************/
  106960. struct alloc_chain{
  106961. void *ptr;
  106962. struct alloc_chain *next;
  106963. };
  106964. /* vorbis_info contains all the setup information specific to the
  106965. specific compression/decompression mode in progress (eg,
  106966. psychoacoustic settings, channel setup, options, codebook
  106967. etc). vorbis_info and substructures are in backends.h.
  106968. *********************************************************************/
  106969. /* the comments are not part of vorbis_info so that vorbis_info can be
  106970. static storage */
  106971. typedef struct vorbis_comment{
  106972. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106973. whatever vendor is set to in encode */
  106974. char **user_comments;
  106975. int *comment_lengths;
  106976. int comments;
  106977. char *vendor;
  106978. } vorbis_comment;
  106979. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106980. and produce a packet (see docs/analysis.txt). The packet is then
  106981. coded into a framed OggSquish bitstream by the second layer (see
  106982. docs/framing.txt). Decode is the reverse process; we sync/frame
  106983. the bitstream and extract individual packets, then decode the
  106984. packet back into PCM audio.
  106985. The extra framing/packetizing is used in streaming formats, such as
  106986. files. Over the net (such as with UDP), the framing and
  106987. packetization aren't necessary as they're provided by the transport
  106988. and the streaming layer is not used */
  106989. /* Vorbis PRIMITIVES: general ***************************************/
  106990. extern void vorbis_info_init(vorbis_info *vi);
  106991. extern void vorbis_info_clear(vorbis_info *vi);
  106992. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106993. extern void vorbis_comment_init(vorbis_comment *vc);
  106994. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106995. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106996. const char *tag, char *contents);
  106997. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106998. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106999. extern void vorbis_comment_clear(vorbis_comment *vc);
  107000. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107001. extern int vorbis_block_clear(vorbis_block *vb);
  107002. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107003. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107004. ogg_int64_t granulepos);
  107005. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107006. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107007. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107008. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107009. vorbis_comment *vc,
  107010. ogg_packet *op,
  107011. ogg_packet *op_comm,
  107012. ogg_packet *op_code);
  107013. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107014. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107015. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107016. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107017. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107018. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107019. ogg_packet *op);
  107020. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107021. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107022. ogg_packet *op);
  107023. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107024. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107025. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107026. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107027. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107028. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107029. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107030. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107031. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107032. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107033. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107034. /* Vorbis ERRORS and return codes ***********************************/
  107035. #define OV_FALSE -1
  107036. #define OV_EOF -2
  107037. #define OV_HOLE -3
  107038. #define OV_EREAD -128
  107039. #define OV_EFAULT -129
  107040. #define OV_EIMPL -130
  107041. #define OV_EINVAL -131
  107042. #define OV_ENOTVORBIS -132
  107043. #define OV_EBADHEADER -133
  107044. #define OV_EVERSION -134
  107045. #define OV_ENOTAUDIO -135
  107046. #define OV_EBADPACKET -136
  107047. #define OV_EBADLINK -137
  107048. #define OV_ENOSEEK -138
  107049. #ifdef __cplusplus
  107050. }
  107051. #endif /* __cplusplus */
  107052. #endif
  107053. /*** End of inlined file: codec.h ***/
  107054. extern int vorbis_encode_init(vorbis_info *vi,
  107055. long channels,
  107056. long rate,
  107057. long max_bitrate,
  107058. long nominal_bitrate,
  107059. long min_bitrate);
  107060. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107061. long channels,
  107062. long rate,
  107063. long max_bitrate,
  107064. long nominal_bitrate,
  107065. long min_bitrate);
  107066. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107067. long channels,
  107068. long rate,
  107069. float quality /* quality level from 0. (lo) to 1. (hi) */
  107070. );
  107071. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107072. long channels,
  107073. long rate,
  107074. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107075. );
  107076. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107077. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107078. /* deprecated rate management supported only for compatability */
  107079. #define OV_ECTL_RATEMANAGE_GET 0x10
  107080. #define OV_ECTL_RATEMANAGE_SET 0x11
  107081. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107082. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107083. struct ovectl_ratemanage_arg {
  107084. int management_active;
  107085. long bitrate_hard_min;
  107086. long bitrate_hard_max;
  107087. double bitrate_hard_window;
  107088. long bitrate_av_lo;
  107089. long bitrate_av_hi;
  107090. double bitrate_av_window;
  107091. double bitrate_av_window_center;
  107092. };
  107093. /* new rate setup */
  107094. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107095. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107096. struct ovectl_ratemanage2_arg {
  107097. int management_active;
  107098. long bitrate_limit_min_kbps;
  107099. long bitrate_limit_max_kbps;
  107100. long bitrate_limit_reservoir_bits;
  107101. double bitrate_limit_reservoir_bias;
  107102. long bitrate_average_kbps;
  107103. double bitrate_average_damping;
  107104. };
  107105. #define OV_ECTL_LOWPASS_GET 0x20
  107106. #define OV_ECTL_LOWPASS_SET 0x21
  107107. #define OV_ECTL_IBLOCK_GET 0x30
  107108. #define OV_ECTL_IBLOCK_SET 0x31
  107109. #ifdef __cplusplus
  107110. }
  107111. #endif /* __cplusplus */
  107112. #endif
  107113. /*** End of inlined file: vorbisenc.h ***/
  107114. /*** Start of inlined file: vorbisfile.h ***/
  107115. #ifndef _OV_FILE_H_
  107116. #define _OV_FILE_H_
  107117. #ifdef __cplusplus
  107118. extern "C"
  107119. {
  107120. #endif /* __cplusplus */
  107121. #include <stdio.h>
  107122. /* The function prototypes for the callbacks are basically the same as for
  107123. * the stdio functions fread, fseek, fclose, ftell.
  107124. * The one difference is that the FILE * arguments have been replaced with
  107125. * a void * - this is to be used as a pointer to whatever internal data these
  107126. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107127. *
  107128. * If you use other functions, check the docs for these functions and return
  107129. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107130. * unseekable
  107131. */
  107132. typedef struct {
  107133. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107134. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107135. int (*close_func) (void *datasource);
  107136. long (*tell_func) (void *datasource);
  107137. } ov_callbacks;
  107138. #define NOTOPEN 0
  107139. #define PARTOPEN 1
  107140. #define OPENED 2
  107141. #define STREAMSET 3
  107142. #define INITSET 4
  107143. typedef struct OggVorbis_File {
  107144. void *datasource; /* Pointer to a FILE *, etc. */
  107145. int seekable;
  107146. ogg_int64_t offset;
  107147. ogg_int64_t end;
  107148. ogg_sync_state oy;
  107149. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107150. stream appears */
  107151. int links;
  107152. ogg_int64_t *offsets;
  107153. ogg_int64_t *dataoffsets;
  107154. long *serialnos;
  107155. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107156. compatability; x2 size, stores both
  107157. beginning and end values */
  107158. vorbis_info *vi;
  107159. vorbis_comment *vc;
  107160. /* Decoding working state local storage */
  107161. ogg_int64_t pcm_offset;
  107162. int ready_state;
  107163. long current_serialno;
  107164. int current_link;
  107165. double bittrack;
  107166. double samptrack;
  107167. ogg_stream_state os; /* take physical pages, weld into a logical
  107168. stream of packets */
  107169. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107170. vorbis_block vb; /* local working space for packet->PCM decode */
  107171. ov_callbacks callbacks;
  107172. } OggVorbis_File;
  107173. extern int ov_clear(OggVorbis_File *vf);
  107174. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107175. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107176. char *initial, long ibytes, ov_callbacks callbacks);
  107177. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107178. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107179. char *initial, long ibytes, ov_callbacks callbacks);
  107180. extern int ov_test_open(OggVorbis_File *vf);
  107181. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107182. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107183. extern long ov_streams(OggVorbis_File *vf);
  107184. extern long ov_seekable(OggVorbis_File *vf);
  107185. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107186. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107187. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107188. extern double ov_time_total(OggVorbis_File *vf,int i);
  107189. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107190. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107191. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107192. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107193. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107194. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107195. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107196. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107197. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107198. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107199. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107200. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107201. extern double ov_time_tell(OggVorbis_File *vf);
  107202. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107203. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107204. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107205. int *bitstream);
  107206. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107207. int bigendianp,int word,int sgned,int *bitstream);
  107208. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107209. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107210. extern int ov_halfrate_p(OggVorbis_File *vf);
  107211. #ifdef __cplusplus
  107212. }
  107213. #endif /* __cplusplus */
  107214. #endif
  107215. /*** End of inlined file: vorbisfile.h ***/
  107216. /*** Start of inlined file: bitwise.c ***/
  107217. /* We're 'LSb' endian; if we write a word but read individual bits,
  107218. then we'll read the lsb first */
  107219. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107220. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107221. // tasks..
  107222. #if JUCE_MSVC
  107223. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107224. #endif
  107225. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107226. #if JUCE_USE_OGGVORBIS
  107227. #include <string.h>
  107228. #include <stdlib.h>
  107229. #define BUFFER_INCREMENT 256
  107230. static const unsigned long mask[]=
  107231. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107232. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107233. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107234. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107235. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107236. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107237. 0x3fffffff,0x7fffffff,0xffffffff };
  107238. static const unsigned int mask8B[]=
  107239. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107240. void oggpack_writeinit(oggpack_buffer *b){
  107241. memset(b,0,sizeof(*b));
  107242. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107243. b->buffer[0]='\0';
  107244. b->storage=BUFFER_INCREMENT;
  107245. }
  107246. void oggpackB_writeinit(oggpack_buffer *b){
  107247. oggpack_writeinit(b);
  107248. }
  107249. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107250. long bytes=bits>>3;
  107251. bits-=bytes*8;
  107252. b->ptr=b->buffer+bytes;
  107253. b->endbit=bits;
  107254. b->endbyte=bytes;
  107255. *b->ptr&=mask[bits];
  107256. }
  107257. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107258. long bytes=bits>>3;
  107259. bits-=bytes*8;
  107260. b->ptr=b->buffer+bytes;
  107261. b->endbit=bits;
  107262. b->endbyte=bytes;
  107263. *b->ptr&=mask8B[bits];
  107264. }
  107265. /* Takes only up to 32 bits. */
  107266. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107267. if(b->endbyte+4>=b->storage){
  107268. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107269. b->storage+=BUFFER_INCREMENT;
  107270. b->ptr=b->buffer+b->endbyte;
  107271. }
  107272. value&=mask[bits];
  107273. bits+=b->endbit;
  107274. b->ptr[0]|=value<<b->endbit;
  107275. if(bits>=8){
  107276. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107277. if(bits>=16){
  107278. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107279. if(bits>=24){
  107280. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107281. if(bits>=32){
  107282. if(b->endbit)
  107283. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107284. else
  107285. b->ptr[4]=0;
  107286. }
  107287. }
  107288. }
  107289. }
  107290. b->endbyte+=bits/8;
  107291. b->ptr+=bits/8;
  107292. b->endbit=bits&7;
  107293. }
  107294. /* Takes only up to 32 bits. */
  107295. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107296. if(b->endbyte+4>=b->storage){
  107297. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107298. b->storage+=BUFFER_INCREMENT;
  107299. b->ptr=b->buffer+b->endbyte;
  107300. }
  107301. value=(value&mask[bits])<<(32-bits);
  107302. bits+=b->endbit;
  107303. b->ptr[0]|=value>>(24+b->endbit);
  107304. if(bits>=8){
  107305. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107306. if(bits>=16){
  107307. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107308. if(bits>=24){
  107309. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107310. if(bits>=32){
  107311. if(b->endbit)
  107312. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107313. else
  107314. b->ptr[4]=0;
  107315. }
  107316. }
  107317. }
  107318. }
  107319. b->endbyte+=bits/8;
  107320. b->ptr+=bits/8;
  107321. b->endbit=bits&7;
  107322. }
  107323. void oggpack_writealign(oggpack_buffer *b){
  107324. int bits=8-b->endbit;
  107325. if(bits<8)
  107326. oggpack_write(b,0,bits);
  107327. }
  107328. void oggpackB_writealign(oggpack_buffer *b){
  107329. int bits=8-b->endbit;
  107330. if(bits<8)
  107331. oggpackB_write(b,0,bits);
  107332. }
  107333. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107334. void *source,
  107335. long bits,
  107336. void (*w)(oggpack_buffer *,
  107337. unsigned long,
  107338. int),
  107339. int msb){
  107340. unsigned char *ptr=(unsigned char *)source;
  107341. long bytes=bits/8;
  107342. bits-=bytes*8;
  107343. if(b->endbit){
  107344. int i;
  107345. /* unaligned copy. Do it the hard way. */
  107346. for(i=0;i<bytes;i++)
  107347. w(b,(unsigned long)(ptr[i]),8);
  107348. }else{
  107349. /* aligned block copy */
  107350. if(b->endbyte+bytes+1>=b->storage){
  107351. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107352. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107353. b->ptr=b->buffer+b->endbyte;
  107354. }
  107355. memmove(b->ptr,source,bytes);
  107356. b->ptr+=bytes;
  107357. b->endbyte+=bytes;
  107358. *b->ptr=0;
  107359. }
  107360. if(bits){
  107361. if(msb)
  107362. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107363. else
  107364. w(b,(unsigned long)(ptr[bytes]),bits);
  107365. }
  107366. }
  107367. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107368. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107369. }
  107370. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107371. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107372. }
  107373. void oggpack_reset(oggpack_buffer *b){
  107374. b->ptr=b->buffer;
  107375. b->buffer[0]=0;
  107376. b->endbit=b->endbyte=0;
  107377. }
  107378. void oggpackB_reset(oggpack_buffer *b){
  107379. oggpack_reset(b);
  107380. }
  107381. void oggpack_writeclear(oggpack_buffer *b){
  107382. _ogg_free(b->buffer);
  107383. memset(b,0,sizeof(*b));
  107384. }
  107385. void oggpackB_writeclear(oggpack_buffer *b){
  107386. oggpack_writeclear(b);
  107387. }
  107388. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107389. memset(b,0,sizeof(*b));
  107390. b->buffer=b->ptr=buf;
  107391. b->storage=bytes;
  107392. }
  107393. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107394. oggpack_readinit(b,buf,bytes);
  107395. }
  107396. /* Read in bits without advancing the bitptr; bits <= 32 */
  107397. long oggpack_look(oggpack_buffer *b,int bits){
  107398. unsigned long ret;
  107399. unsigned long m=mask[bits];
  107400. bits+=b->endbit;
  107401. if(b->endbyte+4>=b->storage){
  107402. /* not the main path */
  107403. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107404. }
  107405. ret=b->ptr[0]>>b->endbit;
  107406. if(bits>8){
  107407. ret|=b->ptr[1]<<(8-b->endbit);
  107408. if(bits>16){
  107409. ret|=b->ptr[2]<<(16-b->endbit);
  107410. if(bits>24){
  107411. ret|=b->ptr[3]<<(24-b->endbit);
  107412. if(bits>32 && b->endbit)
  107413. ret|=b->ptr[4]<<(32-b->endbit);
  107414. }
  107415. }
  107416. }
  107417. return(m&ret);
  107418. }
  107419. /* Read in bits without advancing the bitptr; bits <= 32 */
  107420. long oggpackB_look(oggpack_buffer *b,int bits){
  107421. unsigned long ret;
  107422. int m=32-bits;
  107423. bits+=b->endbit;
  107424. if(b->endbyte+4>=b->storage){
  107425. /* not the main path */
  107426. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107427. }
  107428. ret=b->ptr[0]<<(24+b->endbit);
  107429. if(bits>8){
  107430. ret|=b->ptr[1]<<(16+b->endbit);
  107431. if(bits>16){
  107432. ret|=b->ptr[2]<<(8+b->endbit);
  107433. if(bits>24){
  107434. ret|=b->ptr[3]<<(b->endbit);
  107435. if(bits>32 && b->endbit)
  107436. ret|=b->ptr[4]>>(8-b->endbit);
  107437. }
  107438. }
  107439. }
  107440. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107441. }
  107442. long oggpack_look1(oggpack_buffer *b){
  107443. if(b->endbyte>=b->storage)return(-1);
  107444. return((b->ptr[0]>>b->endbit)&1);
  107445. }
  107446. long oggpackB_look1(oggpack_buffer *b){
  107447. if(b->endbyte>=b->storage)return(-1);
  107448. return((b->ptr[0]>>(7-b->endbit))&1);
  107449. }
  107450. void oggpack_adv(oggpack_buffer *b,int bits){
  107451. bits+=b->endbit;
  107452. b->ptr+=bits/8;
  107453. b->endbyte+=bits/8;
  107454. b->endbit=bits&7;
  107455. }
  107456. void oggpackB_adv(oggpack_buffer *b,int bits){
  107457. oggpack_adv(b,bits);
  107458. }
  107459. void oggpack_adv1(oggpack_buffer *b){
  107460. if(++(b->endbit)>7){
  107461. b->endbit=0;
  107462. b->ptr++;
  107463. b->endbyte++;
  107464. }
  107465. }
  107466. void oggpackB_adv1(oggpack_buffer *b){
  107467. oggpack_adv1(b);
  107468. }
  107469. /* bits <= 32 */
  107470. long oggpack_read(oggpack_buffer *b,int bits){
  107471. long ret;
  107472. unsigned long m=mask[bits];
  107473. bits+=b->endbit;
  107474. if(b->endbyte+4>=b->storage){
  107475. /* not the main path */
  107476. ret=-1L;
  107477. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107478. }
  107479. ret=b->ptr[0]>>b->endbit;
  107480. if(bits>8){
  107481. ret|=b->ptr[1]<<(8-b->endbit);
  107482. if(bits>16){
  107483. ret|=b->ptr[2]<<(16-b->endbit);
  107484. if(bits>24){
  107485. ret|=b->ptr[3]<<(24-b->endbit);
  107486. if(bits>32 && b->endbit){
  107487. ret|=b->ptr[4]<<(32-b->endbit);
  107488. }
  107489. }
  107490. }
  107491. }
  107492. ret&=m;
  107493. overflow:
  107494. b->ptr+=bits/8;
  107495. b->endbyte+=bits/8;
  107496. b->endbit=bits&7;
  107497. return(ret);
  107498. }
  107499. /* bits <= 32 */
  107500. long oggpackB_read(oggpack_buffer *b,int bits){
  107501. long ret;
  107502. long m=32-bits;
  107503. bits+=b->endbit;
  107504. if(b->endbyte+4>=b->storage){
  107505. /* not the main path */
  107506. ret=-1L;
  107507. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107508. }
  107509. ret=b->ptr[0]<<(24+b->endbit);
  107510. if(bits>8){
  107511. ret|=b->ptr[1]<<(16+b->endbit);
  107512. if(bits>16){
  107513. ret|=b->ptr[2]<<(8+b->endbit);
  107514. if(bits>24){
  107515. ret|=b->ptr[3]<<(b->endbit);
  107516. if(bits>32 && b->endbit)
  107517. ret|=b->ptr[4]>>(8-b->endbit);
  107518. }
  107519. }
  107520. }
  107521. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107522. overflow:
  107523. b->ptr+=bits/8;
  107524. b->endbyte+=bits/8;
  107525. b->endbit=bits&7;
  107526. return(ret);
  107527. }
  107528. long oggpack_read1(oggpack_buffer *b){
  107529. long ret;
  107530. if(b->endbyte>=b->storage){
  107531. /* not the main path */
  107532. ret=-1L;
  107533. goto overflow;
  107534. }
  107535. ret=(b->ptr[0]>>b->endbit)&1;
  107536. overflow:
  107537. b->endbit++;
  107538. if(b->endbit>7){
  107539. b->endbit=0;
  107540. b->ptr++;
  107541. b->endbyte++;
  107542. }
  107543. return(ret);
  107544. }
  107545. long oggpackB_read1(oggpack_buffer *b){
  107546. long ret;
  107547. if(b->endbyte>=b->storage){
  107548. /* not the main path */
  107549. ret=-1L;
  107550. goto overflow;
  107551. }
  107552. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107553. overflow:
  107554. b->endbit++;
  107555. if(b->endbit>7){
  107556. b->endbit=0;
  107557. b->ptr++;
  107558. b->endbyte++;
  107559. }
  107560. return(ret);
  107561. }
  107562. long oggpack_bytes(oggpack_buffer *b){
  107563. return(b->endbyte+(b->endbit+7)/8);
  107564. }
  107565. long oggpack_bits(oggpack_buffer *b){
  107566. return(b->endbyte*8+b->endbit);
  107567. }
  107568. long oggpackB_bytes(oggpack_buffer *b){
  107569. return oggpack_bytes(b);
  107570. }
  107571. long oggpackB_bits(oggpack_buffer *b){
  107572. return oggpack_bits(b);
  107573. }
  107574. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107575. return(b->buffer);
  107576. }
  107577. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107578. return oggpack_get_buffer(b);
  107579. }
  107580. /* Self test of the bitwise routines; everything else is based on
  107581. them, so they damned well better be solid. */
  107582. #ifdef _V_SELFTEST
  107583. #include <stdio.h>
  107584. static int ilog(unsigned int v){
  107585. int ret=0;
  107586. while(v){
  107587. ret++;
  107588. v>>=1;
  107589. }
  107590. return(ret);
  107591. }
  107592. oggpack_buffer o;
  107593. oggpack_buffer r;
  107594. void report(char *in){
  107595. fprintf(stderr,"%s",in);
  107596. exit(1);
  107597. }
  107598. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107599. long bytes,i;
  107600. unsigned char *buffer;
  107601. oggpack_reset(&o);
  107602. for(i=0;i<vals;i++)
  107603. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107604. buffer=oggpack_get_buffer(&o);
  107605. bytes=oggpack_bytes(&o);
  107606. if(bytes!=compsize)report("wrong number of bytes!\n");
  107607. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107608. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107609. report("wrote incorrect value!\n");
  107610. }
  107611. oggpack_readinit(&r,buffer,bytes);
  107612. for(i=0;i<vals;i++){
  107613. int tbit=bits?bits:ilog(b[i]);
  107614. if(oggpack_look(&r,tbit)==-1)
  107615. report("out of data!\n");
  107616. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107617. report("looked at incorrect value!\n");
  107618. if(tbit==1)
  107619. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107620. report("looked at single bit incorrect value!\n");
  107621. if(tbit==1){
  107622. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107623. report("read incorrect single bit value!\n");
  107624. }else{
  107625. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107626. report("read incorrect value!\n");
  107627. }
  107628. }
  107629. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107630. }
  107631. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107632. long bytes,i;
  107633. unsigned char *buffer;
  107634. oggpackB_reset(&o);
  107635. for(i=0;i<vals;i++)
  107636. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107637. buffer=oggpackB_get_buffer(&o);
  107638. bytes=oggpackB_bytes(&o);
  107639. if(bytes!=compsize)report("wrong number of bytes!\n");
  107640. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107641. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107642. report("wrote incorrect value!\n");
  107643. }
  107644. oggpackB_readinit(&r,buffer,bytes);
  107645. for(i=0;i<vals;i++){
  107646. int tbit=bits?bits:ilog(b[i]);
  107647. if(oggpackB_look(&r,tbit)==-1)
  107648. report("out of data!\n");
  107649. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107650. report("looked at incorrect value!\n");
  107651. if(tbit==1)
  107652. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107653. report("looked at single bit incorrect value!\n");
  107654. if(tbit==1){
  107655. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107656. report("read incorrect single bit value!\n");
  107657. }else{
  107658. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107659. report("read incorrect value!\n");
  107660. }
  107661. }
  107662. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107663. }
  107664. int main(void){
  107665. unsigned char *buffer;
  107666. long bytes,i;
  107667. static unsigned long testbuffer1[]=
  107668. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107669. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107670. int test1size=43;
  107671. static unsigned long testbuffer2[]=
  107672. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107673. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107674. 85525151,0,12321,1,349528352};
  107675. int test2size=21;
  107676. static unsigned long testbuffer3[]=
  107677. {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,
  107678. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107679. int test3size=56;
  107680. static unsigned long large[]=
  107681. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107682. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107683. 85525151,0,12321,1,2146528352};
  107684. int onesize=33;
  107685. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107686. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107687. 223,4};
  107688. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107689. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107690. 245,251,128};
  107691. int twosize=6;
  107692. static int two[6]={61,255,255,251,231,29};
  107693. static int twoB[6]={247,63,255,253,249,120};
  107694. int threesize=54;
  107695. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107696. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107697. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107698. 100,52,4,14,18,86,77,1};
  107699. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107700. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107701. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107702. 200,20,254,4,58,106,176,144,0};
  107703. int foursize=38;
  107704. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107705. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107706. 28,2,133,0,1};
  107707. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107708. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107709. 129,10,4,32};
  107710. int fivesize=45;
  107711. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107712. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107713. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107714. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107715. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107716. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107717. int sixsize=7;
  107718. static int six[7]={17,177,170,242,169,19,148};
  107719. static int sixB[7]={136,141,85,79,149,200,41};
  107720. /* Test read/write together */
  107721. /* Later we test against pregenerated bitstreams */
  107722. oggpack_writeinit(&o);
  107723. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107724. cliptest(testbuffer1,test1size,0,one,onesize);
  107725. fprintf(stderr,"ok.");
  107726. fprintf(stderr,"\nNull bit call (LSb): ");
  107727. cliptest(testbuffer3,test3size,0,two,twosize);
  107728. fprintf(stderr,"ok.");
  107729. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107730. cliptest(testbuffer2,test2size,0,three,threesize);
  107731. fprintf(stderr,"ok.");
  107732. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107733. oggpack_reset(&o);
  107734. for(i=0;i<test2size;i++)
  107735. oggpack_write(&o,large[i],32);
  107736. buffer=oggpack_get_buffer(&o);
  107737. bytes=oggpack_bytes(&o);
  107738. oggpack_readinit(&r,buffer,bytes);
  107739. for(i=0;i<test2size;i++){
  107740. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107741. if(oggpack_look(&r,32)!=large[i]){
  107742. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107743. oggpack_look(&r,32),large[i]);
  107744. report("read incorrect value!\n");
  107745. }
  107746. oggpack_adv(&r,32);
  107747. }
  107748. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107749. fprintf(stderr,"ok.");
  107750. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107751. cliptest(testbuffer1,test1size,7,four,foursize);
  107752. fprintf(stderr,"ok.");
  107753. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107754. cliptest(testbuffer2,test2size,17,five,fivesize);
  107755. fprintf(stderr,"ok.");
  107756. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107757. cliptest(testbuffer3,test3size,1,six,sixsize);
  107758. fprintf(stderr,"ok.");
  107759. fprintf(stderr,"\nTesting read past end (LSb): ");
  107760. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107761. for(i=0;i<64;i++){
  107762. if(oggpack_read(&r,1)!=0){
  107763. fprintf(stderr,"failed; got -1 prematurely.\n");
  107764. exit(1);
  107765. }
  107766. }
  107767. if(oggpack_look(&r,1)!=-1 ||
  107768. oggpack_read(&r,1)!=-1){
  107769. fprintf(stderr,"failed; read past end without -1.\n");
  107770. exit(1);
  107771. }
  107772. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107773. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107774. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107775. exit(1);
  107776. }
  107777. if(oggpack_look(&r,18)!=0 ||
  107778. oggpack_look(&r,18)!=0){
  107779. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107780. exit(1);
  107781. }
  107782. if(oggpack_look(&r,19)!=-1 ||
  107783. oggpack_look(&r,19)!=-1){
  107784. fprintf(stderr,"failed; read past end without -1.\n");
  107785. exit(1);
  107786. }
  107787. if(oggpack_look(&r,32)!=-1 ||
  107788. oggpack_look(&r,32)!=-1){
  107789. fprintf(stderr,"failed; read past end without -1.\n");
  107790. exit(1);
  107791. }
  107792. oggpack_writeclear(&o);
  107793. fprintf(stderr,"ok.\n");
  107794. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107795. /* Test read/write together */
  107796. /* Later we test against pregenerated bitstreams */
  107797. oggpackB_writeinit(&o);
  107798. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107799. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107800. fprintf(stderr,"ok.");
  107801. fprintf(stderr,"\nNull bit call (MSb): ");
  107802. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107803. fprintf(stderr,"ok.");
  107804. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107805. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107806. fprintf(stderr,"ok.");
  107807. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107808. oggpackB_reset(&o);
  107809. for(i=0;i<test2size;i++)
  107810. oggpackB_write(&o,large[i],32);
  107811. buffer=oggpackB_get_buffer(&o);
  107812. bytes=oggpackB_bytes(&o);
  107813. oggpackB_readinit(&r,buffer,bytes);
  107814. for(i=0;i<test2size;i++){
  107815. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107816. if(oggpackB_look(&r,32)!=large[i]){
  107817. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107818. oggpackB_look(&r,32),large[i]);
  107819. report("read incorrect value!\n");
  107820. }
  107821. oggpackB_adv(&r,32);
  107822. }
  107823. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107824. fprintf(stderr,"ok.");
  107825. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107826. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107827. fprintf(stderr,"ok.");
  107828. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107829. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107830. fprintf(stderr,"ok.");
  107831. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107832. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107833. fprintf(stderr,"ok.");
  107834. fprintf(stderr,"\nTesting read past end (MSb): ");
  107835. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107836. for(i=0;i<64;i++){
  107837. if(oggpackB_read(&r,1)!=0){
  107838. fprintf(stderr,"failed; got -1 prematurely.\n");
  107839. exit(1);
  107840. }
  107841. }
  107842. if(oggpackB_look(&r,1)!=-1 ||
  107843. oggpackB_read(&r,1)!=-1){
  107844. fprintf(stderr,"failed; read past end without -1.\n");
  107845. exit(1);
  107846. }
  107847. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107848. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107849. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107850. exit(1);
  107851. }
  107852. if(oggpackB_look(&r,18)!=0 ||
  107853. oggpackB_look(&r,18)!=0){
  107854. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107855. exit(1);
  107856. }
  107857. if(oggpackB_look(&r,19)!=-1 ||
  107858. oggpackB_look(&r,19)!=-1){
  107859. fprintf(stderr,"failed; read past end without -1.\n");
  107860. exit(1);
  107861. }
  107862. if(oggpackB_look(&r,32)!=-1 ||
  107863. oggpackB_look(&r,32)!=-1){
  107864. fprintf(stderr,"failed; read past end without -1.\n");
  107865. exit(1);
  107866. }
  107867. oggpackB_writeclear(&o);
  107868. fprintf(stderr,"ok.\n\n");
  107869. return(0);
  107870. }
  107871. #endif /* _V_SELFTEST */
  107872. #undef BUFFER_INCREMENT
  107873. #endif
  107874. /*** End of inlined file: bitwise.c ***/
  107875. /*** Start of inlined file: framing.c ***/
  107876. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107877. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107878. // tasks..
  107879. #if JUCE_MSVC
  107880. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107881. #endif
  107882. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107883. #if JUCE_USE_OGGVORBIS
  107884. #include <stdlib.h>
  107885. #include <string.h>
  107886. /* A complete description of Ogg framing exists in docs/framing.html */
  107887. int ogg_page_version(ogg_page *og){
  107888. return((int)(og->header[4]));
  107889. }
  107890. int ogg_page_continued(ogg_page *og){
  107891. return((int)(og->header[5]&0x01));
  107892. }
  107893. int ogg_page_bos(ogg_page *og){
  107894. return((int)(og->header[5]&0x02));
  107895. }
  107896. int ogg_page_eos(ogg_page *og){
  107897. return((int)(og->header[5]&0x04));
  107898. }
  107899. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107900. unsigned char *page=og->header;
  107901. ogg_int64_t granulepos=page[13]&(0xff);
  107902. granulepos= (granulepos<<8)|(page[12]&0xff);
  107903. granulepos= (granulepos<<8)|(page[11]&0xff);
  107904. granulepos= (granulepos<<8)|(page[10]&0xff);
  107905. granulepos= (granulepos<<8)|(page[9]&0xff);
  107906. granulepos= (granulepos<<8)|(page[8]&0xff);
  107907. granulepos= (granulepos<<8)|(page[7]&0xff);
  107908. granulepos= (granulepos<<8)|(page[6]&0xff);
  107909. return(granulepos);
  107910. }
  107911. int ogg_page_serialno(ogg_page *og){
  107912. return(og->header[14] |
  107913. (og->header[15]<<8) |
  107914. (og->header[16]<<16) |
  107915. (og->header[17]<<24));
  107916. }
  107917. long ogg_page_pageno(ogg_page *og){
  107918. return(og->header[18] |
  107919. (og->header[19]<<8) |
  107920. (og->header[20]<<16) |
  107921. (og->header[21]<<24));
  107922. }
  107923. /* returns the number of packets that are completed on this page (if
  107924. the leading packet is begun on a previous page, but ends on this
  107925. page, it's counted */
  107926. /* NOTE:
  107927. If a page consists of a packet begun on a previous page, and a new
  107928. packet begun (but not completed) on this page, the return will be:
  107929. ogg_page_packets(page) ==1,
  107930. ogg_page_continued(page) !=0
  107931. If a page happens to be a single packet that was begun on a
  107932. previous page, and spans to the next page (in the case of a three or
  107933. more page packet), the return will be:
  107934. ogg_page_packets(page) ==0,
  107935. ogg_page_continued(page) !=0
  107936. */
  107937. int ogg_page_packets(ogg_page *og){
  107938. int i,n=og->header[26],count=0;
  107939. for(i=0;i<n;i++)
  107940. if(og->header[27+i]<255)count++;
  107941. return(count);
  107942. }
  107943. #if 0
  107944. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107945. use the static init below) */
  107946. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107947. int i;
  107948. unsigned long r;
  107949. r = index << 24;
  107950. for (i=0; i<8; i++)
  107951. if (r & 0x80000000UL)
  107952. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107953. polynomial, although we use an
  107954. unreflected alg and an init/final
  107955. of 0, not 0xffffffff */
  107956. else
  107957. r<<=1;
  107958. return (r & 0xffffffffUL);
  107959. }
  107960. #endif
  107961. static const ogg_uint32_t crc_lookup[256]={
  107962. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107963. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107964. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107965. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107966. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107967. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107968. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107969. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107970. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107971. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107972. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107973. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107974. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107975. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107976. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107977. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107978. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107979. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107980. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107981. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107982. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107983. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107984. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107985. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107986. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107987. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107988. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107989. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107990. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107991. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107992. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107993. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107994. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107995. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107996. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107997. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107998. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107999. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108000. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108001. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108002. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108003. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108004. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108005. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108006. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108007. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108008. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108009. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108010. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108011. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108012. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108013. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108014. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108015. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108016. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108017. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108018. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108019. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108020. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108021. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108022. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108023. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108024. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108025. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108026. /* init the encode/decode logical stream state */
  108027. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108028. if(os){
  108029. memset(os,0,sizeof(*os));
  108030. os->body_storage=16*1024;
  108031. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108032. os->lacing_storage=1024;
  108033. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108034. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108035. os->serialno=serialno;
  108036. return(0);
  108037. }
  108038. return(-1);
  108039. }
  108040. /* _clear does not free os, only the non-flat storage within */
  108041. int ogg_stream_clear(ogg_stream_state *os){
  108042. if(os){
  108043. if(os->body_data)_ogg_free(os->body_data);
  108044. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108045. if(os->granule_vals)_ogg_free(os->granule_vals);
  108046. memset(os,0,sizeof(*os));
  108047. }
  108048. return(0);
  108049. }
  108050. int ogg_stream_destroy(ogg_stream_state *os){
  108051. if(os){
  108052. ogg_stream_clear(os);
  108053. _ogg_free(os);
  108054. }
  108055. return(0);
  108056. }
  108057. /* Helpers for ogg_stream_encode; this keeps the structure and
  108058. what's happening fairly clear */
  108059. static void _os_body_expand(ogg_stream_state *os,int needed){
  108060. if(os->body_storage<=os->body_fill+needed){
  108061. os->body_storage+=(needed+1024);
  108062. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108063. }
  108064. }
  108065. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108066. if(os->lacing_storage<=os->lacing_fill+needed){
  108067. os->lacing_storage+=(needed+32);
  108068. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108069. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108070. }
  108071. }
  108072. /* checksum the page */
  108073. /* Direct table CRC; note that this will be faster in the future if we
  108074. perform the checksum silmultaneously with other copies */
  108075. void ogg_page_checksum_set(ogg_page *og){
  108076. if(og){
  108077. ogg_uint32_t crc_reg=0;
  108078. int i;
  108079. /* safety; needed for API behavior, but not framing code */
  108080. og->header[22]=0;
  108081. og->header[23]=0;
  108082. og->header[24]=0;
  108083. og->header[25]=0;
  108084. for(i=0;i<og->header_len;i++)
  108085. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108086. for(i=0;i<og->body_len;i++)
  108087. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108088. og->header[22]=(unsigned char)(crc_reg&0xff);
  108089. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108090. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108091. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108092. }
  108093. }
  108094. /* submit data to the internal buffer of the framing engine */
  108095. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108096. int lacing_vals=op->bytes/255+1,i;
  108097. if(os->body_returned){
  108098. /* advance packet data according to the body_returned pointer. We
  108099. had to keep it around to return a pointer into the buffer last
  108100. call */
  108101. os->body_fill-=os->body_returned;
  108102. if(os->body_fill)
  108103. memmove(os->body_data,os->body_data+os->body_returned,
  108104. os->body_fill);
  108105. os->body_returned=0;
  108106. }
  108107. /* make sure we have the buffer storage */
  108108. _os_body_expand(os,op->bytes);
  108109. _os_lacing_expand(os,lacing_vals);
  108110. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108111. the liability of overly clean abstraction for the time being. It
  108112. will actually be fairly easy to eliminate the extra copy in the
  108113. future */
  108114. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108115. os->body_fill+=op->bytes;
  108116. /* Store lacing vals for this packet */
  108117. for(i=0;i<lacing_vals-1;i++){
  108118. os->lacing_vals[os->lacing_fill+i]=255;
  108119. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108120. }
  108121. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108122. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108123. /* flag the first segment as the beginning of the packet */
  108124. os->lacing_vals[os->lacing_fill]|= 0x100;
  108125. os->lacing_fill+=lacing_vals;
  108126. /* for the sake of completeness */
  108127. os->packetno++;
  108128. if(op->e_o_s)os->e_o_s=1;
  108129. return(0);
  108130. }
  108131. /* This will flush remaining packets into a page (returning nonzero),
  108132. even if there is not enough data to trigger a flush normally
  108133. (undersized page). If there are no packets or partial packets to
  108134. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108135. try to flush a normal sized page like ogg_stream_pageout; a call to
  108136. ogg_stream_flush does not guarantee that all packets have flushed.
  108137. Only a return value of 0 from ogg_stream_flush indicates all packet
  108138. data is flushed into pages.
  108139. since ogg_stream_flush will flush the last page in a stream even if
  108140. it's undersized, you almost certainly want to use ogg_stream_pageout
  108141. (and *not* ogg_stream_flush) unless you specifically need to flush
  108142. an page regardless of size in the middle of a stream. */
  108143. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108144. int i;
  108145. int vals=0;
  108146. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108147. int bytes=0;
  108148. long acc=0;
  108149. ogg_int64_t granule_pos=-1;
  108150. if(maxvals==0)return(0);
  108151. /* construct a page */
  108152. /* decide how many segments to include */
  108153. /* If this is the initial header case, the first page must only include
  108154. the initial header packet */
  108155. if(os->b_o_s==0){ /* 'initial header page' case */
  108156. granule_pos=0;
  108157. for(vals=0;vals<maxvals;vals++){
  108158. if((os->lacing_vals[vals]&0x0ff)<255){
  108159. vals++;
  108160. break;
  108161. }
  108162. }
  108163. }else{
  108164. for(vals=0;vals<maxvals;vals++){
  108165. if(acc>4096)break;
  108166. acc+=os->lacing_vals[vals]&0x0ff;
  108167. if((os->lacing_vals[vals]&0xff)<255)
  108168. granule_pos=os->granule_vals[vals];
  108169. }
  108170. }
  108171. /* construct the header in temp storage */
  108172. memcpy(os->header,"OggS",4);
  108173. /* stream structure version */
  108174. os->header[4]=0x00;
  108175. /* continued packet flag? */
  108176. os->header[5]=0x00;
  108177. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108178. /* first page flag? */
  108179. if(os->b_o_s==0)os->header[5]|=0x02;
  108180. /* last page flag? */
  108181. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108182. os->b_o_s=1;
  108183. /* 64 bits of PCM position */
  108184. for(i=6;i<14;i++){
  108185. os->header[i]=(unsigned char)(granule_pos&0xff);
  108186. granule_pos>>=8;
  108187. }
  108188. /* 32 bits of stream serial number */
  108189. {
  108190. long serialno=os->serialno;
  108191. for(i=14;i<18;i++){
  108192. os->header[i]=(unsigned char)(serialno&0xff);
  108193. serialno>>=8;
  108194. }
  108195. }
  108196. /* 32 bits of page counter (we have both counter and page header
  108197. because this val can roll over) */
  108198. if(os->pageno==-1)os->pageno=0; /* because someone called
  108199. stream_reset; this would be a
  108200. strange thing to do in an
  108201. encode stream, but it has
  108202. plausible uses */
  108203. {
  108204. long pageno=os->pageno++;
  108205. for(i=18;i<22;i++){
  108206. os->header[i]=(unsigned char)(pageno&0xff);
  108207. pageno>>=8;
  108208. }
  108209. }
  108210. /* zero for computation; filled in later */
  108211. os->header[22]=0;
  108212. os->header[23]=0;
  108213. os->header[24]=0;
  108214. os->header[25]=0;
  108215. /* segment table */
  108216. os->header[26]=(unsigned char)(vals&0xff);
  108217. for(i=0;i<vals;i++)
  108218. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108219. /* set pointers in the ogg_page struct */
  108220. og->header=os->header;
  108221. og->header_len=os->header_fill=vals+27;
  108222. og->body=os->body_data+os->body_returned;
  108223. og->body_len=bytes;
  108224. /* advance the lacing data and set the body_returned pointer */
  108225. os->lacing_fill-=vals;
  108226. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108227. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108228. os->body_returned+=bytes;
  108229. /* calculate the checksum */
  108230. ogg_page_checksum_set(og);
  108231. /* done */
  108232. return(1);
  108233. }
  108234. /* This constructs pages from buffered packet segments. The pointers
  108235. returned are to static buffers; do not free. The returned buffers are
  108236. good only until the next call (using the same ogg_stream_state) */
  108237. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108238. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108239. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108240. os->lacing_fill>=255 || /* 'segment table full' case */
  108241. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108242. return(ogg_stream_flush(os,og));
  108243. }
  108244. /* not enough data to construct a page and not end of stream */
  108245. return(0);
  108246. }
  108247. int ogg_stream_eos(ogg_stream_state *os){
  108248. return os->e_o_s;
  108249. }
  108250. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108251. /* This has two layers to place more of the multi-serialno and paging
  108252. control in the application's hands. First, we expose a data buffer
  108253. using ogg_sync_buffer(). The app either copies into the
  108254. buffer, or passes it directly to read(), etc. We then call
  108255. ogg_sync_wrote() to tell how many bytes we just added.
  108256. Pages are returned (pointers into the buffer in ogg_sync_state)
  108257. by ogg_sync_pageout(). The page is then submitted to
  108258. ogg_stream_pagein() along with the appropriate
  108259. ogg_stream_state* (ie, matching serialno). We then get raw
  108260. packets out calling ogg_stream_packetout() with a
  108261. ogg_stream_state. */
  108262. /* initialize the struct to a known state */
  108263. int ogg_sync_init(ogg_sync_state *oy){
  108264. if(oy){
  108265. memset(oy,0,sizeof(*oy));
  108266. }
  108267. return(0);
  108268. }
  108269. /* clear non-flat storage within */
  108270. int ogg_sync_clear(ogg_sync_state *oy){
  108271. if(oy){
  108272. if(oy->data)_ogg_free(oy->data);
  108273. ogg_sync_init(oy);
  108274. }
  108275. return(0);
  108276. }
  108277. int ogg_sync_destroy(ogg_sync_state *oy){
  108278. if(oy){
  108279. ogg_sync_clear(oy);
  108280. _ogg_free(oy);
  108281. }
  108282. return(0);
  108283. }
  108284. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108285. /* first, clear out any space that has been previously returned */
  108286. if(oy->returned){
  108287. oy->fill-=oy->returned;
  108288. if(oy->fill>0)
  108289. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108290. oy->returned=0;
  108291. }
  108292. if(size>oy->storage-oy->fill){
  108293. /* We need to extend the internal buffer */
  108294. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108295. if(oy->data)
  108296. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108297. else
  108298. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108299. oy->storage=newsize;
  108300. }
  108301. /* expose a segment at least as large as requested at the fill mark */
  108302. return((char *)oy->data+oy->fill);
  108303. }
  108304. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108305. if(oy->fill+bytes>oy->storage)return(-1);
  108306. oy->fill+=bytes;
  108307. return(0);
  108308. }
  108309. /* sync the stream. This is meant to be useful for finding page
  108310. boundaries.
  108311. return values for this:
  108312. -n) skipped n bytes
  108313. 0) page not ready; more data (no bytes skipped)
  108314. n) page synced at current location; page length n bytes
  108315. */
  108316. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108317. unsigned char *page=oy->data+oy->returned;
  108318. unsigned char *next;
  108319. long bytes=oy->fill-oy->returned;
  108320. if(oy->headerbytes==0){
  108321. int headerbytes,i;
  108322. if(bytes<27)return(0); /* not enough for a header */
  108323. /* verify capture pattern */
  108324. if(memcmp(page,"OggS",4))goto sync_fail;
  108325. headerbytes=page[26]+27;
  108326. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108327. /* count up body length in the segment table */
  108328. for(i=0;i<page[26];i++)
  108329. oy->bodybytes+=page[27+i];
  108330. oy->headerbytes=headerbytes;
  108331. }
  108332. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108333. /* The whole test page is buffered. Verify the checksum */
  108334. {
  108335. /* Grab the checksum bytes, set the header field to zero */
  108336. char chksum[4];
  108337. ogg_page log;
  108338. memcpy(chksum,page+22,4);
  108339. memset(page+22,0,4);
  108340. /* set up a temp page struct and recompute the checksum */
  108341. log.header=page;
  108342. log.header_len=oy->headerbytes;
  108343. log.body=page+oy->headerbytes;
  108344. log.body_len=oy->bodybytes;
  108345. ogg_page_checksum_set(&log);
  108346. /* Compare */
  108347. if(memcmp(chksum,page+22,4)){
  108348. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108349. at all) */
  108350. /* replace the computed checksum with the one actually read in */
  108351. memcpy(page+22,chksum,4);
  108352. /* Bad checksum. Lose sync */
  108353. goto sync_fail;
  108354. }
  108355. }
  108356. /* yes, have a whole page all ready to go */
  108357. {
  108358. unsigned char *page=oy->data+oy->returned;
  108359. long bytes;
  108360. if(og){
  108361. og->header=page;
  108362. og->header_len=oy->headerbytes;
  108363. og->body=page+oy->headerbytes;
  108364. og->body_len=oy->bodybytes;
  108365. }
  108366. oy->unsynced=0;
  108367. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108368. oy->headerbytes=0;
  108369. oy->bodybytes=0;
  108370. return(bytes);
  108371. }
  108372. sync_fail:
  108373. oy->headerbytes=0;
  108374. oy->bodybytes=0;
  108375. /* search for possible capture */
  108376. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108377. if(!next)
  108378. next=oy->data+oy->fill;
  108379. oy->returned=next-oy->data;
  108380. return(-(next-page));
  108381. }
  108382. /* sync the stream and get a page. Keep trying until we find a page.
  108383. Supress 'sync errors' after reporting the first.
  108384. return values:
  108385. -1) recapture (hole in data)
  108386. 0) need more data
  108387. 1) page returned
  108388. Returns pointers into buffered data; invalidated by next call to
  108389. _stream, _clear, _init, or _buffer */
  108390. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108391. /* all we need to do is verify a page at the head of the stream
  108392. buffer. If it doesn't verify, we look for the next potential
  108393. frame */
  108394. for(;;){
  108395. long ret=ogg_sync_pageseek(oy,og);
  108396. if(ret>0){
  108397. /* have a page */
  108398. return(1);
  108399. }
  108400. if(ret==0){
  108401. /* need more data */
  108402. return(0);
  108403. }
  108404. /* head did not start a synced page... skipped some bytes */
  108405. if(!oy->unsynced){
  108406. oy->unsynced=1;
  108407. return(-1);
  108408. }
  108409. /* loop. keep looking */
  108410. }
  108411. }
  108412. /* add the incoming page to the stream state; we decompose the page
  108413. into packet segments here as well. */
  108414. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108415. unsigned char *header=og->header;
  108416. unsigned char *body=og->body;
  108417. long bodysize=og->body_len;
  108418. int segptr=0;
  108419. int version=ogg_page_version(og);
  108420. int continued=ogg_page_continued(og);
  108421. int bos=ogg_page_bos(og);
  108422. int eos=ogg_page_eos(og);
  108423. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108424. int serialno=ogg_page_serialno(og);
  108425. long pageno=ogg_page_pageno(og);
  108426. int segments=header[26];
  108427. /* clean up 'returned data' */
  108428. {
  108429. long lr=os->lacing_returned;
  108430. long br=os->body_returned;
  108431. /* body data */
  108432. if(br){
  108433. os->body_fill-=br;
  108434. if(os->body_fill)
  108435. memmove(os->body_data,os->body_data+br,os->body_fill);
  108436. os->body_returned=0;
  108437. }
  108438. if(lr){
  108439. /* segment table */
  108440. if(os->lacing_fill-lr){
  108441. memmove(os->lacing_vals,os->lacing_vals+lr,
  108442. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108443. memmove(os->granule_vals,os->granule_vals+lr,
  108444. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108445. }
  108446. os->lacing_fill-=lr;
  108447. os->lacing_packet-=lr;
  108448. os->lacing_returned=0;
  108449. }
  108450. }
  108451. /* check the serial number */
  108452. if(serialno!=os->serialno)return(-1);
  108453. if(version>0)return(-1);
  108454. _os_lacing_expand(os,segments+1);
  108455. /* are we in sequence? */
  108456. if(pageno!=os->pageno){
  108457. int i;
  108458. /* unroll previous partial packet (if any) */
  108459. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108460. os->body_fill-=os->lacing_vals[i]&0xff;
  108461. os->lacing_fill=os->lacing_packet;
  108462. /* make a note of dropped data in segment table */
  108463. if(os->pageno!=-1){
  108464. os->lacing_vals[os->lacing_fill++]=0x400;
  108465. os->lacing_packet++;
  108466. }
  108467. }
  108468. /* are we a 'continued packet' page? If so, we may need to skip
  108469. some segments */
  108470. if(continued){
  108471. if(os->lacing_fill<1 ||
  108472. os->lacing_vals[os->lacing_fill-1]==0x400){
  108473. bos=0;
  108474. for(;segptr<segments;segptr++){
  108475. int val=header[27+segptr];
  108476. body+=val;
  108477. bodysize-=val;
  108478. if(val<255){
  108479. segptr++;
  108480. break;
  108481. }
  108482. }
  108483. }
  108484. }
  108485. if(bodysize){
  108486. _os_body_expand(os,bodysize);
  108487. memcpy(os->body_data+os->body_fill,body,bodysize);
  108488. os->body_fill+=bodysize;
  108489. }
  108490. {
  108491. int saved=-1;
  108492. while(segptr<segments){
  108493. int val=header[27+segptr];
  108494. os->lacing_vals[os->lacing_fill]=val;
  108495. os->granule_vals[os->lacing_fill]=-1;
  108496. if(bos){
  108497. os->lacing_vals[os->lacing_fill]|=0x100;
  108498. bos=0;
  108499. }
  108500. if(val<255)saved=os->lacing_fill;
  108501. os->lacing_fill++;
  108502. segptr++;
  108503. if(val<255)os->lacing_packet=os->lacing_fill;
  108504. }
  108505. /* set the granulepos on the last granuleval of the last full packet */
  108506. if(saved!=-1){
  108507. os->granule_vals[saved]=granulepos;
  108508. }
  108509. }
  108510. if(eos){
  108511. os->e_o_s=1;
  108512. if(os->lacing_fill>0)
  108513. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108514. }
  108515. os->pageno=pageno+1;
  108516. return(0);
  108517. }
  108518. /* clear things to an initial state. Good to call, eg, before seeking */
  108519. int ogg_sync_reset(ogg_sync_state *oy){
  108520. oy->fill=0;
  108521. oy->returned=0;
  108522. oy->unsynced=0;
  108523. oy->headerbytes=0;
  108524. oy->bodybytes=0;
  108525. return(0);
  108526. }
  108527. int ogg_stream_reset(ogg_stream_state *os){
  108528. os->body_fill=0;
  108529. os->body_returned=0;
  108530. os->lacing_fill=0;
  108531. os->lacing_packet=0;
  108532. os->lacing_returned=0;
  108533. os->header_fill=0;
  108534. os->e_o_s=0;
  108535. os->b_o_s=0;
  108536. os->pageno=-1;
  108537. os->packetno=0;
  108538. os->granulepos=0;
  108539. return(0);
  108540. }
  108541. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108542. ogg_stream_reset(os);
  108543. os->serialno=serialno;
  108544. return(0);
  108545. }
  108546. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108547. /* The last part of decode. We have the stream broken into packet
  108548. segments. Now we need to group them into packets (or return the
  108549. out of sync markers) */
  108550. int ptr=os->lacing_returned;
  108551. if(os->lacing_packet<=ptr)return(0);
  108552. if(os->lacing_vals[ptr]&0x400){
  108553. /* we need to tell the codec there's a gap; it might need to
  108554. handle previous packet dependencies. */
  108555. os->lacing_returned++;
  108556. os->packetno++;
  108557. return(-1);
  108558. }
  108559. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108560. to ask if there's a whole packet
  108561. waiting */
  108562. /* Gather the whole packet. We'll have no holes or a partial packet */
  108563. {
  108564. int size=os->lacing_vals[ptr]&0xff;
  108565. int bytes=size;
  108566. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108567. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108568. while(size==255){
  108569. int val=os->lacing_vals[++ptr];
  108570. size=val&0xff;
  108571. if(val&0x200)eos=0x200;
  108572. bytes+=size;
  108573. }
  108574. if(op){
  108575. op->e_o_s=eos;
  108576. op->b_o_s=bos;
  108577. op->packet=os->body_data+os->body_returned;
  108578. op->packetno=os->packetno;
  108579. op->granulepos=os->granule_vals[ptr];
  108580. op->bytes=bytes;
  108581. }
  108582. if(adv){
  108583. os->body_returned+=bytes;
  108584. os->lacing_returned=ptr+1;
  108585. os->packetno++;
  108586. }
  108587. }
  108588. return(1);
  108589. }
  108590. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108591. return _packetout(os,op,1);
  108592. }
  108593. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108594. return _packetout(os,op,0);
  108595. }
  108596. void ogg_packet_clear(ogg_packet *op) {
  108597. _ogg_free(op->packet);
  108598. memset(op, 0, sizeof(*op));
  108599. }
  108600. #ifdef _V_SELFTEST
  108601. #include <stdio.h>
  108602. ogg_stream_state os_en, os_de;
  108603. ogg_sync_state oy;
  108604. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108605. long j;
  108606. static int sequence=0;
  108607. static int lastno=0;
  108608. if(op->bytes!=len){
  108609. fprintf(stderr,"incorrect packet length!\n");
  108610. exit(1);
  108611. }
  108612. if(op->granulepos!=pos){
  108613. fprintf(stderr,"incorrect packet position!\n");
  108614. exit(1);
  108615. }
  108616. /* packet number just follows sequence/gap; adjust the input number
  108617. for that */
  108618. if(no==0){
  108619. sequence=0;
  108620. }else{
  108621. sequence++;
  108622. if(no>lastno+1)
  108623. sequence++;
  108624. }
  108625. lastno=no;
  108626. if(op->packetno!=sequence){
  108627. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108628. (long)(op->packetno),sequence);
  108629. exit(1);
  108630. }
  108631. /* Test data */
  108632. for(j=0;j<op->bytes;j++)
  108633. if(op->packet[j]!=((j+no)&0xff)){
  108634. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108635. j,op->packet[j],(j+no)&0xff);
  108636. exit(1);
  108637. }
  108638. }
  108639. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108640. long j;
  108641. /* Test data */
  108642. for(j=0;j<og->body_len;j++)
  108643. if(og->body[j]!=data[j]){
  108644. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108645. j,data[j],og->body[j]);
  108646. exit(1);
  108647. }
  108648. /* Test header */
  108649. for(j=0;j<og->header_len;j++){
  108650. if(og->header[j]!=header[j]){
  108651. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108652. for(j=0;j<header[26]+27;j++)
  108653. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108654. fprintf(stderr,"\n");
  108655. exit(1);
  108656. }
  108657. }
  108658. if(og->header_len!=header[26]+27){
  108659. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108660. og->header_len,header[26]+27);
  108661. exit(1);
  108662. }
  108663. }
  108664. void print_header(ogg_page *og){
  108665. int j;
  108666. fprintf(stderr,"\nHEADER:\n");
  108667. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108668. og->header[0],og->header[1],og->header[2],og->header[3],
  108669. (int)og->header[4],(int)og->header[5]);
  108670. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108671. (og->header[9]<<24)|(og->header[8]<<16)|
  108672. (og->header[7]<<8)|og->header[6],
  108673. (og->header[17]<<24)|(og->header[16]<<16)|
  108674. (og->header[15]<<8)|og->header[14],
  108675. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108676. (og->header[19]<<8)|og->header[18]);
  108677. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108678. (int)og->header[22],(int)og->header[23],
  108679. (int)og->header[24],(int)og->header[25],
  108680. (int)og->header[26]);
  108681. for(j=27;j<og->header_len;j++)
  108682. fprintf(stderr,"%d ",(int)og->header[j]);
  108683. fprintf(stderr,")\n\n");
  108684. }
  108685. void copy_page(ogg_page *og){
  108686. unsigned char *temp=_ogg_malloc(og->header_len);
  108687. memcpy(temp,og->header,og->header_len);
  108688. og->header=temp;
  108689. temp=_ogg_malloc(og->body_len);
  108690. memcpy(temp,og->body,og->body_len);
  108691. og->body=temp;
  108692. }
  108693. void free_page(ogg_page *og){
  108694. _ogg_free (og->header);
  108695. _ogg_free (og->body);
  108696. }
  108697. void error(void){
  108698. fprintf(stderr,"error!\n");
  108699. exit(1);
  108700. }
  108701. /* 17 only */
  108702. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108703. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108704. 0x01,0x02,0x03,0x04,0,0,0,0,
  108705. 0x15,0xed,0xec,0x91,
  108706. 1,
  108707. 17};
  108708. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108709. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108710. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108711. 0x01,0x02,0x03,0x04,0,0,0,0,
  108712. 0x59,0x10,0x6c,0x2c,
  108713. 1,
  108714. 17};
  108715. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108716. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108717. 0x01,0x02,0x03,0x04,1,0,0,0,
  108718. 0x89,0x33,0x85,0xce,
  108719. 13,
  108720. 254,255,0,255,1,255,245,255,255,0,
  108721. 255,255,90};
  108722. /* nil packets; beginning,middle,end */
  108723. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108724. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108725. 0x01,0x02,0x03,0x04,0,0,0,0,
  108726. 0xff,0x7b,0x23,0x17,
  108727. 1,
  108728. 0};
  108729. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108730. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108731. 0x01,0x02,0x03,0x04,1,0,0,0,
  108732. 0x5c,0x3f,0x66,0xcb,
  108733. 17,
  108734. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108735. 255,255,90,0};
  108736. /* large initial packet */
  108737. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108738. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108739. 0x01,0x02,0x03,0x04,0,0,0,0,
  108740. 0x01,0x27,0x31,0xaa,
  108741. 18,
  108742. 255,255,255,255,255,255,255,255,
  108743. 255,255,255,255,255,255,255,255,255,10};
  108744. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108745. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108746. 0x01,0x02,0x03,0x04,1,0,0,0,
  108747. 0x7f,0x4e,0x8a,0xd2,
  108748. 4,
  108749. 255,4,255,0};
  108750. /* continuing packet test */
  108751. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108752. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108753. 0x01,0x02,0x03,0x04,0,0,0,0,
  108754. 0xff,0x7b,0x23,0x17,
  108755. 1,
  108756. 0};
  108757. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108758. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108759. 0x01,0x02,0x03,0x04,1,0,0,0,
  108760. 0x54,0x05,0x51,0xc8,
  108761. 17,
  108762. 255,255,255,255,255,255,255,255,
  108763. 255,255,255,255,255,255,255,255,255};
  108764. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108765. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108766. 0x01,0x02,0x03,0x04,2,0,0,0,
  108767. 0xc8,0xc3,0xcb,0xed,
  108768. 5,
  108769. 10,255,4,255,0};
  108770. /* page with the 255 segment limit */
  108771. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108772. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108773. 0x01,0x02,0x03,0x04,0,0,0,0,
  108774. 0xff,0x7b,0x23,0x17,
  108775. 1,
  108776. 0};
  108777. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108778. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108779. 0x01,0x02,0x03,0x04,1,0,0,0,
  108780. 0xed,0x2a,0x2e,0xa7,
  108781. 255,
  108782. 10,10,10,10,10,10,10,10,
  108783. 10,10,10,10,10,10,10,10,
  108784. 10,10,10,10,10,10,10,10,
  108785. 10,10,10,10,10,10,10,10,
  108786. 10,10,10,10,10,10,10,10,
  108787. 10,10,10,10,10,10,10,10,
  108788. 10,10,10,10,10,10,10,10,
  108789. 10,10,10,10,10,10,10,10,
  108790. 10,10,10,10,10,10,10,10,
  108791. 10,10,10,10,10,10,10,10,
  108792. 10,10,10,10,10,10,10,10,
  108793. 10,10,10,10,10,10,10,10,
  108794. 10,10,10,10,10,10,10,10,
  108795. 10,10,10,10,10,10,10,10,
  108796. 10,10,10,10,10,10,10,10,
  108797. 10,10,10,10,10,10,10,10,
  108798. 10,10,10,10,10,10,10,10,
  108799. 10,10,10,10,10,10,10,10,
  108800. 10,10,10,10,10,10,10,10,
  108801. 10,10,10,10,10,10,10,10,
  108802. 10,10,10,10,10,10,10,10,
  108803. 10,10,10,10,10,10,10,10,
  108804. 10,10,10,10,10,10,10,10,
  108805. 10,10,10,10,10,10,10,10,
  108806. 10,10,10,10,10,10,10,10,
  108807. 10,10,10,10,10,10,10,10,
  108808. 10,10,10,10,10,10,10,10,
  108809. 10,10,10,10,10,10,10,10,
  108810. 10,10,10,10,10,10,10,10,
  108811. 10,10,10,10,10,10,10,10,
  108812. 10,10,10,10,10,10,10,10,
  108813. 10,10,10,10,10,10,10};
  108814. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108815. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108816. 0x01,0x02,0x03,0x04,2,0,0,0,
  108817. 0x6c,0x3b,0x82,0x3d,
  108818. 1,
  108819. 50};
  108820. /* packet that overspans over an entire page */
  108821. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108822. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108823. 0x01,0x02,0x03,0x04,0,0,0,0,
  108824. 0xff,0x7b,0x23,0x17,
  108825. 1,
  108826. 0};
  108827. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108828. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108829. 0x01,0x02,0x03,0x04,1,0,0,0,
  108830. 0x3c,0xd9,0x4d,0x3f,
  108831. 17,
  108832. 100,255,255,255,255,255,255,255,255,
  108833. 255,255,255,255,255,255,255,255};
  108834. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108835. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108836. 0x01,0x02,0x03,0x04,2,0,0,0,
  108837. 0x01,0xd2,0xe5,0xe5,
  108838. 17,
  108839. 255,255,255,255,255,255,255,255,
  108840. 255,255,255,255,255,255,255,255,255};
  108841. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108842. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108843. 0x01,0x02,0x03,0x04,3,0,0,0,
  108844. 0xef,0xdd,0x88,0xde,
  108845. 7,
  108846. 255,255,75,255,4,255,0};
  108847. /* packet that overspans over an entire page */
  108848. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108849. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108850. 0x01,0x02,0x03,0x04,0,0,0,0,
  108851. 0xff,0x7b,0x23,0x17,
  108852. 1,
  108853. 0};
  108854. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108855. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108856. 0x01,0x02,0x03,0x04,1,0,0,0,
  108857. 0x3c,0xd9,0x4d,0x3f,
  108858. 17,
  108859. 100,255,255,255,255,255,255,255,255,
  108860. 255,255,255,255,255,255,255,255};
  108861. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108862. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108863. 0x01,0x02,0x03,0x04,2,0,0,0,
  108864. 0xd4,0xe0,0x60,0xe5,
  108865. 1,0};
  108866. void test_pack(const int *pl, const int **headers, int byteskip,
  108867. int pageskip, int packetskip){
  108868. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108869. long inptr=0;
  108870. long outptr=0;
  108871. long deptr=0;
  108872. long depacket=0;
  108873. long granule_pos=7,pageno=0;
  108874. int i,j,packets,pageout=pageskip;
  108875. int eosflag=0;
  108876. int bosflag=0;
  108877. int byteskipcount=0;
  108878. ogg_stream_reset(&os_en);
  108879. ogg_stream_reset(&os_de);
  108880. ogg_sync_reset(&oy);
  108881. for(packets=0;packets<packetskip;packets++)
  108882. depacket+=pl[packets];
  108883. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108884. for(i=0;i<packets;i++){
  108885. /* construct a test packet */
  108886. ogg_packet op;
  108887. int len=pl[i];
  108888. op.packet=data+inptr;
  108889. op.bytes=len;
  108890. op.e_o_s=(pl[i+1]<0?1:0);
  108891. op.granulepos=granule_pos;
  108892. granule_pos+=1024;
  108893. for(j=0;j<len;j++)data[inptr++]=i+j;
  108894. /* submit the test packet */
  108895. ogg_stream_packetin(&os_en,&op);
  108896. /* retrieve any finished pages */
  108897. {
  108898. ogg_page og;
  108899. while(ogg_stream_pageout(&os_en,&og)){
  108900. /* We have a page. Check it carefully */
  108901. fprintf(stderr,"%ld, ",pageno);
  108902. if(headers[pageno]==NULL){
  108903. fprintf(stderr,"coded too many pages!\n");
  108904. exit(1);
  108905. }
  108906. check_page(data+outptr,headers[pageno],&og);
  108907. outptr+=og.body_len;
  108908. pageno++;
  108909. if(pageskip){
  108910. bosflag=1;
  108911. pageskip--;
  108912. deptr+=og.body_len;
  108913. }
  108914. /* have a complete page; submit it to sync/decode */
  108915. {
  108916. ogg_page og_de;
  108917. ogg_packet op_de,op_de2;
  108918. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108919. char *next=buf;
  108920. byteskipcount+=og.header_len;
  108921. if(byteskipcount>byteskip){
  108922. memcpy(next,og.header,byteskipcount-byteskip);
  108923. next+=byteskipcount-byteskip;
  108924. byteskipcount=byteskip;
  108925. }
  108926. byteskipcount+=og.body_len;
  108927. if(byteskipcount>byteskip){
  108928. memcpy(next,og.body,byteskipcount-byteskip);
  108929. next+=byteskipcount-byteskip;
  108930. byteskipcount=byteskip;
  108931. }
  108932. ogg_sync_wrote(&oy,next-buf);
  108933. while(1){
  108934. int ret=ogg_sync_pageout(&oy,&og_de);
  108935. if(ret==0)break;
  108936. if(ret<0)continue;
  108937. /* got a page. Happy happy. Verify that it's good. */
  108938. fprintf(stderr,"(%ld), ",pageout);
  108939. check_page(data+deptr,headers[pageout],&og_de);
  108940. deptr+=og_de.body_len;
  108941. pageout++;
  108942. /* submit it to deconstitution */
  108943. ogg_stream_pagein(&os_de,&og_de);
  108944. /* packets out? */
  108945. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108946. ogg_stream_packetpeek(&os_de,NULL);
  108947. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108948. /* verify peek and out match */
  108949. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108950. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108951. depacket);
  108952. exit(1);
  108953. }
  108954. /* verify the packet! */
  108955. /* check data */
  108956. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108957. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108958. depacket);
  108959. exit(1);
  108960. }
  108961. /* check bos flag */
  108962. if(bosflag==0 && op_de.b_o_s==0){
  108963. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108964. exit(1);
  108965. }
  108966. if(bosflag && op_de.b_o_s){
  108967. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108968. exit(1);
  108969. }
  108970. bosflag=1;
  108971. depacket+=op_de.bytes;
  108972. /* check eos flag */
  108973. if(eosflag){
  108974. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108975. exit(1);
  108976. }
  108977. if(op_de.e_o_s)eosflag=1;
  108978. /* check granulepos flag */
  108979. if(op_de.granulepos!=-1){
  108980. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108981. }
  108982. }
  108983. }
  108984. }
  108985. }
  108986. }
  108987. }
  108988. _ogg_free(data);
  108989. if(headers[pageno]!=NULL){
  108990. fprintf(stderr,"did not write last page!\n");
  108991. exit(1);
  108992. }
  108993. if(headers[pageout]!=NULL){
  108994. fprintf(stderr,"did not decode last page!\n");
  108995. exit(1);
  108996. }
  108997. if(inptr!=outptr){
  108998. fprintf(stderr,"encoded page data incomplete!\n");
  108999. exit(1);
  109000. }
  109001. if(inptr!=deptr){
  109002. fprintf(stderr,"decoded page data incomplete!\n");
  109003. exit(1);
  109004. }
  109005. if(inptr!=depacket){
  109006. fprintf(stderr,"decoded packet data incomplete!\n");
  109007. exit(1);
  109008. }
  109009. if(!eosflag){
  109010. fprintf(stderr,"Never got a packet with EOS set!\n");
  109011. exit(1);
  109012. }
  109013. fprintf(stderr,"ok.\n");
  109014. }
  109015. int main(void){
  109016. ogg_stream_init(&os_en,0x04030201);
  109017. ogg_stream_init(&os_de,0x04030201);
  109018. ogg_sync_init(&oy);
  109019. /* Exercise each code path in the framing code. Also verify that
  109020. the checksums are working. */
  109021. {
  109022. /* 17 only */
  109023. const int packets[]={17, -1};
  109024. const int *headret[]={head1_0,NULL};
  109025. fprintf(stderr,"testing single page encoding... ");
  109026. test_pack(packets,headret,0,0,0);
  109027. }
  109028. {
  109029. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109030. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109031. const int *headret[]={head1_1,head2_1,NULL};
  109032. fprintf(stderr,"testing basic page encoding... ");
  109033. test_pack(packets,headret,0,0,0);
  109034. }
  109035. {
  109036. /* nil packets; beginning,middle,end */
  109037. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109038. const int *headret[]={head1_2,head2_2,NULL};
  109039. fprintf(stderr,"testing basic nil packets... ");
  109040. test_pack(packets,headret,0,0,0);
  109041. }
  109042. {
  109043. /* large initial packet */
  109044. const int packets[]={4345,259,255,-1};
  109045. const int *headret[]={head1_3,head2_3,NULL};
  109046. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109047. test_pack(packets,headret,0,0,0);
  109048. }
  109049. {
  109050. /* continuing packet test */
  109051. const int packets[]={0,4345,259,255,-1};
  109052. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109053. fprintf(stderr,"testing single packet page span... ");
  109054. test_pack(packets,headret,0,0,0);
  109055. }
  109056. /* page with the 255 segment limit */
  109057. {
  109058. const int packets[]={0,10,10,10,10,10,10,10,10,
  109059. 10,10,10,10,10,10,10,10,
  109060. 10,10,10,10,10,10,10,10,
  109061. 10,10,10,10,10,10,10,10,
  109062. 10,10,10,10,10,10,10,10,
  109063. 10,10,10,10,10,10,10,10,
  109064. 10,10,10,10,10,10,10,10,
  109065. 10,10,10,10,10,10,10,10,
  109066. 10,10,10,10,10,10,10,10,
  109067. 10,10,10,10,10,10,10,10,
  109068. 10,10,10,10,10,10,10,10,
  109069. 10,10,10,10,10,10,10,10,
  109070. 10,10,10,10,10,10,10,10,
  109071. 10,10,10,10,10,10,10,10,
  109072. 10,10,10,10,10,10,10,10,
  109073. 10,10,10,10,10,10,10,10,
  109074. 10,10,10,10,10,10,10,10,
  109075. 10,10,10,10,10,10,10,10,
  109076. 10,10,10,10,10,10,10,10,
  109077. 10,10,10,10,10,10,10,10,
  109078. 10,10,10,10,10,10,10,10,
  109079. 10,10,10,10,10,10,10,10,
  109080. 10,10,10,10,10,10,10,10,
  109081. 10,10,10,10,10,10,10,10,
  109082. 10,10,10,10,10,10,10,10,
  109083. 10,10,10,10,10,10,10,10,
  109084. 10,10,10,10,10,10,10,10,
  109085. 10,10,10,10,10,10,10,10,
  109086. 10,10,10,10,10,10,10,10,
  109087. 10,10,10,10,10,10,10,10,
  109088. 10,10,10,10,10,10,10,10,
  109089. 10,10,10,10,10,10,10,50,-1};
  109090. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109091. fprintf(stderr,"testing max packet segments... ");
  109092. test_pack(packets,headret,0,0,0);
  109093. }
  109094. {
  109095. /* packet that overspans over an entire page */
  109096. const int packets[]={0,100,9000,259,255,-1};
  109097. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109098. fprintf(stderr,"testing very large packets... ");
  109099. test_pack(packets,headret,0,0,0);
  109100. }
  109101. {
  109102. /* test for the libogg 1.1.1 resync in large continuation bug
  109103. found by Josh Coalson) */
  109104. const int packets[]={0,100,9000,259,255,-1};
  109105. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109106. fprintf(stderr,"testing continuation resync in very large packets... ");
  109107. test_pack(packets,headret,100,2,3);
  109108. }
  109109. {
  109110. /* term only page. why not? */
  109111. const int packets[]={0,100,4080,-1};
  109112. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109113. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109114. test_pack(packets,headret,0,0,0);
  109115. }
  109116. {
  109117. /* build a bunch of pages for testing */
  109118. unsigned char *data=_ogg_malloc(1024*1024);
  109119. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109120. int inptr=0,i,j;
  109121. ogg_page og[5];
  109122. ogg_stream_reset(&os_en);
  109123. for(i=0;pl[i]!=-1;i++){
  109124. ogg_packet op;
  109125. int len=pl[i];
  109126. op.packet=data+inptr;
  109127. op.bytes=len;
  109128. op.e_o_s=(pl[i+1]<0?1:0);
  109129. op.granulepos=(i+1)*1000;
  109130. for(j=0;j<len;j++)data[inptr++]=i+j;
  109131. ogg_stream_packetin(&os_en,&op);
  109132. }
  109133. _ogg_free(data);
  109134. /* retrieve finished pages */
  109135. for(i=0;i<5;i++){
  109136. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109137. fprintf(stderr,"Too few pages output building sync tests!\n");
  109138. exit(1);
  109139. }
  109140. copy_page(&og[i]);
  109141. }
  109142. /* Test lost pages on pagein/packetout: no rollback */
  109143. {
  109144. ogg_page temp;
  109145. ogg_packet test;
  109146. fprintf(stderr,"Testing loss of pages... ");
  109147. ogg_sync_reset(&oy);
  109148. ogg_stream_reset(&os_de);
  109149. for(i=0;i<5;i++){
  109150. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109151. og[i].header_len);
  109152. ogg_sync_wrote(&oy,og[i].header_len);
  109153. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109154. ogg_sync_wrote(&oy,og[i].body_len);
  109155. }
  109156. ogg_sync_pageout(&oy,&temp);
  109157. ogg_stream_pagein(&os_de,&temp);
  109158. ogg_sync_pageout(&oy,&temp);
  109159. ogg_stream_pagein(&os_de,&temp);
  109160. ogg_sync_pageout(&oy,&temp);
  109161. /* skip */
  109162. ogg_sync_pageout(&oy,&temp);
  109163. ogg_stream_pagein(&os_de,&temp);
  109164. /* do we get the expected results/packets? */
  109165. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109166. checkpacket(&test,0,0,0);
  109167. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109168. checkpacket(&test,100,1,-1);
  109169. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109170. checkpacket(&test,4079,2,3000);
  109171. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109172. fprintf(stderr,"Error: loss of page did not return error\n");
  109173. exit(1);
  109174. }
  109175. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109176. checkpacket(&test,76,5,-1);
  109177. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109178. checkpacket(&test,34,6,-1);
  109179. fprintf(stderr,"ok.\n");
  109180. }
  109181. /* Test lost pages on pagein/packetout: rollback with continuation */
  109182. {
  109183. ogg_page temp;
  109184. ogg_packet test;
  109185. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109186. ogg_sync_reset(&oy);
  109187. ogg_stream_reset(&os_de);
  109188. for(i=0;i<5;i++){
  109189. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109190. og[i].header_len);
  109191. ogg_sync_wrote(&oy,og[i].header_len);
  109192. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109193. ogg_sync_wrote(&oy,og[i].body_len);
  109194. }
  109195. ogg_sync_pageout(&oy,&temp);
  109196. ogg_stream_pagein(&os_de,&temp);
  109197. ogg_sync_pageout(&oy,&temp);
  109198. ogg_stream_pagein(&os_de,&temp);
  109199. ogg_sync_pageout(&oy,&temp);
  109200. ogg_stream_pagein(&os_de,&temp);
  109201. ogg_sync_pageout(&oy,&temp);
  109202. /* skip */
  109203. ogg_sync_pageout(&oy,&temp);
  109204. ogg_stream_pagein(&os_de,&temp);
  109205. /* do we get the expected results/packets? */
  109206. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109207. checkpacket(&test,0,0,0);
  109208. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109209. checkpacket(&test,100,1,-1);
  109210. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109211. checkpacket(&test,4079,2,3000);
  109212. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109213. checkpacket(&test,2956,3,4000);
  109214. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109215. fprintf(stderr,"Error: loss of page did not return error\n");
  109216. exit(1);
  109217. }
  109218. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109219. checkpacket(&test,300,13,14000);
  109220. fprintf(stderr,"ok.\n");
  109221. }
  109222. /* the rest only test sync */
  109223. {
  109224. ogg_page og_de;
  109225. /* Test fractional page inputs: incomplete capture */
  109226. fprintf(stderr,"Testing sync on partial inputs... ");
  109227. ogg_sync_reset(&oy);
  109228. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109229. 3);
  109230. ogg_sync_wrote(&oy,3);
  109231. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109232. /* Test fractional page inputs: incomplete fixed header */
  109233. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109234. 20);
  109235. ogg_sync_wrote(&oy,20);
  109236. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109237. /* Test fractional page inputs: incomplete header */
  109238. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109239. 5);
  109240. ogg_sync_wrote(&oy,5);
  109241. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109242. /* Test fractional page inputs: incomplete body */
  109243. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109244. og[1].header_len-28);
  109245. ogg_sync_wrote(&oy,og[1].header_len-28);
  109246. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109247. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109248. ogg_sync_wrote(&oy,1000);
  109249. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109250. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109251. og[1].body_len-1000);
  109252. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109253. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109254. fprintf(stderr,"ok.\n");
  109255. }
  109256. /* Test fractional page inputs: page + incomplete capture */
  109257. {
  109258. ogg_page og_de;
  109259. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109260. ogg_sync_reset(&oy);
  109261. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109262. og[1].header_len);
  109263. ogg_sync_wrote(&oy,og[1].header_len);
  109264. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109265. og[1].body_len);
  109266. ogg_sync_wrote(&oy,og[1].body_len);
  109267. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109268. 20);
  109269. ogg_sync_wrote(&oy,20);
  109270. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109271. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109272. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109273. og[1].header_len-20);
  109274. ogg_sync_wrote(&oy,og[1].header_len-20);
  109275. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109276. og[1].body_len);
  109277. ogg_sync_wrote(&oy,og[1].body_len);
  109278. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109279. fprintf(stderr,"ok.\n");
  109280. }
  109281. /* Test recapture: garbage + page */
  109282. {
  109283. ogg_page og_de;
  109284. fprintf(stderr,"Testing search for capture... ");
  109285. ogg_sync_reset(&oy);
  109286. /* 'garbage' */
  109287. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109288. og[1].body_len);
  109289. ogg_sync_wrote(&oy,og[1].body_len);
  109290. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109291. og[1].header_len);
  109292. ogg_sync_wrote(&oy,og[1].header_len);
  109293. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109294. og[1].body_len);
  109295. ogg_sync_wrote(&oy,og[1].body_len);
  109296. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109297. 20);
  109298. ogg_sync_wrote(&oy,20);
  109299. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109300. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109301. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109302. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109303. og[2].header_len-20);
  109304. ogg_sync_wrote(&oy,og[2].header_len-20);
  109305. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109306. og[2].body_len);
  109307. ogg_sync_wrote(&oy,og[2].body_len);
  109308. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109309. fprintf(stderr,"ok.\n");
  109310. }
  109311. /* Test recapture: page + garbage + page */
  109312. {
  109313. ogg_page og_de;
  109314. fprintf(stderr,"Testing recapture... ");
  109315. ogg_sync_reset(&oy);
  109316. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109317. og[1].header_len);
  109318. ogg_sync_wrote(&oy,og[1].header_len);
  109319. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109320. og[1].body_len);
  109321. ogg_sync_wrote(&oy,og[1].body_len);
  109322. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109323. og[2].header_len);
  109324. ogg_sync_wrote(&oy,og[2].header_len);
  109325. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109326. og[2].header_len);
  109327. ogg_sync_wrote(&oy,og[2].header_len);
  109328. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109329. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109330. og[2].body_len-5);
  109331. ogg_sync_wrote(&oy,og[2].body_len-5);
  109332. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109333. og[3].header_len);
  109334. ogg_sync_wrote(&oy,og[3].header_len);
  109335. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109336. og[3].body_len);
  109337. ogg_sync_wrote(&oy,og[3].body_len);
  109338. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109339. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109340. fprintf(stderr,"ok.\n");
  109341. }
  109342. /* Free page data that was previously copied */
  109343. {
  109344. for(i=0;i<5;i++){
  109345. free_page(&og[i]);
  109346. }
  109347. }
  109348. }
  109349. return(0);
  109350. }
  109351. #endif
  109352. #endif
  109353. /*** End of inlined file: framing.c ***/
  109354. /*** Start of inlined file: analysis.c ***/
  109355. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109356. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109357. // tasks..
  109358. #if JUCE_MSVC
  109359. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109360. #endif
  109361. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109362. #if JUCE_USE_OGGVORBIS
  109363. #include <stdio.h>
  109364. #include <string.h>
  109365. #include <math.h>
  109366. /*** Start of inlined file: codec_internal.h ***/
  109367. #ifndef _V_CODECI_H_
  109368. #define _V_CODECI_H_
  109369. /*** Start of inlined file: envelope.h ***/
  109370. #ifndef _V_ENVELOPE_
  109371. #define _V_ENVELOPE_
  109372. /*** Start of inlined file: mdct.h ***/
  109373. #ifndef _OGG_mdct_H_
  109374. #define _OGG_mdct_H_
  109375. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109376. #ifdef MDCT_INTEGERIZED
  109377. #define DATA_TYPE int
  109378. #define REG_TYPE register int
  109379. #define TRIGBITS 14
  109380. #define cPI3_8 6270
  109381. #define cPI2_8 11585
  109382. #define cPI1_8 15137
  109383. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109384. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109385. #define HALVE(x) ((x)>>1)
  109386. #else
  109387. #define DATA_TYPE float
  109388. #define REG_TYPE float
  109389. #define cPI3_8 .38268343236508977175F
  109390. #define cPI2_8 .70710678118654752441F
  109391. #define cPI1_8 .92387953251128675613F
  109392. #define FLOAT_CONV(x) (x)
  109393. #define MULT_NORM(x) (x)
  109394. #define HALVE(x) ((x)*.5f)
  109395. #endif
  109396. typedef struct {
  109397. int n;
  109398. int log2n;
  109399. DATA_TYPE *trig;
  109400. int *bitrev;
  109401. DATA_TYPE scale;
  109402. } mdct_lookup;
  109403. extern void mdct_init(mdct_lookup *lookup,int n);
  109404. extern void mdct_clear(mdct_lookup *l);
  109405. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109406. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109407. #endif
  109408. /*** End of inlined file: mdct.h ***/
  109409. #define VE_PRE 16
  109410. #define VE_WIN 4
  109411. #define VE_POST 2
  109412. #define VE_AMP (VE_PRE+VE_POST-1)
  109413. #define VE_BANDS 7
  109414. #define VE_NEARDC 15
  109415. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109416. #define VE_MAXSTRETCH 12 /* one-third full block */
  109417. typedef struct {
  109418. float ampbuf[VE_AMP];
  109419. int ampptr;
  109420. float nearDC[VE_NEARDC];
  109421. float nearDC_acc;
  109422. float nearDC_partialacc;
  109423. int nearptr;
  109424. } envelope_filter_state;
  109425. typedef struct {
  109426. int begin;
  109427. int end;
  109428. float *window;
  109429. float total;
  109430. } envelope_band;
  109431. typedef struct {
  109432. int ch;
  109433. int winlength;
  109434. int searchstep;
  109435. float minenergy;
  109436. mdct_lookup mdct;
  109437. float *mdct_win;
  109438. envelope_band band[VE_BANDS];
  109439. envelope_filter_state *filter;
  109440. int stretch;
  109441. int *mark;
  109442. long storage;
  109443. long current;
  109444. long curmark;
  109445. long cursor;
  109446. } envelope_lookup;
  109447. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109448. extern void _ve_envelope_clear(envelope_lookup *e);
  109449. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109450. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109451. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109452. #endif
  109453. /*** End of inlined file: envelope.h ***/
  109454. /*** Start of inlined file: codebook.h ***/
  109455. #ifndef _V_CODEBOOK_H_
  109456. #define _V_CODEBOOK_H_
  109457. /* This structure encapsulates huffman and VQ style encoding books; it
  109458. doesn't do anything specific to either.
  109459. valuelist/quantlist are nonNULL (and q_* significant) only if
  109460. there's entry->value mapping to be done.
  109461. If encode-side mapping must be done (and thus the entry needs to be
  109462. hunted), the auxiliary encode pointer will point to a decision
  109463. tree. This is true of both VQ and huffman, but is mostly useful
  109464. with VQ.
  109465. */
  109466. typedef struct static_codebook{
  109467. long dim; /* codebook dimensions (elements per vector) */
  109468. long entries; /* codebook entries */
  109469. long *lengthlist; /* codeword lengths in bits */
  109470. /* mapping ***************************************************************/
  109471. int maptype; /* 0=none
  109472. 1=implicitly populated values from map column
  109473. 2=listed arbitrary values */
  109474. /* The below does a linear, single monotonic sequence mapping. */
  109475. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109476. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109477. int q_quant; /* bits: 0 < quant <= 16 */
  109478. int q_sequencep; /* bitflag */
  109479. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109480. map == 2: list of dim*entries quantized entry vals
  109481. */
  109482. /* encode helpers ********************************************************/
  109483. struct encode_aux_nearestmatch *nearest_tree;
  109484. struct encode_aux_threshmatch *thresh_tree;
  109485. struct encode_aux_pigeonhole *pigeon_tree;
  109486. int allocedp;
  109487. } static_codebook;
  109488. /* this structures an arbitrary trained book to quickly find the
  109489. nearest cell match */
  109490. typedef struct encode_aux_nearestmatch{
  109491. /* pre-calculated partitioning tree */
  109492. long *ptr0;
  109493. long *ptr1;
  109494. long *p; /* decision points (each is an entry) */
  109495. long *q; /* decision points (each is an entry) */
  109496. long aux; /* number of tree entries */
  109497. long alloc;
  109498. } encode_aux_nearestmatch;
  109499. /* assumes a maptype of 1; encode side only, so that's OK */
  109500. typedef struct encode_aux_threshmatch{
  109501. float *quantthresh;
  109502. long *quantmap;
  109503. int quantvals;
  109504. int threshvals;
  109505. } encode_aux_threshmatch;
  109506. typedef struct encode_aux_pigeonhole{
  109507. float min;
  109508. float del;
  109509. int mapentries;
  109510. int quantvals;
  109511. long *pigeonmap;
  109512. long fittotal;
  109513. long *fitlist;
  109514. long *fitmap;
  109515. long *fitlength;
  109516. } encode_aux_pigeonhole;
  109517. typedef struct codebook{
  109518. long dim; /* codebook dimensions (elements per vector) */
  109519. long entries; /* codebook entries */
  109520. long used_entries; /* populated codebook entries */
  109521. const static_codebook *c;
  109522. /* for encode, the below are entry-ordered, fully populated */
  109523. /* for decode, the below are ordered by bitreversed codeword and only
  109524. used entries are populated */
  109525. float *valuelist; /* list of dim*entries actual entry values */
  109526. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109527. int *dec_index; /* only used if sparseness collapsed */
  109528. char *dec_codelengths;
  109529. ogg_uint32_t *dec_firsttable;
  109530. int dec_firsttablen;
  109531. int dec_maxlength;
  109532. } codebook;
  109533. extern void vorbis_staticbook_clear(static_codebook *b);
  109534. extern void vorbis_staticbook_destroy(static_codebook *b);
  109535. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109536. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109537. extern void vorbis_book_clear(codebook *b);
  109538. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109539. extern float *_book_logdist(const static_codebook *b,float *vals);
  109540. extern float _float32_unpack(long val);
  109541. extern long _float32_pack(float val);
  109542. extern int _best(codebook *book, float *a, int step);
  109543. extern int _ilog(unsigned int v);
  109544. extern long _book_maptype1_quantvals(const static_codebook *b);
  109545. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109546. extern long vorbis_book_codeword(codebook *book,int entry);
  109547. extern long vorbis_book_codelen(codebook *book,int entry);
  109548. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109549. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109550. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109551. extern int vorbis_book_errorv(codebook *book, float *a);
  109552. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109553. oggpack_buffer *b);
  109554. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109555. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109556. oggpack_buffer *b,int n);
  109557. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109558. oggpack_buffer *b,int n);
  109559. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109560. oggpack_buffer *b,int n);
  109561. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109562. long off,int ch,
  109563. oggpack_buffer *b,int n);
  109564. #endif
  109565. /*** End of inlined file: codebook.h ***/
  109566. #define BLOCKTYPE_IMPULSE 0
  109567. #define BLOCKTYPE_PADDING 1
  109568. #define BLOCKTYPE_TRANSITION 0
  109569. #define BLOCKTYPE_LONG 1
  109570. #define PACKETBLOBS 15
  109571. typedef struct vorbis_block_internal{
  109572. float **pcmdelay; /* this is a pointer into local storage */
  109573. float ampmax;
  109574. int blocktype;
  109575. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109576. blob [PACKETBLOBS/2] points to
  109577. the oggpack_buffer in the
  109578. main vorbis_block */
  109579. } vorbis_block_internal;
  109580. typedef void vorbis_look_floor;
  109581. typedef void vorbis_look_residue;
  109582. typedef void vorbis_look_transform;
  109583. /* mode ************************************************************/
  109584. typedef struct {
  109585. int blockflag;
  109586. int windowtype;
  109587. int transformtype;
  109588. int mapping;
  109589. } vorbis_info_mode;
  109590. typedef void vorbis_info_floor;
  109591. typedef void vorbis_info_residue;
  109592. typedef void vorbis_info_mapping;
  109593. /*** Start of inlined file: psy.h ***/
  109594. #ifndef _V_PSY_H_
  109595. #define _V_PSY_H_
  109596. /*** Start of inlined file: smallft.h ***/
  109597. #ifndef _V_SMFT_H_
  109598. #define _V_SMFT_H_
  109599. typedef struct {
  109600. int n;
  109601. float *trigcache;
  109602. int *splitcache;
  109603. } drft_lookup;
  109604. extern void drft_forward(drft_lookup *l,float *data);
  109605. extern void drft_backward(drft_lookup *l,float *data);
  109606. extern void drft_init(drft_lookup *l,int n);
  109607. extern void drft_clear(drft_lookup *l);
  109608. #endif
  109609. /*** End of inlined file: smallft.h ***/
  109610. /*** Start of inlined file: backends.h ***/
  109611. /* this is exposed up here because we need it for static modes.
  109612. Lookups for each backend aren't exposed because there's no reason
  109613. to do so */
  109614. #ifndef _vorbis_backend_h_
  109615. #define _vorbis_backend_h_
  109616. /* this would all be simpler/shorter with templates, but.... */
  109617. /* Floor backend generic *****************************************/
  109618. typedef struct{
  109619. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109620. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109621. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109622. void (*free_info) (vorbis_info_floor *);
  109623. void (*free_look) (vorbis_look_floor *);
  109624. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109625. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109626. void *buffer,float *);
  109627. } vorbis_func_floor;
  109628. typedef struct{
  109629. int order;
  109630. long rate;
  109631. long barkmap;
  109632. int ampbits;
  109633. int ampdB;
  109634. int numbooks; /* <= 16 */
  109635. int books[16];
  109636. float lessthan; /* encode-only config setting hacks for libvorbis */
  109637. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109638. } vorbis_info_floor0;
  109639. #define VIF_POSIT 63
  109640. #define VIF_CLASS 16
  109641. #define VIF_PARTS 31
  109642. typedef struct{
  109643. int partitions; /* 0 to 31 */
  109644. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109645. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109646. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109647. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109648. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109649. int mult; /* 1 2 3 or 4 */
  109650. int postlist[VIF_POSIT+2]; /* first two implicit */
  109651. /* encode side analysis parameters */
  109652. float maxover;
  109653. float maxunder;
  109654. float maxerr;
  109655. float twofitweight;
  109656. float twofitatten;
  109657. int n;
  109658. } vorbis_info_floor1;
  109659. /* Residue backend generic *****************************************/
  109660. typedef struct{
  109661. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109662. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109663. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109664. vorbis_info_residue *);
  109665. void (*free_info) (vorbis_info_residue *);
  109666. void (*free_look) (vorbis_look_residue *);
  109667. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109668. float **,int *,int);
  109669. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109670. vorbis_look_residue *,
  109671. float **,float **,int *,int,long **);
  109672. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109673. float **,int *,int);
  109674. } vorbis_func_residue;
  109675. typedef struct vorbis_info_residue0{
  109676. /* block-partitioned VQ coded straight residue */
  109677. long begin;
  109678. long end;
  109679. /* first stage (lossless partitioning) */
  109680. int grouping; /* group n vectors per partition */
  109681. int partitions; /* possible codebooks for a partition */
  109682. int groupbook; /* huffbook for partitioning */
  109683. int secondstages[64]; /* expanded out to pointers in lookup */
  109684. int booklist[256]; /* list of second stage books */
  109685. float classmetric1[64];
  109686. float classmetric2[64];
  109687. } vorbis_info_residue0;
  109688. /* Mapping backend generic *****************************************/
  109689. typedef struct{
  109690. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109691. oggpack_buffer *);
  109692. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109693. void (*free_info) (vorbis_info_mapping *);
  109694. int (*forward) (struct vorbis_block *vb);
  109695. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109696. } vorbis_func_mapping;
  109697. typedef struct vorbis_info_mapping0{
  109698. int submaps; /* <= 16 */
  109699. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109700. int floorsubmap[16]; /* [mux] submap to floors */
  109701. int residuesubmap[16]; /* [mux] submap to residue */
  109702. int coupling_steps;
  109703. int coupling_mag[256];
  109704. int coupling_ang[256];
  109705. } vorbis_info_mapping0;
  109706. #endif
  109707. /*** End of inlined file: backends.h ***/
  109708. #ifndef EHMER_MAX
  109709. #define EHMER_MAX 56
  109710. #endif
  109711. /* psychoacoustic setup ********************************************/
  109712. #define P_BANDS 17 /* 62Hz to 16kHz */
  109713. #define P_LEVELS 8 /* 30dB to 100dB */
  109714. #define P_LEVEL_0 30. /* 30 dB */
  109715. #define P_NOISECURVES 3
  109716. #define NOISE_COMPAND_LEVELS 40
  109717. typedef struct vorbis_info_psy{
  109718. int blockflag;
  109719. float ath_adjatt;
  109720. float ath_maxatt;
  109721. float tone_masteratt[P_NOISECURVES];
  109722. float tone_centerboost;
  109723. float tone_decay;
  109724. float tone_abs_limit;
  109725. float toneatt[P_BANDS];
  109726. int noisemaskp;
  109727. float noisemaxsupp;
  109728. float noisewindowlo;
  109729. float noisewindowhi;
  109730. int noisewindowlomin;
  109731. int noisewindowhimin;
  109732. int noisewindowfixed;
  109733. float noiseoff[P_NOISECURVES][P_BANDS];
  109734. float noisecompand[NOISE_COMPAND_LEVELS];
  109735. float max_curve_dB;
  109736. int normal_channel_p;
  109737. int normal_point_p;
  109738. int normal_start;
  109739. int normal_partition;
  109740. double normal_thresh;
  109741. } vorbis_info_psy;
  109742. typedef struct{
  109743. int eighth_octave_lines;
  109744. /* for block long/short tuning; encode only */
  109745. float preecho_thresh[VE_BANDS];
  109746. float postecho_thresh[VE_BANDS];
  109747. float stretch_penalty;
  109748. float preecho_minenergy;
  109749. float ampmax_att_per_sec;
  109750. /* channel coupling config */
  109751. int coupling_pkHz[PACKETBLOBS];
  109752. int coupling_pointlimit[2][PACKETBLOBS];
  109753. int coupling_prepointamp[PACKETBLOBS];
  109754. int coupling_postpointamp[PACKETBLOBS];
  109755. int sliding_lowpass[2][PACKETBLOBS];
  109756. } vorbis_info_psy_global;
  109757. typedef struct {
  109758. float ampmax;
  109759. int channels;
  109760. vorbis_info_psy_global *gi;
  109761. int coupling_pointlimit[2][P_NOISECURVES];
  109762. } vorbis_look_psy_global;
  109763. typedef struct {
  109764. int n;
  109765. struct vorbis_info_psy *vi;
  109766. float ***tonecurves;
  109767. float **noiseoffset;
  109768. float *ath;
  109769. long *octave; /* in n.ocshift format */
  109770. long *bark;
  109771. long firstoc;
  109772. long shiftoc;
  109773. int eighth_octave_lines; /* power of two, please */
  109774. int total_octave_lines;
  109775. long rate; /* cache it */
  109776. float m_val; /* Masking compensation value */
  109777. } vorbis_look_psy;
  109778. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109779. vorbis_info_psy_global *gi,int n,long rate);
  109780. extern void _vp_psy_clear(vorbis_look_psy *p);
  109781. extern void *_vi_psy_dup(void *source);
  109782. extern void _vi_psy_free(vorbis_info_psy *i);
  109783. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109784. extern void _vp_remove_floor(vorbis_look_psy *p,
  109785. float *mdct,
  109786. int *icodedflr,
  109787. float *residue,
  109788. int sliding_lowpass);
  109789. extern void _vp_noisemask(vorbis_look_psy *p,
  109790. float *logmdct,
  109791. float *logmask);
  109792. extern void _vp_tonemask(vorbis_look_psy *p,
  109793. float *logfft,
  109794. float *logmask,
  109795. float global_specmax,
  109796. float local_specmax);
  109797. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109798. float *noise,
  109799. float *tone,
  109800. int offset_select,
  109801. float *logmask,
  109802. float *mdct,
  109803. float *logmdct);
  109804. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109805. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109806. vorbis_info_psy_global *g,
  109807. vorbis_look_psy *p,
  109808. vorbis_info_mapping0 *vi,
  109809. float **mdct);
  109810. extern void _vp_couple(int blobno,
  109811. vorbis_info_psy_global *g,
  109812. vorbis_look_psy *p,
  109813. vorbis_info_mapping0 *vi,
  109814. float **res,
  109815. float **mag_memo,
  109816. int **mag_sort,
  109817. int **ifloor,
  109818. int *nonzero,
  109819. int sliding_lowpass);
  109820. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109821. float *in,float *out,int *sortedindex);
  109822. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109823. float *magnitudes,int *sortedindex);
  109824. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109825. vorbis_look_psy *p,
  109826. vorbis_info_mapping0 *vi,
  109827. float **mags);
  109828. extern void hf_reduction(vorbis_info_psy_global *g,
  109829. vorbis_look_psy *p,
  109830. vorbis_info_mapping0 *vi,
  109831. float **mdct);
  109832. #endif
  109833. /*** End of inlined file: psy.h ***/
  109834. /*** Start of inlined file: bitrate.h ***/
  109835. #ifndef _V_BITRATE_H_
  109836. #define _V_BITRATE_H_
  109837. /*** Start of inlined file: os.h ***/
  109838. #ifndef _OS_H
  109839. #define _OS_H
  109840. /********************************************************************
  109841. * *
  109842. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109843. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109844. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109845. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109846. * *
  109847. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109848. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109849. * *
  109850. ********************************************************************
  109851. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109852. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109853. ********************************************************************/
  109854. #ifdef HAVE_CONFIG_H
  109855. #include "config.h"
  109856. #endif
  109857. #include <math.h>
  109858. /*** Start of inlined file: misc.h ***/
  109859. #ifndef _V_RANDOM_H_
  109860. #define _V_RANDOM_H_
  109861. extern int analysis_noisy;
  109862. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109863. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109864. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109865. ogg_int64_t off);
  109866. #ifdef DEBUG_MALLOC
  109867. #define _VDBG_GRAPHFILE "malloc.m"
  109868. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109869. extern void _VDBG_free(void *ptr,char *file,long line);
  109870. #ifndef MISC_C
  109871. #undef _ogg_malloc
  109872. #undef _ogg_calloc
  109873. #undef _ogg_realloc
  109874. #undef _ogg_free
  109875. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109876. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109877. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109878. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109879. #endif
  109880. #endif
  109881. #endif
  109882. /*** End of inlined file: misc.h ***/
  109883. #ifndef _V_IFDEFJAIL_H_
  109884. # define _V_IFDEFJAIL_H_
  109885. # ifdef __GNUC__
  109886. # define STIN static __inline__
  109887. # elif _WIN32
  109888. # define STIN static __inline
  109889. # else
  109890. # define STIN static
  109891. # endif
  109892. #ifdef DJGPP
  109893. # define rint(x) (floor((x)+0.5f))
  109894. #endif
  109895. #ifndef M_PI
  109896. # define M_PI (3.1415926536f)
  109897. #endif
  109898. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109899. # include <malloc.h>
  109900. # define rint(x) (floor((x)+0.5f))
  109901. # define NO_FLOAT_MATH_LIB
  109902. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109903. #endif
  109904. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109905. void *_alloca(size_t size);
  109906. # define alloca _alloca
  109907. #endif
  109908. #ifndef FAST_HYPOT
  109909. # define FAST_HYPOT hypot
  109910. #endif
  109911. #endif
  109912. #ifdef HAVE_ALLOCA_H
  109913. # include <alloca.h>
  109914. #endif
  109915. #ifdef USE_MEMORY_H
  109916. # include <memory.h>
  109917. #endif
  109918. #ifndef min
  109919. # define min(x,y) ((x)>(y)?(y):(x))
  109920. #endif
  109921. #ifndef max
  109922. # define max(x,y) ((x)<(y)?(y):(x))
  109923. #endif
  109924. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109925. # define VORBIS_FPU_CONTROL
  109926. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109927. Because of encapsulation constraints (GCC can't see inside the asm
  109928. block and so we end up doing stupid things like a store/load that
  109929. is collectively a noop), we do it this way */
  109930. /* we must set up the fpu before this works!! */
  109931. typedef ogg_int16_t vorbis_fpu_control;
  109932. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109933. ogg_int16_t ret;
  109934. ogg_int16_t temp;
  109935. __asm__ __volatile__("fnstcw %0\n\t"
  109936. "movw %0,%%dx\n\t"
  109937. "orw $62463,%%dx\n\t"
  109938. "movw %%dx,%1\n\t"
  109939. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109940. *fpu=ret;
  109941. }
  109942. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109943. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109944. }
  109945. /* assumes the FPU is in round mode! */
  109946. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109947. we get extra fst/fld to
  109948. truncate precision */
  109949. int i;
  109950. __asm__("fistl %0": "=m"(i) : "t"(f));
  109951. return(i);
  109952. }
  109953. #endif
  109954. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109955. # define VORBIS_FPU_CONTROL
  109956. typedef ogg_int16_t vorbis_fpu_control;
  109957. static __inline int vorbis_ftoi(double f){
  109958. int i;
  109959. __asm{
  109960. fld f
  109961. fistp i
  109962. }
  109963. return i;
  109964. }
  109965. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109966. }
  109967. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109968. }
  109969. #endif
  109970. #ifndef VORBIS_FPU_CONTROL
  109971. typedef int vorbis_fpu_control;
  109972. static int vorbis_ftoi(double f){
  109973. return (int)(f+.5);
  109974. }
  109975. /* We don't have special code for this compiler/arch, so do it the slow way */
  109976. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109977. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109978. #endif
  109979. #endif /* _OS_H */
  109980. /*** End of inlined file: os.h ***/
  109981. /* encode side bitrate tracking */
  109982. typedef struct bitrate_manager_state {
  109983. int managed;
  109984. long avg_reservoir;
  109985. long minmax_reservoir;
  109986. long avg_bitsper;
  109987. long min_bitsper;
  109988. long max_bitsper;
  109989. long short_per_long;
  109990. double avgfloat;
  109991. vorbis_block *vb;
  109992. int choice;
  109993. } bitrate_manager_state;
  109994. typedef struct bitrate_manager_info{
  109995. long avg_rate;
  109996. long min_rate;
  109997. long max_rate;
  109998. long reservoir_bits;
  109999. double reservoir_bias;
  110000. double slew_damp;
  110001. } bitrate_manager_info;
  110002. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110003. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110004. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110005. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110006. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110007. #endif
  110008. /*** End of inlined file: bitrate.h ***/
  110009. static int ilog(unsigned int v){
  110010. int ret=0;
  110011. while(v){
  110012. ret++;
  110013. v>>=1;
  110014. }
  110015. return(ret);
  110016. }
  110017. static int ilog2(unsigned int v){
  110018. int ret=0;
  110019. if(v)--v;
  110020. while(v){
  110021. ret++;
  110022. v>>=1;
  110023. }
  110024. return(ret);
  110025. }
  110026. typedef struct private_state {
  110027. /* local lookup storage */
  110028. envelope_lookup *ve; /* envelope lookup */
  110029. int window[2];
  110030. vorbis_look_transform **transform[2]; /* block, type */
  110031. drft_lookup fft_look[2];
  110032. int modebits;
  110033. vorbis_look_floor **flr;
  110034. vorbis_look_residue **residue;
  110035. vorbis_look_psy *psy;
  110036. vorbis_look_psy_global *psy_g_look;
  110037. /* local storage, only used on the encoding side. This way the
  110038. application does not need to worry about freeing some packets'
  110039. memory and not others'; packet storage is always tracked.
  110040. Cleared next call to a _dsp_ function */
  110041. unsigned char *header;
  110042. unsigned char *header1;
  110043. unsigned char *header2;
  110044. bitrate_manager_state bms;
  110045. ogg_int64_t sample_count;
  110046. } private_state;
  110047. /* codec_setup_info contains all the setup information specific to the
  110048. specific compression/decompression mode in progress (eg,
  110049. psychoacoustic settings, channel setup, options, codebook
  110050. etc).
  110051. *********************************************************************/
  110052. /*** Start of inlined file: highlevel.h ***/
  110053. typedef struct highlevel_byblocktype {
  110054. double tone_mask_setting;
  110055. double tone_peaklimit_setting;
  110056. double noise_bias_setting;
  110057. double noise_compand_setting;
  110058. } highlevel_byblocktype;
  110059. typedef struct highlevel_encode_setup {
  110060. void *setup;
  110061. int set_in_stone;
  110062. double base_setting;
  110063. double long_setting;
  110064. double short_setting;
  110065. double impulse_noisetune;
  110066. int managed;
  110067. long bitrate_min;
  110068. long bitrate_av;
  110069. double bitrate_av_damp;
  110070. long bitrate_max;
  110071. long bitrate_reservoir;
  110072. double bitrate_reservoir_bias;
  110073. int impulse_block_p;
  110074. int noise_normalize_p;
  110075. double stereo_point_setting;
  110076. double lowpass_kHz;
  110077. double ath_floating_dB;
  110078. double ath_absolute_dB;
  110079. double amplitude_track_dBpersec;
  110080. double trigger_setting;
  110081. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110082. } highlevel_encode_setup;
  110083. /*** End of inlined file: highlevel.h ***/
  110084. typedef struct codec_setup_info {
  110085. /* Vorbis supports only short and long blocks, but allows the
  110086. encoder to choose the sizes */
  110087. long blocksizes[2];
  110088. /* modes are the primary means of supporting on-the-fly different
  110089. blocksizes, different channel mappings (LR or M/A),
  110090. different residue backends, etc. Each mode consists of a
  110091. blocksize flag and a mapping (along with the mapping setup */
  110092. int modes;
  110093. int maps;
  110094. int floors;
  110095. int residues;
  110096. int books;
  110097. int psys; /* encode only */
  110098. vorbis_info_mode *mode_param[64];
  110099. int map_type[64];
  110100. vorbis_info_mapping *map_param[64];
  110101. int floor_type[64];
  110102. vorbis_info_floor *floor_param[64];
  110103. int residue_type[64];
  110104. vorbis_info_residue *residue_param[64];
  110105. static_codebook *book_param[256];
  110106. codebook *fullbooks;
  110107. vorbis_info_psy *psy_param[4]; /* encode only */
  110108. vorbis_info_psy_global psy_g_param;
  110109. bitrate_manager_info bi;
  110110. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110111. highly redundant structure, but
  110112. improves clarity of program flow. */
  110113. int halfrate_flag; /* painless downsample for decode */
  110114. } codec_setup_info;
  110115. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110116. extern void _vp_global_free(vorbis_look_psy_global *look);
  110117. #endif
  110118. /*** End of inlined file: codec_internal.h ***/
  110119. /*** Start of inlined file: registry.h ***/
  110120. #ifndef _V_REG_H_
  110121. #define _V_REG_H_
  110122. #define VI_TRANSFORMB 1
  110123. #define VI_WINDOWB 1
  110124. #define VI_TIMEB 1
  110125. #define VI_FLOORB 2
  110126. #define VI_RESB 3
  110127. #define VI_MAPB 1
  110128. extern vorbis_func_floor *_floor_P[];
  110129. extern vorbis_func_residue *_residue_P[];
  110130. extern vorbis_func_mapping *_mapping_P[];
  110131. #endif
  110132. /*** End of inlined file: registry.h ***/
  110133. /*** Start of inlined file: scales.h ***/
  110134. #ifndef _V_SCALES_H_
  110135. #define _V_SCALES_H_
  110136. #include <math.h>
  110137. /* 20log10(x) */
  110138. #define VORBIS_IEEE_FLOAT32 1
  110139. #ifdef VORBIS_IEEE_FLOAT32
  110140. static float unitnorm(float x){
  110141. union {
  110142. ogg_uint32_t i;
  110143. float f;
  110144. } ix;
  110145. ix.f = x;
  110146. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110147. return ix.f;
  110148. }
  110149. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110150. static float todB(const float *x){
  110151. union {
  110152. ogg_uint32_t i;
  110153. float f;
  110154. } ix;
  110155. ix.f = *x;
  110156. ix.i = ix.i&0x7fffffff;
  110157. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110158. }
  110159. #define todB_nn(x) todB(x)
  110160. #else
  110161. static float unitnorm(float x){
  110162. if(x<0)return(-1.f);
  110163. return(1.f);
  110164. }
  110165. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110166. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110167. #endif
  110168. #define fromdB(x) (exp((x)*.11512925f))
  110169. /* The bark scale equations are approximations, since the original
  110170. table was somewhat hand rolled. The below are chosen to have the
  110171. best possible fit to the rolled tables, thus their somewhat odd
  110172. appearance (these are more accurate and over a longer range than
  110173. the oft-quoted bark equations found in the texts I have). The
  110174. approximations are valid from 0 - 30kHz (nyquist) or so.
  110175. all f in Hz, z in Bark */
  110176. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110177. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110178. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110179. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110180. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110181. 0.0 */
  110182. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110183. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110184. #endif
  110185. /*** End of inlined file: scales.h ***/
  110186. int analysis_noisy=1;
  110187. /* decides between modes, dispatches to the appropriate mapping. */
  110188. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110189. int ret,i;
  110190. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110191. vb->glue_bits=0;
  110192. vb->time_bits=0;
  110193. vb->floor_bits=0;
  110194. vb->res_bits=0;
  110195. /* first things first. Make sure encode is ready */
  110196. for(i=0;i<PACKETBLOBS;i++)
  110197. oggpack_reset(vbi->packetblob[i]);
  110198. /* we only have one mapping type (0), and we let the mapping code
  110199. itself figure out what soft mode to use. This allows easier
  110200. bitrate management */
  110201. if((ret=_mapping_P[0]->forward(vb)))
  110202. return(ret);
  110203. if(op){
  110204. if(vorbis_bitrate_managed(vb))
  110205. /* The app is using a bitmanaged mode... but not using the
  110206. bitrate management interface. */
  110207. return(OV_EINVAL);
  110208. op->packet=oggpack_get_buffer(&vb->opb);
  110209. op->bytes=oggpack_bytes(&vb->opb);
  110210. op->b_o_s=0;
  110211. op->e_o_s=vb->eofflag;
  110212. op->granulepos=vb->granulepos;
  110213. op->packetno=vb->sequence; /* for sake of completeness */
  110214. }
  110215. return(0);
  110216. }
  110217. /* there was no great place to put this.... */
  110218. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110219. int j;
  110220. FILE *of;
  110221. char buffer[80];
  110222. /* if(i==5870){*/
  110223. sprintf(buffer,"%s_%d.m",base,i);
  110224. of=fopen(buffer,"w");
  110225. if(!of)perror("failed to open data dump file");
  110226. for(j=0;j<n;j++){
  110227. if(bark){
  110228. float b=toBARK((4000.f*j/n)+.25);
  110229. fprintf(of,"%f ",b);
  110230. }else
  110231. if(off!=0)
  110232. fprintf(of,"%f ",(double)(j+off)/8000.);
  110233. else
  110234. fprintf(of,"%f ",(double)j);
  110235. if(dB){
  110236. float val;
  110237. if(v[j]==0.)
  110238. val=-140.;
  110239. else
  110240. val=todB(v+j);
  110241. fprintf(of,"%f\n",val);
  110242. }else{
  110243. fprintf(of,"%f\n",v[j]);
  110244. }
  110245. }
  110246. fclose(of);
  110247. /* } */
  110248. }
  110249. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110250. ogg_int64_t off){
  110251. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110252. }
  110253. #endif
  110254. /*** End of inlined file: analysis.c ***/
  110255. /*** Start of inlined file: bitrate.c ***/
  110256. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110257. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110258. // tasks..
  110259. #if JUCE_MSVC
  110260. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110261. #endif
  110262. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110263. #if JUCE_USE_OGGVORBIS
  110264. #include <stdlib.h>
  110265. #include <string.h>
  110266. #include <math.h>
  110267. /* compute bitrate tracking setup */
  110268. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110269. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110270. bitrate_manager_info *bi=&ci->bi;
  110271. memset(bm,0,sizeof(*bm));
  110272. if(bi && (bi->reservoir_bits>0)){
  110273. long ratesamples=vi->rate;
  110274. int halfsamples=ci->blocksizes[0]>>1;
  110275. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110276. bm->managed=1;
  110277. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110278. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110279. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110280. bm->avgfloat=PACKETBLOBS/2;
  110281. /* not a necessary fix, but one that leads to a more balanced
  110282. typical initialization */
  110283. {
  110284. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110285. bm->minmax_reservoir=desired_fill;
  110286. bm->avg_reservoir=desired_fill;
  110287. }
  110288. }
  110289. }
  110290. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110291. memset(bm,0,sizeof(*bm));
  110292. return;
  110293. }
  110294. int vorbis_bitrate_managed(vorbis_block *vb){
  110295. vorbis_dsp_state *vd=vb->vd;
  110296. private_state *b=(private_state*)vd->backend_state;
  110297. bitrate_manager_state *bm=&b->bms;
  110298. if(bm && bm->managed)return(1);
  110299. return(0);
  110300. }
  110301. /* finish taking in the block we just processed */
  110302. int vorbis_bitrate_addblock(vorbis_block *vb){
  110303. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110304. vorbis_dsp_state *vd=vb->vd;
  110305. private_state *b=(private_state*)vd->backend_state;
  110306. bitrate_manager_state *bm=&b->bms;
  110307. vorbis_info *vi=vd->vi;
  110308. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110309. bitrate_manager_info *bi=&ci->bi;
  110310. int choice=rint(bm->avgfloat);
  110311. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110312. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110313. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110314. int samples=ci->blocksizes[vb->W]>>1;
  110315. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110316. if(!bm->managed){
  110317. /* not a bitrate managed stream, but for API simplicity, we'll
  110318. buffer the packet to keep the code path clean */
  110319. if(bm->vb)return(-1); /* one has been submitted without
  110320. being claimed */
  110321. bm->vb=vb;
  110322. return(0);
  110323. }
  110324. bm->vb=vb;
  110325. /* look ahead for avg floater */
  110326. if(bm->avg_bitsper>0){
  110327. double slew=0.;
  110328. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110329. double slewlimit= 15./bi->slew_damp;
  110330. /* choosing a new floater:
  110331. if we're over target, we slew down
  110332. if we're under target, we slew up
  110333. choose slew as follows: look through packetblobs of this frame
  110334. and set slew as the first in the appropriate direction that
  110335. gives us the slew we want. This may mean no slew if delta is
  110336. already favorable.
  110337. Then limit slew to slew max */
  110338. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110339. while(choice>0 && this_bits>avg_target_bits &&
  110340. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110341. choice--;
  110342. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110343. }
  110344. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110345. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110346. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110347. choice++;
  110348. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110349. }
  110350. }
  110351. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110352. if(slew<-slewlimit)slew=-slewlimit;
  110353. if(slew>slewlimit)slew=slewlimit;
  110354. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110355. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110356. }
  110357. /* enforce min(if used) on the current floater (if used) */
  110358. if(bm->min_bitsper>0){
  110359. /* do we need to force the bitrate up? */
  110360. if(this_bits<min_target_bits){
  110361. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110362. choice++;
  110363. if(choice>=PACKETBLOBS)break;
  110364. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110365. }
  110366. }
  110367. }
  110368. /* enforce max (if used) on the current floater (if used) */
  110369. if(bm->max_bitsper>0){
  110370. /* do we need to force the bitrate down? */
  110371. if(this_bits>max_target_bits){
  110372. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110373. choice--;
  110374. if(choice<0)break;
  110375. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110376. }
  110377. }
  110378. }
  110379. /* Choice of packetblobs now made based on floater, and min/max
  110380. requirements. Now boundary check extreme choices */
  110381. if(choice<0){
  110382. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110383. frame will need to be truncated */
  110384. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110385. bm->choice=choice=0;
  110386. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110387. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110388. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110389. }
  110390. }else{
  110391. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110392. if(choice>=PACKETBLOBS)
  110393. choice=PACKETBLOBS-1;
  110394. bm->choice=choice;
  110395. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110396. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110397. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110398. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110399. }
  110400. /* now we have the final packet and the final packet size. Update statistics */
  110401. /* min and max reservoir */
  110402. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110403. if(max_target_bits>0 && this_bits>max_target_bits){
  110404. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110405. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110406. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110407. }else{
  110408. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110409. if(bm->minmax_reservoir>desired_fill){
  110410. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110411. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110412. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110413. }else{
  110414. bm->minmax_reservoir=desired_fill;
  110415. }
  110416. }else{
  110417. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110418. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110419. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110420. }else{
  110421. bm->minmax_reservoir=desired_fill;
  110422. }
  110423. }
  110424. }
  110425. }
  110426. /* avg reservoir */
  110427. if(bm->avg_bitsper>0){
  110428. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110429. bm->avg_reservoir+=this_bits-avg_target_bits;
  110430. }
  110431. return(0);
  110432. }
  110433. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110434. private_state *b=(private_state*)vd->backend_state;
  110435. bitrate_manager_state *bm=&b->bms;
  110436. vorbis_block *vb=bm->vb;
  110437. int choice=PACKETBLOBS/2;
  110438. if(!vb)return 0;
  110439. if(op){
  110440. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110441. if(vorbis_bitrate_managed(vb))
  110442. choice=bm->choice;
  110443. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110444. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110445. op->b_o_s=0;
  110446. op->e_o_s=vb->eofflag;
  110447. op->granulepos=vb->granulepos;
  110448. op->packetno=vb->sequence; /* for sake of completeness */
  110449. }
  110450. bm->vb=0;
  110451. return(1);
  110452. }
  110453. #endif
  110454. /*** End of inlined file: bitrate.c ***/
  110455. /*** Start of inlined file: block.c ***/
  110456. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110457. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110458. // tasks..
  110459. #if JUCE_MSVC
  110460. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110461. #endif
  110462. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110463. #if JUCE_USE_OGGVORBIS
  110464. #include <stdio.h>
  110465. #include <stdlib.h>
  110466. #include <string.h>
  110467. /*** Start of inlined file: window.h ***/
  110468. #ifndef _V_WINDOW_
  110469. #define _V_WINDOW_
  110470. extern float *_vorbis_window_get(int n);
  110471. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110472. int lW,int W,int nW);
  110473. #endif
  110474. /*** End of inlined file: window.h ***/
  110475. /*** Start of inlined file: lpc.h ***/
  110476. #ifndef _V_LPC_H_
  110477. #define _V_LPC_H_
  110478. /* simple linear scale LPC code */
  110479. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110480. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110481. float *data,long n);
  110482. #endif
  110483. /*** End of inlined file: lpc.h ***/
  110484. /* pcm accumulator examples (not exhaustive):
  110485. <-------------- lW ---------------->
  110486. <--------------- W ---------------->
  110487. : .....|..... _______________ |
  110488. : .''' | '''_--- | |\ |
  110489. :.....''' |_____--- '''......| | \_______|
  110490. :.................|__________________|_______|__|______|
  110491. |<------ Sl ------>| > Sr < |endW
  110492. |beginSl |endSl | |endSr
  110493. |beginW |endlW |beginSr
  110494. |< lW >|
  110495. <--------------- W ---------------->
  110496. | | .. ______________ |
  110497. | | ' `/ | ---_ |
  110498. |___.'___/`. | ---_____|
  110499. |_______|__|_______|_________________|
  110500. | >|Sl|< |<------ Sr ----->|endW
  110501. | | |endSl |beginSr |endSr
  110502. |beginW | |endlW
  110503. mult[0] |beginSl mult[n]
  110504. <-------------- lW ----------------->
  110505. |<--W-->|
  110506. : .............. ___ | |
  110507. : .''' |`/ \ | |
  110508. :.....''' |/`....\|...|
  110509. :.........................|___|___|___|
  110510. |Sl |Sr |endW
  110511. | | |endSr
  110512. | |beginSr
  110513. | |endSl
  110514. |beginSl
  110515. |beginW
  110516. */
  110517. /* block abstraction setup *********************************************/
  110518. #ifndef WORD_ALIGN
  110519. #define WORD_ALIGN 8
  110520. #endif
  110521. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110522. int i;
  110523. memset(vb,0,sizeof(*vb));
  110524. vb->vd=v;
  110525. vb->localalloc=0;
  110526. vb->localstore=NULL;
  110527. if(v->analysisp){
  110528. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110529. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110530. vbi->ampmax=-9999;
  110531. for(i=0;i<PACKETBLOBS;i++){
  110532. if(i==PACKETBLOBS/2){
  110533. vbi->packetblob[i]=&vb->opb;
  110534. }else{
  110535. vbi->packetblob[i]=
  110536. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110537. }
  110538. oggpack_writeinit(vbi->packetblob[i]);
  110539. }
  110540. }
  110541. return(0);
  110542. }
  110543. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110544. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110545. if(bytes+vb->localtop>vb->localalloc){
  110546. /* can't just _ogg_realloc... there are outstanding pointers */
  110547. if(vb->localstore){
  110548. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110549. vb->totaluse+=vb->localtop;
  110550. link->next=vb->reap;
  110551. link->ptr=vb->localstore;
  110552. vb->reap=link;
  110553. }
  110554. /* highly conservative */
  110555. vb->localalloc=bytes;
  110556. vb->localstore=_ogg_malloc(vb->localalloc);
  110557. vb->localtop=0;
  110558. }
  110559. {
  110560. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110561. vb->localtop+=bytes;
  110562. return ret;
  110563. }
  110564. }
  110565. /* reap the chain, pull the ripcord */
  110566. void _vorbis_block_ripcord(vorbis_block *vb){
  110567. /* reap the chain */
  110568. struct alloc_chain *reap=vb->reap;
  110569. while(reap){
  110570. struct alloc_chain *next=reap->next;
  110571. _ogg_free(reap->ptr);
  110572. memset(reap,0,sizeof(*reap));
  110573. _ogg_free(reap);
  110574. reap=next;
  110575. }
  110576. /* consolidate storage */
  110577. if(vb->totaluse){
  110578. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110579. vb->localalloc+=vb->totaluse;
  110580. vb->totaluse=0;
  110581. }
  110582. /* pull the ripcord */
  110583. vb->localtop=0;
  110584. vb->reap=NULL;
  110585. }
  110586. int vorbis_block_clear(vorbis_block *vb){
  110587. int i;
  110588. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110589. _vorbis_block_ripcord(vb);
  110590. if(vb->localstore)_ogg_free(vb->localstore);
  110591. if(vbi){
  110592. for(i=0;i<PACKETBLOBS;i++){
  110593. oggpack_writeclear(vbi->packetblob[i]);
  110594. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110595. }
  110596. _ogg_free(vbi);
  110597. }
  110598. memset(vb,0,sizeof(*vb));
  110599. return(0);
  110600. }
  110601. /* Analysis side code, but directly related to blocking. Thus it's
  110602. here and not in analysis.c (which is for analysis transforms only).
  110603. The init is here because some of it is shared */
  110604. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110605. int i;
  110606. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110607. private_state *b=NULL;
  110608. int hs;
  110609. if(ci==NULL) return 1;
  110610. hs=ci->halfrate_flag;
  110611. memset(v,0,sizeof(*v));
  110612. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110613. v->vi=vi;
  110614. b->modebits=ilog2(ci->modes);
  110615. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110616. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110617. /* MDCT is tranform 0 */
  110618. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110619. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110620. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110621. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110622. /* Vorbis I uses only window type 0 */
  110623. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110624. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110625. if(encp){ /* encode/decode differ here */
  110626. /* analysis always needs an fft */
  110627. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110628. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110629. /* finish the codebooks */
  110630. if(!ci->fullbooks){
  110631. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110632. for(i=0;i<ci->books;i++)
  110633. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110634. }
  110635. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110636. for(i=0;i<ci->psys;i++){
  110637. _vp_psy_init(b->psy+i,
  110638. ci->psy_param[i],
  110639. &ci->psy_g_param,
  110640. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110641. vi->rate);
  110642. }
  110643. v->analysisp=1;
  110644. }else{
  110645. /* finish the codebooks */
  110646. if(!ci->fullbooks){
  110647. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110648. for(i=0;i<ci->books;i++){
  110649. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110650. /* decode codebooks are now standalone after init */
  110651. vorbis_staticbook_destroy(ci->book_param[i]);
  110652. ci->book_param[i]=NULL;
  110653. }
  110654. }
  110655. }
  110656. /* initialize the storage vectors. blocksize[1] is small for encode,
  110657. but the correct size for decode */
  110658. v->pcm_storage=ci->blocksizes[1];
  110659. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110660. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110661. {
  110662. int i;
  110663. for(i=0;i<vi->channels;i++)
  110664. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110665. }
  110666. /* all 1 (large block) or 0 (small block) */
  110667. /* explicitly set for the sake of clarity */
  110668. v->lW=0; /* previous window size */
  110669. v->W=0; /* current window size */
  110670. /* all vector indexes */
  110671. v->centerW=ci->blocksizes[1]/2;
  110672. v->pcm_current=v->centerW;
  110673. /* initialize all the backend lookups */
  110674. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110675. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110676. for(i=0;i<ci->floors;i++)
  110677. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110678. look(v,ci->floor_param[i]);
  110679. for(i=0;i<ci->residues;i++)
  110680. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110681. look(v,ci->residue_param[i]);
  110682. return 0;
  110683. }
  110684. /* arbitrary settings and spec-mandated numbers get filled in here */
  110685. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110686. private_state *b=NULL;
  110687. if(_vds_shared_init(v,vi,1))return 1;
  110688. b=(private_state*)v->backend_state;
  110689. b->psy_g_look=_vp_global_look(vi);
  110690. /* Initialize the envelope state storage */
  110691. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110692. _ve_envelope_init(b->ve,vi);
  110693. vorbis_bitrate_init(vi,&b->bms);
  110694. /* compressed audio packets start after the headers
  110695. with sequence number 3 */
  110696. v->sequence=3;
  110697. return(0);
  110698. }
  110699. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110700. int i;
  110701. if(v){
  110702. vorbis_info *vi=v->vi;
  110703. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110704. private_state *b=(private_state*)v->backend_state;
  110705. if(b){
  110706. if(b->ve){
  110707. _ve_envelope_clear(b->ve);
  110708. _ogg_free(b->ve);
  110709. }
  110710. if(b->transform[0]){
  110711. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110712. _ogg_free(b->transform[0][0]);
  110713. _ogg_free(b->transform[0]);
  110714. }
  110715. if(b->transform[1]){
  110716. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110717. _ogg_free(b->transform[1][0]);
  110718. _ogg_free(b->transform[1]);
  110719. }
  110720. if(b->flr){
  110721. for(i=0;i<ci->floors;i++)
  110722. _floor_P[ci->floor_type[i]]->
  110723. free_look(b->flr[i]);
  110724. _ogg_free(b->flr);
  110725. }
  110726. if(b->residue){
  110727. for(i=0;i<ci->residues;i++)
  110728. _residue_P[ci->residue_type[i]]->
  110729. free_look(b->residue[i]);
  110730. _ogg_free(b->residue);
  110731. }
  110732. if(b->psy){
  110733. for(i=0;i<ci->psys;i++)
  110734. _vp_psy_clear(b->psy+i);
  110735. _ogg_free(b->psy);
  110736. }
  110737. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110738. vorbis_bitrate_clear(&b->bms);
  110739. drft_clear(&b->fft_look[0]);
  110740. drft_clear(&b->fft_look[1]);
  110741. }
  110742. if(v->pcm){
  110743. for(i=0;i<vi->channels;i++)
  110744. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110745. _ogg_free(v->pcm);
  110746. if(v->pcmret)_ogg_free(v->pcmret);
  110747. }
  110748. if(b){
  110749. /* free header, header1, header2 */
  110750. if(b->header)_ogg_free(b->header);
  110751. if(b->header1)_ogg_free(b->header1);
  110752. if(b->header2)_ogg_free(b->header2);
  110753. _ogg_free(b);
  110754. }
  110755. memset(v,0,sizeof(*v));
  110756. }
  110757. }
  110758. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110759. int i;
  110760. vorbis_info *vi=v->vi;
  110761. private_state *b=(private_state*)v->backend_state;
  110762. /* free header, header1, header2 */
  110763. if(b->header)_ogg_free(b->header);b->header=NULL;
  110764. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110765. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110766. /* Do we have enough storage space for the requested buffer? If not,
  110767. expand the PCM (and envelope) storage */
  110768. if(v->pcm_current+vals>=v->pcm_storage){
  110769. v->pcm_storage=v->pcm_current+vals*2;
  110770. for(i=0;i<vi->channels;i++){
  110771. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110772. }
  110773. }
  110774. for(i=0;i<vi->channels;i++)
  110775. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110776. return(v->pcmret);
  110777. }
  110778. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110779. int i;
  110780. int order=32;
  110781. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110782. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110783. long j;
  110784. v->preextrapolate=1;
  110785. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110786. for(i=0;i<v->vi->channels;i++){
  110787. /* need to run the extrapolation in reverse! */
  110788. for(j=0;j<v->pcm_current;j++)
  110789. work[j]=v->pcm[i][v->pcm_current-j-1];
  110790. /* prime as above */
  110791. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110792. /* run the predictor filter */
  110793. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110794. order,
  110795. work+v->pcm_current-v->centerW,
  110796. v->centerW);
  110797. for(j=0;j<v->pcm_current;j++)
  110798. v->pcm[i][v->pcm_current-j-1]=work[j];
  110799. }
  110800. }
  110801. }
  110802. /* call with val<=0 to set eof */
  110803. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110804. vorbis_info *vi=v->vi;
  110805. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110806. if(vals<=0){
  110807. int order=32;
  110808. int i;
  110809. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110810. /* if it wasn't done earlier (very short sample) */
  110811. if(!v->preextrapolate)
  110812. _preextrapolate_helper(v);
  110813. /* We're encoding the end of the stream. Just make sure we have
  110814. [at least] a few full blocks of zeroes at the end. */
  110815. /* actually, we don't want zeroes; that could drop a large
  110816. amplitude off a cliff, creating spread spectrum noise that will
  110817. suck to encode. Extrapolate for the sake of cleanliness. */
  110818. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110819. v->eofflag=v->pcm_current;
  110820. v->pcm_current+=ci->blocksizes[1]*3;
  110821. for(i=0;i<vi->channels;i++){
  110822. if(v->eofflag>order*2){
  110823. /* extrapolate with LPC to fill in */
  110824. long n;
  110825. /* make a predictor filter */
  110826. n=v->eofflag;
  110827. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110828. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110829. /* run the predictor filter */
  110830. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110831. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110832. }else{
  110833. /* not enough data to extrapolate (unlikely to happen due to
  110834. guarding the overlap, but bulletproof in case that
  110835. assumtion goes away). zeroes will do. */
  110836. memset(v->pcm[i]+v->eofflag,0,
  110837. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110838. }
  110839. }
  110840. }else{
  110841. if(v->pcm_current+vals>v->pcm_storage)
  110842. return(OV_EINVAL);
  110843. v->pcm_current+=vals;
  110844. /* we may want to reverse extrapolate the beginning of a stream
  110845. too... in case we're beginning on a cliff! */
  110846. /* clumsy, but simple. It only runs once, so simple is good. */
  110847. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110848. _preextrapolate_helper(v);
  110849. }
  110850. return(0);
  110851. }
  110852. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110853. the next block on which to continue analysis */
  110854. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110855. int i;
  110856. vorbis_info *vi=v->vi;
  110857. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110858. private_state *b=(private_state*)v->backend_state;
  110859. vorbis_look_psy_global *g=b->psy_g_look;
  110860. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110861. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110862. /* check to see if we're started... */
  110863. if(!v->preextrapolate)return(0);
  110864. /* check to see if we're done... */
  110865. if(v->eofflag==-1)return(0);
  110866. /* By our invariant, we have lW, W and centerW set. Search for
  110867. the next boundary so we can determine nW (the next window size)
  110868. which lets us compute the shape of the current block's window */
  110869. /* we do an envelope search even on a single blocksize; we may still
  110870. be throwing more bits at impulses, and envelope search handles
  110871. marking impulses too. */
  110872. {
  110873. long bp=_ve_envelope_search(v);
  110874. if(bp==-1){
  110875. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110876. full long block */
  110877. v->nW=0;
  110878. }else{
  110879. if(ci->blocksizes[0]==ci->blocksizes[1])
  110880. v->nW=0;
  110881. else
  110882. v->nW=bp;
  110883. }
  110884. }
  110885. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110886. {
  110887. /* center of next block + next block maximum right side. */
  110888. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110889. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110890. although this check is
  110891. less strict that the
  110892. _ve_envelope_search,
  110893. the search is not run
  110894. if we only use one
  110895. block size */
  110896. }
  110897. /* fill in the block. Note that for a short window, lW and nW are *short*
  110898. regardless of actual settings in the stream */
  110899. _vorbis_block_ripcord(vb);
  110900. vb->lW=v->lW;
  110901. vb->W=v->W;
  110902. vb->nW=v->nW;
  110903. if(v->W){
  110904. if(!v->lW || !v->nW){
  110905. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110906. /*fprintf(stderr,"-");*/
  110907. }else{
  110908. vbi->blocktype=BLOCKTYPE_LONG;
  110909. /*fprintf(stderr,"_");*/
  110910. }
  110911. }else{
  110912. if(_ve_envelope_mark(v)){
  110913. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110914. /*fprintf(stderr,"|");*/
  110915. }else{
  110916. vbi->blocktype=BLOCKTYPE_PADDING;
  110917. /*fprintf(stderr,".");*/
  110918. }
  110919. }
  110920. vb->vd=v;
  110921. vb->sequence=v->sequence++;
  110922. vb->granulepos=v->granulepos;
  110923. vb->pcmend=ci->blocksizes[v->W];
  110924. /* copy the vectors; this uses the local storage in vb */
  110925. /* this tracks 'strongest peak' for later psychoacoustics */
  110926. /* moved to the global psy state; clean this mess up */
  110927. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110928. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110929. vbi->ampmax=g->ampmax;
  110930. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110931. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110932. for(i=0;i<vi->channels;i++){
  110933. vbi->pcmdelay[i]=
  110934. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110935. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110936. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110937. /* before we added the delay
  110938. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110939. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110940. */
  110941. }
  110942. /* handle eof detection: eof==0 means that we've not yet received EOF
  110943. eof>0 marks the last 'real' sample in pcm[]
  110944. eof<0 'no more to do'; doesn't get here */
  110945. if(v->eofflag){
  110946. if(v->centerW>=v->eofflag){
  110947. v->eofflag=-1;
  110948. vb->eofflag=1;
  110949. return(1);
  110950. }
  110951. }
  110952. /* advance storage vectors and clean up */
  110953. {
  110954. int new_centerNext=ci->blocksizes[1]/2;
  110955. int movementW=centerNext-new_centerNext;
  110956. if(movementW>0){
  110957. _ve_envelope_shift(b->ve,movementW);
  110958. v->pcm_current-=movementW;
  110959. for(i=0;i<vi->channels;i++)
  110960. memmove(v->pcm[i],v->pcm[i]+movementW,
  110961. v->pcm_current*sizeof(*v->pcm[i]));
  110962. v->lW=v->W;
  110963. v->W=v->nW;
  110964. v->centerW=new_centerNext;
  110965. if(v->eofflag){
  110966. v->eofflag-=movementW;
  110967. if(v->eofflag<=0)v->eofflag=-1;
  110968. /* do not add padding to end of stream! */
  110969. if(v->centerW>=v->eofflag){
  110970. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110971. }else{
  110972. v->granulepos+=movementW;
  110973. }
  110974. }else{
  110975. v->granulepos+=movementW;
  110976. }
  110977. }
  110978. }
  110979. /* done */
  110980. return(1);
  110981. }
  110982. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110983. vorbis_info *vi=v->vi;
  110984. codec_setup_info *ci;
  110985. int hs;
  110986. if(!v->backend_state)return -1;
  110987. if(!vi)return -1;
  110988. ci=(codec_setup_info*) vi->codec_setup;
  110989. if(!ci)return -1;
  110990. hs=ci->halfrate_flag;
  110991. v->centerW=ci->blocksizes[1]>>(hs+1);
  110992. v->pcm_current=v->centerW>>hs;
  110993. v->pcm_returned=-1;
  110994. v->granulepos=-1;
  110995. v->sequence=-1;
  110996. v->eofflag=0;
  110997. ((private_state *)(v->backend_state))->sample_count=-1;
  110998. return(0);
  110999. }
  111000. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111001. if(_vds_shared_init(v,vi,0)) return 1;
  111002. vorbis_synthesis_restart(v);
  111003. return 0;
  111004. }
  111005. /* Unlike in analysis, the window is only partially applied for each
  111006. block. The time domain envelope is not yet handled at the point of
  111007. calling (as it relies on the previous block). */
  111008. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111009. vorbis_info *vi=v->vi;
  111010. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111011. private_state *b=(private_state*)v->backend_state;
  111012. int hs=ci->halfrate_flag;
  111013. int i,j;
  111014. if(!vb)return(OV_EINVAL);
  111015. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111016. v->lW=v->W;
  111017. v->W=vb->W;
  111018. v->nW=-1;
  111019. if((v->sequence==-1)||
  111020. (v->sequence+1 != vb->sequence)){
  111021. v->granulepos=-1; /* out of sequence; lose count */
  111022. b->sample_count=-1;
  111023. }
  111024. v->sequence=vb->sequence;
  111025. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111026. was called on block */
  111027. int n=ci->blocksizes[v->W]>>(hs+1);
  111028. int n0=ci->blocksizes[0]>>(hs+1);
  111029. int n1=ci->blocksizes[1]>>(hs+1);
  111030. int thisCenter;
  111031. int prevCenter;
  111032. v->glue_bits+=vb->glue_bits;
  111033. v->time_bits+=vb->time_bits;
  111034. v->floor_bits+=vb->floor_bits;
  111035. v->res_bits+=vb->res_bits;
  111036. if(v->centerW){
  111037. thisCenter=n1;
  111038. prevCenter=0;
  111039. }else{
  111040. thisCenter=0;
  111041. prevCenter=n1;
  111042. }
  111043. /* v->pcm is now used like a two-stage double buffer. We don't want
  111044. to have to constantly shift *or* adjust memory usage. Don't
  111045. accept a new block until the old is shifted out */
  111046. for(j=0;j<vi->channels;j++){
  111047. /* the overlap/add section */
  111048. if(v->lW){
  111049. if(v->W){
  111050. /* large/large */
  111051. float *w=_vorbis_window_get(b->window[1]-hs);
  111052. float *pcm=v->pcm[j]+prevCenter;
  111053. float *p=vb->pcm[j];
  111054. for(i=0;i<n1;i++)
  111055. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111056. }else{
  111057. /* large/small */
  111058. float *w=_vorbis_window_get(b->window[0]-hs);
  111059. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111060. float *p=vb->pcm[j];
  111061. for(i=0;i<n0;i++)
  111062. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111063. }
  111064. }else{
  111065. if(v->W){
  111066. /* small/large */
  111067. float *w=_vorbis_window_get(b->window[0]-hs);
  111068. float *pcm=v->pcm[j]+prevCenter;
  111069. float *p=vb->pcm[j]+n1/2-n0/2;
  111070. for(i=0;i<n0;i++)
  111071. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111072. for(;i<n1/2+n0/2;i++)
  111073. pcm[i]=p[i];
  111074. }else{
  111075. /* small/small */
  111076. float *w=_vorbis_window_get(b->window[0]-hs);
  111077. float *pcm=v->pcm[j]+prevCenter;
  111078. float *p=vb->pcm[j];
  111079. for(i=0;i<n0;i++)
  111080. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111081. }
  111082. }
  111083. /* the copy section */
  111084. {
  111085. float *pcm=v->pcm[j]+thisCenter;
  111086. float *p=vb->pcm[j]+n;
  111087. for(i=0;i<n;i++)
  111088. pcm[i]=p[i];
  111089. }
  111090. }
  111091. if(v->centerW)
  111092. v->centerW=0;
  111093. else
  111094. v->centerW=n1;
  111095. /* deal with initial packet state; we do this using the explicit
  111096. pcm_returned==-1 flag otherwise we're sensitive to first block
  111097. being short or long */
  111098. if(v->pcm_returned==-1){
  111099. v->pcm_returned=thisCenter;
  111100. v->pcm_current=thisCenter;
  111101. }else{
  111102. v->pcm_returned=prevCenter;
  111103. v->pcm_current=prevCenter+
  111104. ((ci->blocksizes[v->lW]/4+
  111105. ci->blocksizes[v->W]/4)>>hs);
  111106. }
  111107. }
  111108. /* track the frame number... This is for convenience, but also
  111109. making sure our last packet doesn't end with added padding. If
  111110. the last packet is partial, the number of samples we'll have to
  111111. return will be past the vb->granulepos.
  111112. This is not foolproof! It will be confused if we begin
  111113. decoding at the last page after a seek or hole. In that case,
  111114. we don't have a starting point to judge where the last frame
  111115. is. For this reason, vorbisfile will always try to make sure
  111116. it reads the last two marked pages in proper sequence */
  111117. if(b->sample_count==-1){
  111118. b->sample_count=0;
  111119. }else{
  111120. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111121. }
  111122. if(v->granulepos==-1){
  111123. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111124. v->granulepos=vb->granulepos;
  111125. /* is this a short page? */
  111126. if(b->sample_count>v->granulepos){
  111127. /* corner case; if this is both the first and last audio page,
  111128. then spec says the end is cut, not beginning */
  111129. if(vb->eofflag){
  111130. /* trim the end */
  111131. /* no preceeding granulepos; assume we started at zero (we'd
  111132. have to in a short single-page stream) */
  111133. /* granulepos could be -1 due to a seek, but that would result
  111134. in a long count, not short count */
  111135. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111136. }else{
  111137. /* trim the beginning */
  111138. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111139. if(v->pcm_returned>v->pcm_current)
  111140. v->pcm_returned=v->pcm_current;
  111141. }
  111142. }
  111143. }
  111144. }else{
  111145. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111146. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111147. if(v->granulepos>vb->granulepos){
  111148. long extra=v->granulepos-vb->granulepos;
  111149. if(extra)
  111150. if(vb->eofflag){
  111151. /* partial last frame. Strip the extra samples off */
  111152. v->pcm_current-=extra>>hs;
  111153. } /* else {Shouldn't happen *unless* the bitstream is out of
  111154. spec. Either way, believe the bitstream } */
  111155. } /* else {Shouldn't happen *unless* the bitstream is out of
  111156. spec. Either way, believe the bitstream } */
  111157. v->granulepos=vb->granulepos;
  111158. }
  111159. }
  111160. /* Update, cleanup */
  111161. if(vb->eofflag)v->eofflag=1;
  111162. return(0);
  111163. }
  111164. /* pcm==NULL indicates we just want the pending samples, no more */
  111165. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111166. vorbis_info *vi=v->vi;
  111167. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111168. if(pcm){
  111169. int i;
  111170. for(i=0;i<vi->channels;i++)
  111171. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111172. *pcm=v->pcmret;
  111173. }
  111174. return(v->pcm_current-v->pcm_returned);
  111175. }
  111176. return(0);
  111177. }
  111178. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111179. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111180. v->pcm_returned+=n;
  111181. return(0);
  111182. }
  111183. /* intended for use with a specific vorbisfile feature; we want access
  111184. to the [usually synthetic/postextrapolated] buffer and lapping at
  111185. the end of a decode cycle, specifically, a half-short-block worth.
  111186. This funtion works like pcmout above, except it will also expose
  111187. this implicit buffer data not normally decoded. */
  111188. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111189. vorbis_info *vi=v->vi;
  111190. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111191. int hs=ci->halfrate_flag;
  111192. int n=ci->blocksizes[v->W]>>(hs+1);
  111193. int n0=ci->blocksizes[0]>>(hs+1);
  111194. int n1=ci->blocksizes[1]>>(hs+1);
  111195. int i,j;
  111196. if(v->pcm_returned<0)return 0;
  111197. /* our returned data ends at pcm_returned; because the synthesis pcm
  111198. buffer is a two-fragment ring, that means our data block may be
  111199. fragmented by buffering, wrapping or a short block not filling
  111200. out a buffer. To simplify things, we unfragment if it's at all
  111201. possibly needed. Otherwise, we'd need to call lapout more than
  111202. once as well as hold additional dsp state. Opt for
  111203. simplicity. */
  111204. /* centerW was advanced by blockin; it would be the center of the
  111205. *next* block */
  111206. if(v->centerW==n1){
  111207. /* the data buffer wraps; swap the halves */
  111208. /* slow, sure, small */
  111209. for(j=0;j<vi->channels;j++){
  111210. float *p=v->pcm[j];
  111211. for(i=0;i<n1;i++){
  111212. float temp=p[i];
  111213. p[i]=p[i+n1];
  111214. p[i+n1]=temp;
  111215. }
  111216. }
  111217. v->pcm_current-=n1;
  111218. v->pcm_returned-=n1;
  111219. v->centerW=0;
  111220. }
  111221. /* solidify buffer into contiguous space */
  111222. if((v->lW^v->W)==1){
  111223. /* long/short or short/long */
  111224. for(j=0;j<vi->channels;j++){
  111225. float *s=v->pcm[j];
  111226. float *d=v->pcm[j]+(n1-n0)/2;
  111227. for(i=(n1+n0)/2-1;i>=0;--i)
  111228. d[i]=s[i];
  111229. }
  111230. v->pcm_returned+=(n1-n0)/2;
  111231. v->pcm_current+=(n1-n0)/2;
  111232. }else{
  111233. if(v->lW==0){
  111234. /* short/short */
  111235. for(j=0;j<vi->channels;j++){
  111236. float *s=v->pcm[j];
  111237. float *d=v->pcm[j]+n1-n0;
  111238. for(i=n0-1;i>=0;--i)
  111239. d[i]=s[i];
  111240. }
  111241. v->pcm_returned+=n1-n0;
  111242. v->pcm_current+=n1-n0;
  111243. }
  111244. }
  111245. if(pcm){
  111246. int i;
  111247. for(i=0;i<vi->channels;i++)
  111248. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111249. *pcm=v->pcmret;
  111250. }
  111251. return(n1+n-v->pcm_returned);
  111252. }
  111253. float *vorbis_window(vorbis_dsp_state *v,int W){
  111254. vorbis_info *vi=v->vi;
  111255. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111256. int hs=ci->halfrate_flag;
  111257. private_state *b=(private_state*)v->backend_state;
  111258. if(b->window[W]-1<0)return NULL;
  111259. return _vorbis_window_get(b->window[W]-hs);
  111260. }
  111261. #endif
  111262. /*** End of inlined file: block.c ***/
  111263. /*** Start of inlined file: codebook.c ***/
  111264. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111265. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111266. // tasks..
  111267. #if JUCE_MSVC
  111268. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111269. #endif
  111270. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111271. #if JUCE_USE_OGGVORBIS
  111272. #include <stdlib.h>
  111273. #include <string.h>
  111274. #include <math.h>
  111275. /* packs the given codebook into the bitstream **************************/
  111276. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111277. long i,j;
  111278. int ordered=0;
  111279. /* first the basic parameters */
  111280. oggpack_write(opb,0x564342,24);
  111281. oggpack_write(opb,c->dim,16);
  111282. oggpack_write(opb,c->entries,24);
  111283. /* pack the codewords. There are two packings; length ordered and
  111284. length random. Decide between the two now. */
  111285. for(i=1;i<c->entries;i++)
  111286. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111287. if(i==c->entries)ordered=1;
  111288. if(ordered){
  111289. /* length ordered. We only need to say how many codewords of
  111290. each length. The actual codewords are generated
  111291. deterministically */
  111292. long count=0;
  111293. oggpack_write(opb,1,1); /* ordered */
  111294. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111295. for(i=1;i<c->entries;i++){
  111296. long thisx=c->lengthlist[i];
  111297. long last=c->lengthlist[i-1];
  111298. if(thisx>last){
  111299. for(j=last;j<thisx;j++){
  111300. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111301. count=i;
  111302. }
  111303. }
  111304. }
  111305. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111306. }else{
  111307. /* length random. Again, we don't code the codeword itself, just
  111308. the length. This time, though, we have to encode each length */
  111309. oggpack_write(opb,0,1); /* unordered */
  111310. /* algortihmic mapping has use for 'unused entries', which we tag
  111311. here. The algorithmic mapping happens as usual, but the unused
  111312. entry has no codeword. */
  111313. for(i=0;i<c->entries;i++)
  111314. if(c->lengthlist[i]==0)break;
  111315. if(i==c->entries){
  111316. oggpack_write(opb,0,1); /* no unused entries */
  111317. for(i=0;i<c->entries;i++)
  111318. oggpack_write(opb,c->lengthlist[i]-1,5);
  111319. }else{
  111320. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111321. for(i=0;i<c->entries;i++){
  111322. if(c->lengthlist[i]==0){
  111323. oggpack_write(opb,0,1);
  111324. }else{
  111325. oggpack_write(opb,1,1);
  111326. oggpack_write(opb,c->lengthlist[i]-1,5);
  111327. }
  111328. }
  111329. }
  111330. }
  111331. /* is the entry number the desired return value, or do we have a
  111332. mapping? If we have a mapping, what type? */
  111333. oggpack_write(opb,c->maptype,4);
  111334. switch(c->maptype){
  111335. case 0:
  111336. /* no mapping */
  111337. break;
  111338. case 1:case 2:
  111339. /* implicitly populated value mapping */
  111340. /* explicitly populated value mapping */
  111341. if(!c->quantlist){
  111342. /* no quantlist? error */
  111343. return(-1);
  111344. }
  111345. /* values that define the dequantization */
  111346. oggpack_write(opb,c->q_min,32);
  111347. oggpack_write(opb,c->q_delta,32);
  111348. oggpack_write(opb,c->q_quant-1,4);
  111349. oggpack_write(opb,c->q_sequencep,1);
  111350. {
  111351. int quantvals;
  111352. switch(c->maptype){
  111353. case 1:
  111354. /* a single column of (c->entries/c->dim) quantized values for
  111355. building a full value list algorithmically (square lattice) */
  111356. quantvals=_book_maptype1_quantvals(c);
  111357. break;
  111358. case 2:
  111359. /* every value (c->entries*c->dim total) specified explicitly */
  111360. quantvals=c->entries*c->dim;
  111361. break;
  111362. default: /* NOT_REACHABLE */
  111363. quantvals=-1;
  111364. }
  111365. /* quantized values */
  111366. for(i=0;i<quantvals;i++)
  111367. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111368. }
  111369. break;
  111370. default:
  111371. /* error case; we don't have any other map types now */
  111372. return(-1);
  111373. }
  111374. return(0);
  111375. }
  111376. /* unpacks a codebook from the packet buffer into the codebook struct,
  111377. readies the codebook auxiliary structures for decode *************/
  111378. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111379. long i,j;
  111380. memset(s,0,sizeof(*s));
  111381. s->allocedp=1;
  111382. /* make sure alignment is correct */
  111383. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111384. /* first the basic parameters */
  111385. s->dim=oggpack_read(opb,16);
  111386. s->entries=oggpack_read(opb,24);
  111387. if(s->entries==-1)goto _eofout;
  111388. /* codeword ordering.... length ordered or unordered? */
  111389. switch((int)oggpack_read(opb,1)){
  111390. case 0:
  111391. /* unordered */
  111392. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111393. /* allocated but unused entries? */
  111394. if(oggpack_read(opb,1)){
  111395. /* yes, unused entries */
  111396. for(i=0;i<s->entries;i++){
  111397. if(oggpack_read(opb,1)){
  111398. long num=oggpack_read(opb,5);
  111399. if(num==-1)goto _eofout;
  111400. s->lengthlist[i]=num+1;
  111401. }else
  111402. s->lengthlist[i]=0;
  111403. }
  111404. }else{
  111405. /* all entries used; no tagging */
  111406. for(i=0;i<s->entries;i++){
  111407. long num=oggpack_read(opb,5);
  111408. if(num==-1)goto _eofout;
  111409. s->lengthlist[i]=num+1;
  111410. }
  111411. }
  111412. break;
  111413. case 1:
  111414. /* ordered */
  111415. {
  111416. long length=oggpack_read(opb,5)+1;
  111417. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111418. for(i=0;i<s->entries;){
  111419. long num=oggpack_read(opb,_ilog(s->entries-i));
  111420. if(num==-1)goto _eofout;
  111421. for(j=0;j<num && i<s->entries;j++,i++)
  111422. s->lengthlist[i]=length;
  111423. length++;
  111424. }
  111425. }
  111426. break;
  111427. default:
  111428. /* EOF */
  111429. return(-1);
  111430. }
  111431. /* Do we have a mapping to unpack? */
  111432. switch((s->maptype=oggpack_read(opb,4))){
  111433. case 0:
  111434. /* no mapping */
  111435. break;
  111436. case 1: case 2:
  111437. /* implicitly populated value mapping */
  111438. /* explicitly populated value mapping */
  111439. s->q_min=oggpack_read(opb,32);
  111440. s->q_delta=oggpack_read(opb,32);
  111441. s->q_quant=oggpack_read(opb,4)+1;
  111442. s->q_sequencep=oggpack_read(opb,1);
  111443. {
  111444. int quantvals=0;
  111445. switch(s->maptype){
  111446. case 1:
  111447. quantvals=_book_maptype1_quantvals(s);
  111448. break;
  111449. case 2:
  111450. quantvals=s->entries*s->dim;
  111451. break;
  111452. }
  111453. /* quantized values */
  111454. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111455. for(i=0;i<quantvals;i++)
  111456. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111457. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111458. }
  111459. break;
  111460. default:
  111461. goto _errout;
  111462. }
  111463. /* all set */
  111464. return(0);
  111465. _errout:
  111466. _eofout:
  111467. vorbis_staticbook_clear(s);
  111468. return(-1);
  111469. }
  111470. /* returns the number of bits ************************************************/
  111471. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111472. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111473. return(book->c->lengthlist[a]);
  111474. }
  111475. /* One the encode side, our vector writers are each designed for a
  111476. specific purpose, and the encoder is not flexible without modification:
  111477. The LSP vector coder uses a single stage nearest-match with no
  111478. interleave, so no step and no error return. This is specced by floor0
  111479. and doesn't change.
  111480. Residue0 encoding interleaves, uses multiple stages, and each stage
  111481. peels of a specific amount of resolution from a lattice (thus we want
  111482. to match by threshold, not nearest match). Residue doesn't *have* to
  111483. be encoded that way, but to change it, one will need to add more
  111484. infrastructure on the encode side (decode side is specced and simpler) */
  111485. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111486. /* returns entry number and *modifies a* to the quantization value *****/
  111487. int vorbis_book_errorv(codebook *book,float *a){
  111488. int dim=book->dim,k;
  111489. int best=_best(book,a,1);
  111490. for(k=0;k<dim;k++)
  111491. a[k]=(book->valuelist+best*dim)[k];
  111492. return(best);
  111493. }
  111494. /* returns the number of bits and *modifies a* to the quantization value *****/
  111495. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111496. int k,dim=book->dim;
  111497. for(k=0;k<dim;k++)
  111498. a[k]=(book->valuelist+best*dim)[k];
  111499. return(vorbis_book_encode(book,best,b));
  111500. }
  111501. /* the 'eliminate the decode tree' optimization actually requires the
  111502. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111503. (and one of the first places where carefully thought out design
  111504. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111505. to an MSb bitpacker), but not actually the huge hit it appears to
  111506. be. The first-stage decode table catches most words so that
  111507. bitreverse is not in the main execution path. */
  111508. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111509. int read=book->dec_maxlength;
  111510. long lo,hi;
  111511. long lok = oggpack_look(b,book->dec_firsttablen);
  111512. if (lok >= 0) {
  111513. long entry = book->dec_firsttable[lok];
  111514. if(entry&0x80000000UL){
  111515. lo=(entry>>15)&0x7fff;
  111516. hi=book->used_entries-(entry&0x7fff);
  111517. }else{
  111518. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111519. return(entry-1);
  111520. }
  111521. }else{
  111522. lo=0;
  111523. hi=book->used_entries;
  111524. }
  111525. lok = oggpack_look(b, read);
  111526. while(lok<0 && read>1)
  111527. lok = oggpack_look(b, --read);
  111528. if(lok<0)return -1;
  111529. /* bisect search for the codeword in the ordered list */
  111530. {
  111531. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111532. while(hi-lo>1){
  111533. long p=(hi-lo)>>1;
  111534. long test=book->codelist[lo+p]>testword;
  111535. lo+=p&(test-1);
  111536. hi-=p&(-test);
  111537. }
  111538. if(book->dec_codelengths[lo]<=read){
  111539. oggpack_adv(b, book->dec_codelengths[lo]);
  111540. return(lo);
  111541. }
  111542. }
  111543. oggpack_adv(b, read);
  111544. return(-1);
  111545. }
  111546. /* Decode side is specced and easier, because we don't need to find
  111547. matches using different criteria; we simply read and map. There are
  111548. two things we need to do 'depending':
  111549. We may need to support interleave. We don't really, but it's
  111550. convenient to do it here rather than rebuild the vector later.
  111551. Cascades may be additive or multiplicitive; this is not inherent in
  111552. the codebook, but set in the code using the codebook. Like
  111553. interleaving, it's easiest to do it here.
  111554. addmul==0 -> declarative (set the value)
  111555. addmul==1 -> additive
  111556. addmul==2 -> multiplicitive */
  111557. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111558. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111559. long packed_entry=decode_packed_entry_number(book,b);
  111560. if(packed_entry>=0)
  111561. return(book->dec_index[packed_entry]);
  111562. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111563. return(packed_entry);
  111564. }
  111565. /* returns 0 on OK or -1 on eof *************************************/
  111566. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111567. int step=n/book->dim;
  111568. long *entry = (long*)alloca(sizeof(*entry)*step);
  111569. float **t = (float**)alloca(sizeof(*t)*step);
  111570. int i,j,o;
  111571. for (i = 0; i < step; i++) {
  111572. entry[i]=decode_packed_entry_number(book,b);
  111573. if(entry[i]==-1)return(-1);
  111574. t[i] = book->valuelist+entry[i]*book->dim;
  111575. }
  111576. for(i=0,o=0;i<book->dim;i++,o+=step)
  111577. for (j=0;j<step;j++)
  111578. a[o+j]+=t[j][i];
  111579. return(0);
  111580. }
  111581. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111582. int i,j,entry;
  111583. float *t;
  111584. if(book->dim>8){
  111585. for(i=0;i<n;){
  111586. entry = decode_packed_entry_number(book,b);
  111587. if(entry==-1)return(-1);
  111588. t = book->valuelist+entry*book->dim;
  111589. for (j=0;j<book->dim;)
  111590. a[i++]+=t[j++];
  111591. }
  111592. }else{
  111593. for(i=0;i<n;){
  111594. entry = decode_packed_entry_number(book,b);
  111595. if(entry==-1)return(-1);
  111596. t = book->valuelist+entry*book->dim;
  111597. j=0;
  111598. switch((int)book->dim){
  111599. case 8:
  111600. a[i++]+=t[j++];
  111601. case 7:
  111602. a[i++]+=t[j++];
  111603. case 6:
  111604. a[i++]+=t[j++];
  111605. case 5:
  111606. a[i++]+=t[j++];
  111607. case 4:
  111608. a[i++]+=t[j++];
  111609. case 3:
  111610. a[i++]+=t[j++];
  111611. case 2:
  111612. a[i++]+=t[j++];
  111613. case 1:
  111614. a[i++]+=t[j++];
  111615. case 0:
  111616. break;
  111617. }
  111618. }
  111619. }
  111620. return(0);
  111621. }
  111622. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111623. int i,j,entry;
  111624. float *t;
  111625. for(i=0;i<n;){
  111626. entry = decode_packed_entry_number(book,b);
  111627. if(entry==-1)return(-1);
  111628. t = book->valuelist+entry*book->dim;
  111629. for (j=0;j<book->dim;)
  111630. a[i++]=t[j++];
  111631. }
  111632. return(0);
  111633. }
  111634. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111635. oggpack_buffer *b,int n){
  111636. long i,j,entry;
  111637. int chptr=0;
  111638. for(i=offset/ch;i<(offset+n)/ch;){
  111639. entry = decode_packed_entry_number(book,b);
  111640. if(entry==-1)return(-1);
  111641. {
  111642. const float *t = book->valuelist+entry*book->dim;
  111643. for (j=0;j<book->dim;j++){
  111644. a[chptr++][i]+=t[j];
  111645. if(chptr==ch){
  111646. chptr=0;
  111647. i++;
  111648. }
  111649. }
  111650. }
  111651. }
  111652. return(0);
  111653. }
  111654. #ifdef _V_SELFTEST
  111655. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111656. number of vectors through (keeping track of the quantized values),
  111657. and decode using the unpacked book. quantized version of in should
  111658. exactly equal out */
  111659. #include <stdio.h>
  111660. #include "vorbis/book/lsp20_0.vqh"
  111661. #include "vorbis/book/res0a_13.vqh"
  111662. #define TESTSIZE 40
  111663. float test1[TESTSIZE]={
  111664. 0.105939f,
  111665. 0.215373f,
  111666. 0.429117f,
  111667. 0.587974f,
  111668. 0.181173f,
  111669. 0.296583f,
  111670. 0.515707f,
  111671. 0.715261f,
  111672. 0.162327f,
  111673. 0.263834f,
  111674. 0.342876f,
  111675. 0.406025f,
  111676. 0.103571f,
  111677. 0.223561f,
  111678. 0.368513f,
  111679. 0.540313f,
  111680. 0.136672f,
  111681. 0.395882f,
  111682. 0.587183f,
  111683. 0.652476f,
  111684. 0.114338f,
  111685. 0.417300f,
  111686. 0.525486f,
  111687. 0.698679f,
  111688. 0.147492f,
  111689. 0.324481f,
  111690. 0.643089f,
  111691. 0.757582f,
  111692. 0.139556f,
  111693. 0.215795f,
  111694. 0.324559f,
  111695. 0.399387f,
  111696. 0.120236f,
  111697. 0.267420f,
  111698. 0.446940f,
  111699. 0.608760f,
  111700. 0.115587f,
  111701. 0.287234f,
  111702. 0.571081f,
  111703. 0.708603f,
  111704. };
  111705. float test3[TESTSIZE]={
  111706. 0,1,-2,3,4,-5,6,7,8,9,
  111707. 8,-2,7,-1,4,6,8,3,1,-9,
  111708. 10,11,12,13,14,15,26,17,18,19,
  111709. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111710. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111711. &_vq_book_res0a_13,NULL};
  111712. float *testvec[]={test1,test3};
  111713. int main(){
  111714. oggpack_buffer write;
  111715. oggpack_buffer read;
  111716. long ptr=0,i;
  111717. oggpack_writeinit(&write);
  111718. fprintf(stderr,"Testing codebook abstraction...:\n");
  111719. while(testlist[ptr]){
  111720. codebook c;
  111721. static_codebook s;
  111722. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111723. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111724. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111725. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111726. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111727. /* pack the codebook, write the testvector */
  111728. oggpack_reset(&write);
  111729. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111730. we can write */
  111731. vorbis_staticbook_pack(testlist[ptr],&write);
  111732. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111733. for(i=0;i<TESTSIZE;i+=c.dim){
  111734. int best=_best(&c,qv+i,1);
  111735. vorbis_book_encodev(&c,best,qv+i,&write);
  111736. }
  111737. vorbis_book_clear(&c);
  111738. fprintf(stderr,"OK.\n");
  111739. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111740. /* transfer the write data to a read buffer and unpack/read */
  111741. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111742. if(vorbis_staticbook_unpack(&read,&s)){
  111743. fprintf(stderr,"Error unpacking codebook.\n");
  111744. exit(1);
  111745. }
  111746. if(vorbis_book_init_decode(&c,&s)){
  111747. fprintf(stderr,"Error initializing codebook.\n");
  111748. exit(1);
  111749. }
  111750. for(i=0;i<TESTSIZE;i+=c.dim)
  111751. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111752. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111753. exit(1);
  111754. }
  111755. for(i=0;i<TESTSIZE;i++)
  111756. if(fabs(qv[i]-iv[i])>.000001){
  111757. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111758. iv[i],qv[i],i);
  111759. exit(1);
  111760. }
  111761. fprintf(stderr,"OK\n");
  111762. ptr++;
  111763. }
  111764. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111765. exit(0);
  111766. }
  111767. #endif
  111768. #endif
  111769. /*** End of inlined file: codebook.c ***/
  111770. /*** Start of inlined file: envelope.c ***/
  111771. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111772. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111773. // tasks..
  111774. #if JUCE_MSVC
  111775. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111776. #endif
  111777. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111778. #if JUCE_USE_OGGVORBIS
  111779. #include <stdlib.h>
  111780. #include <string.h>
  111781. #include <stdio.h>
  111782. #include <math.h>
  111783. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111784. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111785. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111786. int ch=vi->channels;
  111787. int i,j;
  111788. int n=e->winlength=128;
  111789. e->searchstep=64; /* not random */
  111790. e->minenergy=gi->preecho_minenergy;
  111791. e->ch=ch;
  111792. e->storage=128;
  111793. e->cursor=ci->blocksizes[1]/2;
  111794. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111795. mdct_init(&e->mdct,n);
  111796. for(i=0;i<n;i++){
  111797. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111798. e->mdct_win[i]*=e->mdct_win[i];
  111799. }
  111800. /* magic follows */
  111801. e->band[0].begin=2; e->band[0].end=4;
  111802. e->band[1].begin=4; e->band[1].end=5;
  111803. e->band[2].begin=6; e->band[2].end=6;
  111804. e->band[3].begin=9; e->band[3].end=8;
  111805. e->band[4].begin=13; e->band[4].end=8;
  111806. e->band[5].begin=17; e->band[5].end=8;
  111807. e->band[6].begin=22; e->band[6].end=8;
  111808. for(j=0;j<VE_BANDS;j++){
  111809. n=e->band[j].end;
  111810. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111811. for(i=0;i<n;i++){
  111812. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111813. e->band[j].total+=e->band[j].window[i];
  111814. }
  111815. e->band[j].total=1./e->band[j].total;
  111816. }
  111817. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111818. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111819. }
  111820. void _ve_envelope_clear(envelope_lookup *e){
  111821. int i;
  111822. mdct_clear(&e->mdct);
  111823. for(i=0;i<VE_BANDS;i++)
  111824. _ogg_free(e->band[i].window);
  111825. _ogg_free(e->mdct_win);
  111826. _ogg_free(e->filter);
  111827. _ogg_free(e->mark);
  111828. memset(e,0,sizeof(*e));
  111829. }
  111830. /* fairly straight threshhold-by-band based until we find something
  111831. that works better and isn't patented. */
  111832. static int _ve_amp(envelope_lookup *ve,
  111833. vorbis_info_psy_global *gi,
  111834. float *data,
  111835. envelope_band *bands,
  111836. envelope_filter_state *filters,
  111837. long pos){
  111838. long n=ve->winlength;
  111839. int ret=0;
  111840. long i,j;
  111841. float decay;
  111842. /* we want to have a 'minimum bar' for energy, else we're just
  111843. basing blocks on quantization noise that outweighs the signal
  111844. itself (for low power signals) */
  111845. float minV=ve->minenergy;
  111846. float *vec=(float*) alloca(n*sizeof(*vec));
  111847. /* stretch is used to gradually lengthen the number of windows
  111848. considered prevoius-to-potential-trigger */
  111849. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111850. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111851. if(penalty<0.f)penalty=0.f;
  111852. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111853. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111854. totalshift+pos*ve->searchstep);*/
  111855. /* window and transform */
  111856. for(i=0;i<n;i++)
  111857. vec[i]=data[i]*ve->mdct_win[i];
  111858. mdct_forward(&ve->mdct,vec,vec);
  111859. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111860. /* near-DC spreading function; this has nothing to do with
  111861. psychoacoustics, just sidelobe leakage and window size */
  111862. {
  111863. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111864. int ptr=filters->nearptr;
  111865. /* the accumulation is regularly refreshed from scratch to avoid
  111866. floating point creep */
  111867. if(ptr==0){
  111868. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111869. filters->nearDC_partialacc=temp;
  111870. }else{
  111871. decay=filters->nearDC_acc+=temp;
  111872. filters->nearDC_partialacc+=temp;
  111873. }
  111874. filters->nearDC_acc-=filters->nearDC[ptr];
  111875. filters->nearDC[ptr]=temp;
  111876. decay*=(1./(VE_NEARDC+1));
  111877. filters->nearptr++;
  111878. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111879. decay=todB(&decay)*.5-15.f;
  111880. }
  111881. /* perform spreading and limiting, also smooth the spectrum. yes,
  111882. the MDCT results in all real coefficients, but it still *behaves*
  111883. like real/imaginary pairs */
  111884. for(i=0;i<n/2;i+=2){
  111885. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111886. val=todB(&val)*.5f;
  111887. if(val<decay)val=decay;
  111888. if(val<minV)val=minV;
  111889. vec[i>>1]=val;
  111890. decay-=8.;
  111891. }
  111892. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111893. /* perform preecho/postecho triggering by band */
  111894. for(j=0;j<VE_BANDS;j++){
  111895. float acc=0.;
  111896. float valmax,valmin;
  111897. /* accumulate amplitude */
  111898. for(i=0;i<bands[j].end;i++)
  111899. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111900. acc*=bands[j].total;
  111901. /* convert amplitude to delta */
  111902. {
  111903. int p,thisx=filters[j].ampptr;
  111904. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111905. p=thisx;
  111906. p--;
  111907. if(p<0)p+=VE_AMP;
  111908. postmax=max(acc,filters[j].ampbuf[p]);
  111909. postmin=min(acc,filters[j].ampbuf[p]);
  111910. for(i=0;i<stretch;i++){
  111911. p--;
  111912. if(p<0)p+=VE_AMP;
  111913. premax=max(premax,filters[j].ampbuf[p]);
  111914. premin=min(premin,filters[j].ampbuf[p]);
  111915. }
  111916. valmin=postmin-premin;
  111917. valmax=postmax-premax;
  111918. /*filters[j].markers[pos]=valmax;*/
  111919. filters[j].ampbuf[thisx]=acc;
  111920. filters[j].ampptr++;
  111921. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111922. }
  111923. /* look at min/max, decide trigger */
  111924. if(valmax>gi->preecho_thresh[j]+penalty){
  111925. ret|=1;
  111926. ret|=4;
  111927. }
  111928. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111929. }
  111930. return(ret);
  111931. }
  111932. #if 0
  111933. static int seq=0;
  111934. static ogg_int64_t totalshift=-1024;
  111935. #endif
  111936. long _ve_envelope_search(vorbis_dsp_state *v){
  111937. vorbis_info *vi=v->vi;
  111938. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111939. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111940. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111941. long i,j;
  111942. int first=ve->current/ve->searchstep;
  111943. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111944. if(first<0)first=0;
  111945. /* make sure we have enough storage to match the PCM */
  111946. if(last+VE_WIN+VE_POST>ve->storage){
  111947. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111948. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111949. }
  111950. for(j=first;j<last;j++){
  111951. int ret=0;
  111952. ve->stretch++;
  111953. if(ve->stretch>VE_MAXSTRETCH*2)
  111954. ve->stretch=VE_MAXSTRETCH*2;
  111955. for(i=0;i<ve->ch;i++){
  111956. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111957. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111958. }
  111959. ve->mark[j+VE_POST]=0;
  111960. if(ret&1){
  111961. ve->mark[j]=1;
  111962. ve->mark[j+1]=1;
  111963. }
  111964. if(ret&2){
  111965. ve->mark[j]=1;
  111966. if(j>0)ve->mark[j-1]=1;
  111967. }
  111968. if(ret&4)ve->stretch=-1;
  111969. }
  111970. ve->current=last*ve->searchstep;
  111971. {
  111972. long centerW=v->centerW;
  111973. long testW=
  111974. centerW+
  111975. ci->blocksizes[v->W]/4+
  111976. ci->blocksizes[1]/2+
  111977. ci->blocksizes[0]/4;
  111978. j=ve->cursor;
  111979. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111980. working back one window */
  111981. if(j>=testW)return(1);
  111982. ve->cursor=j;
  111983. if(ve->mark[j/ve->searchstep]){
  111984. if(j>centerW){
  111985. #if 0
  111986. if(j>ve->curmark){
  111987. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111988. int l,m;
  111989. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111990. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111991. seq,
  111992. (totalshift+ve->cursor)/44100.,
  111993. (totalshift+j)/44100.);
  111994. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111995. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111996. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111997. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111998. for(m=0;m<VE_BANDS;m++){
  111999. char buf[80];
  112000. sprintf(buf,"delL%d",m);
  112001. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112002. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112003. }
  112004. for(m=0;m<VE_BANDS;m++){
  112005. char buf[80];
  112006. sprintf(buf,"delR%d",m);
  112007. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112008. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112009. }
  112010. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112011. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112012. seq++;
  112013. }
  112014. #endif
  112015. ve->curmark=j;
  112016. if(j>=testW)return(1);
  112017. return(0);
  112018. }
  112019. }
  112020. j+=ve->searchstep;
  112021. }
  112022. }
  112023. return(-1);
  112024. }
  112025. int _ve_envelope_mark(vorbis_dsp_state *v){
  112026. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112027. vorbis_info *vi=v->vi;
  112028. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112029. long centerW=v->centerW;
  112030. long beginW=centerW-ci->blocksizes[v->W]/4;
  112031. long endW=centerW+ci->blocksizes[v->W]/4;
  112032. if(v->W){
  112033. beginW-=ci->blocksizes[v->lW]/4;
  112034. endW+=ci->blocksizes[v->nW]/4;
  112035. }else{
  112036. beginW-=ci->blocksizes[0]/4;
  112037. endW+=ci->blocksizes[0]/4;
  112038. }
  112039. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112040. {
  112041. long first=beginW/ve->searchstep;
  112042. long last=endW/ve->searchstep;
  112043. long i;
  112044. for(i=first;i<last;i++)
  112045. if(ve->mark[i])return(1);
  112046. }
  112047. return(0);
  112048. }
  112049. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112050. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112051. ahead of ve->current */
  112052. int smallshift=shift/e->searchstep;
  112053. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112054. #if 0
  112055. for(i=0;i<VE_BANDS*e->ch;i++)
  112056. memmove(e->filter[i].markers,
  112057. e->filter[i].markers+smallshift,
  112058. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112059. totalshift+=shift;
  112060. #endif
  112061. e->current-=shift;
  112062. if(e->curmark>=0)
  112063. e->curmark-=shift;
  112064. e->cursor-=shift;
  112065. }
  112066. #endif
  112067. /*** End of inlined file: envelope.c ***/
  112068. /*** Start of inlined file: floor0.c ***/
  112069. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112070. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112071. // tasks..
  112072. #if JUCE_MSVC
  112073. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112074. #endif
  112075. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112076. #if JUCE_USE_OGGVORBIS
  112077. #include <stdlib.h>
  112078. #include <string.h>
  112079. #include <math.h>
  112080. /*** Start of inlined file: lsp.h ***/
  112081. #ifndef _V_LSP_H_
  112082. #define _V_LSP_H_
  112083. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112084. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112085. float *lsp,int m,
  112086. float amp,float ampoffset);
  112087. #endif
  112088. /*** End of inlined file: lsp.h ***/
  112089. #include <stdio.h>
  112090. typedef struct {
  112091. int ln;
  112092. int m;
  112093. int **linearmap;
  112094. int n[2];
  112095. vorbis_info_floor0 *vi;
  112096. long bits;
  112097. long frames;
  112098. } vorbis_look_floor0;
  112099. /***********************************************/
  112100. static void floor0_free_info(vorbis_info_floor *i){
  112101. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112102. if(info){
  112103. memset(info,0,sizeof(*info));
  112104. _ogg_free(info);
  112105. }
  112106. }
  112107. static void floor0_free_look(vorbis_look_floor *i){
  112108. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112109. if(look){
  112110. if(look->linearmap){
  112111. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112112. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112113. _ogg_free(look->linearmap);
  112114. }
  112115. memset(look,0,sizeof(*look));
  112116. _ogg_free(look);
  112117. }
  112118. }
  112119. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112120. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112121. int j;
  112122. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112123. info->order=oggpack_read(opb,8);
  112124. info->rate=oggpack_read(opb,16);
  112125. info->barkmap=oggpack_read(opb,16);
  112126. info->ampbits=oggpack_read(opb,6);
  112127. info->ampdB=oggpack_read(opb,8);
  112128. info->numbooks=oggpack_read(opb,4)+1;
  112129. if(info->order<1)goto err_out;
  112130. if(info->rate<1)goto err_out;
  112131. if(info->barkmap<1)goto err_out;
  112132. if(info->numbooks<1)goto err_out;
  112133. for(j=0;j<info->numbooks;j++){
  112134. info->books[j]=oggpack_read(opb,8);
  112135. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112136. }
  112137. return(info);
  112138. err_out:
  112139. floor0_free_info(info);
  112140. return(NULL);
  112141. }
  112142. /* initialize Bark scale and normalization lookups. We could do this
  112143. with static tables, but Vorbis allows a number of possible
  112144. combinations, so it's best to do it computationally.
  112145. The below is authoritative in terms of defining scale mapping.
  112146. Note that the scale depends on the sampling rate as well as the
  112147. linear block and mapping sizes */
  112148. static void floor0_map_lazy_init(vorbis_block *vb,
  112149. vorbis_info_floor *infoX,
  112150. vorbis_look_floor0 *look){
  112151. if(!look->linearmap[vb->W]){
  112152. vorbis_dsp_state *vd=vb->vd;
  112153. vorbis_info *vi=vd->vi;
  112154. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112155. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112156. int W=vb->W;
  112157. int n=ci->blocksizes[W]/2,j;
  112158. /* we choose a scaling constant so that:
  112159. floor(bark(rate/2-1)*C)=mapped-1
  112160. floor(bark(rate/2)*C)=mapped */
  112161. float scale=look->ln/toBARK(info->rate/2.f);
  112162. /* the mapping from a linear scale to a smaller bark scale is
  112163. straightforward. We do *not* make sure that the linear mapping
  112164. does not skip bark-scale bins; the decoder simply skips them and
  112165. the encoder may do what it wishes in filling them. They're
  112166. necessary in some mapping combinations to keep the scale spacing
  112167. accurate */
  112168. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112169. for(j=0;j<n;j++){
  112170. int val=floor( toBARK((info->rate/2.f)/n*j)
  112171. *scale); /* bark numbers represent band edges */
  112172. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112173. look->linearmap[W][j]=val;
  112174. }
  112175. look->linearmap[W][j]=-1;
  112176. look->n[W]=n;
  112177. }
  112178. }
  112179. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112180. vorbis_info_floor *i){
  112181. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112182. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112183. look->m=info->order;
  112184. look->ln=info->barkmap;
  112185. look->vi=info;
  112186. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112187. return look;
  112188. }
  112189. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112190. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112191. vorbis_info_floor0 *info=look->vi;
  112192. int j,k;
  112193. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112194. if(ampraw>0){ /* also handles the -1 out of data case */
  112195. long maxval=(1<<info->ampbits)-1;
  112196. float amp=(float)ampraw/maxval*info->ampdB;
  112197. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112198. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112199. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112200. codebook *b=ci->fullbooks+info->books[booknum];
  112201. float last=0.f;
  112202. /* the additional b->dim is a guard against any possible stack
  112203. smash; b->dim is provably more than we can overflow the
  112204. vector */
  112205. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112206. for(j=0;j<look->m;j+=b->dim)
  112207. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112208. for(j=0;j<look->m;){
  112209. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112210. last=lsp[j-1];
  112211. }
  112212. lsp[look->m]=amp;
  112213. return(lsp);
  112214. }
  112215. }
  112216. eop:
  112217. return(NULL);
  112218. }
  112219. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112220. void *memo,float *out){
  112221. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112222. vorbis_info_floor0 *info=look->vi;
  112223. floor0_map_lazy_init(vb,info,look);
  112224. if(memo){
  112225. float *lsp=(float *)memo;
  112226. float amp=lsp[look->m];
  112227. /* take the coefficients back to a spectral envelope curve */
  112228. vorbis_lsp_to_curve(out,
  112229. look->linearmap[vb->W],
  112230. look->n[vb->W],
  112231. look->ln,
  112232. lsp,look->m,amp,(float)info->ampdB);
  112233. return(1);
  112234. }
  112235. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112236. return(0);
  112237. }
  112238. /* export hooks */
  112239. vorbis_func_floor floor0_exportbundle={
  112240. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112241. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112242. };
  112243. #endif
  112244. /*** End of inlined file: floor0.c ***/
  112245. /*** Start of inlined file: floor1.c ***/
  112246. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112247. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112248. // tasks..
  112249. #if JUCE_MSVC
  112250. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112251. #endif
  112252. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112253. #if JUCE_USE_OGGVORBIS
  112254. #include <stdlib.h>
  112255. #include <string.h>
  112256. #include <math.h>
  112257. #include <stdio.h>
  112258. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112259. typedef struct {
  112260. int sorted_index[VIF_POSIT+2];
  112261. int forward_index[VIF_POSIT+2];
  112262. int reverse_index[VIF_POSIT+2];
  112263. int hineighbor[VIF_POSIT];
  112264. int loneighbor[VIF_POSIT];
  112265. int posts;
  112266. int n;
  112267. int quant_q;
  112268. vorbis_info_floor1 *vi;
  112269. long phrasebits;
  112270. long postbits;
  112271. long frames;
  112272. } vorbis_look_floor1;
  112273. typedef struct lsfit_acc{
  112274. long x0;
  112275. long x1;
  112276. long xa;
  112277. long ya;
  112278. long x2a;
  112279. long y2a;
  112280. long xya;
  112281. long an;
  112282. } lsfit_acc;
  112283. /***********************************************/
  112284. static void floor1_free_info(vorbis_info_floor *i){
  112285. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112286. if(info){
  112287. memset(info,0,sizeof(*info));
  112288. _ogg_free(info);
  112289. }
  112290. }
  112291. static void floor1_free_look(vorbis_look_floor *i){
  112292. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112293. if(look){
  112294. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112295. (float)look->phrasebits/look->frames,
  112296. (float)look->postbits/look->frames,
  112297. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112298. memset(look,0,sizeof(*look));
  112299. _ogg_free(look);
  112300. }
  112301. }
  112302. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112303. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112304. int j,k;
  112305. int count=0;
  112306. int rangebits;
  112307. int maxposit=info->postlist[1];
  112308. int maxclass=-1;
  112309. /* save out partitions */
  112310. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112311. for(j=0;j<info->partitions;j++){
  112312. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112313. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112314. }
  112315. /* save out partition classes */
  112316. for(j=0;j<maxclass+1;j++){
  112317. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112318. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112319. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112320. for(k=0;k<(1<<info->class_subs[j]);k++)
  112321. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112322. }
  112323. /* save out the post list */
  112324. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112325. oggpack_write(opb,ilog2(maxposit),4);
  112326. rangebits=ilog2(maxposit);
  112327. for(j=0,k=0;j<info->partitions;j++){
  112328. count+=info->class_dim[info->partitionclass[j]];
  112329. for(;k<count;k++)
  112330. oggpack_write(opb,info->postlist[k+2],rangebits);
  112331. }
  112332. }
  112333. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112334. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112335. int j,k,count=0,maxclass=-1,rangebits;
  112336. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112337. /* read partitions */
  112338. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112339. for(j=0;j<info->partitions;j++){
  112340. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112341. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112342. }
  112343. /* read partition classes */
  112344. for(j=0;j<maxclass+1;j++){
  112345. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112346. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112347. if(info->class_subs[j]<0)
  112348. goto err_out;
  112349. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112350. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112351. goto err_out;
  112352. for(k=0;k<(1<<info->class_subs[j]);k++){
  112353. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112354. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112355. goto err_out;
  112356. }
  112357. }
  112358. /* read the post list */
  112359. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112360. rangebits=oggpack_read(opb,4);
  112361. for(j=0,k=0;j<info->partitions;j++){
  112362. count+=info->class_dim[info->partitionclass[j]];
  112363. for(;k<count;k++){
  112364. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112365. if(t<0 || t>=(1<<rangebits))
  112366. goto err_out;
  112367. }
  112368. }
  112369. info->postlist[0]=0;
  112370. info->postlist[1]=1<<rangebits;
  112371. return(info);
  112372. err_out:
  112373. floor1_free_info(info);
  112374. return(NULL);
  112375. }
  112376. static int icomp(const void *a,const void *b){
  112377. return(**(int **)a-**(int **)b);
  112378. }
  112379. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112380. vorbis_info_floor *in){
  112381. int *sortpointer[VIF_POSIT+2];
  112382. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112383. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112384. int i,j,n=0;
  112385. look->vi=info;
  112386. look->n=info->postlist[1];
  112387. /* we drop each position value in-between already decoded values,
  112388. and use linear interpolation to predict each new value past the
  112389. edges. The positions are read in the order of the position
  112390. list... we precompute the bounding positions in the lookup. Of
  112391. course, the neighbors can change (if a position is declined), but
  112392. this is an initial mapping */
  112393. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112394. n+=2;
  112395. look->posts=n;
  112396. /* also store a sorted position index */
  112397. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112398. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112399. /* points from sort order back to range number */
  112400. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112401. /* points from range order to sorted position */
  112402. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112403. /* we actually need the post values too */
  112404. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112405. /* quantize values to multiplier spec */
  112406. switch(info->mult){
  112407. case 1: /* 1024 -> 256 */
  112408. look->quant_q=256;
  112409. break;
  112410. case 2: /* 1024 -> 128 */
  112411. look->quant_q=128;
  112412. break;
  112413. case 3: /* 1024 -> 86 */
  112414. look->quant_q=86;
  112415. break;
  112416. case 4: /* 1024 -> 64 */
  112417. look->quant_q=64;
  112418. break;
  112419. }
  112420. /* discover our neighbors for decode where we don't use fit flags
  112421. (that would push the neighbors outward) */
  112422. for(i=0;i<n-2;i++){
  112423. int lo=0;
  112424. int hi=1;
  112425. int lx=0;
  112426. int hx=look->n;
  112427. int currentx=info->postlist[i+2];
  112428. for(j=0;j<i+2;j++){
  112429. int x=info->postlist[j];
  112430. if(x>lx && x<currentx){
  112431. lo=j;
  112432. lx=x;
  112433. }
  112434. if(x<hx && x>currentx){
  112435. hi=j;
  112436. hx=x;
  112437. }
  112438. }
  112439. look->loneighbor[i]=lo;
  112440. look->hineighbor[i]=hi;
  112441. }
  112442. return(look);
  112443. }
  112444. static int render_point(int x0,int x1,int y0,int y1,int x){
  112445. y0&=0x7fff; /* mask off flag */
  112446. y1&=0x7fff;
  112447. {
  112448. int dy=y1-y0;
  112449. int adx=x1-x0;
  112450. int ady=abs(dy);
  112451. int err=ady*(x-x0);
  112452. int off=err/adx;
  112453. if(dy<0)return(y0-off);
  112454. return(y0+off);
  112455. }
  112456. }
  112457. static int vorbis_dBquant(const float *x){
  112458. int i= *x*7.3142857f+1023.5f;
  112459. if(i>1023)return(1023);
  112460. if(i<0)return(0);
  112461. return i;
  112462. }
  112463. static float FLOOR1_fromdB_LOOKUP[256]={
  112464. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112465. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112466. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112467. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112468. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112469. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112470. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112471. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112472. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112473. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112474. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112475. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112476. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112477. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112478. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112479. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112480. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112481. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112482. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112483. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112484. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112485. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112486. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112487. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112488. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112489. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112490. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112491. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112492. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112493. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112494. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112495. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112496. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112497. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112498. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112499. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112500. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112501. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112502. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112503. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112504. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112505. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112506. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112507. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112508. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112509. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112510. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112511. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112512. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112513. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112514. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112515. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112516. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112517. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112518. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112519. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112520. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112521. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112522. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112523. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112524. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112525. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112526. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112527. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112528. };
  112529. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112530. int dy=y1-y0;
  112531. int adx=x1-x0;
  112532. int ady=abs(dy);
  112533. int base=dy/adx;
  112534. int sy=(dy<0?base-1:base+1);
  112535. int x=x0;
  112536. int y=y0;
  112537. int err=0;
  112538. ady-=abs(base*adx);
  112539. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112540. while(++x<x1){
  112541. err=err+ady;
  112542. if(err>=adx){
  112543. err-=adx;
  112544. y+=sy;
  112545. }else{
  112546. y+=base;
  112547. }
  112548. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112549. }
  112550. }
  112551. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112552. int dy=y1-y0;
  112553. int adx=x1-x0;
  112554. int ady=abs(dy);
  112555. int base=dy/adx;
  112556. int sy=(dy<0?base-1:base+1);
  112557. int x=x0;
  112558. int y=y0;
  112559. int err=0;
  112560. ady-=abs(base*adx);
  112561. d[x]=y;
  112562. while(++x<x1){
  112563. err=err+ady;
  112564. if(err>=adx){
  112565. err-=adx;
  112566. y+=sy;
  112567. }else{
  112568. y+=base;
  112569. }
  112570. d[x]=y;
  112571. }
  112572. }
  112573. /* the floor has already been filtered to only include relevant sections */
  112574. static int accumulate_fit(const float *flr,const float *mdct,
  112575. int x0, int x1,lsfit_acc *a,
  112576. int n,vorbis_info_floor1 *info){
  112577. long i;
  112578. 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;
  112579. memset(a,0,sizeof(*a));
  112580. a->x0=x0;
  112581. a->x1=x1;
  112582. if(x1>=n)x1=n-1;
  112583. for(i=x0;i<=x1;i++){
  112584. int quantized=vorbis_dBquant(flr+i);
  112585. if(quantized){
  112586. if(mdct[i]+info->twofitatten>=flr[i]){
  112587. xa += i;
  112588. ya += quantized;
  112589. x2a += i*i;
  112590. y2a += quantized*quantized;
  112591. xya += i*quantized;
  112592. na++;
  112593. }else{
  112594. xb += i;
  112595. yb += quantized;
  112596. x2b += i*i;
  112597. y2b += quantized*quantized;
  112598. xyb += i*quantized;
  112599. nb++;
  112600. }
  112601. }
  112602. }
  112603. xb+=xa;
  112604. yb+=ya;
  112605. x2b+=x2a;
  112606. y2b+=y2a;
  112607. xyb+=xya;
  112608. nb+=na;
  112609. /* weight toward the actually used frequencies if we meet the threshhold */
  112610. {
  112611. int weight=nb*info->twofitweight/(na+1);
  112612. a->xa=xa*weight+xb;
  112613. a->ya=ya*weight+yb;
  112614. a->x2a=x2a*weight+x2b;
  112615. a->y2a=y2a*weight+y2b;
  112616. a->xya=xya*weight+xyb;
  112617. a->an=na*weight+nb;
  112618. }
  112619. return(na);
  112620. }
  112621. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112622. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112623. long x0=a[0].x0;
  112624. long x1=a[fits-1].x1;
  112625. for(i=0;i<fits;i++){
  112626. x+=a[i].xa;
  112627. y+=a[i].ya;
  112628. x2+=a[i].x2a;
  112629. y2+=a[i].y2a;
  112630. xy+=a[i].xya;
  112631. an+=a[i].an;
  112632. }
  112633. if(*y0>=0){
  112634. x+= x0;
  112635. y+= *y0;
  112636. x2+= x0 * x0;
  112637. y2+= *y0 * *y0;
  112638. xy+= *y0 * x0;
  112639. an++;
  112640. }
  112641. if(*y1>=0){
  112642. x+= x1;
  112643. y+= *y1;
  112644. x2+= x1 * x1;
  112645. y2+= *y1 * *y1;
  112646. xy+= *y1 * x1;
  112647. an++;
  112648. }
  112649. if(an){
  112650. /* need 64 bit multiplies, which C doesn't give portably as int */
  112651. double fx=x;
  112652. double fy=y;
  112653. double fx2=x2;
  112654. double fxy=xy;
  112655. double denom=1./(an*fx2-fx*fx);
  112656. double a=(fy*fx2-fxy*fx)*denom;
  112657. double b=(an*fxy-fx*fy)*denom;
  112658. *y0=rint(a+b*x0);
  112659. *y1=rint(a+b*x1);
  112660. /* limit to our range! */
  112661. if(*y0>1023)*y0=1023;
  112662. if(*y1>1023)*y1=1023;
  112663. if(*y0<0)*y0=0;
  112664. if(*y1<0)*y1=0;
  112665. }else{
  112666. *y0=0;
  112667. *y1=0;
  112668. }
  112669. }
  112670. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112671. long y=0;
  112672. int i;
  112673. for(i=0;i<fits && y==0;i++)
  112674. y+=a[i].ya;
  112675. *y0=*y1=y;
  112676. }*/
  112677. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112678. const float *mdct,
  112679. vorbis_info_floor1 *info){
  112680. int dy=y1-y0;
  112681. int adx=x1-x0;
  112682. int ady=abs(dy);
  112683. int base=dy/adx;
  112684. int sy=(dy<0?base-1:base+1);
  112685. int x=x0;
  112686. int y=y0;
  112687. int err=0;
  112688. int val=vorbis_dBquant(mask+x);
  112689. int mse=0;
  112690. int n=0;
  112691. ady-=abs(base*adx);
  112692. mse=(y-val);
  112693. mse*=mse;
  112694. n++;
  112695. if(mdct[x]+info->twofitatten>=mask[x]){
  112696. if(y+info->maxover<val)return(1);
  112697. if(y-info->maxunder>val)return(1);
  112698. }
  112699. while(++x<x1){
  112700. err=err+ady;
  112701. if(err>=adx){
  112702. err-=adx;
  112703. y+=sy;
  112704. }else{
  112705. y+=base;
  112706. }
  112707. val=vorbis_dBquant(mask+x);
  112708. mse+=((y-val)*(y-val));
  112709. n++;
  112710. if(mdct[x]+info->twofitatten>=mask[x]){
  112711. if(val){
  112712. if(y+info->maxover<val)return(1);
  112713. if(y-info->maxunder>val)return(1);
  112714. }
  112715. }
  112716. }
  112717. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112718. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112719. if(mse/n>info->maxerr)return(1);
  112720. return(0);
  112721. }
  112722. static int post_Y(int *A,int *B,int pos){
  112723. if(A[pos]<0)
  112724. return B[pos];
  112725. if(B[pos]<0)
  112726. return A[pos];
  112727. return (A[pos]+B[pos])>>1;
  112728. }
  112729. int *floor1_fit(vorbis_block *vb,void *look_,
  112730. const float *logmdct, /* in */
  112731. const float *logmask){
  112732. long i,j;
  112733. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112734. vorbis_info_floor1 *info=look->vi;
  112735. long n=look->n;
  112736. long posts=look->posts;
  112737. long nonzero=0;
  112738. lsfit_acc fits[VIF_POSIT+1];
  112739. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112740. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112741. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112742. int hineighbor[VIF_POSIT+2];
  112743. int *output=NULL;
  112744. int memo[VIF_POSIT+2];
  112745. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112746. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112747. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112748. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112749. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112750. /* quantize the relevant floor points and collect them into line fit
  112751. structures (one per minimal division) at the same time */
  112752. if(posts==0){
  112753. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112754. }else{
  112755. for(i=0;i<posts-1;i++)
  112756. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112757. look->sorted_index[i+1],fits+i,
  112758. n,info);
  112759. }
  112760. if(nonzero){
  112761. /* start by fitting the implicit base case.... */
  112762. int y0=-200;
  112763. int y1=-200;
  112764. fit_line(fits,posts-1,&y0,&y1);
  112765. fit_valueA[0]=y0;
  112766. fit_valueB[0]=y0;
  112767. fit_valueB[1]=y1;
  112768. fit_valueA[1]=y1;
  112769. /* Non degenerate case */
  112770. /* start progressive splitting. This is a greedy, non-optimal
  112771. algorithm, but simple and close enough to the best
  112772. answer. */
  112773. for(i=2;i<posts;i++){
  112774. int sortpos=look->reverse_index[i];
  112775. int ln=loneighbor[sortpos];
  112776. int hn=hineighbor[sortpos];
  112777. /* eliminate repeat searches of a particular range with a memo */
  112778. if(memo[ln]!=hn){
  112779. /* haven't performed this error search yet */
  112780. int lsortpos=look->reverse_index[ln];
  112781. int hsortpos=look->reverse_index[hn];
  112782. memo[ln]=hn;
  112783. {
  112784. /* A note: we want to bound/minimize *local*, not global, error */
  112785. int lx=info->postlist[ln];
  112786. int hx=info->postlist[hn];
  112787. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112788. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112789. if(ly==-1 || hy==-1){
  112790. exit(1);
  112791. }
  112792. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112793. /* outside error bounds/begin search area. Split it. */
  112794. int ly0=-200;
  112795. int ly1=-200;
  112796. int hy0=-200;
  112797. int hy1=-200;
  112798. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112799. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112800. /* store new edge values */
  112801. fit_valueB[ln]=ly0;
  112802. if(ln==0)fit_valueA[ln]=ly0;
  112803. fit_valueA[i]=ly1;
  112804. fit_valueB[i]=hy0;
  112805. fit_valueA[hn]=hy1;
  112806. if(hn==1)fit_valueB[hn]=hy1;
  112807. if(ly1>=0 || hy0>=0){
  112808. /* store new neighbor values */
  112809. for(j=sortpos-1;j>=0;j--)
  112810. if(hineighbor[j]==hn)
  112811. hineighbor[j]=i;
  112812. else
  112813. break;
  112814. for(j=sortpos+1;j<posts;j++)
  112815. if(loneighbor[j]==ln)
  112816. loneighbor[j]=i;
  112817. else
  112818. break;
  112819. }
  112820. }else{
  112821. fit_valueA[i]=-200;
  112822. fit_valueB[i]=-200;
  112823. }
  112824. }
  112825. }
  112826. }
  112827. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112828. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112829. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112830. /* fill in posts marked as not using a fit; we will zero
  112831. back out to 'unused' when encoding them so long as curve
  112832. interpolation doesn't force them into use */
  112833. for(i=2;i<posts;i++){
  112834. int ln=look->loneighbor[i-2];
  112835. int hn=look->hineighbor[i-2];
  112836. int x0=info->postlist[ln];
  112837. int x1=info->postlist[hn];
  112838. int y0=output[ln];
  112839. int y1=output[hn];
  112840. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112841. int vx=post_Y(fit_valueA,fit_valueB,i);
  112842. if(vx>=0 && predicted!=vx){
  112843. output[i]=vx;
  112844. }else{
  112845. output[i]= predicted|0x8000;
  112846. }
  112847. }
  112848. }
  112849. return(output);
  112850. }
  112851. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112852. int *A,int *B,
  112853. int del){
  112854. long i;
  112855. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112856. long posts=look->posts;
  112857. int *output=NULL;
  112858. if(A && B){
  112859. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112860. for(i=0;i<posts;i++){
  112861. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112862. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112863. }
  112864. }
  112865. return(output);
  112866. }
  112867. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112868. void*look_,
  112869. int *post,int *ilogmask){
  112870. long i,j;
  112871. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112872. vorbis_info_floor1 *info=look->vi;
  112873. long posts=look->posts;
  112874. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112875. int out[VIF_POSIT+2];
  112876. static_codebook **sbooks=ci->book_param;
  112877. codebook *books=ci->fullbooks;
  112878. static long seq=0;
  112879. /* quantize values to multiplier spec */
  112880. if(post){
  112881. for(i=0;i<posts;i++){
  112882. int val=post[i]&0x7fff;
  112883. switch(info->mult){
  112884. case 1: /* 1024 -> 256 */
  112885. val>>=2;
  112886. break;
  112887. case 2: /* 1024 -> 128 */
  112888. val>>=3;
  112889. break;
  112890. case 3: /* 1024 -> 86 */
  112891. val/=12;
  112892. break;
  112893. case 4: /* 1024 -> 64 */
  112894. val>>=4;
  112895. break;
  112896. }
  112897. post[i]=val | (post[i]&0x8000);
  112898. }
  112899. out[0]=post[0];
  112900. out[1]=post[1];
  112901. /* find prediction values for each post and subtract them */
  112902. for(i=2;i<posts;i++){
  112903. int ln=look->loneighbor[i-2];
  112904. int hn=look->hineighbor[i-2];
  112905. int x0=info->postlist[ln];
  112906. int x1=info->postlist[hn];
  112907. int y0=post[ln];
  112908. int y1=post[hn];
  112909. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112910. if((post[i]&0x8000) || (predicted==post[i])){
  112911. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112912. in interpolation */
  112913. out[i]=0;
  112914. }else{
  112915. int headroom=(look->quant_q-predicted<predicted?
  112916. look->quant_q-predicted:predicted);
  112917. int val=post[i]-predicted;
  112918. /* at this point the 'deviation' value is in the range +/- max
  112919. range, but the real, unique range can always be mapped to
  112920. only [0-maxrange). So we want to wrap the deviation into
  112921. this limited range, but do it in the way that least screws
  112922. an essentially gaussian probability distribution. */
  112923. if(val<0)
  112924. if(val<-headroom)
  112925. val=headroom-val-1;
  112926. else
  112927. val=-1-(val<<1);
  112928. else
  112929. if(val>=headroom)
  112930. val= val+headroom;
  112931. else
  112932. val<<=1;
  112933. out[i]=val;
  112934. post[ln]&=0x7fff;
  112935. post[hn]&=0x7fff;
  112936. }
  112937. }
  112938. /* we have everything we need. pack it out */
  112939. /* mark nontrivial floor */
  112940. oggpack_write(opb,1,1);
  112941. /* beginning/end post */
  112942. look->frames++;
  112943. look->postbits+=ilog(look->quant_q-1)*2;
  112944. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112945. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112946. /* partition by partition */
  112947. for(i=0,j=2;i<info->partitions;i++){
  112948. int classx=info->partitionclass[i];
  112949. int cdim=info->class_dim[classx];
  112950. int csubbits=info->class_subs[classx];
  112951. int csub=1<<csubbits;
  112952. int bookas[8]={0,0,0,0,0,0,0,0};
  112953. int cval=0;
  112954. int cshift=0;
  112955. int k,l;
  112956. /* generate the partition's first stage cascade value */
  112957. if(csubbits){
  112958. int maxval[8];
  112959. for(k=0;k<csub;k++){
  112960. int booknum=info->class_subbook[classx][k];
  112961. if(booknum<0){
  112962. maxval[k]=1;
  112963. }else{
  112964. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112965. }
  112966. }
  112967. for(k=0;k<cdim;k++){
  112968. for(l=0;l<csub;l++){
  112969. int val=out[j+k];
  112970. if(val<maxval[l]){
  112971. bookas[k]=l;
  112972. break;
  112973. }
  112974. }
  112975. cval|= bookas[k]<<cshift;
  112976. cshift+=csubbits;
  112977. }
  112978. /* write it */
  112979. look->phrasebits+=
  112980. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112981. #ifdef TRAIN_FLOOR1
  112982. {
  112983. FILE *of;
  112984. char buffer[80];
  112985. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112986. vb->pcmend/2,posts-2,class);
  112987. of=fopen(buffer,"a");
  112988. fprintf(of,"%d\n",cval);
  112989. fclose(of);
  112990. }
  112991. #endif
  112992. }
  112993. /* write post values */
  112994. for(k=0;k<cdim;k++){
  112995. int book=info->class_subbook[classx][bookas[k]];
  112996. if(book>=0){
  112997. /* hack to allow training with 'bad' books */
  112998. if(out[j+k]<(books+book)->entries)
  112999. look->postbits+=vorbis_book_encode(books+book,
  113000. out[j+k],opb);
  113001. /*else
  113002. fprintf(stderr,"+!");*/
  113003. #ifdef TRAIN_FLOOR1
  113004. {
  113005. FILE *of;
  113006. char buffer[80];
  113007. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113008. vb->pcmend/2,posts-2,class,bookas[k]);
  113009. of=fopen(buffer,"a");
  113010. fprintf(of,"%d\n",out[j+k]);
  113011. fclose(of);
  113012. }
  113013. #endif
  113014. }
  113015. }
  113016. j+=cdim;
  113017. }
  113018. {
  113019. /* generate quantized floor equivalent to what we'd unpack in decode */
  113020. /* render the lines */
  113021. int hx=0;
  113022. int lx=0;
  113023. int ly=post[0]*info->mult;
  113024. for(j=1;j<look->posts;j++){
  113025. int current=look->forward_index[j];
  113026. int hy=post[current]&0x7fff;
  113027. if(hy==post[current]){
  113028. hy*=info->mult;
  113029. hx=info->postlist[current];
  113030. render_line0(lx,hx,ly,hy,ilogmask);
  113031. lx=hx;
  113032. ly=hy;
  113033. }
  113034. }
  113035. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113036. seq++;
  113037. return(1);
  113038. }
  113039. }else{
  113040. oggpack_write(opb,0,1);
  113041. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113042. seq++;
  113043. return(0);
  113044. }
  113045. }
  113046. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113047. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113048. vorbis_info_floor1 *info=look->vi;
  113049. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113050. int i,j,k;
  113051. codebook *books=ci->fullbooks;
  113052. /* unpack wrapped/predicted values from stream */
  113053. if(oggpack_read(&vb->opb,1)==1){
  113054. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113055. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113056. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113057. /* partition by partition */
  113058. for(i=0,j=2;i<info->partitions;i++){
  113059. int classx=info->partitionclass[i];
  113060. int cdim=info->class_dim[classx];
  113061. int csubbits=info->class_subs[classx];
  113062. int csub=1<<csubbits;
  113063. int cval=0;
  113064. /* decode the partition's first stage cascade value */
  113065. if(csubbits){
  113066. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113067. if(cval==-1)goto eop;
  113068. }
  113069. for(k=0;k<cdim;k++){
  113070. int book=info->class_subbook[classx][cval&(csub-1)];
  113071. cval>>=csubbits;
  113072. if(book>=0){
  113073. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113074. goto eop;
  113075. }else{
  113076. fit_value[j+k]=0;
  113077. }
  113078. }
  113079. j+=cdim;
  113080. }
  113081. /* unwrap positive values and reconsitute via linear interpolation */
  113082. for(i=2;i<look->posts;i++){
  113083. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113084. info->postlist[look->hineighbor[i-2]],
  113085. fit_value[look->loneighbor[i-2]],
  113086. fit_value[look->hineighbor[i-2]],
  113087. info->postlist[i]);
  113088. int hiroom=look->quant_q-predicted;
  113089. int loroom=predicted;
  113090. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113091. int val=fit_value[i];
  113092. if(val){
  113093. if(val>=room){
  113094. if(hiroom>loroom){
  113095. val = val-loroom;
  113096. }else{
  113097. val = -1-(val-hiroom);
  113098. }
  113099. }else{
  113100. if(val&1){
  113101. val= -((val+1)>>1);
  113102. }else{
  113103. val>>=1;
  113104. }
  113105. }
  113106. fit_value[i]=val+predicted;
  113107. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113108. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113109. }else{
  113110. fit_value[i]=predicted|0x8000;
  113111. }
  113112. }
  113113. return(fit_value);
  113114. }
  113115. eop:
  113116. return(NULL);
  113117. }
  113118. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113119. float *out){
  113120. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113121. vorbis_info_floor1 *info=look->vi;
  113122. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113123. int n=ci->blocksizes[vb->W]/2;
  113124. int j;
  113125. if(memo){
  113126. /* render the lines */
  113127. int *fit_value=(int *)memo;
  113128. int hx=0;
  113129. int lx=0;
  113130. int ly=fit_value[0]*info->mult;
  113131. for(j=1;j<look->posts;j++){
  113132. int current=look->forward_index[j];
  113133. int hy=fit_value[current]&0x7fff;
  113134. if(hy==fit_value[current]){
  113135. hy*=info->mult;
  113136. hx=info->postlist[current];
  113137. render_line(lx,hx,ly,hy,out);
  113138. lx=hx;
  113139. ly=hy;
  113140. }
  113141. }
  113142. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113143. return(1);
  113144. }
  113145. memset(out,0,sizeof(*out)*n);
  113146. return(0);
  113147. }
  113148. /* export hooks */
  113149. vorbis_func_floor floor1_exportbundle={
  113150. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113151. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113152. };
  113153. #endif
  113154. /*** End of inlined file: floor1.c ***/
  113155. /*** Start of inlined file: info.c ***/
  113156. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113157. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113158. // tasks..
  113159. #if JUCE_MSVC
  113160. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113161. #endif
  113162. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113163. #if JUCE_USE_OGGVORBIS
  113164. /* general handling of the header and the vorbis_info structure (and
  113165. substructures) */
  113166. #include <stdlib.h>
  113167. #include <string.h>
  113168. #include <ctype.h>
  113169. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113170. while(bytes--){
  113171. oggpack_write(o,*s++,8);
  113172. }
  113173. }
  113174. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113175. while(bytes--){
  113176. *buf++=oggpack_read(o,8);
  113177. }
  113178. }
  113179. void vorbis_comment_init(vorbis_comment *vc){
  113180. memset(vc,0,sizeof(*vc));
  113181. }
  113182. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113183. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113184. (vc->comments+2)*sizeof(*vc->user_comments));
  113185. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113186. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113187. vc->comment_lengths[vc->comments]=strlen(comment);
  113188. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113189. strcpy(vc->user_comments[vc->comments], comment);
  113190. vc->comments++;
  113191. vc->user_comments[vc->comments]=NULL;
  113192. }
  113193. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113194. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113195. strcpy(comment, tag);
  113196. strcat(comment, "=");
  113197. strcat(comment, contents);
  113198. vorbis_comment_add(vc, comment);
  113199. }
  113200. /* This is more or less the same as strncasecmp - but that doesn't exist
  113201. * everywhere, and this is a fairly trivial function, so we include it */
  113202. static int tagcompare(const char *s1, const char *s2, int n){
  113203. int c=0;
  113204. while(c < n){
  113205. if(toupper(s1[c]) != toupper(s2[c]))
  113206. return !0;
  113207. c++;
  113208. }
  113209. return 0;
  113210. }
  113211. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113212. long i;
  113213. int found = 0;
  113214. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113215. char *fulltag = (char*)alloca(taglen+ 1);
  113216. strcpy(fulltag, tag);
  113217. strcat(fulltag, "=");
  113218. for(i=0;i<vc->comments;i++){
  113219. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113220. if(count == found)
  113221. /* We return a pointer to the data, not a copy */
  113222. return vc->user_comments[i] + taglen;
  113223. else
  113224. found++;
  113225. }
  113226. }
  113227. return NULL; /* didn't find anything */
  113228. }
  113229. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113230. int i,count=0;
  113231. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113232. char *fulltag = (char*)alloca(taglen+1);
  113233. strcpy(fulltag,tag);
  113234. strcat(fulltag, "=");
  113235. for(i=0;i<vc->comments;i++){
  113236. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113237. count++;
  113238. }
  113239. return count;
  113240. }
  113241. void vorbis_comment_clear(vorbis_comment *vc){
  113242. if(vc){
  113243. long i;
  113244. for(i=0;i<vc->comments;i++)
  113245. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113246. if(vc->user_comments)_ogg_free(vc->user_comments);
  113247. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113248. if(vc->vendor)_ogg_free(vc->vendor);
  113249. }
  113250. memset(vc,0,sizeof(*vc));
  113251. }
  113252. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113253. They may be equal, but short will never ge greater than long */
  113254. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113255. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113256. return ci ? ci->blocksizes[zo] : -1;
  113257. }
  113258. /* used by synthesis, which has a full, alloced vi */
  113259. void vorbis_info_init(vorbis_info *vi){
  113260. memset(vi,0,sizeof(*vi));
  113261. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113262. }
  113263. void vorbis_info_clear(vorbis_info *vi){
  113264. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113265. int i;
  113266. if(ci){
  113267. for(i=0;i<ci->modes;i++)
  113268. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113269. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113270. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113271. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113272. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113273. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113274. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113275. for(i=0;i<ci->books;i++){
  113276. if(ci->book_param[i]){
  113277. /* knows if the book was not alloced */
  113278. vorbis_staticbook_destroy(ci->book_param[i]);
  113279. }
  113280. if(ci->fullbooks)
  113281. vorbis_book_clear(ci->fullbooks+i);
  113282. }
  113283. if(ci->fullbooks)
  113284. _ogg_free(ci->fullbooks);
  113285. for(i=0;i<ci->psys;i++)
  113286. _vi_psy_free(ci->psy_param[i]);
  113287. _ogg_free(ci);
  113288. }
  113289. memset(vi,0,sizeof(*vi));
  113290. }
  113291. /* Header packing/unpacking ********************************************/
  113292. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113293. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113294. if(!ci)return(OV_EFAULT);
  113295. vi->version=oggpack_read(opb,32);
  113296. if(vi->version!=0)return(OV_EVERSION);
  113297. vi->channels=oggpack_read(opb,8);
  113298. vi->rate=oggpack_read(opb,32);
  113299. vi->bitrate_upper=oggpack_read(opb,32);
  113300. vi->bitrate_nominal=oggpack_read(opb,32);
  113301. vi->bitrate_lower=oggpack_read(opb,32);
  113302. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113303. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113304. if(vi->rate<1)goto err_out;
  113305. if(vi->channels<1)goto err_out;
  113306. if(ci->blocksizes[0]<8)goto err_out;
  113307. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113308. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113309. return(0);
  113310. err_out:
  113311. vorbis_info_clear(vi);
  113312. return(OV_EBADHEADER);
  113313. }
  113314. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113315. int i;
  113316. int vendorlen=oggpack_read(opb,32);
  113317. if(vendorlen<0)goto err_out;
  113318. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113319. _v_readstring(opb,vc->vendor,vendorlen);
  113320. vc->comments=oggpack_read(opb,32);
  113321. if(vc->comments<0)goto err_out;
  113322. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113323. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113324. for(i=0;i<vc->comments;i++){
  113325. int len=oggpack_read(opb,32);
  113326. if(len<0)goto err_out;
  113327. vc->comment_lengths[i]=len;
  113328. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113329. _v_readstring(opb,vc->user_comments[i],len);
  113330. }
  113331. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113332. return(0);
  113333. err_out:
  113334. vorbis_comment_clear(vc);
  113335. return(OV_EBADHEADER);
  113336. }
  113337. /* all of the real encoding details are here. The modes, books,
  113338. everything */
  113339. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113340. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113341. int i;
  113342. if(!ci)return(OV_EFAULT);
  113343. /* codebooks */
  113344. ci->books=oggpack_read(opb,8)+1;
  113345. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113346. for(i=0;i<ci->books;i++){
  113347. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113348. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113349. }
  113350. /* time backend settings; hooks are unused */
  113351. {
  113352. int times=oggpack_read(opb,6)+1;
  113353. for(i=0;i<times;i++){
  113354. int test=oggpack_read(opb,16);
  113355. if(test<0 || test>=VI_TIMEB)goto err_out;
  113356. }
  113357. }
  113358. /* floor backend settings */
  113359. ci->floors=oggpack_read(opb,6)+1;
  113360. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113361. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113362. for(i=0;i<ci->floors;i++){
  113363. ci->floor_type[i]=oggpack_read(opb,16);
  113364. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113365. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113366. if(!ci->floor_param[i])goto err_out;
  113367. }
  113368. /* residue backend settings */
  113369. ci->residues=oggpack_read(opb,6)+1;
  113370. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113371. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113372. for(i=0;i<ci->residues;i++){
  113373. ci->residue_type[i]=oggpack_read(opb,16);
  113374. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113375. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113376. if(!ci->residue_param[i])goto err_out;
  113377. }
  113378. /* map backend settings */
  113379. ci->maps=oggpack_read(opb,6)+1;
  113380. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113381. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113382. for(i=0;i<ci->maps;i++){
  113383. ci->map_type[i]=oggpack_read(opb,16);
  113384. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113385. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113386. if(!ci->map_param[i])goto err_out;
  113387. }
  113388. /* mode settings */
  113389. ci->modes=oggpack_read(opb,6)+1;
  113390. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113391. for(i=0;i<ci->modes;i++){
  113392. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113393. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113394. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113395. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113396. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113397. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113398. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113399. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113400. }
  113401. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113402. return(0);
  113403. err_out:
  113404. vorbis_info_clear(vi);
  113405. return(OV_EBADHEADER);
  113406. }
  113407. /* The Vorbis header is in three packets; the initial small packet in
  113408. the first page that identifies basic parameters, a second packet
  113409. with bitstream comments and a third packet that holds the
  113410. codebook. */
  113411. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113412. oggpack_buffer opb;
  113413. if(op){
  113414. oggpack_readinit(&opb,op->packet,op->bytes);
  113415. /* Which of the three types of header is this? */
  113416. /* Also verify header-ness, vorbis */
  113417. {
  113418. char buffer[6];
  113419. int packtype=oggpack_read(&opb,8);
  113420. memset(buffer,0,6);
  113421. _v_readstring(&opb,buffer,6);
  113422. if(memcmp(buffer,"vorbis",6)){
  113423. /* not a vorbis header */
  113424. return(OV_ENOTVORBIS);
  113425. }
  113426. switch(packtype){
  113427. case 0x01: /* least significant *bit* is read first */
  113428. if(!op->b_o_s){
  113429. /* Not the initial packet */
  113430. return(OV_EBADHEADER);
  113431. }
  113432. if(vi->rate!=0){
  113433. /* previously initialized info header */
  113434. return(OV_EBADHEADER);
  113435. }
  113436. return(_vorbis_unpack_info(vi,&opb));
  113437. case 0x03: /* least significant *bit* is read first */
  113438. if(vi->rate==0){
  113439. /* um... we didn't get the initial header */
  113440. return(OV_EBADHEADER);
  113441. }
  113442. return(_vorbis_unpack_comment(vc,&opb));
  113443. case 0x05: /* least significant *bit* is read first */
  113444. if(vi->rate==0 || vc->vendor==NULL){
  113445. /* um... we didn;t get the initial header or comments yet */
  113446. return(OV_EBADHEADER);
  113447. }
  113448. return(_vorbis_unpack_books(vi,&opb));
  113449. default:
  113450. /* Not a valid vorbis header type */
  113451. return(OV_EBADHEADER);
  113452. break;
  113453. }
  113454. }
  113455. }
  113456. return(OV_EBADHEADER);
  113457. }
  113458. /* pack side **********************************************************/
  113459. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113460. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113461. if(!ci)return(OV_EFAULT);
  113462. /* preamble */
  113463. oggpack_write(opb,0x01,8);
  113464. _v_writestring(opb,"vorbis", 6);
  113465. /* basic information about the stream */
  113466. oggpack_write(opb,0x00,32);
  113467. oggpack_write(opb,vi->channels,8);
  113468. oggpack_write(opb,vi->rate,32);
  113469. oggpack_write(opb,vi->bitrate_upper,32);
  113470. oggpack_write(opb,vi->bitrate_nominal,32);
  113471. oggpack_write(opb,vi->bitrate_lower,32);
  113472. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113473. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113474. oggpack_write(opb,1,1);
  113475. return(0);
  113476. }
  113477. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113478. char temp[]="Xiph.Org libVorbis I 20050304";
  113479. int bytes = strlen(temp);
  113480. /* preamble */
  113481. oggpack_write(opb,0x03,8);
  113482. _v_writestring(opb,"vorbis", 6);
  113483. /* vendor */
  113484. oggpack_write(opb,bytes,32);
  113485. _v_writestring(opb,temp, bytes);
  113486. /* comments */
  113487. oggpack_write(opb,vc->comments,32);
  113488. if(vc->comments){
  113489. int i;
  113490. for(i=0;i<vc->comments;i++){
  113491. if(vc->user_comments[i]){
  113492. oggpack_write(opb,vc->comment_lengths[i],32);
  113493. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113494. }else{
  113495. oggpack_write(opb,0,32);
  113496. }
  113497. }
  113498. }
  113499. oggpack_write(opb,1,1);
  113500. return(0);
  113501. }
  113502. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113503. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113504. int i;
  113505. if(!ci)return(OV_EFAULT);
  113506. oggpack_write(opb,0x05,8);
  113507. _v_writestring(opb,"vorbis", 6);
  113508. /* books */
  113509. oggpack_write(opb,ci->books-1,8);
  113510. for(i=0;i<ci->books;i++)
  113511. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113512. /* times; hook placeholders */
  113513. oggpack_write(opb,0,6);
  113514. oggpack_write(opb,0,16);
  113515. /* floors */
  113516. oggpack_write(opb,ci->floors-1,6);
  113517. for(i=0;i<ci->floors;i++){
  113518. oggpack_write(opb,ci->floor_type[i],16);
  113519. if(_floor_P[ci->floor_type[i]]->pack)
  113520. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113521. else
  113522. goto err_out;
  113523. }
  113524. /* residues */
  113525. oggpack_write(opb,ci->residues-1,6);
  113526. for(i=0;i<ci->residues;i++){
  113527. oggpack_write(opb,ci->residue_type[i],16);
  113528. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113529. }
  113530. /* maps */
  113531. oggpack_write(opb,ci->maps-1,6);
  113532. for(i=0;i<ci->maps;i++){
  113533. oggpack_write(opb,ci->map_type[i],16);
  113534. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113535. }
  113536. /* modes */
  113537. oggpack_write(opb,ci->modes-1,6);
  113538. for(i=0;i<ci->modes;i++){
  113539. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113540. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113541. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113542. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113543. }
  113544. oggpack_write(opb,1,1);
  113545. return(0);
  113546. err_out:
  113547. return(-1);
  113548. }
  113549. int vorbis_commentheader_out(vorbis_comment *vc,
  113550. ogg_packet *op){
  113551. oggpack_buffer opb;
  113552. oggpack_writeinit(&opb);
  113553. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113554. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113555. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113556. op->bytes=oggpack_bytes(&opb);
  113557. op->b_o_s=0;
  113558. op->e_o_s=0;
  113559. op->granulepos=0;
  113560. op->packetno=1;
  113561. return 0;
  113562. }
  113563. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113564. vorbis_comment *vc,
  113565. ogg_packet *op,
  113566. ogg_packet *op_comm,
  113567. ogg_packet *op_code){
  113568. int ret=OV_EIMPL;
  113569. vorbis_info *vi=v->vi;
  113570. oggpack_buffer opb;
  113571. private_state *b=(private_state*)v->backend_state;
  113572. if(!b){
  113573. ret=OV_EFAULT;
  113574. goto err_out;
  113575. }
  113576. /* first header packet **********************************************/
  113577. oggpack_writeinit(&opb);
  113578. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113579. /* build the packet */
  113580. if(b->header)_ogg_free(b->header);
  113581. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113582. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113583. op->packet=b->header;
  113584. op->bytes=oggpack_bytes(&opb);
  113585. op->b_o_s=1;
  113586. op->e_o_s=0;
  113587. op->granulepos=0;
  113588. op->packetno=0;
  113589. /* second header packet (comments) **********************************/
  113590. oggpack_reset(&opb);
  113591. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113592. if(b->header1)_ogg_free(b->header1);
  113593. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113594. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113595. op_comm->packet=b->header1;
  113596. op_comm->bytes=oggpack_bytes(&opb);
  113597. op_comm->b_o_s=0;
  113598. op_comm->e_o_s=0;
  113599. op_comm->granulepos=0;
  113600. op_comm->packetno=1;
  113601. /* third header packet (modes/codebooks) ****************************/
  113602. oggpack_reset(&opb);
  113603. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113604. if(b->header2)_ogg_free(b->header2);
  113605. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113606. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113607. op_code->packet=b->header2;
  113608. op_code->bytes=oggpack_bytes(&opb);
  113609. op_code->b_o_s=0;
  113610. op_code->e_o_s=0;
  113611. op_code->granulepos=0;
  113612. op_code->packetno=2;
  113613. oggpack_writeclear(&opb);
  113614. return(0);
  113615. err_out:
  113616. oggpack_writeclear(&opb);
  113617. memset(op,0,sizeof(*op));
  113618. memset(op_comm,0,sizeof(*op_comm));
  113619. memset(op_code,0,sizeof(*op_code));
  113620. if(b->header)_ogg_free(b->header);
  113621. if(b->header1)_ogg_free(b->header1);
  113622. if(b->header2)_ogg_free(b->header2);
  113623. b->header=NULL;
  113624. b->header1=NULL;
  113625. b->header2=NULL;
  113626. return(ret);
  113627. }
  113628. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113629. if(granulepos>=0)
  113630. return((double)granulepos/v->vi->rate);
  113631. return(-1);
  113632. }
  113633. #endif
  113634. /*** End of inlined file: info.c ***/
  113635. /*** Start of inlined file: lpc.c ***/
  113636. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113637. are derived from code written by Jutta Degener and Carsten Bormann;
  113638. thus we include their copyright below. The entirety of this file
  113639. is freely redistributable on the condition that both of these
  113640. copyright notices are preserved without modification. */
  113641. /* Preserved Copyright: *********************************************/
  113642. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113643. Technische Universita"t Berlin
  113644. Any use of this software is permitted provided that this notice is not
  113645. removed and that neither the authors nor the Technische Universita"t
  113646. Berlin are deemed to have made any representations as to the
  113647. suitability of this software for any purpose nor are held responsible
  113648. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113649. THIS SOFTWARE.
  113650. As a matter of courtesy, the authors request to be informed about uses
  113651. this software has found, about bugs in this software, and about any
  113652. improvements that may be of general interest.
  113653. Berlin, 28.11.1994
  113654. Jutta Degener
  113655. Carsten Bormann
  113656. *********************************************************************/
  113657. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113658. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113659. // tasks..
  113660. #if JUCE_MSVC
  113661. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113662. #endif
  113663. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113664. #if JUCE_USE_OGGVORBIS
  113665. #include <stdlib.h>
  113666. #include <string.h>
  113667. #include <math.h>
  113668. /* Autocorrelation LPC coeff generation algorithm invented by
  113669. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113670. /* Input : n elements of time doamin data
  113671. Output: m lpc coefficients, excitation energy */
  113672. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113673. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113674. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113675. double error;
  113676. int i,j;
  113677. /* autocorrelation, p+1 lag coefficients */
  113678. j=m+1;
  113679. while(j--){
  113680. double d=0; /* double needed for accumulator depth */
  113681. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113682. aut[j]=d;
  113683. }
  113684. /* Generate lpc coefficients from autocorr values */
  113685. error=aut[0];
  113686. for(i=0;i<m;i++){
  113687. double r= -aut[i+1];
  113688. if(error==0){
  113689. memset(lpci,0,m*sizeof(*lpci));
  113690. return 0;
  113691. }
  113692. /* Sum up this iteration's reflection coefficient; note that in
  113693. Vorbis we don't save it. If anyone wants to recycle this code
  113694. and needs reflection coefficients, save the results of 'r' from
  113695. each iteration. */
  113696. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113697. r/=error;
  113698. /* Update LPC coefficients and total error */
  113699. lpc[i]=r;
  113700. for(j=0;j<i/2;j++){
  113701. double tmp=lpc[j];
  113702. lpc[j]+=r*lpc[i-1-j];
  113703. lpc[i-1-j]+=r*tmp;
  113704. }
  113705. if(i%2)lpc[j]+=lpc[j]*r;
  113706. error*=1.f-r*r;
  113707. }
  113708. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113709. /* we need the error value to know how big an impulse to hit the
  113710. filter with later */
  113711. return error;
  113712. }
  113713. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113714. float *data,long n){
  113715. /* in: coeff[0...m-1] LPC coefficients
  113716. prime[0...m-1] initial values (allocated size of n+m-1)
  113717. out: data[0...n-1] data samples */
  113718. long i,j,o,p;
  113719. float y;
  113720. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113721. if(!prime)
  113722. for(i=0;i<m;i++)
  113723. work[i]=0.f;
  113724. else
  113725. for(i=0;i<m;i++)
  113726. work[i]=prime[i];
  113727. for(i=0;i<n;i++){
  113728. y=0;
  113729. o=i;
  113730. p=m;
  113731. for(j=0;j<m;j++)
  113732. y-=work[o++]*coeff[--p];
  113733. data[i]=work[o]=y;
  113734. }
  113735. }
  113736. #endif
  113737. /*** End of inlined file: lpc.c ***/
  113738. /*** Start of inlined file: lsp.c ***/
  113739. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113740. an iterative root polisher (CACM algorithm 283). It *is* possible
  113741. to confuse this algorithm into not converging; that should only
  113742. happen with absurdly closely spaced roots (very sharp peaks in the
  113743. LPC f response) which in turn should be impossible in our use of
  113744. the code. If this *does* happen anyway, it's a bug in the floor
  113745. finder; find the cause of the confusion (probably a single bin
  113746. spike or accidental near-float-limit resolution problems) and
  113747. correct it. */
  113748. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113749. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113750. // tasks..
  113751. #if JUCE_MSVC
  113752. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113753. #endif
  113754. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113755. #if JUCE_USE_OGGVORBIS
  113756. #include <math.h>
  113757. #include <string.h>
  113758. #include <stdlib.h>
  113759. /*** Start of inlined file: lookup.h ***/
  113760. #ifndef _V_LOOKUP_H_
  113761. #ifdef FLOAT_LOOKUP
  113762. extern float vorbis_coslook(float a);
  113763. extern float vorbis_invsqlook(float a);
  113764. extern float vorbis_invsq2explook(int a);
  113765. extern float vorbis_fromdBlook(float a);
  113766. #endif
  113767. #ifdef INT_LOOKUP
  113768. extern long vorbis_invsqlook_i(long a,long e);
  113769. extern long vorbis_coslook_i(long a);
  113770. extern float vorbis_fromdBlook_i(long a);
  113771. #endif
  113772. #endif
  113773. /*** End of inlined file: lookup.h ***/
  113774. /* three possible LSP to f curve functions; the exact computation
  113775. (float), a lookup based float implementation, and an integer
  113776. implementation. The float lookup is likely the optimal choice on
  113777. any machine with an FPU. The integer implementation is *not* fixed
  113778. point (due to the need for a large dynamic range and thus a
  113779. seperately tracked exponent) and thus much more complex than the
  113780. relatively simple float implementations. It's mostly for future
  113781. work on a fully fixed point implementation for processors like the
  113782. ARM family. */
  113783. /* undefine both for the 'old' but more precise implementation */
  113784. #define FLOAT_LOOKUP
  113785. #undef INT_LOOKUP
  113786. #ifdef FLOAT_LOOKUP
  113787. /*** Start of inlined file: lookup.c ***/
  113788. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113789. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113790. // tasks..
  113791. #if JUCE_MSVC
  113792. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113793. #endif
  113794. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113795. #if JUCE_USE_OGGVORBIS
  113796. #include <math.h>
  113797. /*** Start of inlined file: lookup.h ***/
  113798. #ifndef _V_LOOKUP_H_
  113799. #ifdef FLOAT_LOOKUP
  113800. extern float vorbis_coslook(float a);
  113801. extern float vorbis_invsqlook(float a);
  113802. extern float vorbis_invsq2explook(int a);
  113803. extern float vorbis_fromdBlook(float a);
  113804. #endif
  113805. #ifdef INT_LOOKUP
  113806. extern long vorbis_invsqlook_i(long a,long e);
  113807. extern long vorbis_coslook_i(long a);
  113808. extern float vorbis_fromdBlook_i(long a);
  113809. #endif
  113810. #endif
  113811. /*** End of inlined file: lookup.h ***/
  113812. /*** Start of inlined file: lookup_data.h ***/
  113813. #ifndef _V_LOOKUP_DATA_H_
  113814. #ifdef FLOAT_LOOKUP
  113815. #define COS_LOOKUP_SZ 128
  113816. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113817. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113818. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113819. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113820. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113821. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113822. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113823. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113824. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113825. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113826. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113827. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113828. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113829. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113830. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113831. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113832. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113833. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113834. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113835. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113836. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113837. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113838. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113839. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113840. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113841. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113842. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113843. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113844. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113845. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113846. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113847. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113848. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113849. -1.0000000000000f,
  113850. };
  113851. #define INVSQ_LOOKUP_SZ 32
  113852. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113853. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113854. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113855. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113856. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113857. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113858. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113859. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113860. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113861. 1.000000000000f,
  113862. };
  113863. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113864. #define INVSQ2EXP_LOOKUP_MAX 32
  113865. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113866. INVSQ2EXP_LOOKUP_MIN+1]={
  113867. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113868. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113869. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113870. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113871. 256.f, 181.019336f, 128.f, 90.50966799f,
  113872. 64.f, 45.254834f, 32.f, 22.627417f,
  113873. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113874. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113875. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113876. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113877. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113878. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113879. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113880. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113881. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113882. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113883. 1.525878906e-05f,
  113884. };
  113885. #endif
  113886. #define FROMdB_LOOKUP_SZ 35
  113887. #define FROMdB2_LOOKUP_SZ 32
  113888. #define FROMdB_SHIFT 5
  113889. #define FROMdB2_SHIFT 3
  113890. #define FROMdB2_MASK 31
  113891. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113892. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113893. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113894. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113895. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113896. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113897. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113898. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113899. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113900. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113901. };
  113902. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113903. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113904. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113905. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113906. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113907. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113908. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113909. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113910. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113911. };
  113912. #ifdef INT_LOOKUP
  113913. #define INVSQ_LOOKUP_I_SHIFT 10
  113914. #define INVSQ_LOOKUP_I_MASK 1023
  113915. static long INVSQ_LOOKUP_I[64+1]={
  113916. 92682l, 91966l, 91267l, 90583l,
  113917. 89915l, 89261l, 88621l, 87995l,
  113918. 87381l, 86781l, 86192l, 85616l,
  113919. 85051l, 84497l, 83953l, 83420l,
  113920. 82897l, 82384l, 81880l, 81385l,
  113921. 80899l, 80422l, 79953l, 79492l,
  113922. 79039l, 78594l, 78156l, 77726l,
  113923. 77302l, 76885l, 76475l, 76072l,
  113924. 75674l, 75283l, 74898l, 74519l,
  113925. 74146l, 73778l, 73415l, 73058l,
  113926. 72706l, 72359l, 72016l, 71679l,
  113927. 71347l, 71019l, 70695l, 70376l,
  113928. 70061l, 69750l, 69444l, 69141l,
  113929. 68842l, 68548l, 68256l, 67969l,
  113930. 67685l, 67405l, 67128l, 66855l,
  113931. 66585l, 66318l, 66054l, 65794l,
  113932. 65536l,
  113933. };
  113934. #define COS_LOOKUP_I_SHIFT 9
  113935. #define COS_LOOKUP_I_MASK 511
  113936. #define COS_LOOKUP_I_SZ 128
  113937. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113938. 16384l, 16379l, 16364l, 16340l,
  113939. 16305l, 16261l, 16207l, 16143l,
  113940. 16069l, 15986l, 15893l, 15791l,
  113941. 15679l, 15557l, 15426l, 15286l,
  113942. 15137l, 14978l, 14811l, 14635l,
  113943. 14449l, 14256l, 14053l, 13842l,
  113944. 13623l, 13395l, 13160l, 12916l,
  113945. 12665l, 12406l, 12140l, 11866l,
  113946. 11585l, 11297l, 11003l, 10702l,
  113947. 10394l, 10080l, 9760l, 9434l,
  113948. 9102l, 8765l, 8423l, 8076l,
  113949. 7723l, 7366l, 7005l, 6639l,
  113950. 6270l, 5897l, 5520l, 5139l,
  113951. 4756l, 4370l, 3981l, 3590l,
  113952. 3196l, 2801l, 2404l, 2006l,
  113953. 1606l, 1205l, 804l, 402l,
  113954. 0l, -401l, -803l, -1204l,
  113955. -1605l, -2005l, -2403l, -2800l,
  113956. -3195l, -3589l, -3980l, -4369l,
  113957. -4755l, -5138l, -5519l, -5896l,
  113958. -6269l, -6638l, -7004l, -7365l,
  113959. -7722l, -8075l, -8422l, -8764l,
  113960. -9101l, -9433l, -9759l, -10079l,
  113961. -10393l, -10701l, -11002l, -11296l,
  113962. -11584l, -11865l, -12139l, -12405l,
  113963. -12664l, -12915l, -13159l, -13394l,
  113964. -13622l, -13841l, -14052l, -14255l,
  113965. -14448l, -14634l, -14810l, -14977l,
  113966. -15136l, -15285l, -15425l, -15556l,
  113967. -15678l, -15790l, -15892l, -15985l,
  113968. -16068l, -16142l, -16206l, -16260l,
  113969. -16304l, -16339l, -16363l, -16378l,
  113970. -16383l,
  113971. };
  113972. #endif
  113973. #endif
  113974. /*** End of inlined file: lookup_data.h ***/
  113975. #ifdef FLOAT_LOOKUP
  113976. /* interpolated lookup based cos function, domain 0 to PI only */
  113977. float vorbis_coslook(float a){
  113978. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113979. int i=vorbis_ftoi(d-.5);
  113980. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113981. }
  113982. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113983. float vorbis_invsqlook(float a){
  113984. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113985. int i=vorbis_ftoi(d-.5f);
  113986. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113987. }
  113988. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113989. float vorbis_invsq2explook(int a){
  113990. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113991. }
  113992. #include <stdio.h>
  113993. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113994. float vorbis_fromdBlook(float a){
  113995. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113996. return (i<0)?1.f:
  113997. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113998. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113999. }
  114000. #endif
  114001. #ifdef INT_LOOKUP
  114002. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114003. 16.16 format
  114004. returns in m.8 format */
  114005. long vorbis_invsqlook_i(long a,long e){
  114006. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114007. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114008. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114009. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114010. d)>>16); /* result 1.16 */
  114011. e+=32;
  114012. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114013. e=(e>>1)-8;
  114014. return(val>>e);
  114015. }
  114016. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114017. /* a is in n.12 format */
  114018. float vorbis_fromdBlook_i(long a){
  114019. int i=(-a)>>(12-FROMdB2_SHIFT);
  114020. return (i<0)?1.f:
  114021. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114022. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114023. }
  114024. /* interpolated lookup based cos function, domain 0 to PI only */
  114025. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114026. long vorbis_coslook_i(long a){
  114027. int i=a>>COS_LOOKUP_I_SHIFT;
  114028. int d=a&COS_LOOKUP_I_MASK;
  114029. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114030. COS_LOOKUP_I_SHIFT);
  114031. }
  114032. #endif
  114033. #endif
  114034. /*** End of inlined file: lookup.c ***/
  114035. /* catch this in the build system; we #include for
  114036. compilers (like gcc) that can't inline across
  114037. modules */
  114038. /* side effect: changes *lsp to cosines of lsp */
  114039. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114040. float amp,float ampoffset){
  114041. int i;
  114042. float wdel=M_PI/ln;
  114043. vorbis_fpu_control fpu;
  114044. (void) fpu; // to avoid an unused variable warning
  114045. vorbis_fpu_setround(&fpu);
  114046. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114047. i=0;
  114048. while(i<n){
  114049. int k=map[i];
  114050. int qexp;
  114051. float p=.7071067812f;
  114052. float q=.7071067812f;
  114053. float w=vorbis_coslook(wdel*k);
  114054. float *ftmp=lsp;
  114055. int c=m>>1;
  114056. do{
  114057. q*=ftmp[0]-w;
  114058. p*=ftmp[1]-w;
  114059. ftmp+=2;
  114060. }while(--c);
  114061. if(m&1){
  114062. /* odd order filter; slightly assymetric */
  114063. /* the last coefficient */
  114064. q*=ftmp[0]-w;
  114065. q*=q;
  114066. p*=p*(1.f-w*w);
  114067. }else{
  114068. /* even order filter; still symmetric */
  114069. q*=q*(1.f+w);
  114070. p*=p*(1.f-w);
  114071. }
  114072. q=frexp(p+q,&qexp);
  114073. q=vorbis_fromdBlook(amp*
  114074. vorbis_invsqlook(q)*
  114075. vorbis_invsq2explook(qexp+m)-
  114076. ampoffset);
  114077. do{
  114078. curve[i++]*=q;
  114079. }while(map[i]==k);
  114080. }
  114081. vorbis_fpu_restore(fpu);
  114082. }
  114083. #else
  114084. #ifdef INT_LOOKUP
  114085. /*** Start of inlined file: lookup.c ***/
  114086. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114087. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114088. // tasks..
  114089. #if JUCE_MSVC
  114090. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114091. #endif
  114092. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114093. #if JUCE_USE_OGGVORBIS
  114094. #include <math.h>
  114095. /*** Start of inlined file: lookup.h ***/
  114096. #ifndef _V_LOOKUP_H_
  114097. #ifdef FLOAT_LOOKUP
  114098. extern float vorbis_coslook(float a);
  114099. extern float vorbis_invsqlook(float a);
  114100. extern float vorbis_invsq2explook(int a);
  114101. extern float vorbis_fromdBlook(float a);
  114102. #endif
  114103. #ifdef INT_LOOKUP
  114104. extern long vorbis_invsqlook_i(long a,long e);
  114105. extern long vorbis_coslook_i(long a);
  114106. extern float vorbis_fromdBlook_i(long a);
  114107. #endif
  114108. #endif
  114109. /*** End of inlined file: lookup.h ***/
  114110. /*** Start of inlined file: lookup_data.h ***/
  114111. #ifndef _V_LOOKUP_DATA_H_
  114112. #ifdef FLOAT_LOOKUP
  114113. #define COS_LOOKUP_SZ 128
  114114. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114115. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114116. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114117. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114118. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114119. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114120. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114121. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114122. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114123. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114124. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114125. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114126. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114127. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114128. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114129. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114130. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114131. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114132. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114133. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114134. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114135. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114136. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114137. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114138. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114139. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114140. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114141. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114142. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114143. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114144. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114145. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114146. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114147. -1.0000000000000f,
  114148. };
  114149. #define INVSQ_LOOKUP_SZ 32
  114150. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114151. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114152. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114153. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114154. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114155. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114156. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114157. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114158. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114159. 1.000000000000f,
  114160. };
  114161. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114162. #define INVSQ2EXP_LOOKUP_MAX 32
  114163. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114164. INVSQ2EXP_LOOKUP_MIN+1]={
  114165. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114166. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114167. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114168. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114169. 256.f, 181.019336f, 128.f, 90.50966799f,
  114170. 64.f, 45.254834f, 32.f, 22.627417f,
  114171. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114172. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114173. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114174. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114175. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114176. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114177. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114178. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114179. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114180. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114181. 1.525878906e-05f,
  114182. };
  114183. #endif
  114184. #define FROMdB_LOOKUP_SZ 35
  114185. #define FROMdB2_LOOKUP_SZ 32
  114186. #define FROMdB_SHIFT 5
  114187. #define FROMdB2_SHIFT 3
  114188. #define FROMdB2_MASK 31
  114189. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114190. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114191. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114192. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114193. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114194. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114195. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114196. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114197. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114198. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114199. };
  114200. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114201. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114202. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114203. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114204. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114205. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114206. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114207. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114208. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114209. };
  114210. #ifdef INT_LOOKUP
  114211. #define INVSQ_LOOKUP_I_SHIFT 10
  114212. #define INVSQ_LOOKUP_I_MASK 1023
  114213. static long INVSQ_LOOKUP_I[64+1]={
  114214. 92682l, 91966l, 91267l, 90583l,
  114215. 89915l, 89261l, 88621l, 87995l,
  114216. 87381l, 86781l, 86192l, 85616l,
  114217. 85051l, 84497l, 83953l, 83420l,
  114218. 82897l, 82384l, 81880l, 81385l,
  114219. 80899l, 80422l, 79953l, 79492l,
  114220. 79039l, 78594l, 78156l, 77726l,
  114221. 77302l, 76885l, 76475l, 76072l,
  114222. 75674l, 75283l, 74898l, 74519l,
  114223. 74146l, 73778l, 73415l, 73058l,
  114224. 72706l, 72359l, 72016l, 71679l,
  114225. 71347l, 71019l, 70695l, 70376l,
  114226. 70061l, 69750l, 69444l, 69141l,
  114227. 68842l, 68548l, 68256l, 67969l,
  114228. 67685l, 67405l, 67128l, 66855l,
  114229. 66585l, 66318l, 66054l, 65794l,
  114230. 65536l,
  114231. };
  114232. #define COS_LOOKUP_I_SHIFT 9
  114233. #define COS_LOOKUP_I_MASK 511
  114234. #define COS_LOOKUP_I_SZ 128
  114235. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114236. 16384l, 16379l, 16364l, 16340l,
  114237. 16305l, 16261l, 16207l, 16143l,
  114238. 16069l, 15986l, 15893l, 15791l,
  114239. 15679l, 15557l, 15426l, 15286l,
  114240. 15137l, 14978l, 14811l, 14635l,
  114241. 14449l, 14256l, 14053l, 13842l,
  114242. 13623l, 13395l, 13160l, 12916l,
  114243. 12665l, 12406l, 12140l, 11866l,
  114244. 11585l, 11297l, 11003l, 10702l,
  114245. 10394l, 10080l, 9760l, 9434l,
  114246. 9102l, 8765l, 8423l, 8076l,
  114247. 7723l, 7366l, 7005l, 6639l,
  114248. 6270l, 5897l, 5520l, 5139l,
  114249. 4756l, 4370l, 3981l, 3590l,
  114250. 3196l, 2801l, 2404l, 2006l,
  114251. 1606l, 1205l, 804l, 402l,
  114252. 0l, -401l, -803l, -1204l,
  114253. -1605l, -2005l, -2403l, -2800l,
  114254. -3195l, -3589l, -3980l, -4369l,
  114255. -4755l, -5138l, -5519l, -5896l,
  114256. -6269l, -6638l, -7004l, -7365l,
  114257. -7722l, -8075l, -8422l, -8764l,
  114258. -9101l, -9433l, -9759l, -10079l,
  114259. -10393l, -10701l, -11002l, -11296l,
  114260. -11584l, -11865l, -12139l, -12405l,
  114261. -12664l, -12915l, -13159l, -13394l,
  114262. -13622l, -13841l, -14052l, -14255l,
  114263. -14448l, -14634l, -14810l, -14977l,
  114264. -15136l, -15285l, -15425l, -15556l,
  114265. -15678l, -15790l, -15892l, -15985l,
  114266. -16068l, -16142l, -16206l, -16260l,
  114267. -16304l, -16339l, -16363l, -16378l,
  114268. -16383l,
  114269. };
  114270. #endif
  114271. #endif
  114272. /*** End of inlined file: lookup_data.h ***/
  114273. #ifdef FLOAT_LOOKUP
  114274. /* interpolated lookup based cos function, domain 0 to PI only */
  114275. float vorbis_coslook(float a){
  114276. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114277. int i=vorbis_ftoi(d-.5);
  114278. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114279. }
  114280. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114281. float vorbis_invsqlook(float a){
  114282. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114283. int i=vorbis_ftoi(d-.5f);
  114284. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114285. }
  114286. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114287. float vorbis_invsq2explook(int a){
  114288. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114289. }
  114290. #include <stdio.h>
  114291. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114292. float vorbis_fromdBlook(float a){
  114293. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114294. return (i<0)?1.f:
  114295. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114296. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114297. }
  114298. #endif
  114299. #ifdef INT_LOOKUP
  114300. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114301. 16.16 format
  114302. returns in m.8 format */
  114303. long vorbis_invsqlook_i(long a,long e){
  114304. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114305. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114306. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114307. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114308. d)>>16); /* result 1.16 */
  114309. e+=32;
  114310. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114311. e=(e>>1)-8;
  114312. return(val>>e);
  114313. }
  114314. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114315. /* a is in n.12 format */
  114316. float vorbis_fromdBlook_i(long a){
  114317. int i=(-a)>>(12-FROMdB2_SHIFT);
  114318. return (i<0)?1.f:
  114319. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114320. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114321. }
  114322. /* interpolated lookup based cos function, domain 0 to PI only */
  114323. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114324. long vorbis_coslook_i(long a){
  114325. int i=a>>COS_LOOKUP_I_SHIFT;
  114326. int d=a&COS_LOOKUP_I_MASK;
  114327. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114328. COS_LOOKUP_I_SHIFT);
  114329. }
  114330. #endif
  114331. #endif
  114332. /*** End of inlined file: lookup.c ***/
  114333. /* catch this in the build system; we #include for
  114334. compilers (like gcc) that can't inline across
  114335. modules */
  114336. static int MLOOP_1[64]={
  114337. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114338. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114339. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114340. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114341. };
  114342. static int MLOOP_2[64]={
  114343. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114344. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114345. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114346. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114347. };
  114348. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114349. /* side effect: changes *lsp to cosines of lsp */
  114350. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114351. float amp,float ampoffset){
  114352. /* 0 <= m < 256 */
  114353. /* set up for using all int later */
  114354. int i;
  114355. int ampoffseti=rint(ampoffset*4096.f);
  114356. int ampi=rint(amp*16.f);
  114357. long *ilsp=alloca(m*sizeof(*ilsp));
  114358. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114359. i=0;
  114360. while(i<n){
  114361. int j,k=map[i];
  114362. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114363. unsigned long qi=46341;
  114364. int qexp=0,shift;
  114365. long wi=vorbis_coslook_i(k*65536/ln);
  114366. qi*=labs(ilsp[0]-wi);
  114367. pi*=labs(ilsp[1]-wi);
  114368. for(j=3;j<m;j+=2){
  114369. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114370. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114371. shift=MLOOP_3[(pi|qi)>>16];
  114372. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114373. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114374. qexp+=shift;
  114375. }
  114376. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114377. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114378. shift=MLOOP_3[(pi|qi)>>16];
  114379. /* pi,qi normalized collectively, both tracked using qexp */
  114380. if(m&1){
  114381. /* odd order filter; slightly assymetric */
  114382. /* the last coefficient */
  114383. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114384. pi=(pi>>shift)<<14;
  114385. qexp+=shift;
  114386. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114387. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114388. shift=MLOOP_3[(pi|qi)>>16];
  114389. pi>>=shift;
  114390. qi>>=shift;
  114391. qexp+=shift-14*((m+1)>>1);
  114392. pi=((pi*pi)>>16);
  114393. qi=((qi*qi)>>16);
  114394. qexp=qexp*2+m;
  114395. pi*=(1<<14)-((wi*wi)>>14);
  114396. qi+=pi>>14;
  114397. }else{
  114398. /* even order filter; still symmetric */
  114399. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114400. worth tracking step by step */
  114401. pi>>=shift;
  114402. qi>>=shift;
  114403. qexp+=shift-7*m;
  114404. pi=((pi*pi)>>16);
  114405. qi=((qi*qi)>>16);
  114406. qexp=qexp*2+m;
  114407. pi*=(1<<14)-wi;
  114408. qi*=(1<<14)+wi;
  114409. qi=(qi+pi)>>14;
  114410. }
  114411. /* we've let the normalization drift because it wasn't important;
  114412. however, for the lookup, things must be normalized again. We
  114413. need at most one right shift or a number of left shifts */
  114414. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114415. qi>>=1; qexp++;
  114416. }else
  114417. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114418. qi<<=1; qexp--;
  114419. }
  114420. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114421. vorbis_invsqlook_i(qi,qexp)-
  114422. /* m.8, m+n<=8 */
  114423. ampoffseti); /* 8.12[0] */
  114424. curve[i]*=amp;
  114425. while(map[++i]==k)curve[i]*=amp;
  114426. }
  114427. }
  114428. #else
  114429. /* old, nonoptimized but simple version for any poor sap who needs to
  114430. figure out what the hell this code does, or wants the other
  114431. fraction of a dB precision */
  114432. /* side effect: changes *lsp to cosines of lsp */
  114433. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114434. float amp,float ampoffset){
  114435. int i;
  114436. float wdel=M_PI/ln;
  114437. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114438. i=0;
  114439. while(i<n){
  114440. int j,k=map[i];
  114441. float p=.5f;
  114442. float q=.5f;
  114443. float w=2.f*cos(wdel*k);
  114444. for(j=1;j<m;j+=2){
  114445. q *= w-lsp[j-1];
  114446. p *= w-lsp[j];
  114447. }
  114448. if(j==m){
  114449. /* odd order filter; slightly assymetric */
  114450. /* the last coefficient */
  114451. q*=w-lsp[j-1];
  114452. p*=p*(4.f-w*w);
  114453. q*=q;
  114454. }else{
  114455. /* even order filter; still symmetric */
  114456. p*=p*(2.f-w);
  114457. q*=q*(2.f+w);
  114458. }
  114459. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114460. curve[i]*=q;
  114461. while(map[++i]==k)curve[i]*=q;
  114462. }
  114463. }
  114464. #endif
  114465. #endif
  114466. static void cheby(float *g, int ord) {
  114467. int i, j;
  114468. g[0] *= .5f;
  114469. for(i=2; i<= ord; i++) {
  114470. for(j=ord; j >= i; j--) {
  114471. g[j-2] -= g[j];
  114472. g[j] += g[j];
  114473. }
  114474. }
  114475. }
  114476. static int comp(const void *a,const void *b){
  114477. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114478. }
  114479. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114480. but there are root sets for which it gets into limit cycles
  114481. (exacerbated by zero suppression) and fails. We can't afford to
  114482. fail, even if the failure is 1 in 100,000,000, so we now use
  114483. Laguerre and later polish with Newton-Raphson (which can then
  114484. afford to fail) */
  114485. #define EPSILON 10e-7
  114486. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114487. int i,m;
  114488. double lastdelta=0.f;
  114489. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114490. for(i=0;i<=ord;i++)defl[i]=a[i];
  114491. for(m=ord;m>0;m--){
  114492. double newx=0.f,delta;
  114493. /* iterate a root */
  114494. while(1){
  114495. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114496. /* eval the polynomial and its first two derivatives */
  114497. for(i=m;i>0;i--){
  114498. ppp = newx*ppp + pp;
  114499. pp = newx*pp + p;
  114500. p = newx*p + defl[i-1];
  114501. }
  114502. /* Laguerre's method */
  114503. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114504. if(denom<0)
  114505. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114506. if(pp>0){
  114507. denom = pp + sqrt(denom);
  114508. if(denom<EPSILON)denom=EPSILON;
  114509. }else{
  114510. denom = pp - sqrt(denom);
  114511. if(denom>-(EPSILON))denom=-(EPSILON);
  114512. }
  114513. delta = m*p/denom;
  114514. newx -= delta;
  114515. if(delta<0.f)delta*=-1;
  114516. if(fabs(delta/newx)<10e-12)break;
  114517. lastdelta=delta;
  114518. }
  114519. r[m-1]=newx;
  114520. /* forward deflation */
  114521. for(i=m;i>0;i--)
  114522. defl[i-1]+=newx*defl[i];
  114523. defl++;
  114524. }
  114525. return(0);
  114526. }
  114527. /* for spit-and-polish only */
  114528. static int Newton_Raphson(float *a,int ord,float *r){
  114529. int i, k, count=0;
  114530. double error=1.f;
  114531. double *root=(double*)alloca(ord*sizeof(*root));
  114532. for(i=0; i<ord;i++) root[i] = r[i];
  114533. while(error>1e-20){
  114534. error=0;
  114535. for(i=0; i<ord; i++) { /* Update each point. */
  114536. double pp=0.,delta;
  114537. double rooti=root[i];
  114538. double p=a[ord];
  114539. for(k=ord-1; k>= 0; k--) {
  114540. pp= pp* rooti + p;
  114541. p = p * rooti + a[k];
  114542. }
  114543. delta = p/pp;
  114544. root[i] -= delta;
  114545. error+= delta*delta;
  114546. }
  114547. if(count>40)return(-1);
  114548. count++;
  114549. }
  114550. /* Replaced the original bubble sort with a real sort. With your
  114551. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114552. for(i=0; i<ord;i++) r[i] = root[i];
  114553. return(0);
  114554. }
  114555. /* Convert lpc coefficients to lsp coefficients */
  114556. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114557. int order2=(m+1)>>1;
  114558. int g1_order,g2_order;
  114559. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114560. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114561. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114562. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114563. int i;
  114564. /* even and odd are slightly different base cases */
  114565. g1_order=(m+1)>>1;
  114566. g2_order=(m) >>1;
  114567. /* Compute the lengths of the x polynomials. */
  114568. /* Compute the first half of K & R F1 & F2 polynomials. */
  114569. /* Compute half of the symmetric and antisymmetric polynomials. */
  114570. /* Remove the roots at +1 and -1. */
  114571. g1[g1_order] = 1.f;
  114572. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114573. g2[g2_order] = 1.f;
  114574. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114575. if(g1_order>g2_order){
  114576. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114577. }else{
  114578. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114579. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114580. }
  114581. /* Convert into polynomials in cos(alpha) */
  114582. cheby(g1,g1_order);
  114583. cheby(g2,g2_order);
  114584. /* Find the roots of the 2 even polynomials.*/
  114585. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114586. Laguerre_With_Deflation(g2,g2_order,g2r))
  114587. return(-1);
  114588. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114589. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114590. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114591. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114592. for(i=0;i<g1_order;i++)
  114593. lsp[i*2] = acos(g1r[i]);
  114594. for(i=0;i<g2_order;i++)
  114595. lsp[i*2+1] = acos(g2r[i]);
  114596. return(0);
  114597. }
  114598. #endif
  114599. /*** End of inlined file: lsp.c ***/
  114600. /*** Start of inlined file: mapping0.c ***/
  114601. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114602. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114603. // tasks..
  114604. #if JUCE_MSVC
  114605. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114606. #endif
  114607. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114608. #if JUCE_USE_OGGVORBIS
  114609. #include <stdlib.h>
  114610. #include <stdio.h>
  114611. #include <string.h>
  114612. #include <math.h>
  114613. /* simplistic, wasteful way of doing this (unique lookup for each
  114614. mode/submapping); there should be a central repository for
  114615. identical lookups. That will require minor work, so I'm putting it
  114616. off as low priority.
  114617. Why a lookup for each backend in a given mode? Because the
  114618. blocksize is set by the mode, and low backend lookups may require
  114619. parameters from other areas of the mode/mapping */
  114620. static void mapping0_free_info(vorbis_info_mapping *i){
  114621. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114622. if(info){
  114623. memset(info,0,sizeof(*info));
  114624. _ogg_free(info);
  114625. }
  114626. }
  114627. static int ilog3(unsigned int v){
  114628. int ret=0;
  114629. if(v)--v;
  114630. while(v){
  114631. ret++;
  114632. v>>=1;
  114633. }
  114634. return(ret);
  114635. }
  114636. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114637. oggpack_buffer *opb){
  114638. int i;
  114639. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114640. /* another 'we meant to do it this way' hack... up to beta 4, we
  114641. packed 4 binary zeros here to signify one submapping in use. We
  114642. now redefine that to mean four bitflags that indicate use of
  114643. deeper features; bit0:submappings, bit1:coupling,
  114644. bit2,3:reserved. This is backward compatable with all actual uses
  114645. of the beta code. */
  114646. if(info->submaps>1){
  114647. oggpack_write(opb,1,1);
  114648. oggpack_write(opb,info->submaps-1,4);
  114649. }else
  114650. oggpack_write(opb,0,1);
  114651. if(info->coupling_steps>0){
  114652. oggpack_write(opb,1,1);
  114653. oggpack_write(opb,info->coupling_steps-1,8);
  114654. for(i=0;i<info->coupling_steps;i++){
  114655. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114656. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114657. }
  114658. }else
  114659. oggpack_write(opb,0,1);
  114660. oggpack_write(opb,0,2); /* 2,3:reserved */
  114661. /* we don't write the channel submappings if we only have one... */
  114662. if(info->submaps>1){
  114663. for(i=0;i<vi->channels;i++)
  114664. oggpack_write(opb,info->chmuxlist[i],4);
  114665. }
  114666. for(i=0;i<info->submaps;i++){
  114667. oggpack_write(opb,0,8); /* time submap unused */
  114668. oggpack_write(opb,info->floorsubmap[i],8);
  114669. oggpack_write(opb,info->residuesubmap[i],8);
  114670. }
  114671. }
  114672. /* also responsible for range checking */
  114673. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114674. int i;
  114675. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114676. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114677. memset(info,0,sizeof(*info));
  114678. if(oggpack_read(opb,1))
  114679. info->submaps=oggpack_read(opb,4)+1;
  114680. else
  114681. info->submaps=1;
  114682. if(oggpack_read(opb,1)){
  114683. info->coupling_steps=oggpack_read(opb,8)+1;
  114684. for(i=0;i<info->coupling_steps;i++){
  114685. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114686. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114687. if(testM<0 ||
  114688. testA<0 ||
  114689. testM==testA ||
  114690. testM>=vi->channels ||
  114691. testA>=vi->channels) goto err_out;
  114692. }
  114693. }
  114694. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114695. if(info->submaps>1){
  114696. for(i=0;i<vi->channels;i++){
  114697. info->chmuxlist[i]=oggpack_read(opb,4);
  114698. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114699. }
  114700. }
  114701. for(i=0;i<info->submaps;i++){
  114702. oggpack_read(opb,8); /* time submap unused */
  114703. info->floorsubmap[i]=oggpack_read(opb,8);
  114704. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114705. info->residuesubmap[i]=oggpack_read(opb,8);
  114706. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114707. }
  114708. return info;
  114709. err_out:
  114710. mapping0_free_info(info);
  114711. return(NULL);
  114712. }
  114713. #if 0
  114714. static long seq=0;
  114715. static ogg_int64_t total=0;
  114716. static float FLOOR1_fromdB_LOOKUP[256]={
  114717. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114718. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114719. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114720. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114721. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114722. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114723. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114724. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114725. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114726. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114727. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114728. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114729. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114730. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114731. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114732. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114733. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114734. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114735. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114736. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114737. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114738. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114739. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114740. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114741. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114742. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114743. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114744. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114745. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114746. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114747. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114748. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114749. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114750. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114751. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114752. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114753. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114754. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114755. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114756. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114757. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114758. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114759. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114760. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114761. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114762. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114763. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114764. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114765. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114766. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114767. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114768. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114769. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114770. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114771. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114772. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114773. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114774. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114775. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114776. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114777. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114778. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114779. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114780. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114781. };
  114782. #endif
  114783. extern int *floor1_fit(vorbis_block *vb,void *look,
  114784. const float *logmdct, /* in */
  114785. const float *logmask);
  114786. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114787. int *A,int *B,
  114788. int del);
  114789. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114790. void*look,
  114791. int *post,int *ilogmask);
  114792. static int mapping0_forward(vorbis_block *vb){
  114793. vorbis_dsp_state *vd=vb->vd;
  114794. vorbis_info *vi=vd->vi;
  114795. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114796. private_state *b=(private_state*)vb->vd->backend_state;
  114797. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114798. int n=vb->pcmend;
  114799. int i,j,k;
  114800. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114801. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114802. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114803. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114804. float global_ampmax=vbi->ampmax;
  114805. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114806. int blocktype=vbi->blocktype;
  114807. int modenumber=vb->W;
  114808. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114809. vorbis_look_psy *psy_look=
  114810. b->psy+blocktype+(vb->W?2:0);
  114811. vb->mode=modenumber;
  114812. for(i=0;i<vi->channels;i++){
  114813. float scale=4.f/n;
  114814. float scale_dB;
  114815. float *pcm =vb->pcm[i];
  114816. float *logfft =pcm;
  114817. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114818. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114819. todB estimation used on IEEE 754
  114820. compliant machines had a bug that
  114821. returned dB values about a third
  114822. of a decibel too high. The bug
  114823. was harmless because tunings
  114824. implicitly took that into
  114825. account. However, fixing the bug
  114826. in the estimator requires
  114827. changing all the tunings as well.
  114828. For now, it's easier to sync
  114829. things back up here, and
  114830. recalibrate the tunings in the
  114831. next major model upgrade. */
  114832. #if 0
  114833. if(vi->channels==2)
  114834. if(i==0)
  114835. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114836. else
  114837. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114838. #endif
  114839. /* window the PCM data */
  114840. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114841. #if 0
  114842. if(vi->channels==2)
  114843. if(i==0)
  114844. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114845. else
  114846. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114847. #endif
  114848. /* transform the PCM data */
  114849. /* only MDCT right now.... */
  114850. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114851. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114852. drft_forward(&b->fft_look[vb->W],pcm);
  114853. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114854. original todB estimation used on
  114855. IEEE 754 compliant machines had a
  114856. bug that returned dB values about
  114857. a third of a decibel too high.
  114858. The bug was harmless because
  114859. tunings implicitly took that into
  114860. account. However, fixing the bug
  114861. in the estimator requires
  114862. changing all the tunings as well.
  114863. For now, it's easier to sync
  114864. things back up here, and
  114865. recalibrate the tunings in the
  114866. next major model upgrade. */
  114867. local_ampmax[i]=logfft[0];
  114868. for(j=1;j<n-1;j+=2){
  114869. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114870. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114871. .345 is a hack; the original todB
  114872. estimation used on IEEE 754
  114873. compliant machines had a bug that
  114874. returned dB values about a third
  114875. of a decibel too high. The bug
  114876. was harmless because tunings
  114877. implicitly took that into
  114878. account. However, fixing the bug
  114879. in the estimator requires
  114880. changing all the tunings as well.
  114881. For now, it's easier to sync
  114882. things back up here, and
  114883. recalibrate the tunings in the
  114884. next major model upgrade. */
  114885. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114886. }
  114887. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114888. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114889. #if 0
  114890. if(vi->channels==2){
  114891. if(i==0){
  114892. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114893. }else{
  114894. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114895. }
  114896. }
  114897. #endif
  114898. }
  114899. {
  114900. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114901. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114902. for(i=0;i<vi->channels;i++){
  114903. /* the encoder setup assumes that all the modes used by any
  114904. specific bitrate tweaking use the same floor */
  114905. int submap=info->chmuxlist[i];
  114906. /* the following makes things clearer to *me* anyway */
  114907. float *mdct =gmdct[i];
  114908. float *logfft =vb->pcm[i];
  114909. float *logmdct =logfft+n/2;
  114910. float *logmask =logfft;
  114911. vb->mode=modenumber;
  114912. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114913. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114914. for(j=0;j<n/2;j++)
  114915. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114916. todB estimation used on IEEE 754
  114917. compliant machines had a bug that
  114918. returned dB values about a third
  114919. of a decibel too high. The bug
  114920. was harmless because tunings
  114921. implicitly took that into
  114922. account. However, fixing the bug
  114923. in the estimator requires
  114924. changing all the tunings as well.
  114925. For now, it's easier to sync
  114926. things back up here, and
  114927. recalibrate the tunings in the
  114928. next major model upgrade. */
  114929. #if 0
  114930. if(vi->channels==2){
  114931. if(i==0)
  114932. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114933. else
  114934. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114935. }else{
  114936. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114937. }
  114938. #endif
  114939. /* first step; noise masking. Not only does 'noise masking'
  114940. give us curves from which we can decide how much resolution
  114941. to give noise parts of the spectrum, it also implicitly hands
  114942. us a tonality estimate (the larger the value in the
  114943. 'noise_depth' vector, the more tonal that area is) */
  114944. _vp_noisemask(psy_look,
  114945. logmdct,
  114946. noise); /* noise does not have by-frequency offset
  114947. bias applied yet */
  114948. #if 0
  114949. if(vi->channels==2){
  114950. if(i==0)
  114951. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114952. else
  114953. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114954. }
  114955. #endif
  114956. /* second step: 'all the other crap'; all the stuff that isn't
  114957. computed/fit for bitrate management goes in the second psy
  114958. vector. This includes tone masking, peak limiting and ATH */
  114959. _vp_tonemask(psy_look,
  114960. logfft,
  114961. tone,
  114962. global_ampmax,
  114963. local_ampmax[i]);
  114964. #if 0
  114965. if(vi->channels==2){
  114966. if(i==0)
  114967. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114968. else
  114969. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114970. }
  114971. #endif
  114972. /* third step; we offset the noise vectors, overlay tone
  114973. masking. We then do a floor1-specific line fit. If we're
  114974. performing bitrate management, the line fit is performed
  114975. multiple times for up/down tweakage on demand. */
  114976. #if 0
  114977. {
  114978. float aotuv[psy_look->n];
  114979. #endif
  114980. _vp_offset_and_mix(psy_look,
  114981. noise,
  114982. tone,
  114983. 1,
  114984. logmask,
  114985. mdct,
  114986. logmdct);
  114987. #if 0
  114988. if(vi->channels==2){
  114989. if(i==0)
  114990. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114991. else
  114992. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114993. }
  114994. }
  114995. #endif
  114996. #if 0
  114997. if(vi->channels==2){
  114998. if(i==0)
  114999. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115000. else
  115001. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115002. }
  115003. #endif
  115004. /* this algorithm is hardwired to floor 1 for now; abort out if
  115005. we're *not* floor1. This won't happen unless someone has
  115006. broken the encode setup lib. Guard it anyway. */
  115007. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115008. floor_posts[i][PACKETBLOBS/2]=
  115009. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115010. logmdct,
  115011. logmask);
  115012. /* are we managing bitrate? If so, perform two more fits for
  115013. later rate tweaking (fits represent hi/lo) */
  115014. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115015. /* higher rate by way of lower noise curve */
  115016. _vp_offset_and_mix(psy_look,
  115017. noise,
  115018. tone,
  115019. 2,
  115020. logmask,
  115021. mdct,
  115022. logmdct);
  115023. #if 0
  115024. if(vi->channels==2){
  115025. if(i==0)
  115026. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115027. else
  115028. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115029. }
  115030. #endif
  115031. floor_posts[i][PACKETBLOBS-1]=
  115032. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115033. logmdct,
  115034. logmask);
  115035. /* lower rate by way of higher noise curve */
  115036. _vp_offset_and_mix(psy_look,
  115037. noise,
  115038. tone,
  115039. 0,
  115040. logmask,
  115041. mdct,
  115042. logmdct);
  115043. #if 0
  115044. if(vi->channels==2)
  115045. if(i==0)
  115046. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115047. else
  115048. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115049. #endif
  115050. floor_posts[i][0]=
  115051. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115052. logmdct,
  115053. logmask);
  115054. /* we also interpolate a range of intermediate curves for
  115055. intermediate rates */
  115056. for(k=1;k<PACKETBLOBS/2;k++)
  115057. floor_posts[i][k]=
  115058. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115059. floor_posts[i][0],
  115060. floor_posts[i][PACKETBLOBS/2],
  115061. k*65536/(PACKETBLOBS/2));
  115062. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115063. floor_posts[i][k]=
  115064. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115065. floor_posts[i][PACKETBLOBS/2],
  115066. floor_posts[i][PACKETBLOBS-1],
  115067. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115068. }
  115069. }
  115070. }
  115071. vbi->ampmax=global_ampmax;
  115072. /*
  115073. the next phases are performed once for vbr-only and PACKETBLOB
  115074. times for bitrate managed modes.
  115075. 1) encode actual mode being used
  115076. 2) encode the floor for each channel, compute coded mask curve/res
  115077. 3) normalize and couple.
  115078. 4) encode residue
  115079. 5) save packet bytes to the packetblob vector
  115080. */
  115081. /* iterate over the many masking curve fits we've created */
  115082. {
  115083. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115084. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115085. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115086. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115087. float **mag_memo;
  115088. int **mag_sort;
  115089. if(info->coupling_steps){
  115090. mag_memo=_vp_quantize_couple_memo(vb,
  115091. &ci->psy_g_param,
  115092. psy_look,
  115093. info,
  115094. gmdct);
  115095. mag_sort=_vp_quantize_couple_sort(vb,
  115096. psy_look,
  115097. info,
  115098. mag_memo);
  115099. hf_reduction(&ci->psy_g_param,
  115100. psy_look,
  115101. info,
  115102. mag_memo);
  115103. }
  115104. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115105. if(psy_look->vi->normal_channel_p){
  115106. for(i=0;i<vi->channels;i++){
  115107. float *mdct =gmdct[i];
  115108. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115109. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115110. }
  115111. }
  115112. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115113. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115114. k++){
  115115. oggpack_buffer *opb=vbi->packetblob[k];
  115116. /* start out our new packet blob with packet type and mode */
  115117. /* Encode the packet type */
  115118. oggpack_write(opb,0,1);
  115119. /* Encode the modenumber */
  115120. /* Encode frame mode, pre,post windowsize, then dispatch */
  115121. oggpack_write(opb,modenumber,b->modebits);
  115122. if(vb->W){
  115123. oggpack_write(opb,vb->lW,1);
  115124. oggpack_write(opb,vb->nW,1);
  115125. }
  115126. /* encode floor, compute masking curve, sep out residue */
  115127. for(i=0;i<vi->channels;i++){
  115128. int submap=info->chmuxlist[i];
  115129. float *mdct =gmdct[i];
  115130. float *res =vb->pcm[i];
  115131. int *ilogmask=ilogmaskch[i]=
  115132. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115133. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115134. floor_posts[i][k],
  115135. ilogmask);
  115136. #if 0
  115137. {
  115138. char buf[80];
  115139. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115140. float work[n/2];
  115141. for(j=0;j<n/2;j++)
  115142. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115143. _analysis_output(buf,seq,work,n/2,1,1,0);
  115144. }
  115145. #endif
  115146. _vp_remove_floor(psy_look,
  115147. mdct,
  115148. ilogmask,
  115149. res,
  115150. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115151. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115152. #if 0
  115153. {
  115154. char buf[80];
  115155. float work[n/2];
  115156. for(j=0;j<n/2;j++)
  115157. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115158. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115159. _analysis_output(buf,seq,work,n/2,1,1,0);
  115160. }
  115161. #endif
  115162. }
  115163. /* our iteration is now based on masking curve, not prequant and
  115164. coupling. Only one prequant/coupling step */
  115165. /* quantize/couple */
  115166. /* incomplete implementation that assumes the tree is all depth
  115167. one, or no tree at all */
  115168. if(info->coupling_steps){
  115169. _vp_couple(k,
  115170. &ci->psy_g_param,
  115171. psy_look,
  115172. info,
  115173. vb->pcm,
  115174. mag_memo,
  115175. mag_sort,
  115176. ilogmaskch,
  115177. nonzero,
  115178. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115179. }
  115180. /* classify and encode by submap */
  115181. for(i=0;i<info->submaps;i++){
  115182. int ch_in_bundle=0;
  115183. long **classifications;
  115184. int resnum=info->residuesubmap[i];
  115185. for(j=0;j<vi->channels;j++){
  115186. if(info->chmuxlist[j]==i){
  115187. zerobundle[ch_in_bundle]=0;
  115188. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115189. res_bundle[ch_in_bundle]=vb->pcm[j];
  115190. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115191. }
  115192. }
  115193. classifications=_residue_P[ci->residue_type[resnum]]->
  115194. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115195. _residue_P[ci->residue_type[resnum]]->
  115196. forward(opb,vb,b->residue[resnum],
  115197. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115198. }
  115199. /* ok, done encoding. Next protopacket. */
  115200. }
  115201. }
  115202. #if 0
  115203. seq++;
  115204. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115205. #endif
  115206. return(0);
  115207. }
  115208. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115209. vorbis_dsp_state *vd=vb->vd;
  115210. vorbis_info *vi=vd->vi;
  115211. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115212. private_state *b=(private_state*)vd->backend_state;
  115213. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115214. int i,j;
  115215. long n=vb->pcmend=ci->blocksizes[vb->W];
  115216. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115217. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115218. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115219. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115220. /* recover the spectral envelope; store it in the PCM vector for now */
  115221. for(i=0;i<vi->channels;i++){
  115222. int submap=info->chmuxlist[i];
  115223. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115224. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115225. if(floormemo[i])
  115226. nonzero[i]=1;
  115227. else
  115228. nonzero[i]=0;
  115229. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115230. }
  115231. /* channel coupling can 'dirty' the nonzero listing */
  115232. for(i=0;i<info->coupling_steps;i++){
  115233. if(nonzero[info->coupling_mag[i]] ||
  115234. nonzero[info->coupling_ang[i]]){
  115235. nonzero[info->coupling_mag[i]]=1;
  115236. nonzero[info->coupling_ang[i]]=1;
  115237. }
  115238. }
  115239. /* recover the residue into our working vectors */
  115240. for(i=0;i<info->submaps;i++){
  115241. int ch_in_bundle=0;
  115242. for(j=0;j<vi->channels;j++){
  115243. if(info->chmuxlist[j]==i){
  115244. if(nonzero[j])
  115245. zerobundle[ch_in_bundle]=1;
  115246. else
  115247. zerobundle[ch_in_bundle]=0;
  115248. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115249. }
  115250. }
  115251. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115252. inverse(vb,b->residue[info->residuesubmap[i]],
  115253. pcmbundle,zerobundle,ch_in_bundle);
  115254. }
  115255. /* channel coupling */
  115256. for(i=info->coupling_steps-1;i>=0;i--){
  115257. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115258. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115259. for(j=0;j<n/2;j++){
  115260. float mag=pcmM[j];
  115261. float ang=pcmA[j];
  115262. if(mag>0)
  115263. if(ang>0){
  115264. pcmM[j]=mag;
  115265. pcmA[j]=mag-ang;
  115266. }else{
  115267. pcmA[j]=mag;
  115268. pcmM[j]=mag+ang;
  115269. }
  115270. else
  115271. if(ang>0){
  115272. pcmM[j]=mag;
  115273. pcmA[j]=mag+ang;
  115274. }else{
  115275. pcmA[j]=mag;
  115276. pcmM[j]=mag-ang;
  115277. }
  115278. }
  115279. }
  115280. /* compute and apply spectral envelope */
  115281. for(i=0;i<vi->channels;i++){
  115282. float *pcm=vb->pcm[i];
  115283. int submap=info->chmuxlist[i];
  115284. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115285. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115286. floormemo[i],pcm);
  115287. }
  115288. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115289. /* only MDCT right now.... */
  115290. for(i=0;i<vi->channels;i++){
  115291. float *pcm=vb->pcm[i];
  115292. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115293. }
  115294. /* all done! */
  115295. return(0);
  115296. }
  115297. /* export hooks */
  115298. vorbis_func_mapping mapping0_exportbundle={
  115299. &mapping0_pack,
  115300. &mapping0_unpack,
  115301. &mapping0_free_info,
  115302. &mapping0_forward,
  115303. &mapping0_inverse
  115304. };
  115305. #endif
  115306. /*** End of inlined file: mapping0.c ***/
  115307. /*** Start of inlined file: mdct.c ***/
  115308. /* this can also be run as an integer transform by uncommenting a
  115309. define in mdct.h; the integerization is a first pass and although
  115310. it's likely stable for Vorbis, the dynamic range is constrained and
  115311. roundoff isn't done (so it's noisy). Consider it functional, but
  115312. only a starting point. There's no point on a machine with an FPU */
  115313. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115314. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115315. // tasks..
  115316. #if JUCE_MSVC
  115317. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115318. #endif
  115319. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115320. #if JUCE_USE_OGGVORBIS
  115321. #include <stdio.h>
  115322. #include <stdlib.h>
  115323. #include <string.h>
  115324. #include <math.h>
  115325. /* build lookups for trig functions; also pre-figure scaling and
  115326. some window function algebra. */
  115327. void mdct_init(mdct_lookup *lookup,int n){
  115328. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115329. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115330. int i;
  115331. int n2=n>>1;
  115332. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115333. lookup->n=n;
  115334. lookup->trig=T;
  115335. lookup->bitrev=bitrev;
  115336. /* trig lookups... */
  115337. for(i=0;i<n/4;i++){
  115338. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115339. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115340. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115341. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115342. }
  115343. for(i=0;i<n/8;i++){
  115344. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115345. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115346. }
  115347. /* bitreverse lookup... */
  115348. {
  115349. int mask=(1<<(log2n-1))-1,i,j;
  115350. int msb=1<<(log2n-2);
  115351. for(i=0;i<n/8;i++){
  115352. int acc=0;
  115353. for(j=0;msb>>j;j++)
  115354. if((msb>>j)&i)acc|=1<<j;
  115355. bitrev[i*2]=((~acc)&mask)-1;
  115356. bitrev[i*2+1]=acc;
  115357. }
  115358. }
  115359. lookup->scale=FLOAT_CONV(4.f/n);
  115360. }
  115361. /* 8 point butterfly (in place, 4 register) */
  115362. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115363. REG_TYPE r0 = x[6] + x[2];
  115364. REG_TYPE r1 = x[6] - x[2];
  115365. REG_TYPE r2 = x[4] + x[0];
  115366. REG_TYPE r3 = x[4] - x[0];
  115367. x[6] = r0 + r2;
  115368. x[4] = r0 - r2;
  115369. r0 = x[5] - x[1];
  115370. r2 = x[7] - x[3];
  115371. x[0] = r1 + r0;
  115372. x[2] = r1 - r0;
  115373. r0 = x[5] + x[1];
  115374. r1 = x[7] + x[3];
  115375. x[3] = r2 + r3;
  115376. x[1] = r2 - r3;
  115377. x[7] = r1 + r0;
  115378. x[5] = r1 - r0;
  115379. }
  115380. /* 16 point butterfly (in place, 4 register) */
  115381. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115382. REG_TYPE r0 = x[1] - x[9];
  115383. REG_TYPE r1 = x[0] - x[8];
  115384. x[8] += x[0];
  115385. x[9] += x[1];
  115386. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115387. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115388. r0 = x[3] - x[11];
  115389. r1 = x[10] - x[2];
  115390. x[10] += x[2];
  115391. x[11] += x[3];
  115392. x[2] = r0;
  115393. x[3] = r1;
  115394. r0 = x[12] - x[4];
  115395. r1 = x[13] - x[5];
  115396. x[12] += x[4];
  115397. x[13] += x[5];
  115398. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115399. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115400. r0 = x[14] - x[6];
  115401. r1 = x[15] - x[7];
  115402. x[14] += x[6];
  115403. x[15] += x[7];
  115404. x[6] = r0;
  115405. x[7] = r1;
  115406. mdct_butterfly_8(x);
  115407. mdct_butterfly_8(x+8);
  115408. }
  115409. /* 32 point butterfly (in place, 4 register) */
  115410. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115411. REG_TYPE r0 = x[30] - x[14];
  115412. REG_TYPE r1 = x[31] - x[15];
  115413. x[30] += x[14];
  115414. x[31] += x[15];
  115415. x[14] = r0;
  115416. x[15] = r1;
  115417. r0 = x[28] - x[12];
  115418. r1 = x[29] - x[13];
  115419. x[28] += x[12];
  115420. x[29] += x[13];
  115421. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115422. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115423. r0 = x[26] - x[10];
  115424. r1 = x[27] - x[11];
  115425. x[26] += x[10];
  115426. x[27] += x[11];
  115427. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115428. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115429. r0 = x[24] - x[8];
  115430. r1 = x[25] - x[9];
  115431. x[24] += x[8];
  115432. x[25] += x[9];
  115433. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115434. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115435. r0 = x[22] - x[6];
  115436. r1 = x[7] - x[23];
  115437. x[22] += x[6];
  115438. x[23] += x[7];
  115439. x[6] = r1;
  115440. x[7] = r0;
  115441. r0 = x[4] - x[20];
  115442. r1 = x[5] - x[21];
  115443. x[20] += x[4];
  115444. x[21] += x[5];
  115445. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115446. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115447. r0 = x[2] - x[18];
  115448. r1 = x[3] - x[19];
  115449. x[18] += x[2];
  115450. x[19] += x[3];
  115451. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115452. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115453. r0 = x[0] - x[16];
  115454. r1 = x[1] - x[17];
  115455. x[16] += x[0];
  115456. x[17] += x[1];
  115457. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115458. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115459. mdct_butterfly_16(x);
  115460. mdct_butterfly_16(x+16);
  115461. }
  115462. /* N point first stage butterfly (in place, 2 register) */
  115463. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115464. DATA_TYPE *x,
  115465. int points){
  115466. DATA_TYPE *x1 = x + points - 8;
  115467. DATA_TYPE *x2 = x + (points>>1) - 8;
  115468. REG_TYPE r0;
  115469. REG_TYPE r1;
  115470. do{
  115471. r0 = x1[6] - x2[6];
  115472. r1 = x1[7] - x2[7];
  115473. x1[6] += x2[6];
  115474. x1[7] += x2[7];
  115475. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115476. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115477. r0 = x1[4] - x2[4];
  115478. r1 = x1[5] - x2[5];
  115479. x1[4] += x2[4];
  115480. x1[5] += x2[5];
  115481. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115482. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115483. r0 = x1[2] - x2[2];
  115484. r1 = x1[3] - x2[3];
  115485. x1[2] += x2[2];
  115486. x1[3] += x2[3];
  115487. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115488. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115489. r0 = x1[0] - x2[0];
  115490. r1 = x1[1] - x2[1];
  115491. x1[0] += x2[0];
  115492. x1[1] += x2[1];
  115493. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115494. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115495. x1-=8;
  115496. x2-=8;
  115497. T+=16;
  115498. }while(x2>=x);
  115499. }
  115500. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115501. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115502. DATA_TYPE *x,
  115503. int points,
  115504. int trigint){
  115505. DATA_TYPE *x1 = x + points - 8;
  115506. DATA_TYPE *x2 = x + (points>>1) - 8;
  115507. REG_TYPE r0;
  115508. REG_TYPE r1;
  115509. do{
  115510. r0 = x1[6] - x2[6];
  115511. r1 = x1[7] - x2[7];
  115512. x1[6] += x2[6];
  115513. x1[7] += x2[7];
  115514. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115515. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115516. T+=trigint;
  115517. r0 = x1[4] - x2[4];
  115518. r1 = x1[5] - x2[5];
  115519. x1[4] += x2[4];
  115520. x1[5] += x2[5];
  115521. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115522. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115523. T+=trigint;
  115524. r0 = x1[2] - x2[2];
  115525. r1 = x1[3] - x2[3];
  115526. x1[2] += x2[2];
  115527. x1[3] += x2[3];
  115528. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115529. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115530. T+=trigint;
  115531. r0 = x1[0] - x2[0];
  115532. r1 = x1[1] - x2[1];
  115533. x1[0] += x2[0];
  115534. x1[1] += x2[1];
  115535. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115536. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115537. T+=trigint;
  115538. x1-=8;
  115539. x2-=8;
  115540. }while(x2>=x);
  115541. }
  115542. STIN void mdct_butterflies(mdct_lookup *init,
  115543. DATA_TYPE *x,
  115544. int points){
  115545. DATA_TYPE *T=init->trig;
  115546. int stages=init->log2n-5;
  115547. int i,j;
  115548. if(--stages>0){
  115549. mdct_butterfly_first(T,x,points);
  115550. }
  115551. for(i=1;--stages>0;i++){
  115552. for(j=0;j<(1<<i);j++)
  115553. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115554. }
  115555. for(j=0;j<points;j+=32)
  115556. mdct_butterfly_32(x+j);
  115557. }
  115558. void mdct_clear(mdct_lookup *l){
  115559. if(l){
  115560. if(l->trig)_ogg_free(l->trig);
  115561. if(l->bitrev)_ogg_free(l->bitrev);
  115562. memset(l,0,sizeof(*l));
  115563. }
  115564. }
  115565. STIN void mdct_bitreverse(mdct_lookup *init,
  115566. DATA_TYPE *x){
  115567. int n = init->n;
  115568. int *bit = init->bitrev;
  115569. DATA_TYPE *w0 = x;
  115570. DATA_TYPE *w1 = x = w0+(n>>1);
  115571. DATA_TYPE *T = init->trig+n;
  115572. do{
  115573. DATA_TYPE *x0 = x+bit[0];
  115574. DATA_TYPE *x1 = x+bit[1];
  115575. REG_TYPE r0 = x0[1] - x1[1];
  115576. REG_TYPE r1 = x0[0] + x1[0];
  115577. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115578. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115579. w1 -= 4;
  115580. r0 = HALVE(x0[1] + x1[1]);
  115581. r1 = HALVE(x0[0] - x1[0]);
  115582. w0[0] = r0 + r2;
  115583. w1[2] = r0 - r2;
  115584. w0[1] = r1 + r3;
  115585. w1[3] = r3 - r1;
  115586. x0 = x+bit[2];
  115587. x1 = x+bit[3];
  115588. r0 = x0[1] - x1[1];
  115589. r1 = x0[0] + x1[0];
  115590. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115591. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115592. r0 = HALVE(x0[1] + x1[1]);
  115593. r1 = HALVE(x0[0] - x1[0]);
  115594. w0[2] = r0 + r2;
  115595. w1[0] = r0 - r2;
  115596. w0[3] = r1 + r3;
  115597. w1[1] = r3 - r1;
  115598. T += 4;
  115599. bit += 4;
  115600. w0 += 4;
  115601. }while(w0<w1);
  115602. }
  115603. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115604. int n=init->n;
  115605. int n2=n>>1;
  115606. int n4=n>>2;
  115607. /* rotate */
  115608. DATA_TYPE *iX = in+n2-7;
  115609. DATA_TYPE *oX = out+n2+n4;
  115610. DATA_TYPE *T = init->trig+n4;
  115611. do{
  115612. oX -= 4;
  115613. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115614. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115615. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115616. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115617. iX -= 8;
  115618. T += 4;
  115619. }while(iX>=in);
  115620. iX = in+n2-8;
  115621. oX = out+n2+n4;
  115622. T = init->trig+n4;
  115623. do{
  115624. T -= 4;
  115625. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115626. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115627. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115628. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115629. iX -= 8;
  115630. oX += 4;
  115631. }while(iX>=in);
  115632. mdct_butterflies(init,out+n2,n2);
  115633. mdct_bitreverse(init,out);
  115634. /* roatate + window */
  115635. {
  115636. DATA_TYPE *oX1=out+n2+n4;
  115637. DATA_TYPE *oX2=out+n2+n4;
  115638. DATA_TYPE *iX =out;
  115639. T =init->trig+n2;
  115640. do{
  115641. oX1-=4;
  115642. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115643. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115644. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115645. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115646. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115647. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115648. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115649. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115650. oX2+=4;
  115651. iX += 8;
  115652. T += 8;
  115653. }while(iX<oX1);
  115654. iX=out+n2+n4;
  115655. oX1=out+n4;
  115656. oX2=oX1;
  115657. do{
  115658. oX1-=4;
  115659. iX-=4;
  115660. oX2[0] = -(oX1[3] = iX[3]);
  115661. oX2[1] = -(oX1[2] = iX[2]);
  115662. oX2[2] = -(oX1[1] = iX[1]);
  115663. oX2[3] = -(oX1[0] = iX[0]);
  115664. oX2+=4;
  115665. }while(oX2<iX);
  115666. iX=out+n2+n4;
  115667. oX1=out+n2+n4;
  115668. oX2=out+n2;
  115669. do{
  115670. oX1-=4;
  115671. oX1[0]= iX[3];
  115672. oX1[1]= iX[2];
  115673. oX1[2]= iX[1];
  115674. oX1[3]= iX[0];
  115675. iX+=4;
  115676. }while(oX1>oX2);
  115677. }
  115678. }
  115679. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115680. int n=init->n;
  115681. int n2=n>>1;
  115682. int n4=n>>2;
  115683. int n8=n>>3;
  115684. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115685. DATA_TYPE *w2=w+n2;
  115686. /* rotate */
  115687. /* window + rotate + step 1 */
  115688. REG_TYPE r0;
  115689. REG_TYPE r1;
  115690. DATA_TYPE *x0=in+n2+n4;
  115691. DATA_TYPE *x1=x0+1;
  115692. DATA_TYPE *T=init->trig+n2;
  115693. int i=0;
  115694. for(i=0;i<n8;i+=2){
  115695. x0 -=4;
  115696. T-=2;
  115697. r0= x0[2] + x1[0];
  115698. r1= x0[0] + x1[2];
  115699. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115700. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115701. x1 +=4;
  115702. }
  115703. x1=in+1;
  115704. for(;i<n2-n8;i+=2){
  115705. T-=2;
  115706. x0 -=4;
  115707. r0= x0[2] - x1[0];
  115708. r1= x0[0] - x1[2];
  115709. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115710. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115711. x1 +=4;
  115712. }
  115713. x0=in+n;
  115714. for(;i<n2;i+=2){
  115715. T-=2;
  115716. x0 -=4;
  115717. r0= -x0[2] - x1[0];
  115718. r1= -x0[0] - x1[2];
  115719. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115720. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115721. x1 +=4;
  115722. }
  115723. mdct_butterflies(init,w+n2,n2);
  115724. mdct_bitreverse(init,w);
  115725. /* roatate + window */
  115726. T=init->trig+n2;
  115727. x0=out+n2;
  115728. for(i=0;i<n4;i++){
  115729. x0--;
  115730. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115731. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115732. w+=2;
  115733. T+=2;
  115734. }
  115735. }
  115736. #endif
  115737. /*** End of inlined file: mdct.c ***/
  115738. /*** Start of inlined file: psy.c ***/
  115739. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115740. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115741. // tasks..
  115742. #if JUCE_MSVC
  115743. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115744. #endif
  115745. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115746. #if JUCE_USE_OGGVORBIS
  115747. #include <stdlib.h>
  115748. #include <math.h>
  115749. #include <string.h>
  115750. /*** Start of inlined file: masking.h ***/
  115751. #ifndef _V_MASKING_H_
  115752. #define _V_MASKING_H_
  115753. /* more detailed ATH; the bass if flat to save stressing the floor
  115754. overly for only a bin or two of savings. */
  115755. #define MAX_ATH 88
  115756. static float ATH[]={
  115757. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115758. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115759. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115760. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115761. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115762. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115763. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115764. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115765. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115766. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115767. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115768. };
  115769. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115770. replaced by an empirically collected data set. The previously
  115771. published values were, far too often, simply on crack. */
  115772. #define EHMER_OFFSET 16
  115773. #define EHMER_MAX 56
  115774. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115775. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115776. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115777. for collection of these curves) */
  115778. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115779. /* 62.5 Hz */
  115780. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115781. -60, -60, -60, -60, -62, -62, -65, -73,
  115782. -69, -68, -68, -67, -70, -70, -72, -74,
  115783. -75, -79, -79, -80, -83, -88, -93, -100,
  115784. -110, -999, -999, -999, -999, -999, -999, -999,
  115785. -999, -999, -999, -999, -999, -999, -999, -999,
  115786. -999, -999, -999, -999, -999, -999, -999, -999},
  115787. { -48, -48, -48, -48, -48, -48, -48, -48,
  115788. -48, -48, -48, -48, -48, -53, -61, -66,
  115789. -66, -68, -67, -70, -76, -76, -72, -73,
  115790. -75, -76, -78, -79, -83, -88, -93, -100,
  115791. -110, -999, -999, -999, -999, -999, -999, -999,
  115792. -999, -999, -999, -999, -999, -999, -999, -999,
  115793. -999, -999, -999, -999, -999, -999, -999, -999},
  115794. { -37, -37, -37, -37, -37, -37, -37, -37,
  115795. -38, -40, -42, -46, -48, -53, -55, -62,
  115796. -65, -58, -56, -56, -61, -60, -65, -67,
  115797. -69, -71, -77, -77, -78, -80, -82, -84,
  115798. -88, -93, -98, -106, -112, -999, -999, -999,
  115799. -999, -999, -999, -999, -999, -999, -999, -999,
  115800. -999, -999, -999, -999, -999, -999, -999, -999},
  115801. { -25, -25, -25, -25, -25, -25, -25, -25,
  115802. -25, -26, -27, -29, -32, -38, -48, -52,
  115803. -52, -50, -48, -48, -51, -52, -54, -60,
  115804. -67, -67, -66, -68, -69, -73, -73, -76,
  115805. -80, -81, -81, -85, -85, -86, -88, -93,
  115806. -100, -110, -999, -999, -999, -999, -999, -999,
  115807. -999, -999, -999, -999, -999, -999, -999, -999},
  115808. { -16, -16, -16, -16, -16, -16, -16, -16,
  115809. -17, -19, -20, -22, -26, -28, -31, -40,
  115810. -47, -39, -39, -40, -42, -43, -47, -51,
  115811. -57, -52, -55, -55, -60, -58, -62, -63,
  115812. -70, -67, -69, -72, -73, -77, -80, -82,
  115813. -83, -87, -90, -94, -98, -104, -115, -999,
  115814. -999, -999, -999, -999, -999, -999, -999, -999},
  115815. { -8, -8, -8, -8, -8, -8, -8, -8,
  115816. -8, -8, -10, -11, -15, -19, -25, -30,
  115817. -34, -31, -30, -31, -29, -32, -35, -42,
  115818. -48, -42, -44, -46, -50, -50, -51, -52,
  115819. -59, -54, -55, -55, -58, -62, -63, -66,
  115820. -72, -73, -76, -75, -78, -80, -80, -81,
  115821. -84, -88, -90, -94, -98, -101, -106, -110}},
  115822. /* 88Hz */
  115823. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115824. -66, -66, -66, -66, -66, -67, -67, -67,
  115825. -76, -72, -71, -74, -76, -76, -75, -78,
  115826. -79, -79, -81, -83, -86, -89, -93, -97,
  115827. -100, -105, -110, -999, -999, -999, -999, -999,
  115828. -999, -999, -999, -999, -999, -999, -999, -999,
  115829. -999, -999, -999, -999, -999, -999, -999, -999},
  115830. { -47, -47, -47, -47, -47, -47, -47, -47,
  115831. -47, -47, -47, -48, -51, -55, -59, -66,
  115832. -66, -66, -67, -66, -68, -69, -70, -74,
  115833. -79, -77, -77, -78, -80, -81, -82, -84,
  115834. -86, -88, -91, -95, -100, -108, -116, -999,
  115835. -999, -999, -999, -999, -999, -999, -999, -999,
  115836. -999, -999, -999, -999, -999, -999, -999, -999},
  115837. { -36, -36, -36, -36, -36, -36, -36, -36,
  115838. -36, -37, -37, -41, -44, -48, -51, -58,
  115839. -62, -60, -57, -59, -59, -60, -63, -65,
  115840. -72, -71, -70, -72, -74, -77, -76, -78,
  115841. -81, -81, -80, -83, -86, -91, -96, -100,
  115842. -105, -110, -999, -999, -999, -999, -999, -999,
  115843. -999, -999, -999, -999, -999, -999, -999, -999},
  115844. { -28, -28, -28, -28, -28, -28, -28, -28,
  115845. -28, -30, -32, -32, -33, -35, -41, -49,
  115846. -50, -49, -47, -48, -48, -52, -51, -57,
  115847. -65, -61, -59, -61, -64, -69, -70, -74,
  115848. -77, -77, -78, -81, -84, -85, -87, -90,
  115849. -92, -96, -100, -107, -112, -999, -999, -999,
  115850. -999, -999, -999, -999, -999, -999, -999, -999},
  115851. { -19, -19, -19, -19, -19, -19, -19, -19,
  115852. -20, -21, -23, -27, -30, -35, -36, -41,
  115853. -46, -44, -42, -40, -41, -41, -43, -48,
  115854. -55, -53, -52, -53, -56, -59, -58, -60,
  115855. -67, -66, -69, -71, -72, -75, -79, -81,
  115856. -84, -87, -90, -93, -97, -101, -107, -114,
  115857. -999, -999, -999, -999, -999, -999, -999, -999},
  115858. { -9, -9, -9, -9, -9, -9, -9, -9,
  115859. -11, -12, -12, -15, -16, -20, -23, -30,
  115860. -37, -34, -33, -34, -31, -32, -32, -38,
  115861. -47, -44, -41, -40, -47, -49, -46, -46,
  115862. -58, -50, -50, -54, -58, -62, -64, -67,
  115863. -67, -70, -72, -76, -79, -83, -87, -91,
  115864. -96, -100, -104, -110, -999, -999, -999, -999}},
  115865. /* 125 Hz */
  115866. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115867. -62, -62, -63, -64, -66, -67, -66, -68,
  115868. -75, -72, -76, -75, -76, -78, -79, -82,
  115869. -84, -85, -90, -94, -101, -110, -999, -999,
  115870. -999, -999, -999, -999, -999, -999, -999, -999,
  115871. -999, -999, -999, -999, -999, -999, -999, -999,
  115872. -999, -999, -999, -999, -999, -999, -999, -999},
  115873. { -59, -59, -59, -59, -59, -59, -59, -59,
  115874. -59, -59, -59, -60, -60, -61, -63, -66,
  115875. -71, -68, -70, -70, -71, -72, -72, -75,
  115876. -81, -78, -79, -82, -83, -86, -90, -97,
  115877. -103, -113, -999, -999, -999, -999, -999, -999,
  115878. -999, -999, -999, -999, -999, -999, -999, -999,
  115879. -999, -999, -999, -999, -999, -999, -999, -999},
  115880. { -53, -53, -53, -53, -53, -53, -53, -53,
  115881. -53, -54, -55, -57, -56, -57, -55, -61,
  115882. -65, -60, -60, -62, -63, -63, -66, -68,
  115883. -74, -73, -75, -75, -78, -80, -80, -82,
  115884. -85, -90, -96, -101, -108, -999, -999, -999,
  115885. -999, -999, -999, -999, -999, -999, -999, -999,
  115886. -999, -999, -999, -999, -999, -999, -999, -999},
  115887. { -46, -46, -46, -46, -46, -46, -46, -46,
  115888. -46, -46, -47, -47, -47, -47, -48, -51,
  115889. -57, -51, -49, -50, -51, -53, -54, -59,
  115890. -66, -60, -62, -67, -67, -70, -72, -75,
  115891. -76, -78, -81, -85, -88, -94, -97, -104,
  115892. -112, -999, -999, -999, -999, -999, -999, -999,
  115893. -999, -999, -999, -999, -999, -999, -999, -999},
  115894. { -36, -36, -36, -36, -36, -36, -36, -36,
  115895. -39, -41, -42, -42, -39, -38, -41, -43,
  115896. -52, -44, -40, -39, -37, -37, -40, -47,
  115897. -54, -50, -48, -50, -55, -61, -59, -62,
  115898. -66, -66, -66, -69, -69, -73, -74, -74,
  115899. -75, -77, -79, -82, -87, -91, -95, -100,
  115900. -108, -115, -999, -999, -999, -999, -999, -999},
  115901. { -28, -26, -24, -22, -20, -20, -23, -29,
  115902. -30, -31, -28, -27, -28, -28, -28, -35,
  115903. -40, -33, -32, -29, -30, -30, -30, -37,
  115904. -45, -41, -37, -38, -45, -47, -47, -48,
  115905. -53, -49, -48, -50, -49, -49, -51, -52,
  115906. -58, -56, -57, -56, -60, -61, -62, -70,
  115907. -72, -74, -78, -83, -88, -93, -100, -106}},
  115908. /* 177 Hz */
  115909. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115910. -999, -110, -105, -100, -95, -91, -87, -83,
  115911. -80, -78, -76, -78, -78, -81, -83, -85,
  115912. -86, -85, -86, -87, -90, -97, -107, -999,
  115913. -999, -999, -999, -999, -999, -999, -999, -999,
  115914. -999, -999, -999, -999, -999, -999, -999, -999,
  115915. -999, -999, -999, -999, -999, -999, -999, -999},
  115916. {-999, -999, -999, -110, -105, -100, -95, -90,
  115917. -85, -81, -77, -73, -70, -67, -67, -68,
  115918. -75, -73, -70, -69, -70, -72, -75, -79,
  115919. -84, -83, -84, -86, -88, -89, -89, -93,
  115920. -98, -105, -112, -999, -999, -999, -999, -999,
  115921. -999, -999, -999, -999, -999, -999, -999, -999,
  115922. -999, -999, -999, -999, -999, -999, -999, -999},
  115923. {-105, -100, -95, -90, -85, -80, -76, -71,
  115924. -68, -68, -65, -63, -63, -62, -62, -64,
  115925. -65, -64, -61, -62, -63, -64, -66, -68,
  115926. -73, -73, -74, -75, -76, -81, -83, -85,
  115927. -88, -89, -92, -95, -100, -108, -999, -999,
  115928. -999, -999, -999, -999, -999, -999, -999, -999,
  115929. -999, -999, -999, -999, -999, -999, -999, -999},
  115930. { -80, -75, -71, -68, -65, -63, -62, -61,
  115931. -61, -61, -61, -59, -56, -57, -53, -50,
  115932. -58, -52, -50, -50, -52, -53, -54, -58,
  115933. -67, -63, -67, -68, -72, -75, -78, -80,
  115934. -81, -81, -82, -85, -89, -90, -93, -97,
  115935. -101, -107, -114, -999, -999, -999, -999, -999,
  115936. -999, -999, -999, -999, -999, -999, -999, -999},
  115937. { -65, -61, -59, -57, -56, -55, -55, -56,
  115938. -56, -57, -55, -53, -52, -47, -44, -44,
  115939. -50, -44, -41, -39, -39, -42, -40, -46,
  115940. -51, -49, -50, -53, -54, -63, -60, -61,
  115941. -62, -66, -66, -66, -70, -73, -74, -75,
  115942. -76, -75, -79, -85, -89, -91, -96, -102,
  115943. -110, -999, -999, -999, -999, -999, -999, -999},
  115944. { -52, -50, -49, -49, -48, -48, -48, -49,
  115945. -50, -50, -49, -46, -43, -39, -35, -33,
  115946. -38, -36, -32, -29, -32, -32, -32, -35,
  115947. -44, -39, -38, -38, -46, -50, -45, -46,
  115948. -53, -50, -50, -50, -54, -54, -53, -53,
  115949. -56, -57, -59, -66, -70, -72, -74, -79,
  115950. -83, -85, -90, -97, -114, -999, -999, -999}},
  115951. /* 250 Hz */
  115952. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115953. -100, -95, -90, -86, -80, -75, -75, -79,
  115954. -80, -79, -80, -81, -82, -88, -95, -103,
  115955. -110, -999, -999, -999, -999, -999, -999, -999,
  115956. -999, -999, -999, -999, -999, -999, -999, -999,
  115957. -999, -999, -999, -999, -999, -999, -999, -999,
  115958. -999, -999, -999, -999, -999, -999, -999, -999},
  115959. {-999, -999, -999, -999, -108, -103, -98, -93,
  115960. -88, -83, -79, -78, -75, -71, -67, -68,
  115961. -73, -73, -72, -73, -75, -77, -80, -82,
  115962. -88, -93, -100, -107, -114, -999, -999, -999,
  115963. -999, -999, -999, -999, -999, -999, -999, -999,
  115964. -999, -999, -999, -999, -999, -999, -999, -999,
  115965. -999, -999, -999, -999, -999, -999, -999, -999},
  115966. {-999, -999, -999, -110, -105, -101, -96, -90,
  115967. -86, -81, -77, -73, -69, -66, -61, -62,
  115968. -66, -64, -62, -65, -66, -70, -72, -76,
  115969. -81, -80, -84, -90, -95, -102, -110, -999,
  115970. -999, -999, -999, -999, -999, -999, -999, -999,
  115971. -999, -999, -999, -999, -999, -999, -999, -999,
  115972. -999, -999, -999, -999, -999, -999, -999, -999},
  115973. {-999, -999, -999, -107, -103, -97, -92, -88,
  115974. -83, -79, -74, -70, -66, -59, -53, -58,
  115975. -62, -55, -54, -54, -54, -58, -61, -62,
  115976. -72, -70, -72, -75, -78, -80, -81, -80,
  115977. -83, -83, -88, -93, -100, -107, -115, -999,
  115978. -999, -999, -999, -999, -999, -999, -999, -999,
  115979. -999, -999, -999, -999, -999, -999, -999, -999},
  115980. {-999, -999, -999, -105, -100, -95, -90, -85,
  115981. -80, -75, -70, -66, -62, -56, -48, -44,
  115982. -48, -46, -46, -43, -46, -48, -48, -51,
  115983. -58, -58, -59, -60, -62, -62, -61, -61,
  115984. -65, -64, -65, -68, -70, -74, -75, -78,
  115985. -81, -86, -95, -110, -999, -999, -999, -999,
  115986. -999, -999, -999, -999, -999, -999, -999, -999},
  115987. {-999, -999, -105, -100, -95, -90, -85, -80,
  115988. -75, -70, -65, -61, -55, -49, -39, -33,
  115989. -40, -35, -32, -38, -40, -33, -35, -37,
  115990. -46, -41, -45, -44, -46, -42, -45, -46,
  115991. -52, -50, -50, -50, -54, -54, -55, -57,
  115992. -62, -64, -66, -68, -70, -76, -81, -90,
  115993. -100, -110, -999, -999, -999, -999, -999, -999}},
  115994. /* 354 hz */
  115995. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115996. -105, -98, -90, -85, -82, -83, -80, -78,
  115997. -84, -79, -80, -83, -87, -89, -91, -93,
  115998. -99, -106, -117, -999, -999, -999, -999, -999,
  115999. -999, -999, -999, -999, -999, -999, -999, -999,
  116000. -999, -999, -999, -999, -999, -999, -999, -999,
  116001. -999, -999, -999, -999, -999, -999, -999, -999},
  116002. {-999, -999, -999, -999, -999, -999, -999, -999,
  116003. -105, -98, -90, -85, -80, -75, -70, -68,
  116004. -74, -72, -74, -77, -80, -82, -85, -87,
  116005. -92, -89, -91, -95, -100, -106, -112, -999,
  116006. -999, -999, -999, -999, -999, -999, -999, -999,
  116007. -999, -999, -999, -999, -999, -999, -999, -999,
  116008. -999, -999, -999, -999, -999, -999, -999, -999},
  116009. {-999, -999, -999, -999, -999, -999, -999, -999,
  116010. -105, -98, -90, -83, -75, -71, -63, -64,
  116011. -67, -62, -64, -67, -70, -73, -77, -81,
  116012. -84, -83, -85, -89, -90, -93, -98, -104,
  116013. -109, -114, -999, -999, -999, -999, -999, -999,
  116014. -999, -999, -999, -999, -999, -999, -999, -999,
  116015. -999, -999, -999, -999, -999, -999, -999, -999},
  116016. {-999, -999, -999, -999, -999, -999, -999, -999,
  116017. -103, -96, -88, -81, -75, -68, -58, -54,
  116018. -56, -54, -56, -56, -58, -60, -63, -66,
  116019. -74, -69, -72, -72, -75, -74, -77, -81,
  116020. -81, -82, -84, -87, -93, -96, -99, -104,
  116021. -110, -999, -999, -999, -999, -999, -999, -999,
  116022. -999, -999, -999, -999, -999, -999, -999, -999},
  116023. {-999, -999, -999, -999, -999, -108, -102, -96,
  116024. -91, -85, -80, -74, -68, -60, -51, -46,
  116025. -48, -46, -43, -45, -47, -47, -49, -48,
  116026. -56, -53, -55, -58, -57, -63, -58, -60,
  116027. -66, -64, -67, -70, -70, -74, -77, -84,
  116028. -86, -89, -91, -93, -94, -101, -109, -118,
  116029. -999, -999, -999, -999, -999, -999, -999, -999},
  116030. {-999, -999, -999, -108, -103, -98, -93, -88,
  116031. -83, -78, -73, -68, -60, -53, -44, -35,
  116032. -38, -38, -34, -34, -36, -40, -41, -44,
  116033. -51, -45, -46, -47, -46, -54, -50, -49,
  116034. -50, -50, -50, -51, -54, -57, -58, -60,
  116035. -66, -66, -66, -64, -65, -68, -77, -82,
  116036. -87, -95, -110, -999, -999, -999, -999, -999}},
  116037. /* 500 Hz */
  116038. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116039. -107, -102, -97, -92, -87, -83, -78, -75,
  116040. -82, -79, -83, -85, -89, -92, -95, -98,
  116041. -101, -105, -109, -113, -999, -999, -999, -999,
  116042. -999, -999, -999, -999, -999, -999, -999, -999,
  116043. -999, -999, -999, -999, -999, -999, -999, -999,
  116044. -999, -999, -999, -999, -999, -999, -999, -999},
  116045. {-999, -999, -999, -999, -999, -999, -999, -106,
  116046. -100, -95, -90, -86, -81, -78, -74, -69,
  116047. -74, -74, -76, -79, -83, -84, -86, -89,
  116048. -92, -97, -93, -100, -103, -107, -110, -999,
  116049. -999, -999, -999, -999, -999, -999, -999, -999,
  116050. -999, -999, -999, -999, -999, -999, -999, -999,
  116051. -999, -999, -999, -999, -999, -999, -999, -999},
  116052. {-999, -999, -999, -999, -999, -999, -106, -100,
  116053. -95, -90, -87, -83, -80, -75, -69, -60,
  116054. -66, -66, -68, -70, -74, -78, -79, -81,
  116055. -81, -83, -84, -87, -93, -96, -99, -103,
  116056. -107, -110, -999, -999, -999, -999, -999, -999,
  116057. -999, -999, -999, -999, -999, -999, -999, -999,
  116058. -999, -999, -999, -999, -999, -999, -999, -999},
  116059. {-999, -999, -999, -999, -999, -108, -103, -98,
  116060. -93, -89, -85, -82, -78, -71, -62, -55,
  116061. -58, -58, -54, -54, -55, -59, -61, -62,
  116062. -70, -66, -66, -67, -70, -72, -75, -78,
  116063. -84, -84, -84, -88, -91, -90, -95, -98,
  116064. -102, -103, -106, -110, -999, -999, -999, -999,
  116065. -999, -999, -999, -999, -999, -999, -999, -999},
  116066. {-999, -999, -999, -999, -108, -103, -98, -94,
  116067. -90, -87, -82, -79, -73, -67, -58, -47,
  116068. -50, -45, -41, -45, -48, -44, -44, -49,
  116069. -54, -51, -48, -47, -49, -50, -51, -57,
  116070. -58, -60, -63, -69, -70, -69, -71, -74,
  116071. -78, -82, -90, -95, -101, -105, -110, -999,
  116072. -999, -999, -999, -999, -999, -999, -999, -999},
  116073. {-999, -999, -999, -105, -101, -97, -93, -90,
  116074. -85, -80, -77, -72, -65, -56, -48, -37,
  116075. -40, -36, -34, -40, -50, -47, -38, -41,
  116076. -47, -38, -35, -39, -38, -43, -40, -45,
  116077. -50, -45, -44, -47, -50, -55, -48, -48,
  116078. -52, -66, -70, -76, -82, -90, -97, -105,
  116079. -110, -999, -999, -999, -999, -999, -999, -999}},
  116080. /* 707 Hz */
  116081. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116082. -999, -108, -103, -98, -93, -86, -79, -76,
  116083. -83, -81, -85, -87, -89, -93, -98, -102,
  116084. -107, -112, -999, -999, -999, -999, -999, -999,
  116085. -999, -999, -999, -999, -999, -999, -999, -999,
  116086. -999, -999, -999, -999, -999, -999, -999, -999,
  116087. -999, -999, -999, -999, -999, -999, -999, -999},
  116088. {-999, -999, -999, -999, -999, -999, -999, -999,
  116089. -999, -108, -103, -98, -93, -86, -79, -71,
  116090. -77, -74, -77, -79, -81, -84, -85, -90,
  116091. -92, -93, -92, -98, -101, -108, -112, -999,
  116092. -999, -999, -999, -999, -999, -999, -999, -999,
  116093. -999, -999, -999, -999, -999, -999, -999, -999,
  116094. -999, -999, -999, -999, -999, -999, -999, -999},
  116095. {-999, -999, -999, -999, -999, -999, -999, -999,
  116096. -108, -103, -98, -93, -87, -78, -68, -65,
  116097. -66, -62, -65, -67, -70, -73, -75, -78,
  116098. -82, -82, -83, -84, -91, -93, -98, -102,
  116099. -106, -110, -999, -999, -999, -999, -999, -999,
  116100. -999, -999, -999, -999, -999, -999, -999, -999,
  116101. -999, -999, -999, -999, -999, -999, -999, -999},
  116102. {-999, -999, -999, -999, -999, -999, -999, -999,
  116103. -105, -100, -95, -90, -82, -74, -62, -57,
  116104. -58, -56, -51, -52, -52, -54, -54, -58,
  116105. -66, -59, -60, -63, -66, -69, -73, -79,
  116106. -83, -84, -80, -81, -81, -82, -88, -92,
  116107. -98, -105, -113, -999, -999, -999, -999, -999,
  116108. -999, -999, -999, -999, -999, -999, -999, -999},
  116109. {-999, -999, -999, -999, -999, -999, -999, -107,
  116110. -102, -97, -92, -84, -79, -69, -57, -47,
  116111. -52, -47, -44, -45, -50, -52, -42, -42,
  116112. -53, -43, -43, -48, -51, -56, -55, -52,
  116113. -57, -59, -61, -62, -67, -71, -78, -83,
  116114. -86, -94, -98, -103, -110, -999, -999, -999,
  116115. -999, -999, -999, -999, -999, -999, -999, -999},
  116116. {-999, -999, -999, -999, -999, -999, -105, -100,
  116117. -95, -90, -84, -78, -70, -61, -51, -41,
  116118. -40, -38, -40, -46, -52, -51, -41, -40,
  116119. -46, -40, -38, -38, -41, -46, -41, -46,
  116120. -47, -43, -43, -45, -41, -45, -56, -67,
  116121. -68, -83, -87, -90, -95, -102, -107, -113,
  116122. -999, -999, -999, -999, -999, -999, -999, -999}},
  116123. /* 1000 Hz */
  116124. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116125. -999, -109, -105, -101, -96, -91, -84, -77,
  116126. -82, -82, -85, -89, -94, -100, -106, -110,
  116127. -999, -999, -999, -999, -999, -999, -999, -999,
  116128. -999, -999, -999, -999, -999, -999, -999, -999,
  116129. -999, -999, -999, -999, -999, -999, -999, -999,
  116130. -999, -999, -999, -999, -999, -999, -999, -999},
  116131. {-999, -999, -999, -999, -999, -999, -999, -999,
  116132. -999, -106, -103, -98, -92, -85, -80, -71,
  116133. -75, -72, -76, -80, -84, -86, -89, -93,
  116134. -100, -107, -113, -999, -999, -999, -999, -999,
  116135. -999, -999, -999, -999, -999, -999, -999, -999,
  116136. -999, -999, -999, -999, -999, -999, -999, -999,
  116137. -999, -999, -999, -999, -999, -999, -999, -999},
  116138. {-999, -999, -999, -999, -999, -999, -999, -107,
  116139. -104, -101, -97, -92, -88, -84, -80, -64,
  116140. -66, -63, -64, -66, -69, -73, -77, -83,
  116141. -83, -86, -91, -98, -104, -111, -999, -999,
  116142. -999, -999, -999, -999, -999, -999, -999, -999,
  116143. -999, -999, -999, -999, -999, -999, -999, -999,
  116144. -999, -999, -999, -999, -999, -999, -999, -999},
  116145. {-999, -999, -999, -999, -999, -999, -999, -107,
  116146. -104, -101, -97, -92, -90, -84, -74, -57,
  116147. -58, -52, -55, -54, -50, -52, -50, -52,
  116148. -63, -62, -69, -76, -77, -78, -78, -79,
  116149. -82, -88, -94, -100, -106, -111, -999, -999,
  116150. -999, -999, -999, -999, -999, -999, -999, -999,
  116151. -999, -999, -999, -999, -999, -999, -999, -999},
  116152. {-999, -999, -999, -999, -999, -999, -106, -102,
  116153. -98, -95, -90, -85, -83, -78, -70, -50,
  116154. -50, -41, -44, -49, -47, -50, -50, -44,
  116155. -55, -46, -47, -48, -48, -54, -49, -49,
  116156. -58, -62, -71, -81, -87, -92, -97, -102,
  116157. -108, -114, -999, -999, -999, -999, -999, -999,
  116158. -999, -999, -999, -999, -999, -999, -999, -999},
  116159. {-999, -999, -999, -999, -999, -999, -106, -102,
  116160. -98, -95, -90, -85, -83, -78, -70, -45,
  116161. -43, -41, -47, -50, -51, -50, -49, -45,
  116162. -47, -41, -44, -41, -39, -43, -38, -37,
  116163. -40, -41, -44, -50, -58, -65, -73, -79,
  116164. -85, -92, -97, -101, -105, -109, -113, -999,
  116165. -999, -999, -999, -999, -999, -999, -999, -999}},
  116166. /* 1414 Hz */
  116167. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116168. -999, -999, -999, -107, -100, -95, -87, -81,
  116169. -85, -83, -88, -93, -100, -107, -114, -999,
  116170. -999, -999, -999, -999, -999, -999, -999, -999,
  116171. -999, -999, -999, -999, -999, -999, -999, -999,
  116172. -999, -999, -999, -999, -999, -999, -999, -999,
  116173. -999, -999, -999, -999, -999, -999, -999, -999},
  116174. {-999, -999, -999, -999, -999, -999, -999, -999,
  116175. -999, -999, -107, -101, -95, -88, -83, -76,
  116176. -73, -72, -79, -84, -90, -95, -100, -105,
  116177. -110, -115, -999, -999, -999, -999, -999, -999,
  116178. -999, -999, -999, -999, -999, -999, -999, -999,
  116179. -999, -999, -999, -999, -999, -999, -999, -999,
  116180. -999, -999, -999, -999, -999, -999, -999, -999},
  116181. {-999, -999, -999, -999, -999, -999, -999, -999,
  116182. -999, -999, -104, -98, -92, -87, -81, -70,
  116183. -65, -62, -67, -71, -74, -80, -85, -91,
  116184. -95, -99, -103, -108, -111, -114, -999, -999,
  116185. -999, -999, -999, -999, -999, -999, -999, -999,
  116186. -999, -999, -999, -999, -999, -999, -999, -999,
  116187. -999, -999, -999, -999, -999, -999, -999, -999},
  116188. {-999, -999, -999, -999, -999, -999, -999, -999,
  116189. -999, -999, -103, -97, -90, -85, -76, -60,
  116190. -56, -54, -60, -62, -61, -56, -63, -65,
  116191. -73, -74, -77, -75, -78, -81, -86, -87,
  116192. -88, -91, -94, -98, -103, -110, -999, -999,
  116193. -999, -999, -999, -999, -999, -999, -999, -999,
  116194. -999, -999, -999, -999, -999, -999, -999, -999},
  116195. {-999, -999, -999, -999, -999, -999, -999, -105,
  116196. -100, -97, -92, -86, -81, -79, -70, -57,
  116197. -51, -47, -51, -58, -60, -56, -53, -50,
  116198. -58, -52, -50, -50, -53, -55, -64, -69,
  116199. -71, -85, -82, -78, -81, -85, -95, -102,
  116200. -112, -999, -999, -999, -999, -999, -999, -999,
  116201. -999, -999, -999, -999, -999, -999, -999, -999},
  116202. {-999, -999, -999, -999, -999, -999, -999, -105,
  116203. -100, -97, -92, -85, -83, -79, -72, -49,
  116204. -40, -43, -43, -54, -56, -51, -50, -40,
  116205. -43, -38, -36, -35, -37, -38, -37, -44,
  116206. -54, -60, -57, -60, -70, -75, -84, -92,
  116207. -103, -112, -999, -999, -999, -999, -999, -999,
  116208. -999, -999, -999, -999, -999, -999, -999, -999}},
  116209. /* 2000 Hz */
  116210. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116211. -999, -999, -999, -110, -102, -95, -89, -82,
  116212. -83, -84, -90, -92, -99, -107, -113, -999,
  116213. -999, -999, -999, -999, -999, -999, -999, -999,
  116214. -999, -999, -999, -999, -999, -999, -999, -999,
  116215. -999, -999, -999, -999, -999, -999, -999, -999,
  116216. -999, -999, -999, -999, -999, -999, -999, -999},
  116217. {-999, -999, -999, -999, -999, -999, -999, -999,
  116218. -999, -999, -107, -101, -95, -89, -83, -72,
  116219. -74, -78, -85, -88, -88, -90, -92, -98,
  116220. -105, -111, -999, -999, -999, -999, -999, -999,
  116221. -999, -999, -999, -999, -999, -999, -999, -999,
  116222. -999, -999, -999, -999, -999, -999, -999, -999,
  116223. -999, -999, -999, -999, -999, -999, -999, -999},
  116224. {-999, -999, -999, -999, -999, -999, -999, -999,
  116225. -999, -109, -103, -97, -93, -87, -81, -70,
  116226. -70, -67, -75, -73, -76, -79, -81, -83,
  116227. -88, -89, -97, -103, -110, -999, -999, -999,
  116228. -999, -999, -999, -999, -999, -999, -999, -999,
  116229. -999, -999, -999, -999, -999, -999, -999, -999,
  116230. -999, -999, -999, -999, -999, -999, -999, -999},
  116231. {-999, -999, -999, -999, -999, -999, -999, -999,
  116232. -999, -107, -100, -94, -88, -83, -75, -63,
  116233. -59, -59, -63, -66, -60, -62, -67, -67,
  116234. -77, -76, -81, -88, -86, -92, -96, -102,
  116235. -109, -116, -999, -999, -999, -999, -999, -999,
  116236. -999, -999, -999, -999, -999, -999, -999, -999,
  116237. -999, -999, -999, -999, -999, -999, -999, -999},
  116238. {-999, -999, -999, -999, -999, -999, -999, -999,
  116239. -999, -105, -98, -92, -86, -81, -73, -56,
  116240. -52, -47, -55, -60, -58, -52, -51, -45,
  116241. -49, -50, -53, -54, -61, -71, -70, -69,
  116242. -78, -79, -87, -90, -96, -104, -112, -999,
  116243. -999, -999, -999, -999, -999, -999, -999, -999,
  116244. -999, -999, -999, -999, -999, -999, -999, -999},
  116245. {-999, -999, -999, -999, -999, -999, -999, -999,
  116246. -999, -103, -96, -90, -86, -78, -70, -51,
  116247. -42, -47, -48, -55, -54, -54, -53, -42,
  116248. -35, -28, -33, -38, -37, -44, -47, -49,
  116249. -54, -63, -68, -78, -82, -89, -94, -99,
  116250. -104, -109, -114, -999, -999, -999, -999, -999,
  116251. -999, -999, -999, -999, -999, -999, -999, -999}},
  116252. /* 2828 Hz */
  116253. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116254. -999, -999, -999, -999, -110, -100, -90, -79,
  116255. -85, -81, -82, -82, -89, -94, -99, -103,
  116256. -109, -115, -999, -999, -999, -999, -999, -999,
  116257. -999, -999, -999, -999, -999, -999, -999, -999,
  116258. -999, -999, -999, -999, -999, -999, -999, -999,
  116259. -999, -999, -999, -999, -999, -999, -999, -999},
  116260. {-999, -999, -999, -999, -999, -999, -999, -999,
  116261. -999, -999, -999, -999, -105, -97, -85, -72,
  116262. -74, -70, -70, -70, -76, -85, -91, -93,
  116263. -97, -103, -109, -115, -999, -999, -999, -999,
  116264. -999, -999, -999, -999, -999, -999, -999, -999,
  116265. -999, -999, -999, -999, -999, -999, -999, -999,
  116266. -999, -999, -999, -999, -999, -999, -999, -999},
  116267. {-999, -999, -999, -999, -999, -999, -999, -999,
  116268. -999, -999, -999, -999, -112, -93, -81, -68,
  116269. -62, -60, -60, -57, -63, -70, -77, -82,
  116270. -90, -93, -98, -104, -109, -113, -999, -999,
  116271. -999, -999, -999, -999, -999, -999, -999, -999,
  116272. -999, -999, -999, -999, -999, -999, -999, -999,
  116273. -999, -999, -999, -999, -999, -999, -999, -999},
  116274. {-999, -999, -999, -999, -999, -999, -999, -999,
  116275. -999, -999, -999, -113, -100, -93, -84, -63,
  116276. -58, -48, -53, -54, -52, -52, -57, -64,
  116277. -66, -76, -83, -81, -85, -85, -90, -95,
  116278. -98, -101, -103, -106, -108, -111, -999, -999,
  116279. -999, -999, -999, -999, -999, -999, -999, -999,
  116280. -999, -999, -999, -999, -999, -999, -999, -999},
  116281. {-999, -999, -999, -999, -999, -999, -999, -999,
  116282. -999, -999, -999, -105, -95, -86, -74, -53,
  116283. -50, -38, -43, -49, -43, -42, -39, -39,
  116284. -46, -52, -57, -56, -72, -69, -74, -81,
  116285. -87, -92, -94, -97, -99, -102, -105, -108,
  116286. -999, -999, -999, -999, -999, -999, -999, -999,
  116287. -999, -999, -999, -999, -999, -999, -999, -999},
  116288. {-999, -999, -999, -999, -999, -999, -999, -999,
  116289. -999, -999, -108, -99, -90, -76, -66, -45,
  116290. -43, -41, -44, -47, -43, -47, -40, -30,
  116291. -31, -31, -39, -33, -40, -41, -43, -53,
  116292. -59, -70, -73, -77, -79, -82, -84, -87,
  116293. -999, -999, -999, -999, -999, -999, -999, -999,
  116294. -999, -999, -999, -999, -999, -999, -999, -999}},
  116295. /* 4000 Hz */
  116296. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116297. -999, -999, -999, -999, -999, -110, -91, -76,
  116298. -75, -85, -93, -98, -104, -110, -999, -999,
  116299. -999, -999, -999, -999, -999, -999, -999, -999,
  116300. -999, -999, -999, -999, -999, -999, -999, -999,
  116301. -999, -999, -999, -999, -999, -999, -999, -999,
  116302. -999, -999, -999, -999, -999, -999, -999, -999},
  116303. {-999, -999, -999, -999, -999, -999, -999, -999,
  116304. -999, -999, -999, -999, -999, -110, -91, -70,
  116305. -70, -75, -86, -89, -94, -98, -101, -106,
  116306. -110, -999, -999, -999, -999, -999, -999, -999,
  116307. -999, -999, -999, -999, -999, -999, -999, -999,
  116308. -999, -999, -999, -999, -999, -999, -999, -999,
  116309. -999, -999, -999, -999, -999, -999, -999, -999},
  116310. {-999, -999, -999, -999, -999, -999, -999, -999,
  116311. -999, -999, -999, -999, -110, -95, -80, -60,
  116312. -65, -64, -74, -83, -88, -91, -95, -99,
  116313. -103, -107, -110, -999, -999, -999, -999, -999,
  116314. -999, -999, -999, -999, -999, -999, -999, -999,
  116315. -999, -999, -999, -999, -999, -999, -999, -999,
  116316. -999, -999, -999, -999, -999, -999, -999, -999},
  116317. {-999, -999, -999, -999, -999, -999, -999, -999,
  116318. -999, -999, -999, -999, -110, -95, -80, -58,
  116319. -55, -49, -66, -68, -71, -78, -78, -80,
  116320. -88, -85, -89, -97, -100, -105, -110, -999,
  116321. -999, -999, -999, -999, -999, -999, -999, -999,
  116322. -999, -999, -999, -999, -999, -999, -999, -999,
  116323. -999, -999, -999, -999, -999, -999, -999, -999},
  116324. {-999, -999, -999, -999, -999, -999, -999, -999,
  116325. -999, -999, -999, -999, -110, -95, -80, -53,
  116326. -52, -41, -59, -59, -49, -58, -56, -63,
  116327. -86, -79, -90, -93, -98, -103, -107, -112,
  116328. -999, -999, -999, -999, -999, -999, -999, -999,
  116329. -999, -999, -999, -999, -999, -999, -999, -999,
  116330. -999, -999, -999, -999, -999, -999, -999, -999},
  116331. {-999, -999, -999, -999, -999, -999, -999, -999,
  116332. -999, -999, -999, -110, -97, -91, -73, -45,
  116333. -40, -33, -53, -61, -49, -54, -50, -50,
  116334. -60, -52, -67, -74, -81, -92, -96, -100,
  116335. -105, -110, -999, -999, -999, -999, -999, -999,
  116336. -999, -999, -999, -999, -999, -999, -999, -999,
  116337. -999, -999, -999, -999, -999, -999, -999, -999}},
  116338. /* 5657 Hz */
  116339. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116340. -999, -999, -999, -113, -106, -99, -92, -77,
  116341. -80, -88, -97, -106, -115, -999, -999, -999,
  116342. -999, -999, -999, -999, -999, -999, -999, -999,
  116343. -999, -999, -999, -999, -999, -999, -999, -999,
  116344. -999, -999, -999, -999, -999, -999, -999, -999,
  116345. -999, -999, -999, -999, -999, -999, -999, -999},
  116346. {-999, -999, -999, -999, -999, -999, -999, -999,
  116347. -999, -999, -116, -109, -102, -95, -89, -74,
  116348. -72, -88, -87, -95, -102, -109, -116, -999,
  116349. -999, -999, -999, -999, -999, -999, -999, -999,
  116350. -999, -999, -999, -999, -999, -999, -999, -999,
  116351. -999, -999, -999, -999, -999, -999, -999, -999,
  116352. -999, -999, -999, -999, -999, -999, -999, -999},
  116353. {-999, -999, -999, -999, -999, -999, -999, -999,
  116354. -999, -999, -116, -109, -102, -95, -89, -75,
  116355. -66, -74, -77, -78, -86, -87, -90, -96,
  116356. -105, -115, -999, -999, -999, -999, -999, -999,
  116357. -999, -999, -999, -999, -999, -999, -999, -999,
  116358. -999, -999, -999, -999, -999, -999, -999, -999,
  116359. -999, -999, -999, -999, -999, -999, -999, -999},
  116360. {-999, -999, -999, -999, -999, -999, -999, -999,
  116361. -999, -999, -115, -108, -101, -94, -88, -66,
  116362. -56, -61, -70, -65, -78, -72, -83, -84,
  116363. -93, -98, -105, -110, -999, -999, -999, -999,
  116364. -999, -999, -999, -999, -999, -999, -999, -999,
  116365. -999, -999, -999, -999, -999, -999, -999, -999,
  116366. -999, -999, -999, -999, -999, -999, -999, -999},
  116367. {-999, -999, -999, -999, -999, -999, -999, -999,
  116368. -999, -999, -110, -105, -95, -89, -82, -57,
  116369. -52, -52, -59, -56, -59, -58, -69, -67,
  116370. -88, -82, -82, -89, -94, -100, -108, -999,
  116371. -999, -999, -999, -999, -999, -999, -999, -999,
  116372. -999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -999, -999, -999, -999, -999, -999},
  116374. {-999, -999, -999, -999, -999, -999, -999, -999,
  116375. -999, -110, -101, -96, -90, -83, -77, -54,
  116376. -43, -38, -50, -48, -52, -48, -42, -42,
  116377. -51, -52, -53, -59, -65, -71, -78, -85,
  116378. -95, -999, -999, -999, -999, -999, -999, -999,
  116379. -999, -999, -999, -999, -999, -999, -999, -999,
  116380. -999, -999, -999, -999, -999, -999, -999, -999}},
  116381. /* 8000 Hz */
  116382. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116383. -999, -999, -999, -999, -120, -105, -86, -68,
  116384. -78, -79, -90, -100, -110, -999, -999, -999,
  116385. -999, -999, -999, -999, -999, -999, -999, -999,
  116386. -999, -999, -999, -999, -999, -999, -999, -999,
  116387. -999, -999, -999, -999, -999, -999, -999, -999,
  116388. -999, -999, -999, -999, -999, -999, -999, -999},
  116389. {-999, -999, -999, -999, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -120, -105, -86, -66,
  116391. -73, -77, -88, -96, -105, -115, -999, -999,
  116392. -999, -999, -999, -999, -999, -999, -999, -999,
  116393. -999, -999, -999, -999, -999, -999, -999, -999,
  116394. -999, -999, -999, -999, -999, -999, -999, -999,
  116395. -999, -999, -999, -999, -999, -999, -999, -999},
  116396. {-999, -999, -999, -999, -999, -999, -999, -999,
  116397. -999, -999, -999, -120, -105, -92, -80, -61,
  116398. -64, -68, -80, -87, -92, -100, -110, -999,
  116399. -999, -999, -999, -999, -999, -999, -999, -999,
  116400. -999, -999, -999, -999, -999, -999, -999, -999,
  116401. -999, -999, -999, -999, -999, -999, -999, -999,
  116402. -999, -999, -999, -999, -999, -999, -999, -999},
  116403. {-999, -999, -999, -999, -999, -999, -999, -999,
  116404. -999, -999, -999, -120, -104, -91, -79, -52,
  116405. -60, -54, -64, -69, -77, -80, -82, -84,
  116406. -85, -87, -88, -90, -999, -999, -999, -999,
  116407. -999, -999, -999, -999, -999, -999, -999, -999,
  116408. -999, -999, -999, -999, -999, -999, -999, -999,
  116409. -999, -999, -999, -999, -999, -999, -999, -999},
  116410. {-999, -999, -999, -999, -999, -999, -999, -999,
  116411. -999, -999, -999, -118, -100, -87, -77, -49,
  116412. -50, -44, -58, -61, -61, -67, -65, -62,
  116413. -62, -62, -65, -68, -999, -999, -999, -999,
  116414. -999, -999, -999, -999, -999, -999, -999, -999,
  116415. -999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -999, -999, -999},
  116417. {-999, -999, -999, -999, -999, -999, -999, -999,
  116418. -999, -999, -999, -115, -98, -84, -62, -49,
  116419. -44, -38, -46, -49, -49, -46, -39, -37,
  116420. -39, -40, -42, -43, -999, -999, -999, -999,
  116421. -999, -999, -999, -999, -999, -999, -999, -999,
  116422. -999, -999, -999, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -999, -999, -999, -999}},
  116424. /* 11314 Hz */
  116425. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -110, -88, -74,
  116427. -77, -82, -82, -85, -90, -94, -99, -104,
  116428. -999, -999, -999, -999, -999, -999, -999, -999,
  116429. -999, -999, -999, -999, -999, -999, -999, -999,
  116430. -999, -999, -999, -999, -999, -999, -999, -999,
  116431. -999, -999, -999, -999, -999, -999, -999, -999},
  116432. {-999, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -110, -88, -66,
  116434. -70, -81, -80, -81, -84, -88, -91, -93,
  116435. -999, -999, -999, -999, -999, -999, -999, -999,
  116436. -999, -999, -999, -999, -999, -999, -999, -999,
  116437. -999, -999, -999, -999, -999, -999, -999, -999,
  116438. -999, -999, -999, -999, -999, -999, -999, -999},
  116439. {-999, -999, -999, -999, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -110, -88, -61,
  116441. -63, -70, -71, -74, -77, -80, -83, -85,
  116442. -999, -999, -999, -999, -999, -999, -999, -999,
  116443. -999, -999, -999, -999, -999, -999, -999, -999,
  116444. -999, -999, -999, -999, -999, -999, -999, -999,
  116445. -999, -999, -999, -999, -999, -999, -999, -999},
  116446. {-999, -999, -999, -999, -999, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -110, -86, -62,
  116448. -63, -62, -62, -58, -52, -50, -50, -52,
  116449. -54, -999, -999, -999, -999, -999, -999, -999,
  116450. -999, -999, -999, -999, -999, -999, -999, -999,
  116451. -999, -999, -999, -999, -999, -999, -999, -999,
  116452. -999, -999, -999, -999, -999, -999, -999, -999},
  116453. {-999, -999, -999, -999, -999, -999, -999, -999,
  116454. -999, -999, -999, -999, -118, -108, -84, -53,
  116455. -50, -50, -50, -55, -47, -45, -40, -40,
  116456. -40, -999, -999, -999, -999, -999, -999, -999,
  116457. -999, -999, -999, -999, -999, -999, -999, -999,
  116458. -999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999},
  116460. {-999, -999, -999, -999, -999, -999, -999, -999,
  116461. -999, -999, -999, -999, -118, -100, -73, -43,
  116462. -37, -42, -43, -53, -38, -37, -35, -35,
  116463. -38, -999, -999, -999, -999, -999, -999, -999,
  116464. -999, -999, -999, -999, -999, -999, -999, -999,
  116465. -999, -999, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999}},
  116467. /* 16000 Hz */
  116468. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -110, -100, -91, -84, -74,
  116470. -80, -80, -80, -80, -80, -999, -999, -999,
  116471. -999, -999, -999, -999, -999, -999, -999, -999,
  116472. -999, -999, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -999, -999, -999, -999,
  116474. -999, -999, -999, -999, -999, -999, -999, -999},
  116475. {-999, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -110, -100, -91, -84, -74,
  116477. -68, -68, -68, -68, -68, -999, -999, -999,
  116478. -999, -999, -999, -999, -999, -999, -999, -999,
  116479. -999, -999, -999, -999, -999, -999, -999, -999,
  116480. -999, -999, -999, -999, -999, -999, -999, -999,
  116481. -999, -999, -999, -999, -999, -999, -999, -999},
  116482. {-999, -999, -999, -999, -999, -999, -999, -999,
  116483. -999, -999, -999, -110, -100, -86, -78, -70,
  116484. -60, -45, -30, -21, -999, -999, -999, -999,
  116485. -999, -999, -999, -999, -999, -999, -999, -999,
  116486. -999, -999, -999, -999, -999, -999, -999, -999,
  116487. -999, -999, -999, -999, -999, -999, -999, -999,
  116488. -999, -999, -999, -999, -999, -999, -999, -999},
  116489. {-999, -999, -999, -999, -999, -999, -999, -999,
  116490. -999, -999, -999, -110, -100, -87, -78, -67,
  116491. -48, -38, -29, -21, -999, -999, -999, -999,
  116492. -999, -999, -999, -999, -999, -999, -999, -999,
  116493. -999, -999, -999, -999, -999, -999, -999, -999,
  116494. -999, -999, -999, -999, -999, -999, -999, -999,
  116495. -999, -999, -999, -999, -999, -999, -999, -999},
  116496. {-999, -999, -999, -999, -999, -999, -999, -999,
  116497. -999, -999, -999, -110, -100, -86, -69, -56,
  116498. -45, -35, -33, -29, -999, -999, -999, -999,
  116499. -999, -999, -999, -999, -999, -999, -999, -999,
  116500. -999, -999, -999, -999, -999, -999, -999, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -999, -999, -999, -999, -999, -999},
  116503. {-999, -999, -999, -999, -999, -999, -999, -999,
  116504. -999, -999, -999, -110, -100, -83, -71, -48,
  116505. -27, -38, -37, -34, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999,
  116507. -999, -999, -999, -999, -999, -999, -999, -999,
  116508. -999, -999, -999, -999, -999, -999, -999, -999,
  116509. -999, -999, -999, -999, -999, -999, -999, -999}}
  116510. };
  116511. #endif
  116512. /*** End of inlined file: masking.h ***/
  116513. #define NEGINF -9999.f
  116514. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116515. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116516. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116517. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116518. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116519. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116520. look->channels=vi->channels;
  116521. look->ampmax=-9999.;
  116522. look->gi=gi;
  116523. return(look);
  116524. }
  116525. void _vp_global_free(vorbis_look_psy_global *look){
  116526. if(look){
  116527. memset(look,0,sizeof(*look));
  116528. _ogg_free(look);
  116529. }
  116530. }
  116531. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116532. if(i){
  116533. memset(i,0,sizeof(*i));
  116534. _ogg_free(i);
  116535. }
  116536. }
  116537. void _vi_psy_free(vorbis_info_psy *i){
  116538. if(i){
  116539. memset(i,0,sizeof(*i));
  116540. _ogg_free(i);
  116541. }
  116542. }
  116543. static void min_curve(float *c,
  116544. float *c2){
  116545. int i;
  116546. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116547. }
  116548. static void max_curve(float *c,
  116549. float *c2){
  116550. int i;
  116551. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116552. }
  116553. static void attenuate_curve(float *c,float att){
  116554. int i;
  116555. for(i=0;i<EHMER_MAX;i++)
  116556. c[i]+=att;
  116557. }
  116558. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116559. float center_boost, float center_decay_rate){
  116560. int i,j,k,m;
  116561. float ath[EHMER_MAX];
  116562. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116563. float athc[P_LEVELS][EHMER_MAX];
  116564. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116565. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116566. memset(workc,0,sizeof(workc));
  116567. for(i=0;i<P_BANDS;i++){
  116568. /* we add back in the ATH to avoid low level curves falling off to
  116569. -infinity and unnecessarily cutting off high level curves in the
  116570. curve limiting (last step). */
  116571. /* A half-band's settings must be valid over the whole band, and
  116572. it's better to mask too little than too much */
  116573. int ath_offset=i*4;
  116574. for(j=0;j<EHMER_MAX;j++){
  116575. float min=999.;
  116576. for(k=0;k<4;k++)
  116577. if(j+k+ath_offset<MAX_ATH){
  116578. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116579. }else{
  116580. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116581. }
  116582. ath[j]=min;
  116583. }
  116584. /* copy curves into working space, replicate the 50dB curve to 30
  116585. and 40, replicate the 100dB curve to 110 */
  116586. for(j=0;j<6;j++)
  116587. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116588. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116589. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116590. /* apply centered curve boost/decay */
  116591. for(j=0;j<P_LEVELS;j++){
  116592. for(k=0;k<EHMER_MAX;k++){
  116593. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116594. if(adj<0. && center_boost>0)adj=0.;
  116595. if(adj>0. && center_boost<0)adj=0.;
  116596. workc[i][j][k]+=adj;
  116597. }
  116598. }
  116599. /* normalize curves so the driving amplitude is 0dB */
  116600. /* make temp curves with the ATH overlayed */
  116601. for(j=0;j<P_LEVELS;j++){
  116602. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116603. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116604. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116605. max_curve(athc[j],workc[i][j]);
  116606. }
  116607. /* Now limit the louder curves.
  116608. the idea is this: We don't know what the playback attenuation
  116609. will be; 0dB SL moves every time the user twiddles the volume
  116610. knob. So that means we have to use a single 'most pessimal' curve
  116611. for all masking amplitudes, right? Wrong. The *loudest* sound
  116612. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116613. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116614. etc... */
  116615. for(j=1;j<P_LEVELS;j++){
  116616. min_curve(athc[j],athc[j-1]);
  116617. min_curve(workc[i][j],athc[j]);
  116618. }
  116619. }
  116620. for(i=0;i<P_BANDS;i++){
  116621. int hi_curve,lo_curve,bin;
  116622. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116623. /* low frequency curves are measured with greater resolution than
  116624. the MDCT/FFT will actually give us; we want the curve applied
  116625. to the tone data to be pessimistic and thus apply the minimum
  116626. masking possible for a given bin. That means that a single bin
  116627. could span more than one octave and that the curve will be a
  116628. composite of multiple octaves. It also may mean that a single
  116629. bin may span > an eighth of an octave and that the eighth
  116630. octave values may also be composited. */
  116631. /* which octave curves will we be compositing? */
  116632. bin=floor(fromOC(i*.5)/binHz);
  116633. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116634. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116635. if(lo_curve>i)lo_curve=i;
  116636. if(lo_curve<0)lo_curve=0;
  116637. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116638. for(m=0;m<P_LEVELS;m++){
  116639. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116640. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116641. /* render the curve into bins, then pull values back into curve.
  116642. The point is that any inherent subsampling aliasing results in
  116643. a safe minimum */
  116644. for(k=lo_curve;k<=hi_curve;k++){
  116645. int l=0;
  116646. for(j=0;j<EHMER_MAX;j++){
  116647. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116648. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116649. if(lo_bin<0)lo_bin=0;
  116650. if(lo_bin>n)lo_bin=n;
  116651. if(lo_bin<l)l=lo_bin;
  116652. if(hi_bin<0)hi_bin=0;
  116653. if(hi_bin>n)hi_bin=n;
  116654. for(;l<hi_bin && l<n;l++)
  116655. if(brute_buffer[l]>workc[k][m][j])
  116656. brute_buffer[l]=workc[k][m][j];
  116657. }
  116658. for(;l<n;l++)
  116659. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116660. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116661. }
  116662. /* be equally paranoid about being valid up to next half ocatve */
  116663. if(i+1<P_BANDS){
  116664. int l=0;
  116665. k=i+1;
  116666. for(j=0;j<EHMER_MAX;j++){
  116667. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116668. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116669. if(lo_bin<0)lo_bin=0;
  116670. if(lo_bin>n)lo_bin=n;
  116671. if(lo_bin<l)l=lo_bin;
  116672. if(hi_bin<0)hi_bin=0;
  116673. if(hi_bin>n)hi_bin=n;
  116674. for(;l<hi_bin && l<n;l++)
  116675. if(brute_buffer[l]>workc[k][m][j])
  116676. brute_buffer[l]=workc[k][m][j];
  116677. }
  116678. for(;l<n;l++)
  116679. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116680. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116681. }
  116682. for(j=0;j<EHMER_MAX;j++){
  116683. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116684. if(bin<0){
  116685. ret[i][m][j+2]=-999.;
  116686. }else{
  116687. if(bin>=n){
  116688. ret[i][m][j+2]=-999.;
  116689. }else{
  116690. ret[i][m][j+2]=brute_buffer[bin];
  116691. }
  116692. }
  116693. }
  116694. /* add fenceposts */
  116695. for(j=0;j<EHMER_OFFSET;j++)
  116696. if(ret[i][m][j+2]>-200.f)break;
  116697. ret[i][m][0]=j;
  116698. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116699. if(ret[i][m][j+2]>-200.f)
  116700. break;
  116701. ret[i][m][1]=j;
  116702. }
  116703. }
  116704. return(ret);
  116705. }
  116706. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116707. vorbis_info_psy_global *gi,int n,long rate){
  116708. long i,j,lo=-99,hi=1;
  116709. long maxoc;
  116710. memset(p,0,sizeof(*p));
  116711. p->eighth_octave_lines=gi->eighth_octave_lines;
  116712. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116713. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116714. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116715. p->total_octave_lines=maxoc-p->firstoc+1;
  116716. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116717. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116718. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116719. p->vi=vi;
  116720. p->n=n;
  116721. p->rate=rate;
  116722. /* AoTuV HF weighting */
  116723. p->m_val = 1.;
  116724. if(rate < 26000) p->m_val = 0;
  116725. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116726. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116727. /* set up the lookups for a given blocksize and sample rate */
  116728. for(i=0,j=0;i<MAX_ATH-1;i++){
  116729. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116730. float base=ATH[i];
  116731. if(j<endpos){
  116732. float delta=(ATH[i+1]-base)/(endpos-j);
  116733. for(;j<endpos && j<n;j++){
  116734. p->ath[j]=base+100.;
  116735. base+=delta;
  116736. }
  116737. }
  116738. }
  116739. for(i=0;i<n;i++){
  116740. float bark=toBARK(rate/(2*n)*i);
  116741. for(;lo+vi->noisewindowlomin<i &&
  116742. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116743. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116744. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116745. p->bark[i]=((lo-1)<<16)+(hi-1);
  116746. }
  116747. for(i=0;i<n;i++)
  116748. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116749. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116750. vi->tone_centerboost,vi->tone_decay);
  116751. /* set up rolling noise median */
  116752. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116753. for(i=0;i<P_NOISECURVES;i++)
  116754. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116755. for(i=0;i<n;i++){
  116756. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116757. int inthalfoc;
  116758. float del;
  116759. if(halfoc<0)halfoc=0;
  116760. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116761. inthalfoc=(int)halfoc;
  116762. del=halfoc-inthalfoc;
  116763. for(j=0;j<P_NOISECURVES;j++)
  116764. p->noiseoffset[j][i]=
  116765. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116766. p->vi->noiseoff[j][inthalfoc+1]*del;
  116767. }
  116768. #if 0
  116769. {
  116770. static int ls=0;
  116771. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116772. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116773. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116774. }
  116775. #endif
  116776. }
  116777. void _vp_psy_clear(vorbis_look_psy *p){
  116778. int i,j;
  116779. if(p){
  116780. if(p->ath)_ogg_free(p->ath);
  116781. if(p->octave)_ogg_free(p->octave);
  116782. if(p->bark)_ogg_free(p->bark);
  116783. if(p->tonecurves){
  116784. for(i=0;i<P_BANDS;i++){
  116785. for(j=0;j<P_LEVELS;j++){
  116786. _ogg_free(p->tonecurves[i][j]);
  116787. }
  116788. _ogg_free(p->tonecurves[i]);
  116789. }
  116790. _ogg_free(p->tonecurves);
  116791. }
  116792. if(p->noiseoffset){
  116793. for(i=0;i<P_NOISECURVES;i++){
  116794. _ogg_free(p->noiseoffset[i]);
  116795. }
  116796. _ogg_free(p->noiseoffset);
  116797. }
  116798. memset(p,0,sizeof(*p));
  116799. }
  116800. }
  116801. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116802. static void seed_curve(float *seed,
  116803. const float **curves,
  116804. float amp,
  116805. int oc, int n,
  116806. int linesper,float dBoffset){
  116807. int i,post1;
  116808. int seedptr;
  116809. const float *posts,*curve;
  116810. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116811. choice=max(choice,0);
  116812. choice=min(choice,P_LEVELS-1);
  116813. posts=curves[choice];
  116814. curve=posts+2;
  116815. post1=(int)posts[1];
  116816. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116817. for(i=posts[0];i<post1;i++){
  116818. if(seedptr>0){
  116819. float lin=amp+curve[i];
  116820. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116821. }
  116822. seedptr+=linesper;
  116823. if(seedptr>=n)break;
  116824. }
  116825. }
  116826. static void seed_loop(vorbis_look_psy *p,
  116827. const float ***curves,
  116828. const float *f,
  116829. const float *flr,
  116830. float *seed,
  116831. float specmax){
  116832. vorbis_info_psy *vi=p->vi;
  116833. long n=p->n,i;
  116834. float dBoffset=vi->max_curve_dB-specmax;
  116835. /* prime the working vector with peak values */
  116836. for(i=0;i<n;i++){
  116837. float max=f[i];
  116838. long oc=p->octave[i];
  116839. while(i+1<n && p->octave[i+1]==oc){
  116840. i++;
  116841. if(f[i]>max)max=f[i];
  116842. }
  116843. if(max+6.f>flr[i]){
  116844. oc=oc>>p->shiftoc;
  116845. if(oc>=P_BANDS)oc=P_BANDS-1;
  116846. if(oc<0)oc=0;
  116847. seed_curve(seed,
  116848. curves[oc],
  116849. max,
  116850. p->octave[i]-p->firstoc,
  116851. p->total_octave_lines,
  116852. p->eighth_octave_lines,
  116853. dBoffset);
  116854. }
  116855. }
  116856. }
  116857. static void seed_chase(float *seeds, int linesper, long n){
  116858. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116859. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116860. long stack=0;
  116861. long pos=0;
  116862. long i;
  116863. for(i=0;i<n;i++){
  116864. if(stack<2){
  116865. posstack[stack]=i;
  116866. ampstack[stack++]=seeds[i];
  116867. }else{
  116868. while(1){
  116869. if(seeds[i]<ampstack[stack-1]){
  116870. posstack[stack]=i;
  116871. ampstack[stack++]=seeds[i];
  116872. break;
  116873. }else{
  116874. if(i<posstack[stack-1]+linesper){
  116875. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116876. i<posstack[stack-2]+linesper){
  116877. /* we completely overlap, making stack-1 irrelevant. pop it */
  116878. stack--;
  116879. continue;
  116880. }
  116881. }
  116882. posstack[stack]=i;
  116883. ampstack[stack++]=seeds[i];
  116884. break;
  116885. }
  116886. }
  116887. }
  116888. }
  116889. /* the stack now contains only the positions that are relevant. Scan
  116890. 'em straight through */
  116891. for(i=0;i<stack;i++){
  116892. long endpos;
  116893. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116894. endpos=posstack[i+1];
  116895. }else{
  116896. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116897. discarded in short frames */
  116898. }
  116899. if(endpos>n)endpos=n;
  116900. for(;pos<endpos;pos++)
  116901. seeds[pos]=ampstack[i];
  116902. }
  116903. /* there. Linear time. I now remember this was on a problem set I
  116904. had in Grad Skool... I didn't solve it at the time ;-) */
  116905. }
  116906. /* bleaugh, this is more complicated than it needs to be */
  116907. #include<stdio.h>
  116908. static void max_seeds(vorbis_look_psy *p,
  116909. float *seed,
  116910. float *flr){
  116911. long n=p->total_octave_lines;
  116912. int linesper=p->eighth_octave_lines;
  116913. long linpos=0;
  116914. long pos;
  116915. seed_chase(seed,linesper,n); /* for masking */
  116916. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116917. while(linpos+1<p->n){
  116918. float minV=seed[pos];
  116919. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116920. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116921. while(pos+1<=end){
  116922. pos++;
  116923. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116924. minV=seed[pos];
  116925. }
  116926. end=pos+p->firstoc;
  116927. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116928. if(flr[linpos]<minV)flr[linpos]=minV;
  116929. }
  116930. {
  116931. float minV=seed[p->total_octave_lines-1];
  116932. for(;linpos<p->n;linpos++)
  116933. if(flr[linpos]<minV)flr[linpos]=minV;
  116934. }
  116935. }
  116936. static void bark_noise_hybridmp(int n,const long *b,
  116937. const float *f,
  116938. float *noise,
  116939. const float offset,
  116940. const int fixed){
  116941. float *N=(float*) alloca(n*sizeof(*N));
  116942. float *X=(float*) alloca(n*sizeof(*N));
  116943. float *XX=(float*) alloca(n*sizeof(*N));
  116944. float *Y=(float*) alloca(n*sizeof(*N));
  116945. float *XY=(float*) alloca(n*sizeof(*N));
  116946. float tN, tX, tXX, tY, tXY;
  116947. int i;
  116948. int lo, hi;
  116949. float R, A, B, D;
  116950. float w, x, y;
  116951. tN = tX = tXX = tY = tXY = 0.f;
  116952. y = f[0] + offset;
  116953. if (y < 1.f) y = 1.f;
  116954. w = y * y * .5;
  116955. tN += w;
  116956. tX += w;
  116957. tY += w * y;
  116958. N[0] = tN;
  116959. X[0] = tX;
  116960. XX[0] = tXX;
  116961. Y[0] = tY;
  116962. XY[0] = tXY;
  116963. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116964. y = f[i] + offset;
  116965. if (y < 1.f) y = 1.f;
  116966. w = y * y;
  116967. tN += w;
  116968. tX += w * x;
  116969. tXX += w * x * x;
  116970. tY += w * y;
  116971. tXY += w * x * y;
  116972. N[i] = tN;
  116973. X[i] = tX;
  116974. XX[i] = tXX;
  116975. Y[i] = tY;
  116976. XY[i] = tXY;
  116977. }
  116978. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116979. lo = b[i] >> 16;
  116980. if( lo>=0 ) break;
  116981. hi = b[i] & 0xffff;
  116982. tN = N[hi] + N[-lo];
  116983. tX = X[hi] - X[-lo];
  116984. tXX = XX[hi] + XX[-lo];
  116985. tY = Y[hi] + Y[-lo];
  116986. tXY = XY[hi] - XY[-lo];
  116987. A = tY * tXX - tX * tXY;
  116988. B = tN * tXY - tX * tY;
  116989. D = tN * tXX - tX * tX;
  116990. R = (A + x * B) / D;
  116991. if (R < 0.f)
  116992. R = 0.f;
  116993. noise[i] = R - offset;
  116994. }
  116995. for ( ;; i++, x += 1.f) {
  116996. lo = b[i] >> 16;
  116997. hi = b[i] & 0xffff;
  116998. if(hi>=n)break;
  116999. tN = N[hi] - N[lo];
  117000. tX = X[hi] - X[lo];
  117001. tXX = XX[hi] - XX[lo];
  117002. tY = Y[hi] - Y[lo];
  117003. tXY = XY[hi] - XY[lo];
  117004. A = tY * tXX - tX * tXY;
  117005. B = tN * tXY - tX * tY;
  117006. D = tN * tXX - tX * tX;
  117007. R = (A + x * B) / D;
  117008. if (R < 0.f) R = 0.f;
  117009. noise[i] = R - offset;
  117010. }
  117011. for ( ; i < n; i++, x += 1.f) {
  117012. R = (A + x * B) / D;
  117013. if (R < 0.f) R = 0.f;
  117014. noise[i] = R - offset;
  117015. }
  117016. if (fixed <= 0) return;
  117017. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117018. hi = i + fixed / 2;
  117019. lo = hi - fixed;
  117020. if(lo>=0)break;
  117021. tN = N[hi] + N[-lo];
  117022. tX = X[hi] - X[-lo];
  117023. tXX = XX[hi] + XX[-lo];
  117024. tY = Y[hi] + Y[-lo];
  117025. tXY = XY[hi] - XY[-lo];
  117026. A = tY * tXX - tX * tXY;
  117027. B = tN * tXY - tX * tY;
  117028. D = tN * tXX - tX * tX;
  117029. R = (A + x * B) / D;
  117030. if (R - offset < noise[i]) noise[i] = R - offset;
  117031. }
  117032. for ( ;; i++, x += 1.f) {
  117033. hi = i + fixed / 2;
  117034. lo = hi - fixed;
  117035. if(hi>=n)break;
  117036. tN = N[hi] - N[lo];
  117037. tX = X[hi] - X[lo];
  117038. tXX = XX[hi] - XX[lo];
  117039. tY = Y[hi] - Y[lo];
  117040. tXY = XY[hi] - XY[lo];
  117041. A = tY * tXX - tX * tXY;
  117042. B = tN * tXY - tX * tY;
  117043. D = tN * tXX - tX * tX;
  117044. R = (A + x * B) / D;
  117045. if (R - offset < noise[i]) noise[i] = R - offset;
  117046. }
  117047. for ( ; i < n; i++, x += 1.f) {
  117048. R = (A + x * B) / D;
  117049. if (R - offset < noise[i]) noise[i] = R - offset;
  117050. }
  117051. }
  117052. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117053. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117054. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117055. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117056. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117057. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117058. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117059. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117060. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117061. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117062. 973377.F, 913981.F, 858210.F, 805842.F,
  117063. 756669.F, 710497.F, 667142.F, 626433.F,
  117064. 588208.F, 552316.F, 518613.F, 486967.F,
  117065. 457252.F, 429351.F, 403152.F, 378551.F,
  117066. 355452.F, 333762.F, 313396.F, 294273.F,
  117067. 276316.F, 259455.F, 243623.F, 228757.F,
  117068. 214798.F, 201691.F, 189384.F, 177828.F,
  117069. 166977.F, 156788.F, 147221.F, 138237.F,
  117070. 129802.F, 121881.F, 114444.F, 107461.F,
  117071. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117072. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117073. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117074. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117075. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117076. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117077. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117078. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117079. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117080. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117081. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117082. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117083. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117084. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117085. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117086. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117087. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117088. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117089. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117090. 842.910F, 791.475F, 743.179F, 697.830F,
  117091. 655.249F, 615.265F, 577.722F, 542.469F,
  117092. 509.367F, 478.286F, 449.101F, 421.696F,
  117093. 395.964F, 371.803F, 349.115F, 327.812F,
  117094. 307.809F, 289.026F, 271.390F, 254.830F,
  117095. 239.280F, 224.679F, 210.969F, 198.096F,
  117096. 186.008F, 174.658F, 164.000F, 153.993F,
  117097. 144.596F, 135.773F, 127.488F, 119.708F,
  117098. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117099. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117100. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117101. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117102. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117103. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117104. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117105. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117106. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117107. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117108. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117109. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117110. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117111. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117112. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117113. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117114. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117115. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117116. 1.20790F, 1.13419F, 1.06499F, 1.F
  117117. };
  117118. void _vp_remove_floor(vorbis_look_psy *p,
  117119. float *mdct,
  117120. int *codedflr,
  117121. float *residue,
  117122. int sliding_lowpass){
  117123. int i,n=p->n;
  117124. if(sliding_lowpass>n)sliding_lowpass=n;
  117125. for(i=0;i<sliding_lowpass;i++){
  117126. residue[i]=
  117127. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117128. }
  117129. for(;i<n;i++)
  117130. residue[i]=0.;
  117131. }
  117132. void _vp_noisemask(vorbis_look_psy *p,
  117133. float *logmdct,
  117134. float *logmask){
  117135. int i,n=p->n;
  117136. float *work=(float*) alloca(n*sizeof(*work));
  117137. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117138. 140.,-1);
  117139. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117140. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117141. p->vi->noisewindowfixed);
  117142. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117143. #if 0
  117144. {
  117145. static int seq=0;
  117146. float work2[n];
  117147. for(i=0;i<n;i++){
  117148. work2[i]=logmask[i]+work[i];
  117149. }
  117150. if(seq&1)
  117151. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117152. else
  117153. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117154. if(seq&1)
  117155. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117156. else
  117157. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117158. seq++;
  117159. }
  117160. #endif
  117161. for(i=0;i<n;i++){
  117162. int dB=logmask[i]+.5;
  117163. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117164. if(dB<0)dB=0;
  117165. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117166. }
  117167. }
  117168. void _vp_tonemask(vorbis_look_psy *p,
  117169. float *logfft,
  117170. float *logmask,
  117171. float global_specmax,
  117172. float local_specmax){
  117173. int i,n=p->n;
  117174. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117175. float att=local_specmax+p->vi->ath_adjatt;
  117176. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117177. /* set the ATH (floating below localmax, not global max by a
  117178. specified att) */
  117179. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117180. for(i=0;i<n;i++)
  117181. logmask[i]=p->ath[i]+att;
  117182. /* tone masking */
  117183. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117184. max_seeds(p,seed,logmask);
  117185. }
  117186. void _vp_offset_and_mix(vorbis_look_psy *p,
  117187. float *noise,
  117188. float *tone,
  117189. int offset_select,
  117190. float *logmask,
  117191. float *mdct,
  117192. float *logmdct){
  117193. int i,n=p->n;
  117194. float de, coeffi, cx;/* AoTuV */
  117195. float toneatt=p->vi->tone_masteratt[offset_select];
  117196. cx = p->m_val;
  117197. for(i=0;i<n;i++){
  117198. float val= noise[i]+p->noiseoffset[offset_select][i];
  117199. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117200. logmask[i]=max(val,tone[i]+toneatt);
  117201. /* AoTuV */
  117202. /** @ M1 **
  117203. The following codes improve a noise problem.
  117204. A fundamental idea uses the value of masking and carries out
  117205. the relative compensation of the MDCT.
  117206. However, this code is not perfect and all noise problems cannot be solved.
  117207. by Aoyumi @ 2004/04/18
  117208. */
  117209. if(offset_select == 1) {
  117210. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117211. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117212. if(val > coeffi){
  117213. /* mdct value is > -17.2 dB below floor */
  117214. de = 1.0-((val-coeffi)*0.005*cx);
  117215. /* pro-rated attenuation:
  117216. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117217. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117218. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117219. etc... */
  117220. if(de < 0) de = 0.0001;
  117221. }else
  117222. /* mdct value is <= -17.2 dB below floor */
  117223. de = 1.0-((val-coeffi)*0.0003*cx);
  117224. /* pro-rated attenuation:
  117225. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117226. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117227. etc... */
  117228. mdct[i] *= de;
  117229. }
  117230. }
  117231. }
  117232. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117233. vorbis_info *vi=vd->vi;
  117234. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117235. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117236. int n=ci->blocksizes[vd->W]/2;
  117237. float secs=(float)n/vi->rate;
  117238. amp+=secs*gi->ampmax_att_per_sec;
  117239. if(amp<-9999)amp=-9999;
  117240. return(amp);
  117241. }
  117242. static void couple_lossless(float A, float B,
  117243. float *qA, float *qB){
  117244. int test1=fabs(*qA)>fabs(*qB);
  117245. test1-= fabs(*qA)<fabs(*qB);
  117246. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117247. if(test1==1){
  117248. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117249. }else{
  117250. float temp=*qB;
  117251. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117252. *qA=temp;
  117253. }
  117254. if(*qB>fabs(*qA)*1.9999f){
  117255. *qB= -fabs(*qA)*2.f;
  117256. *qA= -*qA;
  117257. }
  117258. }
  117259. static float hypot_lookup[32]={
  117260. -0.009935, -0.011245, -0.012726, -0.014397,
  117261. -0.016282, -0.018407, -0.020800, -0.023494,
  117262. -0.026522, -0.029923, -0.033737, -0.038010,
  117263. -0.042787, -0.048121, -0.054064, -0.060671,
  117264. -0.068000, -0.076109, -0.085054, -0.094892,
  117265. -0.105675, -0.117451, -0.130260, -0.144134,
  117266. -0.159093, -0.175146, -0.192286, -0.210490,
  117267. -0.229718, -0.249913, -0.271001, -0.292893};
  117268. static void precomputed_couple_point(float premag,
  117269. int floorA,int floorB,
  117270. float *mag, float *ang){
  117271. int test=(floorA>floorB)-1;
  117272. int offset=31-abs(floorA-floorB);
  117273. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117274. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117275. *mag=premag*floormag;
  117276. *ang=0.f;
  117277. }
  117278. /* just like below, this is currently set up to only do
  117279. single-step-depth coupling. Otherwise, we'd have to do more
  117280. copying (which will be inevitable later) */
  117281. /* doing the real circular magnitude calculation is audibly superior
  117282. to (A+B)/sqrt(2) */
  117283. static float dipole_hypot(float a, float b){
  117284. if(a>0.){
  117285. if(b>0.)return sqrt(a*a+b*b);
  117286. if(a>-b)return sqrt(a*a-b*b);
  117287. return -sqrt(b*b-a*a);
  117288. }
  117289. if(b<0.)return -sqrt(a*a+b*b);
  117290. if(-a>b)return -sqrt(a*a-b*b);
  117291. return sqrt(b*b-a*a);
  117292. }
  117293. static float round_hypot(float a, float b){
  117294. if(a>0.){
  117295. if(b>0.)return sqrt(a*a+b*b);
  117296. if(a>-b)return sqrt(a*a+b*b);
  117297. return -sqrt(b*b+a*a);
  117298. }
  117299. if(b<0.)return -sqrt(a*a+b*b);
  117300. if(-a>b)return -sqrt(a*a+b*b);
  117301. return sqrt(b*b+a*a);
  117302. }
  117303. /* revert to round hypot for now */
  117304. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117305. vorbis_info_psy_global *g,
  117306. vorbis_look_psy *p,
  117307. vorbis_info_mapping0 *vi,
  117308. float **mdct){
  117309. int i,j,n=p->n;
  117310. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117311. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117312. for(i=0;i<vi->coupling_steps;i++){
  117313. float *mdctM=mdct[vi->coupling_mag[i]];
  117314. float *mdctA=mdct[vi->coupling_ang[i]];
  117315. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117316. for(j=0;j<limit;j++)
  117317. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117318. for(;j<n;j++)
  117319. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117320. }
  117321. return(ret);
  117322. }
  117323. /* this is for per-channel noise normalization */
  117324. static int apsort(const void *a, const void *b){
  117325. float f1=fabs(**(float**)a);
  117326. float f2=fabs(**(float**)b);
  117327. return (f1<f2)-(f1>f2);
  117328. }
  117329. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117330. vorbis_look_psy *p,
  117331. vorbis_info_mapping0 *vi,
  117332. float **mags){
  117333. if(p->vi->normal_point_p){
  117334. int i,j,k,n=p->n;
  117335. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117336. int partition=p->vi->normal_partition;
  117337. float **work=(float**) alloca(sizeof(*work)*partition);
  117338. for(i=0;i<vi->coupling_steps;i++){
  117339. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117340. for(j=0;j<n;j+=partition){
  117341. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117342. qsort(work,partition,sizeof(*work),apsort);
  117343. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117344. }
  117345. }
  117346. return(ret);
  117347. }
  117348. return(NULL);
  117349. }
  117350. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117351. float *magnitudes,int *sortedindex){
  117352. int i,j,n=p->n;
  117353. vorbis_info_psy *vi=p->vi;
  117354. int partition=vi->normal_partition;
  117355. float **work=(float**) alloca(sizeof(*work)*partition);
  117356. int start=vi->normal_start;
  117357. for(j=start;j<n;j+=partition){
  117358. if(j+partition>n)partition=n-j;
  117359. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117360. qsort(work,partition,sizeof(*work),apsort);
  117361. for(i=0;i<partition;i++){
  117362. sortedindex[i+j-start]=work[i]-magnitudes;
  117363. }
  117364. }
  117365. }
  117366. void _vp_noise_normalize(vorbis_look_psy *p,
  117367. float *in,float *out,int *sortedindex){
  117368. int flag=0,i,j=0,n=p->n;
  117369. vorbis_info_psy *vi=p->vi;
  117370. int partition=vi->normal_partition;
  117371. int start=vi->normal_start;
  117372. if(start>n)start=n;
  117373. if(vi->normal_channel_p){
  117374. for(;j<start;j++)
  117375. out[j]=rint(in[j]);
  117376. for(;j+partition<=n;j+=partition){
  117377. float acc=0.;
  117378. int k;
  117379. for(i=j;i<j+partition;i++)
  117380. acc+=in[i]*in[i];
  117381. for(i=0;i<partition;i++){
  117382. k=sortedindex[i+j-start];
  117383. if(in[k]*in[k]>=.25f){
  117384. out[k]=rint(in[k]);
  117385. acc-=in[k]*in[k];
  117386. flag=1;
  117387. }else{
  117388. if(acc<vi->normal_thresh)break;
  117389. out[k]=unitnorm(in[k]);
  117390. acc-=1.;
  117391. }
  117392. }
  117393. for(;i<partition;i++){
  117394. k=sortedindex[i+j-start];
  117395. out[k]=0.;
  117396. }
  117397. }
  117398. }
  117399. for(;j<n;j++)
  117400. out[j]=rint(in[j]);
  117401. }
  117402. void _vp_couple(int blobno,
  117403. vorbis_info_psy_global *g,
  117404. vorbis_look_psy *p,
  117405. vorbis_info_mapping0 *vi,
  117406. float **res,
  117407. float **mag_memo,
  117408. int **mag_sort,
  117409. int **ifloor,
  117410. int *nonzero,
  117411. int sliding_lowpass){
  117412. int i,j,k,n=p->n;
  117413. /* perform any requested channel coupling */
  117414. /* point stereo can only be used in a first stage (in this encoder)
  117415. because of the dependency on floor lookups */
  117416. for(i=0;i<vi->coupling_steps;i++){
  117417. /* once we're doing multistage coupling in which a channel goes
  117418. through more than one coupling step, the floor vector
  117419. magnitudes will also have to be recalculated an propogated
  117420. along with PCM. Right now, we're not (that will wait until 5.1
  117421. most likely), so the code isn't here yet. The memory management
  117422. here is all assuming single depth couplings anyway. */
  117423. /* make sure coupling a zero and a nonzero channel results in two
  117424. nonzero channels. */
  117425. if(nonzero[vi->coupling_mag[i]] ||
  117426. nonzero[vi->coupling_ang[i]]){
  117427. float *rM=res[vi->coupling_mag[i]];
  117428. float *rA=res[vi->coupling_ang[i]];
  117429. float *qM=rM+n;
  117430. float *qA=rA+n;
  117431. int *floorM=ifloor[vi->coupling_mag[i]];
  117432. int *floorA=ifloor[vi->coupling_ang[i]];
  117433. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117434. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117435. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117436. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117437. int pointlimit=limit;
  117438. nonzero[vi->coupling_mag[i]]=1;
  117439. nonzero[vi->coupling_ang[i]]=1;
  117440. /* The threshold of a stereo is changed with the size of n */
  117441. if(n > 1000)
  117442. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117443. for(j=0;j<p->n;j+=partition){
  117444. float acc=0.f;
  117445. for(k=0;k<partition;k++){
  117446. int l=k+j;
  117447. if(l<sliding_lowpass){
  117448. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117449. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117450. precomputed_couple_point(mag_memo[i][l],
  117451. floorM[l],floorA[l],
  117452. qM+l,qA+l);
  117453. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117454. }else{
  117455. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117456. }
  117457. }else{
  117458. qM[l]=0.;
  117459. qA[l]=0.;
  117460. }
  117461. }
  117462. if(p->vi->normal_point_p){
  117463. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117464. int l=mag_sort[i][j+k];
  117465. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117466. qM[l]=unitnorm(qM[l]);
  117467. acc-=1.f;
  117468. }
  117469. }
  117470. }
  117471. }
  117472. }
  117473. }
  117474. }
  117475. /* AoTuV */
  117476. /** @ M2 **
  117477. The boost problem by the combination of noise normalization and point stereo is eased.
  117478. However, this is a temporary patch.
  117479. by Aoyumi @ 2004/04/18
  117480. */
  117481. void hf_reduction(vorbis_info_psy_global *g,
  117482. vorbis_look_psy *p,
  117483. vorbis_info_mapping0 *vi,
  117484. float **mdct){
  117485. int i,j,n=p->n, de=0.3*p->m_val;
  117486. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117487. for(i=0; i<vi->coupling_steps; i++){
  117488. /* for(j=start; j<limit; j++){} // ???*/
  117489. for(j=limit; j<n; j++)
  117490. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117491. }
  117492. }
  117493. #endif
  117494. /*** End of inlined file: psy.c ***/
  117495. /*** Start of inlined file: registry.c ***/
  117496. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117497. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117498. // tasks..
  117499. #if JUCE_MSVC
  117500. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117501. #endif
  117502. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117503. #if JUCE_USE_OGGVORBIS
  117504. /* seems like major overkill now; the backend numbers will grow into
  117505. the infrastructure soon enough */
  117506. extern vorbis_func_floor floor0_exportbundle;
  117507. extern vorbis_func_floor floor1_exportbundle;
  117508. extern vorbis_func_residue residue0_exportbundle;
  117509. extern vorbis_func_residue residue1_exportbundle;
  117510. extern vorbis_func_residue residue2_exportbundle;
  117511. extern vorbis_func_mapping mapping0_exportbundle;
  117512. vorbis_func_floor *_floor_P[]={
  117513. &floor0_exportbundle,
  117514. &floor1_exportbundle,
  117515. };
  117516. vorbis_func_residue *_residue_P[]={
  117517. &residue0_exportbundle,
  117518. &residue1_exportbundle,
  117519. &residue2_exportbundle,
  117520. };
  117521. vorbis_func_mapping *_mapping_P[]={
  117522. &mapping0_exportbundle,
  117523. };
  117524. #endif
  117525. /*** End of inlined file: registry.c ***/
  117526. /*** Start of inlined file: res0.c ***/
  117527. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117528. encode/decode loops are coded for clarity and performance is not
  117529. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117530. it's slow. */
  117531. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117532. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117533. // tasks..
  117534. #if JUCE_MSVC
  117535. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117536. #endif
  117537. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117538. #if JUCE_USE_OGGVORBIS
  117539. #include <stdlib.h>
  117540. #include <string.h>
  117541. #include <math.h>
  117542. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117543. #include <stdio.h>
  117544. #endif
  117545. typedef struct {
  117546. vorbis_info_residue0 *info;
  117547. int parts;
  117548. int stages;
  117549. codebook *fullbooks;
  117550. codebook *phrasebook;
  117551. codebook ***partbooks;
  117552. int partvals;
  117553. int **decodemap;
  117554. long postbits;
  117555. long phrasebits;
  117556. long frames;
  117557. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117558. int train_seq;
  117559. long *training_data[8][64];
  117560. float training_max[8][64];
  117561. float training_min[8][64];
  117562. float tmin;
  117563. float tmax;
  117564. #endif
  117565. } vorbis_look_residue0;
  117566. void res0_free_info(vorbis_info_residue *i){
  117567. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117568. if(info){
  117569. memset(info,0,sizeof(*info));
  117570. _ogg_free(info);
  117571. }
  117572. }
  117573. void res0_free_look(vorbis_look_residue *i){
  117574. int j;
  117575. if(i){
  117576. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117577. #ifdef TRAIN_RES
  117578. {
  117579. int j,k,l;
  117580. for(j=0;j<look->parts;j++){
  117581. /*fprintf(stderr,"partition %d: ",j);*/
  117582. for(k=0;k<8;k++)
  117583. if(look->training_data[k][j]){
  117584. char buffer[80];
  117585. FILE *of;
  117586. codebook *statebook=look->partbooks[j][k];
  117587. /* long and short into the same bucket by current convention */
  117588. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117589. of=fopen(buffer,"a");
  117590. for(l=0;l<statebook->entries;l++)
  117591. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117592. fclose(of);
  117593. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117594. look->training_min[k][j],look->training_max[k][j]);*/
  117595. _ogg_free(look->training_data[k][j]);
  117596. look->training_data[k][j]=NULL;
  117597. }
  117598. /*fprintf(stderr,"\n");*/
  117599. }
  117600. }
  117601. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117602. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117603. (float)look->phrasebits/look->frames,
  117604. (float)look->postbits/look->frames,
  117605. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117606. #endif
  117607. /*vorbis_info_residue0 *info=look->info;
  117608. fprintf(stderr,
  117609. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117610. "(%g/frame) \n",look->frames,look->phrasebits,
  117611. look->resbitsflat,
  117612. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117613. for(j=0;j<look->parts;j++){
  117614. long acc=0;
  117615. fprintf(stderr,"\t[%d] == ",j);
  117616. for(k=0;k<look->stages;k++)
  117617. if((info->secondstages[j]>>k)&1){
  117618. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117619. acc+=look->resbits[j][k];
  117620. }
  117621. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117622. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117623. }
  117624. fprintf(stderr,"\n");*/
  117625. for(j=0;j<look->parts;j++)
  117626. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117627. _ogg_free(look->partbooks);
  117628. for(j=0;j<look->partvals;j++)
  117629. _ogg_free(look->decodemap[j]);
  117630. _ogg_free(look->decodemap);
  117631. memset(look,0,sizeof(*look));
  117632. _ogg_free(look);
  117633. }
  117634. }
  117635. static int icount(unsigned int v){
  117636. int ret=0;
  117637. while(v){
  117638. ret+=v&1;
  117639. v>>=1;
  117640. }
  117641. return(ret);
  117642. }
  117643. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117644. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117645. int j,acc=0;
  117646. oggpack_write(opb,info->begin,24);
  117647. oggpack_write(opb,info->end,24);
  117648. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117649. code with a partitioned book */
  117650. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117651. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117652. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117653. bitmask of one indicates this partition class has bits to write
  117654. this pass */
  117655. for(j=0;j<info->partitions;j++){
  117656. if(ilog(info->secondstages[j])>3){
  117657. /* yes, this is a minor hack due to not thinking ahead */
  117658. oggpack_write(opb,info->secondstages[j],3);
  117659. oggpack_write(opb,1,1);
  117660. oggpack_write(opb,info->secondstages[j]>>3,5);
  117661. }else
  117662. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117663. acc+=icount(info->secondstages[j]);
  117664. }
  117665. for(j=0;j<acc;j++)
  117666. oggpack_write(opb,info->booklist[j],8);
  117667. }
  117668. /* vorbis_info is for range checking */
  117669. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117670. int j,acc=0;
  117671. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117672. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117673. info->begin=oggpack_read(opb,24);
  117674. info->end=oggpack_read(opb,24);
  117675. info->grouping=oggpack_read(opb,24)+1;
  117676. info->partitions=oggpack_read(opb,6)+1;
  117677. info->groupbook=oggpack_read(opb,8);
  117678. for(j=0;j<info->partitions;j++){
  117679. int cascade=oggpack_read(opb,3);
  117680. if(oggpack_read(opb,1))
  117681. cascade|=(oggpack_read(opb,5)<<3);
  117682. info->secondstages[j]=cascade;
  117683. acc+=icount(cascade);
  117684. }
  117685. for(j=0;j<acc;j++)
  117686. info->booklist[j]=oggpack_read(opb,8);
  117687. if(info->groupbook>=ci->books)goto errout;
  117688. for(j=0;j<acc;j++)
  117689. if(info->booklist[j]>=ci->books)goto errout;
  117690. return(info);
  117691. errout:
  117692. res0_free_info(info);
  117693. return(NULL);
  117694. }
  117695. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117696. vorbis_info_residue *vr){
  117697. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117698. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117699. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117700. int j,k,acc=0;
  117701. int dim;
  117702. int maxstage=0;
  117703. look->info=info;
  117704. look->parts=info->partitions;
  117705. look->fullbooks=ci->fullbooks;
  117706. look->phrasebook=ci->fullbooks+info->groupbook;
  117707. dim=look->phrasebook->dim;
  117708. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117709. for(j=0;j<look->parts;j++){
  117710. int stages=ilog(info->secondstages[j]);
  117711. if(stages){
  117712. if(stages>maxstage)maxstage=stages;
  117713. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117714. for(k=0;k<stages;k++)
  117715. if(info->secondstages[j]&(1<<k)){
  117716. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117717. #ifdef TRAIN_RES
  117718. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117719. sizeof(***look->training_data));
  117720. #endif
  117721. }
  117722. }
  117723. }
  117724. look->partvals=rint(pow((float)look->parts,(float)dim));
  117725. look->stages=maxstage;
  117726. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117727. for(j=0;j<look->partvals;j++){
  117728. long val=j;
  117729. long mult=look->partvals/look->parts;
  117730. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117731. for(k=0;k<dim;k++){
  117732. long deco=val/mult;
  117733. val-=deco*mult;
  117734. mult/=look->parts;
  117735. look->decodemap[j][k]=deco;
  117736. }
  117737. }
  117738. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117739. {
  117740. static int train_seq=0;
  117741. look->train_seq=train_seq++;
  117742. }
  117743. #endif
  117744. return(look);
  117745. }
  117746. /* break an abstraction and copy some code for performance purposes */
  117747. static int local_book_besterror(codebook *book,float *a){
  117748. int dim=book->dim,i,k,o;
  117749. int best=0;
  117750. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117751. /* find the quant val of each scalar */
  117752. for(k=0,o=dim;k<dim;++k){
  117753. float val=a[--o];
  117754. i=tt->threshvals>>1;
  117755. if(val<tt->quantthresh[i]){
  117756. if(val<tt->quantthresh[i-1]){
  117757. for(--i;i>0;--i)
  117758. if(val>=tt->quantthresh[i-1])
  117759. break;
  117760. }
  117761. }else{
  117762. for(++i;i<tt->threshvals-1;++i)
  117763. if(val<tt->quantthresh[i])break;
  117764. }
  117765. best=(best*tt->quantvals)+tt->quantmap[i];
  117766. }
  117767. /* regular lattices are easy :-) */
  117768. if(book->c->lengthlist[best]<=0){
  117769. const static_codebook *c=book->c;
  117770. int i,j;
  117771. float bestf=0.f;
  117772. float *e=book->valuelist;
  117773. best=-1;
  117774. for(i=0;i<book->entries;i++){
  117775. if(c->lengthlist[i]>0){
  117776. float thisx=0.f;
  117777. for(j=0;j<dim;j++){
  117778. float val=(e[j]-a[j]);
  117779. thisx+=val*val;
  117780. }
  117781. if(best==-1 || thisx<bestf){
  117782. bestf=thisx;
  117783. best=i;
  117784. }
  117785. }
  117786. e+=dim;
  117787. }
  117788. }
  117789. {
  117790. float *ptr=book->valuelist+best*dim;
  117791. for(i=0;i<dim;i++)
  117792. *a++ -= *ptr++;
  117793. }
  117794. return(best);
  117795. }
  117796. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117797. codebook *book,long *acc){
  117798. int i,bits=0;
  117799. int dim=book->dim;
  117800. int step=n/dim;
  117801. for(i=0;i<step;i++){
  117802. int entry=local_book_besterror(book,vec+i*dim);
  117803. #ifdef TRAIN_RES
  117804. acc[entry]++;
  117805. #endif
  117806. bits+=vorbis_book_encode(book,entry,opb);
  117807. }
  117808. return(bits);
  117809. }
  117810. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117811. float **in,int ch){
  117812. long i,j,k;
  117813. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117814. vorbis_info_residue0 *info=look->info;
  117815. /* move all this setup out later */
  117816. int samples_per_partition=info->grouping;
  117817. int possible_partitions=info->partitions;
  117818. int n=info->end-info->begin;
  117819. int partvals=n/samples_per_partition;
  117820. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117821. float scale=100./samples_per_partition;
  117822. /* we find the partition type for each partition of each
  117823. channel. We'll go back and do the interleaved encoding in a
  117824. bit. For now, clarity */
  117825. for(i=0;i<ch;i++){
  117826. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117827. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117828. }
  117829. for(i=0;i<partvals;i++){
  117830. int offset=i*samples_per_partition+info->begin;
  117831. for(j=0;j<ch;j++){
  117832. float max=0.;
  117833. float ent=0.;
  117834. for(k=0;k<samples_per_partition;k++){
  117835. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117836. ent+=fabs(rint(in[j][offset+k]));
  117837. }
  117838. ent*=scale;
  117839. for(k=0;k<possible_partitions-1;k++)
  117840. if(max<=info->classmetric1[k] &&
  117841. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117842. break;
  117843. partword[j][i]=k;
  117844. }
  117845. }
  117846. #ifdef TRAIN_RESAUX
  117847. {
  117848. FILE *of;
  117849. char buffer[80];
  117850. for(i=0;i<ch;i++){
  117851. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117852. of=fopen(buffer,"a");
  117853. for(j=0;j<partvals;j++)
  117854. fprintf(of,"%ld, ",partword[i][j]);
  117855. fprintf(of,"\n");
  117856. fclose(of);
  117857. }
  117858. }
  117859. #endif
  117860. look->frames++;
  117861. return(partword);
  117862. }
  117863. /* designed for stereo or other modes where the partition size is an
  117864. integer multiple of the number of channels encoded in the current
  117865. submap */
  117866. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117867. int ch){
  117868. long i,j,k,l;
  117869. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117870. vorbis_info_residue0 *info=look->info;
  117871. /* move all this setup out later */
  117872. int samples_per_partition=info->grouping;
  117873. int possible_partitions=info->partitions;
  117874. int n=info->end-info->begin;
  117875. int partvals=n/samples_per_partition;
  117876. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117877. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117878. FILE *of;
  117879. char buffer[80];
  117880. #endif
  117881. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117882. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117883. for(i=0,l=info->begin/ch;i<partvals;i++){
  117884. float magmax=0.f;
  117885. float angmax=0.f;
  117886. for(j=0;j<samples_per_partition;j+=ch){
  117887. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117888. for(k=1;k<ch;k++)
  117889. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117890. l++;
  117891. }
  117892. for(j=0;j<possible_partitions-1;j++)
  117893. if(magmax<=info->classmetric1[j] &&
  117894. angmax<=info->classmetric2[j])
  117895. break;
  117896. partword[0][i]=j;
  117897. }
  117898. #ifdef TRAIN_RESAUX
  117899. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117900. of=fopen(buffer,"a");
  117901. for(i=0;i<partvals;i++)
  117902. fprintf(of,"%ld, ",partword[0][i]);
  117903. fprintf(of,"\n");
  117904. fclose(of);
  117905. #endif
  117906. look->frames++;
  117907. return(partword);
  117908. }
  117909. static int _01forward(oggpack_buffer *opb,
  117910. vorbis_block *vb,vorbis_look_residue *vl,
  117911. float **in,int ch,
  117912. long **partword,
  117913. int (*encode)(oggpack_buffer *,float *,int,
  117914. codebook *,long *)){
  117915. long i,j,k,s;
  117916. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117917. vorbis_info_residue0 *info=look->info;
  117918. /* move all this setup out later */
  117919. int samples_per_partition=info->grouping;
  117920. int possible_partitions=info->partitions;
  117921. int partitions_per_word=look->phrasebook->dim;
  117922. int n=info->end-info->begin;
  117923. int partvals=n/samples_per_partition;
  117924. long resbits[128];
  117925. long resvals[128];
  117926. #ifdef TRAIN_RES
  117927. for(i=0;i<ch;i++)
  117928. for(j=info->begin;j<info->end;j++){
  117929. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117930. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117931. }
  117932. #endif
  117933. memset(resbits,0,sizeof(resbits));
  117934. memset(resvals,0,sizeof(resvals));
  117935. /* we code the partition words for each channel, then the residual
  117936. words for a partition per channel until we've written all the
  117937. residual words for that partition word. Then write the next
  117938. partition channel words... */
  117939. for(s=0;s<look->stages;s++){
  117940. for(i=0;i<partvals;){
  117941. /* first we encode a partition codeword for each channel */
  117942. if(s==0){
  117943. for(j=0;j<ch;j++){
  117944. long val=partword[j][i];
  117945. for(k=1;k<partitions_per_word;k++){
  117946. val*=possible_partitions;
  117947. if(i+k<partvals)
  117948. val+=partword[j][i+k];
  117949. }
  117950. /* training hack */
  117951. if(val<look->phrasebook->entries)
  117952. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117953. #if 0 /*def TRAIN_RES*/
  117954. else
  117955. fprintf(stderr,"!");
  117956. #endif
  117957. }
  117958. }
  117959. /* now we encode interleaved residual values for the partitions */
  117960. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117961. long offset=i*samples_per_partition+info->begin;
  117962. for(j=0;j<ch;j++){
  117963. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117964. if(info->secondstages[partword[j][i]]&(1<<s)){
  117965. codebook *statebook=look->partbooks[partword[j][i]][s];
  117966. if(statebook){
  117967. int ret;
  117968. long *accumulator=NULL;
  117969. #ifdef TRAIN_RES
  117970. accumulator=look->training_data[s][partword[j][i]];
  117971. {
  117972. int l;
  117973. float *samples=in[j]+offset;
  117974. for(l=0;l<samples_per_partition;l++){
  117975. if(samples[l]<look->training_min[s][partword[j][i]])
  117976. look->training_min[s][partword[j][i]]=samples[l];
  117977. if(samples[l]>look->training_max[s][partword[j][i]])
  117978. look->training_max[s][partword[j][i]]=samples[l];
  117979. }
  117980. }
  117981. #endif
  117982. ret=encode(opb,in[j]+offset,samples_per_partition,
  117983. statebook,accumulator);
  117984. look->postbits+=ret;
  117985. resbits[partword[j][i]]+=ret;
  117986. }
  117987. }
  117988. }
  117989. }
  117990. }
  117991. }
  117992. /*{
  117993. long total=0;
  117994. long totalbits=0;
  117995. fprintf(stderr,"%d :: ",vb->mode);
  117996. for(k=0;k<possible_partitions;k++){
  117997. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117998. total+=resvals[k];
  117999. totalbits+=resbits[k];
  118000. }
  118001. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118002. }*/
  118003. return(0);
  118004. }
  118005. /* a truncated packet here just means 'stop working'; it's not an error */
  118006. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118007. float **in,int ch,
  118008. long (*decodepart)(codebook *, float *,
  118009. oggpack_buffer *,int)){
  118010. long i,j,k,l,s;
  118011. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118012. vorbis_info_residue0 *info=look->info;
  118013. /* move all this setup out later */
  118014. int samples_per_partition=info->grouping;
  118015. int partitions_per_word=look->phrasebook->dim;
  118016. int n=info->end-info->begin;
  118017. int partvals=n/samples_per_partition;
  118018. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118019. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118020. for(j=0;j<ch;j++)
  118021. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118022. for(s=0;s<look->stages;s++){
  118023. /* each loop decodes on partition codeword containing
  118024. partitions_pre_word partitions */
  118025. for(i=0,l=0;i<partvals;l++){
  118026. if(s==0){
  118027. /* fetch the partition word for each channel */
  118028. for(j=0;j<ch;j++){
  118029. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118030. if(temp==-1)goto eopbreak;
  118031. partword[j][l]=look->decodemap[temp];
  118032. if(partword[j][l]==NULL)goto errout;
  118033. }
  118034. }
  118035. /* now we decode residual values for the partitions */
  118036. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118037. for(j=0;j<ch;j++){
  118038. long offset=info->begin+i*samples_per_partition;
  118039. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118040. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118041. if(stagebook){
  118042. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118043. samples_per_partition)==-1)goto eopbreak;
  118044. }
  118045. }
  118046. }
  118047. }
  118048. }
  118049. errout:
  118050. eopbreak:
  118051. return(0);
  118052. }
  118053. #if 0
  118054. /* residue 0 and 1 are just slight variants of one another. 0 is
  118055. interleaved, 1 is not */
  118056. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118057. float **in,int *nonzero,int ch){
  118058. /* we encode only the nonzero parts of a bundle */
  118059. int i,used=0;
  118060. for(i=0;i<ch;i++)
  118061. if(nonzero[i])
  118062. in[used++]=in[i];
  118063. if(used)
  118064. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118065. return(_01class(vb,vl,in,used));
  118066. else
  118067. return(0);
  118068. }
  118069. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118070. float **in,float **out,int *nonzero,int ch,
  118071. long **partword){
  118072. /* we encode only the nonzero parts of a bundle */
  118073. int i,j,used=0,n=vb->pcmend/2;
  118074. for(i=0;i<ch;i++)
  118075. if(nonzero[i]){
  118076. if(out)
  118077. for(j=0;j<n;j++)
  118078. out[i][j]+=in[i][j];
  118079. in[used++]=in[i];
  118080. }
  118081. if(used){
  118082. int ret=_01forward(vb,vl,in,used,partword,
  118083. _interleaved_encodepart);
  118084. if(out){
  118085. used=0;
  118086. for(i=0;i<ch;i++)
  118087. if(nonzero[i]){
  118088. for(j=0;j<n;j++)
  118089. out[i][j]-=in[used][j];
  118090. used++;
  118091. }
  118092. }
  118093. return(ret);
  118094. }else{
  118095. return(0);
  118096. }
  118097. }
  118098. #endif
  118099. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118100. float **in,int *nonzero,int ch){
  118101. int i,used=0;
  118102. for(i=0;i<ch;i++)
  118103. if(nonzero[i])
  118104. in[used++]=in[i];
  118105. if(used)
  118106. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118107. else
  118108. return(0);
  118109. }
  118110. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118111. float **in,float **out,int *nonzero,int ch,
  118112. long **partword){
  118113. int i,j,used=0,n=vb->pcmend/2;
  118114. for(i=0;i<ch;i++)
  118115. if(nonzero[i]){
  118116. if(out)
  118117. for(j=0;j<n;j++)
  118118. out[i][j]+=in[i][j];
  118119. in[used++]=in[i];
  118120. }
  118121. if(used){
  118122. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118123. if(out){
  118124. used=0;
  118125. for(i=0;i<ch;i++)
  118126. if(nonzero[i]){
  118127. for(j=0;j<n;j++)
  118128. out[i][j]-=in[used][j];
  118129. used++;
  118130. }
  118131. }
  118132. return(ret);
  118133. }else{
  118134. return(0);
  118135. }
  118136. }
  118137. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118138. float **in,int *nonzero,int ch){
  118139. int i,used=0;
  118140. for(i=0;i<ch;i++)
  118141. if(nonzero[i])
  118142. in[used++]=in[i];
  118143. if(used)
  118144. return(_01class(vb,vl,in,used));
  118145. else
  118146. return(0);
  118147. }
  118148. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118149. float **in,int *nonzero,int ch){
  118150. int i,used=0;
  118151. for(i=0;i<ch;i++)
  118152. if(nonzero[i])
  118153. in[used++]=in[i];
  118154. if(used)
  118155. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118156. else
  118157. return(0);
  118158. }
  118159. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118160. float **in,int *nonzero,int ch){
  118161. int i,used=0;
  118162. for(i=0;i<ch;i++)
  118163. if(nonzero[i])used++;
  118164. if(used)
  118165. return(_2class(vb,vl,in,ch));
  118166. else
  118167. return(0);
  118168. }
  118169. /* res2 is slightly more different; all the channels are interleaved
  118170. into a single vector and encoded. */
  118171. int res2_forward(oggpack_buffer *opb,
  118172. vorbis_block *vb,vorbis_look_residue *vl,
  118173. float **in,float **out,int *nonzero,int ch,
  118174. long **partword){
  118175. long i,j,k,n=vb->pcmend/2,used=0;
  118176. /* don't duplicate the code; use a working vector hack for now and
  118177. reshape ourselves into a single channel res1 */
  118178. /* ugly; reallocs for each coupling pass :-( */
  118179. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118180. for(i=0;i<ch;i++){
  118181. float *pcm=in[i];
  118182. if(nonzero[i])used++;
  118183. for(j=0,k=i;j<n;j++,k+=ch)
  118184. work[k]=pcm[j];
  118185. }
  118186. if(used){
  118187. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118188. /* update the sofar vector */
  118189. if(out){
  118190. for(i=0;i<ch;i++){
  118191. float *pcm=in[i];
  118192. float *sofar=out[i];
  118193. for(j=0,k=i;j<n;j++,k+=ch)
  118194. sofar[j]+=pcm[j]-work[k];
  118195. }
  118196. }
  118197. return(ret);
  118198. }else{
  118199. return(0);
  118200. }
  118201. }
  118202. /* duplicate code here as speed is somewhat more important */
  118203. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118204. float **in,int *nonzero,int ch){
  118205. long i,k,l,s;
  118206. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118207. vorbis_info_residue0 *info=look->info;
  118208. /* move all this setup out later */
  118209. int samples_per_partition=info->grouping;
  118210. int partitions_per_word=look->phrasebook->dim;
  118211. int n=info->end-info->begin;
  118212. int partvals=n/samples_per_partition;
  118213. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118214. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118215. for(i=0;i<ch;i++)if(nonzero[i])break;
  118216. if(i==ch)return(0); /* no nonzero vectors */
  118217. for(s=0;s<look->stages;s++){
  118218. for(i=0,l=0;i<partvals;l++){
  118219. if(s==0){
  118220. /* fetch the partition word */
  118221. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118222. if(temp==-1)goto eopbreak;
  118223. partword[l]=look->decodemap[temp];
  118224. if(partword[l]==NULL)goto errout;
  118225. }
  118226. /* now we decode residual values for the partitions */
  118227. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118228. if(info->secondstages[partword[l][k]]&(1<<s)){
  118229. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118230. if(stagebook){
  118231. if(vorbis_book_decodevv_add(stagebook,in,
  118232. i*samples_per_partition+info->begin,ch,
  118233. &vb->opb,samples_per_partition)==-1)
  118234. goto eopbreak;
  118235. }
  118236. }
  118237. }
  118238. }
  118239. errout:
  118240. eopbreak:
  118241. return(0);
  118242. }
  118243. vorbis_func_residue residue0_exportbundle={
  118244. NULL,
  118245. &res0_unpack,
  118246. &res0_look,
  118247. &res0_free_info,
  118248. &res0_free_look,
  118249. NULL,
  118250. NULL,
  118251. &res0_inverse
  118252. };
  118253. vorbis_func_residue residue1_exportbundle={
  118254. &res0_pack,
  118255. &res0_unpack,
  118256. &res0_look,
  118257. &res0_free_info,
  118258. &res0_free_look,
  118259. &res1_class,
  118260. &res1_forward,
  118261. &res1_inverse
  118262. };
  118263. vorbis_func_residue residue2_exportbundle={
  118264. &res0_pack,
  118265. &res0_unpack,
  118266. &res0_look,
  118267. &res0_free_info,
  118268. &res0_free_look,
  118269. &res2_class,
  118270. &res2_forward,
  118271. &res2_inverse
  118272. };
  118273. #endif
  118274. /*** End of inlined file: res0.c ***/
  118275. /*** Start of inlined file: sharedbook.c ***/
  118276. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118277. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118278. // tasks..
  118279. #if JUCE_MSVC
  118280. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118281. #endif
  118282. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118283. #if JUCE_USE_OGGVORBIS
  118284. #include <stdlib.h>
  118285. #include <math.h>
  118286. #include <string.h>
  118287. /**** pack/unpack helpers ******************************************/
  118288. int _ilog(unsigned int v){
  118289. int ret=0;
  118290. while(v){
  118291. ret++;
  118292. v>>=1;
  118293. }
  118294. return(ret);
  118295. }
  118296. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118297. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118298. Why not IEEE? It's just not that important here. */
  118299. #define VQ_FEXP 10
  118300. #define VQ_FMAN 21
  118301. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118302. /* doesn't currently guard under/overflow */
  118303. long _float32_pack(float val){
  118304. int sign=0;
  118305. long exp;
  118306. long mant;
  118307. if(val<0){
  118308. sign=0x80000000;
  118309. val= -val;
  118310. }
  118311. exp= floor(log(val)/log(2.f));
  118312. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118313. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118314. return(sign|exp|mant);
  118315. }
  118316. float _float32_unpack(long val){
  118317. double mant=val&0x1fffff;
  118318. int sign=val&0x80000000;
  118319. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118320. if(sign)mant= -mant;
  118321. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118322. }
  118323. /* given a list of word lengths, generate a list of codewords. Works
  118324. for length ordered or unordered, always assigns the lowest valued
  118325. codewords first. Extended to handle unused entries (length 0) */
  118326. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118327. long i,j,count=0;
  118328. ogg_uint32_t marker[33];
  118329. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118330. memset(marker,0,sizeof(marker));
  118331. for(i=0;i<n;i++){
  118332. long length=l[i];
  118333. if(length>0){
  118334. ogg_uint32_t entry=marker[length];
  118335. /* when we claim a node for an entry, we also claim the nodes
  118336. below it (pruning off the imagined tree that may have dangled
  118337. from it) as well as blocking the use of any nodes directly
  118338. above for leaves */
  118339. /* update ourself */
  118340. if(length<32 && (entry>>length)){
  118341. /* error condition; the lengths must specify an overpopulated tree */
  118342. _ogg_free(r);
  118343. return(NULL);
  118344. }
  118345. r[count++]=entry;
  118346. /* Look to see if the next shorter marker points to the node
  118347. above. if so, update it and repeat. */
  118348. {
  118349. for(j=length;j>0;j--){
  118350. if(marker[j]&1){
  118351. /* have to jump branches */
  118352. if(j==1)
  118353. marker[1]++;
  118354. else
  118355. marker[j]=marker[j-1]<<1;
  118356. break; /* invariant says next upper marker would already
  118357. have been moved if it was on the same path */
  118358. }
  118359. marker[j]++;
  118360. }
  118361. }
  118362. /* prune the tree; the implicit invariant says all the longer
  118363. markers were dangling from our just-taken node. Dangle them
  118364. from our *new* node. */
  118365. for(j=length+1;j<33;j++)
  118366. if((marker[j]>>1) == entry){
  118367. entry=marker[j];
  118368. marker[j]=marker[j-1]<<1;
  118369. }else
  118370. break;
  118371. }else
  118372. if(sparsecount==0)count++;
  118373. }
  118374. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118375. endian */
  118376. for(i=0,count=0;i<n;i++){
  118377. ogg_uint32_t temp=0;
  118378. for(j=0;j<l[i];j++){
  118379. temp<<=1;
  118380. temp|=(r[count]>>j)&1;
  118381. }
  118382. if(sparsecount){
  118383. if(l[i])
  118384. r[count++]=temp;
  118385. }else
  118386. r[count++]=temp;
  118387. }
  118388. return(r);
  118389. }
  118390. /* there might be a straightforward one-line way to do the below
  118391. that's portable and totally safe against roundoff, but I haven't
  118392. thought of it. Therefore, we opt on the side of caution */
  118393. long _book_maptype1_quantvals(const static_codebook *b){
  118394. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118395. /* the above *should* be reliable, but we'll not assume that FP is
  118396. ever reliable when bitstream sync is at stake; verify via integer
  118397. means that vals really is the greatest value of dim for which
  118398. vals^b->bim <= b->entries */
  118399. /* treat the above as an initial guess */
  118400. while(1){
  118401. long acc=1;
  118402. long acc1=1;
  118403. int i;
  118404. for(i=0;i<b->dim;i++){
  118405. acc*=vals;
  118406. acc1*=vals+1;
  118407. }
  118408. if(acc<=b->entries && acc1>b->entries){
  118409. return(vals);
  118410. }else{
  118411. if(acc>b->entries){
  118412. vals--;
  118413. }else{
  118414. vals++;
  118415. }
  118416. }
  118417. }
  118418. }
  118419. /* unpack the quantized list of values for encode/decode ***********/
  118420. /* we need to deal with two map types: in map type 1, the values are
  118421. generated algorithmically (each column of the vector counts through
  118422. the values in the quant vector). in map type 2, all the values came
  118423. in in an explicit list. Both value lists must be unpacked */
  118424. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118425. long j,k,count=0;
  118426. if(b->maptype==1 || b->maptype==2){
  118427. int quantvals;
  118428. float mindel=_float32_unpack(b->q_min);
  118429. float delta=_float32_unpack(b->q_delta);
  118430. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118431. /* maptype 1 and 2 both use a quantized value vector, but
  118432. different sizes */
  118433. switch(b->maptype){
  118434. case 1:
  118435. /* most of the time, entries%dimensions == 0, but we need to be
  118436. well defined. We define that the possible vales at each
  118437. scalar is values == entries/dim. If entries%dim != 0, we'll
  118438. have 'too few' values (values*dim<entries), which means that
  118439. we'll have 'left over' entries; left over entries use zeroed
  118440. values (and are wasted). So don't generate codebooks like
  118441. that */
  118442. quantvals=_book_maptype1_quantvals(b);
  118443. for(j=0;j<b->entries;j++){
  118444. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118445. float last=0.f;
  118446. int indexdiv=1;
  118447. for(k=0;k<b->dim;k++){
  118448. int index= (j/indexdiv)%quantvals;
  118449. float val=b->quantlist[index];
  118450. val=fabs(val)*delta+mindel+last;
  118451. if(b->q_sequencep)last=val;
  118452. if(sparsemap)
  118453. r[sparsemap[count]*b->dim+k]=val;
  118454. else
  118455. r[count*b->dim+k]=val;
  118456. indexdiv*=quantvals;
  118457. }
  118458. count++;
  118459. }
  118460. }
  118461. break;
  118462. case 2:
  118463. for(j=0;j<b->entries;j++){
  118464. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118465. float last=0.f;
  118466. for(k=0;k<b->dim;k++){
  118467. float val=b->quantlist[j*b->dim+k];
  118468. val=fabs(val)*delta+mindel+last;
  118469. if(b->q_sequencep)last=val;
  118470. if(sparsemap)
  118471. r[sparsemap[count]*b->dim+k]=val;
  118472. else
  118473. r[count*b->dim+k]=val;
  118474. }
  118475. count++;
  118476. }
  118477. }
  118478. break;
  118479. }
  118480. return(r);
  118481. }
  118482. return(NULL);
  118483. }
  118484. void vorbis_staticbook_clear(static_codebook *b){
  118485. if(b->allocedp){
  118486. if(b->quantlist)_ogg_free(b->quantlist);
  118487. if(b->lengthlist)_ogg_free(b->lengthlist);
  118488. if(b->nearest_tree){
  118489. _ogg_free(b->nearest_tree->ptr0);
  118490. _ogg_free(b->nearest_tree->ptr1);
  118491. _ogg_free(b->nearest_tree->p);
  118492. _ogg_free(b->nearest_tree->q);
  118493. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118494. _ogg_free(b->nearest_tree);
  118495. }
  118496. if(b->thresh_tree){
  118497. _ogg_free(b->thresh_tree->quantthresh);
  118498. _ogg_free(b->thresh_tree->quantmap);
  118499. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118500. _ogg_free(b->thresh_tree);
  118501. }
  118502. memset(b,0,sizeof(*b));
  118503. }
  118504. }
  118505. void vorbis_staticbook_destroy(static_codebook *b){
  118506. if(b->allocedp){
  118507. vorbis_staticbook_clear(b);
  118508. _ogg_free(b);
  118509. }
  118510. }
  118511. void vorbis_book_clear(codebook *b){
  118512. /* static book is not cleared; we're likely called on the lookup and
  118513. the static codebook belongs to the info struct */
  118514. if(b->valuelist)_ogg_free(b->valuelist);
  118515. if(b->codelist)_ogg_free(b->codelist);
  118516. if(b->dec_index)_ogg_free(b->dec_index);
  118517. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118518. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118519. memset(b,0,sizeof(*b));
  118520. }
  118521. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118522. memset(c,0,sizeof(*c));
  118523. c->c=s;
  118524. c->entries=s->entries;
  118525. c->used_entries=s->entries;
  118526. c->dim=s->dim;
  118527. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118528. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118529. return(0);
  118530. }
  118531. static int sort32a(const void *a,const void *b){
  118532. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118533. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118534. }
  118535. /* decode codebook arrangement is more heavily optimized than encode */
  118536. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118537. int i,j,n=0,tabn;
  118538. int *sortindex;
  118539. memset(c,0,sizeof(*c));
  118540. /* count actually used entries */
  118541. for(i=0;i<s->entries;i++)
  118542. if(s->lengthlist[i]>0)
  118543. n++;
  118544. c->entries=s->entries;
  118545. c->used_entries=n;
  118546. c->dim=s->dim;
  118547. /* two different remappings go on here.
  118548. First, we collapse the likely sparse codebook down only to
  118549. actually represented values/words. This collapsing needs to be
  118550. indexed as map-valueless books are used to encode original entry
  118551. positions as integers.
  118552. Second, we reorder all vectors, including the entry index above,
  118553. by sorted bitreversed codeword to allow treeless decode. */
  118554. {
  118555. /* perform sort */
  118556. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118557. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118558. if(codes==NULL)goto err_out;
  118559. for(i=0;i<n;i++){
  118560. codes[i]=ogg_bitreverse(codes[i]);
  118561. codep[i]=codes+i;
  118562. }
  118563. qsort(codep,n,sizeof(*codep),sort32a);
  118564. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118565. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118566. /* the index is a reverse index */
  118567. for(i=0;i<n;i++){
  118568. int position=codep[i]-codes;
  118569. sortindex[position]=i;
  118570. }
  118571. for(i=0;i<n;i++)
  118572. c->codelist[sortindex[i]]=codes[i];
  118573. _ogg_free(codes);
  118574. }
  118575. c->valuelist=_book_unquantize(s,n,sortindex);
  118576. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118577. for(n=0,i=0;i<s->entries;i++)
  118578. if(s->lengthlist[i]>0)
  118579. c->dec_index[sortindex[n++]]=i;
  118580. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118581. for(n=0,i=0;i<s->entries;i++)
  118582. if(s->lengthlist[i]>0)
  118583. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118584. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118585. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118586. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118587. tabn=1<<c->dec_firsttablen;
  118588. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118589. c->dec_maxlength=0;
  118590. for(i=0;i<n;i++){
  118591. if(c->dec_maxlength<c->dec_codelengths[i])
  118592. c->dec_maxlength=c->dec_codelengths[i];
  118593. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118594. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118595. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118596. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118597. }
  118598. }
  118599. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118600. hints for the non-direct-hits */
  118601. {
  118602. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118603. long lo=0,hi=0;
  118604. for(i=0;i<tabn;i++){
  118605. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118606. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118607. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118608. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118609. /* we only actually have 15 bits per hint to play with here.
  118610. In order to overflow gracefully (nothing breaks, efficiency
  118611. just drops), encode as the difference from the extremes. */
  118612. {
  118613. unsigned long loval=lo;
  118614. unsigned long hival=n-hi;
  118615. if(loval>0x7fff)loval=0x7fff;
  118616. if(hival>0x7fff)hival=0x7fff;
  118617. c->dec_firsttable[ogg_bitreverse(word)]=
  118618. 0x80000000UL | (loval<<15) | hival;
  118619. }
  118620. }
  118621. }
  118622. }
  118623. return(0);
  118624. err_out:
  118625. vorbis_book_clear(c);
  118626. return(-1);
  118627. }
  118628. static float _dist(int el,float *ref, float *b,int step){
  118629. int i;
  118630. float acc=0.f;
  118631. for(i=0;i<el;i++){
  118632. float val=(ref[i]-b[i*step]);
  118633. acc+=val*val;
  118634. }
  118635. return(acc);
  118636. }
  118637. int _best(codebook *book, float *a, int step){
  118638. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118639. #if 0
  118640. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118641. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118642. #endif
  118643. int dim=book->dim;
  118644. int k,o;
  118645. /*int savebest=-1;
  118646. float saverr;*/
  118647. /* do we have a threshhold encode hint? */
  118648. if(tt){
  118649. int index=0,i;
  118650. /* find the quant val of each scalar */
  118651. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118652. i=tt->threshvals>>1;
  118653. if(a[o]<tt->quantthresh[i]){
  118654. for(;i>0;i--)
  118655. if(a[o]>=tt->quantthresh[i-1])
  118656. break;
  118657. }else{
  118658. for(i++;i<tt->threshvals-1;i++)
  118659. if(a[o]<tt->quantthresh[i])break;
  118660. }
  118661. index=(index*tt->quantvals)+tt->quantmap[i];
  118662. }
  118663. /* regular lattices are easy :-) */
  118664. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118665. use a decision tree after all
  118666. and fall through*/
  118667. return(index);
  118668. }
  118669. #if 0
  118670. /* do we have a pigeonhole encode hint? */
  118671. if(pt){
  118672. const static_codebook *c=book->c;
  118673. int i,besti=-1;
  118674. float best=0.f;
  118675. int entry=0;
  118676. /* dealing with sequentialness is a pain in the ass */
  118677. if(c->q_sequencep){
  118678. int pv;
  118679. long mul=1;
  118680. float qlast=0;
  118681. for(k=0,o=0;k<dim;k++,o+=step){
  118682. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118683. if(pv<0 || pv>=pt->mapentries)break;
  118684. entry+=pt->pigeonmap[pv]*mul;
  118685. mul*=pt->quantvals;
  118686. qlast+=pv*pt->del+pt->min;
  118687. }
  118688. }else{
  118689. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118690. int pv=(int)((a[o]-pt->min)/pt->del);
  118691. if(pv<0 || pv>=pt->mapentries)break;
  118692. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118693. }
  118694. }
  118695. /* must be within the pigeonholable range; if we quant outside (or
  118696. in an entry that we define no list for), brute force it */
  118697. if(k==dim && pt->fitlength[entry]){
  118698. /* search the abbreviated list */
  118699. long *list=pt->fitlist+pt->fitmap[entry];
  118700. for(i=0;i<pt->fitlength[entry];i++){
  118701. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118702. if(besti==-1 || this<best){
  118703. best=this;
  118704. besti=list[i];
  118705. }
  118706. }
  118707. return(besti);
  118708. }
  118709. }
  118710. if(nt){
  118711. /* optimized using the decision tree */
  118712. while(1){
  118713. float c=0.f;
  118714. float *p=book->valuelist+nt->p[ptr];
  118715. float *q=book->valuelist+nt->q[ptr];
  118716. for(k=0,o=0;k<dim;k++,o+=step)
  118717. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118718. if(c>0.f) /* in A */
  118719. ptr= -nt->ptr0[ptr];
  118720. else /* in B */
  118721. ptr= -nt->ptr1[ptr];
  118722. if(ptr<=0)break;
  118723. }
  118724. return(-ptr);
  118725. }
  118726. #endif
  118727. /* brute force it! */
  118728. {
  118729. const static_codebook *c=book->c;
  118730. int i,besti=-1;
  118731. float best=0.f;
  118732. float *e=book->valuelist;
  118733. for(i=0;i<book->entries;i++){
  118734. if(c->lengthlist[i]>0){
  118735. float thisx=_dist(dim,e,a,step);
  118736. if(besti==-1 || thisx<best){
  118737. best=thisx;
  118738. besti=i;
  118739. }
  118740. }
  118741. e+=dim;
  118742. }
  118743. /*if(savebest!=-1 && savebest!=besti){
  118744. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118745. "original:");
  118746. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118747. fprintf(stderr,"\n"
  118748. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118749. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118750. (book->valuelist+savebest*dim)[i]);
  118751. fprintf(stderr,"\n"
  118752. "bruteforce (entry %d, err %g):",besti,best);
  118753. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118754. (book->valuelist+besti*dim)[i]);
  118755. fprintf(stderr,"\n");
  118756. }*/
  118757. return(besti);
  118758. }
  118759. }
  118760. long vorbis_book_codeword(codebook *book,int entry){
  118761. if(book->c) /* only use with encode; decode optimizations are
  118762. allowed to break this */
  118763. return book->codelist[entry];
  118764. return -1;
  118765. }
  118766. long vorbis_book_codelen(codebook *book,int entry){
  118767. if(book->c) /* only use with encode; decode optimizations are
  118768. allowed to break this */
  118769. return book->c->lengthlist[entry];
  118770. return -1;
  118771. }
  118772. #ifdef _V_SELFTEST
  118773. /* Unit tests of the dequantizer; this stuff will be OK
  118774. cross-platform, I simply want to be sure that special mapping cases
  118775. actually work properly; a bug could go unnoticed for a while */
  118776. #include <stdio.h>
  118777. /* cases:
  118778. no mapping
  118779. full, explicit mapping
  118780. algorithmic mapping
  118781. nonsequential
  118782. sequential
  118783. */
  118784. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118785. static long partial_quantlist1[]={0,7,2};
  118786. /* no mapping */
  118787. static_codebook test1={
  118788. 4,16,
  118789. NULL,
  118790. 0,
  118791. 0,0,0,0,
  118792. NULL,
  118793. NULL,NULL
  118794. };
  118795. static float *test1_result=NULL;
  118796. /* linear, full mapping, nonsequential */
  118797. static_codebook test2={
  118798. 4,3,
  118799. NULL,
  118800. 2,
  118801. -533200896,1611661312,4,0,
  118802. full_quantlist1,
  118803. NULL,NULL
  118804. };
  118805. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118806. /* linear, full mapping, sequential */
  118807. static_codebook test3={
  118808. 4,3,
  118809. NULL,
  118810. 2,
  118811. -533200896,1611661312,4,1,
  118812. full_quantlist1,
  118813. NULL,NULL
  118814. };
  118815. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118816. /* linear, algorithmic mapping, nonsequential */
  118817. static_codebook test4={
  118818. 3,27,
  118819. NULL,
  118820. 1,
  118821. -533200896,1611661312,4,0,
  118822. partial_quantlist1,
  118823. NULL,NULL
  118824. };
  118825. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118826. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118827. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118828. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118829. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118830. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118831. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118832. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118833. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118834. /* linear, algorithmic mapping, sequential */
  118835. static_codebook test5={
  118836. 3,27,
  118837. NULL,
  118838. 1,
  118839. -533200896,1611661312,4,1,
  118840. partial_quantlist1,
  118841. NULL,NULL
  118842. };
  118843. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118844. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118845. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118846. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118847. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118848. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118849. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118850. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118851. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118852. void run_test(static_codebook *b,float *comp){
  118853. float *out=_book_unquantize(b,b->entries,NULL);
  118854. int i;
  118855. if(comp){
  118856. if(!out){
  118857. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118858. exit(1);
  118859. }
  118860. for(i=0;i<b->entries*b->dim;i++)
  118861. if(fabs(out[i]-comp[i])>.0001){
  118862. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118863. "position %d, %g != %g\n",i,out[i],comp[i]);
  118864. exit(1);
  118865. }
  118866. }else{
  118867. if(out){
  118868. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118869. " correct result should have been NULL\n");
  118870. exit(1);
  118871. }
  118872. }
  118873. }
  118874. int main(){
  118875. /* run the nine dequant tests, and compare to the hand-rolled results */
  118876. fprintf(stderr,"Dequant test 1... ");
  118877. run_test(&test1,test1_result);
  118878. fprintf(stderr,"OK\nDequant test 2... ");
  118879. run_test(&test2,test2_result);
  118880. fprintf(stderr,"OK\nDequant test 3... ");
  118881. run_test(&test3,test3_result);
  118882. fprintf(stderr,"OK\nDequant test 4... ");
  118883. run_test(&test4,test4_result);
  118884. fprintf(stderr,"OK\nDequant test 5... ");
  118885. run_test(&test5,test5_result);
  118886. fprintf(stderr,"OK\n\n");
  118887. return(0);
  118888. }
  118889. #endif
  118890. #endif
  118891. /*** End of inlined file: sharedbook.c ***/
  118892. /*** Start of inlined file: smallft.c ***/
  118893. /* FFT implementation from OggSquish, minus cosine transforms,
  118894. * minus all but radix 2/4 case. In Vorbis we only need this
  118895. * cut-down version.
  118896. *
  118897. * To do more than just power-of-two sized vectors, see the full
  118898. * version I wrote for NetLib.
  118899. *
  118900. * Note that the packing is a little strange; rather than the FFT r/i
  118901. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118902. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118903. * FORTRAN version
  118904. */
  118905. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118906. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118907. // tasks..
  118908. #if JUCE_MSVC
  118909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118910. #endif
  118911. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118912. #if JUCE_USE_OGGVORBIS
  118913. #include <stdlib.h>
  118914. #include <string.h>
  118915. #include <math.h>
  118916. static void drfti1(int n, float *wa, int *ifac){
  118917. static int ntryh[4] = { 4,2,3,5 };
  118918. static float tpi = 6.28318530717958648f;
  118919. float arg,argh,argld,fi;
  118920. int ntry=0,i,j=-1;
  118921. int k1, l1, l2, ib;
  118922. int ld, ii, ip, is, nq, nr;
  118923. int ido, ipm, nfm1;
  118924. int nl=n;
  118925. int nf=0;
  118926. L101:
  118927. j++;
  118928. if (j < 4)
  118929. ntry=ntryh[j];
  118930. else
  118931. ntry+=2;
  118932. L104:
  118933. nq=nl/ntry;
  118934. nr=nl-ntry*nq;
  118935. if (nr!=0) goto L101;
  118936. nf++;
  118937. ifac[nf+1]=ntry;
  118938. nl=nq;
  118939. if(ntry!=2)goto L107;
  118940. if(nf==1)goto L107;
  118941. for (i=1;i<nf;i++){
  118942. ib=nf-i+1;
  118943. ifac[ib+1]=ifac[ib];
  118944. }
  118945. ifac[2] = 2;
  118946. L107:
  118947. if(nl!=1)goto L104;
  118948. ifac[0]=n;
  118949. ifac[1]=nf;
  118950. argh=tpi/n;
  118951. is=0;
  118952. nfm1=nf-1;
  118953. l1=1;
  118954. if(nfm1==0)return;
  118955. for (k1=0;k1<nfm1;k1++){
  118956. ip=ifac[k1+2];
  118957. ld=0;
  118958. l2=l1*ip;
  118959. ido=n/l2;
  118960. ipm=ip-1;
  118961. for (j=0;j<ipm;j++){
  118962. ld+=l1;
  118963. i=is;
  118964. argld=(float)ld*argh;
  118965. fi=0.f;
  118966. for (ii=2;ii<ido;ii+=2){
  118967. fi+=1.f;
  118968. arg=fi*argld;
  118969. wa[i++]=cos(arg);
  118970. wa[i++]=sin(arg);
  118971. }
  118972. is+=ido;
  118973. }
  118974. l1=l2;
  118975. }
  118976. }
  118977. static void fdrffti(int n, float *wsave, int *ifac){
  118978. if (n == 1) return;
  118979. drfti1(n, wsave+n, ifac);
  118980. }
  118981. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118982. int i,k;
  118983. float ti2,tr2;
  118984. int t0,t1,t2,t3,t4,t5,t6;
  118985. t1=0;
  118986. t0=(t2=l1*ido);
  118987. t3=ido<<1;
  118988. for(k=0;k<l1;k++){
  118989. ch[t1<<1]=cc[t1]+cc[t2];
  118990. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118991. t1+=ido;
  118992. t2+=ido;
  118993. }
  118994. if(ido<2)return;
  118995. if(ido==2)goto L105;
  118996. t1=0;
  118997. t2=t0;
  118998. for(k=0;k<l1;k++){
  118999. t3=t2;
  119000. t4=(t1<<1)+(ido<<1);
  119001. t5=t1;
  119002. t6=t1+t1;
  119003. for(i=2;i<ido;i+=2){
  119004. t3+=2;
  119005. t4-=2;
  119006. t5+=2;
  119007. t6+=2;
  119008. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119009. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119010. ch[t6]=cc[t5]+ti2;
  119011. ch[t4]=ti2-cc[t5];
  119012. ch[t6-1]=cc[t5-1]+tr2;
  119013. ch[t4-1]=cc[t5-1]-tr2;
  119014. }
  119015. t1+=ido;
  119016. t2+=ido;
  119017. }
  119018. if(ido%2==1)return;
  119019. L105:
  119020. t3=(t2=(t1=ido)-1);
  119021. t2+=t0;
  119022. for(k=0;k<l1;k++){
  119023. ch[t1]=-cc[t2];
  119024. ch[t1-1]=cc[t3];
  119025. t1+=ido<<1;
  119026. t2+=ido;
  119027. t3+=ido;
  119028. }
  119029. }
  119030. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119031. float *wa2,float *wa3){
  119032. static float hsqt2 = .70710678118654752f;
  119033. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119034. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119035. t0=l1*ido;
  119036. t1=t0;
  119037. t4=t1<<1;
  119038. t2=t1+(t1<<1);
  119039. t3=0;
  119040. for(k=0;k<l1;k++){
  119041. tr1=cc[t1]+cc[t2];
  119042. tr2=cc[t3]+cc[t4];
  119043. ch[t5=t3<<2]=tr1+tr2;
  119044. ch[(ido<<2)+t5-1]=tr2-tr1;
  119045. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119046. ch[t5]=cc[t2]-cc[t1];
  119047. t1+=ido;
  119048. t2+=ido;
  119049. t3+=ido;
  119050. t4+=ido;
  119051. }
  119052. if(ido<2)return;
  119053. if(ido==2)goto L105;
  119054. t1=0;
  119055. for(k=0;k<l1;k++){
  119056. t2=t1;
  119057. t4=t1<<2;
  119058. t5=(t6=ido<<1)+t4;
  119059. for(i=2;i<ido;i+=2){
  119060. t3=(t2+=2);
  119061. t4+=2;
  119062. t5-=2;
  119063. t3+=t0;
  119064. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119065. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119066. t3+=t0;
  119067. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119068. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119069. t3+=t0;
  119070. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119071. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119072. tr1=cr2+cr4;
  119073. tr4=cr4-cr2;
  119074. ti1=ci2+ci4;
  119075. ti4=ci2-ci4;
  119076. ti2=cc[t2]+ci3;
  119077. ti3=cc[t2]-ci3;
  119078. tr2=cc[t2-1]+cr3;
  119079. tr3=cc[t2-1]-cr3;
  119080. ch[t4-1]=tr1+tr2;
  119081. ch[t4]=ti1+ti2;
  119082. ch[t5-1]=tr3-ti4;
  119083. ch[t5]=tr4-ti3;
  119084. ch[t4+t6-1]=ti4+tr3;
  119085. ch[t4+t6]=tr4+ti3;
  119086. ch[t5+t6-1]=tr2-tr1;
  119087. ch[t5+t6]=ti1-ti2;
  119088. }
  119089. t1+=ido;
  119090. }
  119091. if(ido&1)return;
  119092. L105:
  119093. t2=(t1=t0+ido-1)+(t0<<1);
  119094. t3=ido<<2;
  119095. t4=ido;
  119096. t5=ido<<1;
  119097. t6=ido;
  119098. for(k=0;k<l1;k++){
  119099. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119100. tr1=hsqt2*(cc[t1]-cc[t2]);
  119101. ch[t4-1]=tr1+cc[t6-1];
  119102. ch[t4+t5-1]=cc[t6-1]-tr1;
  119103. ch[t4]=ti1-cc[t1+t0];
  119104. ch[t4+t5]=ti1+cc[t1+t0];
  119105. t1+=ido;
  119106. t2+=ido;
  119107. t4+=t3;
  119108. t6+=ido;
  119109. }
  119110. }
  119111. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119112. float *c2,float *ch,float *ch2,float *wa){
  119113. static float tpi=6.283185307179586f;
  119114. int idij,ipph,i,j,k,l,ic,ik,is;
  119115. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119116. float dc2,ai1,ai2,ar1,ar2,ds2;
  119117. int nbd;
  119118. float dcp,arg,dsp,ar1h,ar2h;
  119119. int idp2,ipp2;
  119120. arg=tpi/(float)ip;
  119121. dcp=cos(arg);
  119122. dsp=sin(arg);
  119123. ipph=(ip+1)>>1;
  119124. ipp2=ip;
  119125. idp2=ido;
  119126. nbd=(ido-1)>>1;
  119127. t0=l1*ido;
  119128. t10=ip*ido;
  119129. if(ido==1)goto L119;
  119130. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119131. t1=0;
  119132. for(j=1;j<ip;j++){
  119133. t1+=t0;
  119134. t2=t1;
  119135. for(k=0;k<l1;k++){
  119136. ch[t2]=c1[t2];
  119137. t2+=ido;
  119138. }
  119139. }
  119140. is=-ido;
  119141. t1=0;
  119142. if(nbd>l1){
  119143. for(j=1;j<ip;j++){
  119144. t1+=t0;
  119145. is+=ido;
  119146. t2= -ido+t1;
  119147. for(k=0;k<l1;k++){
  119148. idij=is-1;
  119149. t2+=ido;
  119150. t3=t2;
  119151. for(i=2;i<ido;i+=2){
  119152. idij+=2;
  119153. t3+=2;
  119154. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119155. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119156. }
  119157. }
  119158. }
  119159. }else{
  119160. for(j=1;j<ip;j++){
  119161. is+=ido;
  119162. idij=is-1;
  119163. t1+=t0;
  119164. t2=t1;
  119165. for(i=2;i<ido;i+=2){
  119166. idij+=2;
  119167. t2+=2;
  119168. t3=t2;
  119169. for(k=0;k<l1;k++){
  119170. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119171. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119172. t3+=ido;
  119173. }
  119174. }
  119175. }
  119176. }
  119177. t1=0;
  119178. t2=ipp2*t0;
  119179. if(nbd<l1){
  119180. for(j=1;j<ipph;j++){
  119181. t1+=t0;
  119182. t2-=t0;
  119183. t3=t1;
  119184. t4=t2;
  119185. for(i=2;i<ido;i+=2){
  119186. t3+=2;
  119187. t4+=2;
  119188. t5=t3-ido;
  119189. t6=t4-ido;
  119190. for(k=0;k<l1;k++){
  119191. t5+=ido;
  119192. t6+=ido;
  119193. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119194. c1[t6-1]=ch[t5]-ch[t6];
  119195. c1[t5]=ch[t5]+ch[t6];
  119196. c1[t6]=ch[t6-1]-ch[t5-1];
  119197. }
  119198. }
  119199. }
  119200. }else{
  119201. for(j=1;j<ipph;j++){
  119202. t1+=t0;
  119203. t2-=t0;
  119204. t3=t1;
  119205. t4=t2;
  119206. for(k=0;k<l1;k++){
  119207. t5=t3;
  119208. t6=t4;
  119209. for(i=2;i<ido;i+=2){
  119210. t5+=2;
  119211. t6+=2;
  119212. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119213. c1[t6-1]=ch[t5]-ch[t6];
  119214. c1[t5]=ch[t5]+ch[t6];
  119215. c1[t6]=ch[t6-1]-ch[t5-1];
  119216. }
  119217. t3+=ido;
  119218. t4+=ido;
  119219. }
  119220. }
  119221. }
  119222. L119:
  119223. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119224. t1=0;
  119225. t2=ipp2*idl1;
  119226. for(j=1;j<ipph;j++){
  119227. t1+=t0;
  119228. t2-=t0;
  119229. t3=t1-ido;
  119230. t4=t2-ido;
  119231. for(k=0;k<l1;k++){
  119232. t3+=ido;
  119233. t4+=ido;
  119234. c1[t3]=ch[t3]+ch[t4];
  119235. c1[t4]=ch[t4]-ch[t3];
  119236. }
  119237. }
  119238. ar1=1.f;
  119239. ai1=0.f;
  119240. t1=0;
  119241. t2=ipp2*idl1;
  119242. t3=(ip-1)*idl1;
  119243. for(l=1;l<ipph;l++){
  119244. t1+=idl1;
  119245. t2-=idl1;
  119246. ar1h=dcp*ar1-dsp*ai1;
  119247. ai1=dcp*ai1+dsp*ar1;
  119248. ar1=ar1h;
  119249. t4=t1;
  119250. t5=t2;
  119251. t6=t3;
  119252. t7=idl1;
  119253. for(ik=0;ik<idl1;ik++){
  119254. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119255. ch2[t5++]=ai1*c2[t6++];
  119256. }
  119257. dc2=ar1;
  119258. ds2=ai1;
  119259. ar2=ar1;
  119260. ai2=ai1;
  119261. t4=idl1;
  119262. t5=(ipp2-1)*idl1;
  119263. for(j=2;j<ipph;j++){
  119264. t4+=idl1;
  119265. t5-=idl1;
  119266. ar2h=dc2*ar2-ds2*ai2;
  119267. ai2=dc2*ai2+ds2*ar2;
  119268. ar2=ar2h;
  119269. t6=t1;
  119270. t7=t2;
  119271. t8=t4;
  119272. t9=t5;
  119273. for(ik=0;ik<idl1;ik++){
  119274. ch2[t6++]+=ar2*c2[t8++];
  119275. ch2[t7++]+=ai2*c2[t9++];
  119276. }
  119277. }
  119278. }
  119279. t1=0;
  119280. for(j=1;j<ipph;j++){
  119281. t1+=idl1;
  119282. t2=t1;
  119283. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119284. }
  119285. if(ido<l1)goto L132;
  119286. t1=0;
  119287. t2=0;
  119288. for(k=0;k<l1;k++){
  119289. t3=t1;
  119290. t4=t2;
  119291. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119292. t1+=ido;
  119293. t2+=t10;
  119294. }
  119295. goto L135;
  119296. L132:
  119297. for(i=0;i<ido;i++){
  119298. t1=i;
  119299. t2=i;
  119300. for(k=0;k<l1;k++){
  119301. cc[t2]=ch[t1];
  119302. t1+=ido;
  119303. t2+=t10;
  119304. }
  119305. }
  119306. L135:
  119307. t1=0;
  119308. t2=ido<<1;
  119309. t3=0;
  119310. t4=ipp2*t0;
  119311. for(j=1;j<ipph;j++){
  119312. t1+=t2;
  119313. t3+=t0;
  119314. t4-=t0;
  119315. t5=t1;
  119316. t6=t3;
  119317. t7=t4;
  119318. for(k=0;k<l1;k++){
  119319. cc[t5-1]=ch[t6];
  119320. cc[t5]=ch[t7];
  119321. t5+=t10;
  119322. t6+=ido;
  119323. t7+=ido;
  119324. }
  119325. }
  119326. if(ido==1)return;
  119327. if(nbd<l1)goto L141;
  119328. t1=-ido;
  119329. t3=0;
  119330. t4=0;
  119331. t5=ipp2*t0;
  119332. for(j=1;j<ipph;j++){
  119333. t1+=t2;
  119334. t3+=t2;
  119335. t4+=t0;
  119336. t5-=t0;
  119337. t6=t1;
  119338. t7=t3;
  119339. t8=t4;
  119340. t9=t5;
  119341. for(k=0;k<l1;k++){
  119342. for(i=2;i<ido;i+=2){
  119343. ic=idp2-i;
  119344. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119345. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119346. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119347. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119348. }
  119349. t6+=t10;
  119350. t7+=t10;
  119351. t8+=ido;
  119352. t9+=ido;
  119353. }
  119354. }
  119355. return;
  119356. L141:
  119357. t1=-ido;
  119358. t3=0;
  119359. t4=0;
  119360. t5=ipp2*t0;
  119361. for(j=1;j<ipph;j++){
  119362. t1+=t2;
  119363. t3+=t2;
  119364. t4+=t0;
  119365. t5-=t0;
  119366. for(i=2;i<ido;i+=2){
  119367. t6=idp2+t1-i;
  119368. t7=i+t3;
  119369. t8=i+t4;
  119370. t9=i+t5;
  119371. for(k=0;k<l1;k++){
  119372. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119373. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119374. cc[t7]=ch[t8]+ch[t9];
  119375. cc[t6]=ch[t9]-ch[t8];
  119376. t6+=t10;
  119377. t7+=t10;
  119378. t8+=ido;
  119379. t9+=ido;
  119380. }
  119381. }
  119382. }
  119383. }
  119384. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119385. int i,k1,l1,l2;
  119386. int na,kh,nf;
  119387. int ip,iw,ido,idl1,ix2,ix3;
  119388. nf=ifac[1];
  119389. na=1;
  119390. l2=n;
  119391. iw=n;
  119392. for(k1=0;k1<nf;k1++){
  119393. kh=nf-k1;
  119394. ip=ifac[kh+1];
  119395. l1=l2/ip;
  119396. ido=n/l2;
  119397. idl1=ido*l1;
  119398. iw-=(ip-1)*ido;
  119399. na=1-na;
  119400. if(ip!=4)goto L102;
  119401. ix2=iw+ido;
  119402. ix3=ix2+ido;
  119403. if(na!=0)
  119404. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119405. else
  119406. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119407. goto L110;
  119408. L102:
  119409. if(ip!=2)goto L104;
  119410. if(na!=0)goto L103;
  119411. dradf2(ido,l1,c,ch,wa+iw-1);
  119412. goto L110;
  119413. L103:
  119414. dradf2(ido,l1,ch,c,wa+iw-1);
  119415. goto L110;
  119416. L104:
  119417. if(ido==1)na=1-na;
  119418. if(na!=0)goto L109;
  119419. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119420. na=1;
  119421. goto L110;
  119422. L109:
  119423. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119424. na=0;
  119425. L110:
  119426. l2=l1;
  119427. }
  119428. if(na==1)return;
  119429. for(i=0;i<n;i++)c[i]=ch[i];
  119430. }
  119431. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119432. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119433. float ti2,tr2;
  119434. t0=l1*ido;
  119435. t1=0;
  119436. t2=0;
  119437. t3=(ido<<1)-1;
  119438. for(k=0;k<l1;k++){
  119439. ch[t1]=cc[t2]+cc[t3+t2];
  119440. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119441. t2=(t1+=ido)<<1;
  119442. }
  119443. if(ido<2)return;
  119444. if(ido==2)goto L105;
  119445. t1=0;
  119446. t2=0;
  119447. for(k=0;k<l1;k++){
  119448. t3=t1;
  119449. t5=(t4=t2)+(ido<<1);
  119450. t6=t0+t1;
  119451. for(i=2;i<ido;i+=2){
  119452. t3+=2;
  119453. t4+=2;
  119454. t5-=2;
  119455. t6+=2;
  119456. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119457. tr2=cc[t4-1]-cc[t5-1];
  119458. ch[t3]=cc[t4]-cc[t5];
  119459. ti2=cc[t4]+cc[t5];
  119460. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119461. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119462. }
  119463. t2=(t1+=ido)<<1;
  119464. }
  119465. if(ido%2==1)return;
  119466. L105:
  119467. t1=ido-1;
  119468. t2=ido-1;
  119469. for(k=0;k<l1;k++){
  119470. ch[t1]=cc[t2]+cc[t2];
  119471. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119472. t1+=ido;
  119473. t2+=ido<<1;
  119474. }
  119475. }
  119476. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119477. float *wa2){
  119478. static float taur = -.5f;
  119479. static float taui = .8660254037844386f;
  119480. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119481. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119482. t0=l1*ido;
  119483. t1=0;
  119484. t2=t0<<1;
  119485. t3=ido<<1;
  119486. t4=ido+(ido<<1);
  119487. t5=0;
  119488. for(k=0;k<l1;k++){
  119489. tr2=cc[t3-1]+cc[t3-1];
  119490. cr2=cc[t5]+(taur*tr2);
  119491. ch[t1]=cc[t5]+tr2;
  119492. ci3=taui*(cc[t3]+cc[t3]);
  119493. ch[t1+t0]=cr2-ci3;
  119494. ch[t1+t2]=cr2+ci3;
  119495. t1+=ido;
  119496. t3+=t4;
  119497. t5+=t4;
  119498. }
  119499. if(ido==1)return;
  119500. t1=0;
  119501. t3=ido<<1;
  119502. for(k=0;k<l1;k++){
  119503. t7=t1+(t1<<1);
  119504. t6=(t5=t7+t3);
  119505. t8=t1;
  119506. t10=(t9=t1+t0)+t0;
  119507. for(i=2;i<ido;i+=2){
  119508. t5+=2;
  119509. t6-=2;
  119510. t7+=2;
  119511. t8+=2;
  119512. t9+=2;
  119513. t10+=2;
  119514. tr2=cc[t5-1]+cc[t6-1];
  119515. cr2=cc[t7-1]+(taur*tr2);
  119516. ch[t8-1]=cc[t7-1]+tr2;
  119517. ti2=cc[t5]-cc[t6];
  119518. ci2=cc[t7]+(taur*ti2);
  119519. ch[t8]=cc[t7]+ti2;
  119520. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119521. ci3=taui*(cc[t5]+cc[t6]);
  119522. dr2=cr2-ci3;
  119523. dr3=cr2+ci3;
  119524. di2=ci2+cr3;
  119525. di3=ci2-cr3;
  119526. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119527. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119528. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119529. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119530. }
  119531. t1+=ido;
  119532. }
  119533. }
  119534. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119535. float *wa2,float *wa3){
  119536. static float sqrt2=1.414213562373095f;
  119537. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119538. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119539. t0=l1*ido;
  119540. t1=0;
  119541. t2=ido<<2;
  119542. t3=0;
  119543. t6=ido<<1;
  119544. for(k=0;k<l1;k++){
  119545. t4=t3+t6;
  119546. t5=t1;
  119547. tr3=cc[t4-1]+cc[t4-1];
  119548. tr4=cc[t4]+cc[t4];
  119549. tr1=cc[t3]-cc[(t4+=t6)-1];
  119550. tr2=cc[t3]+cc[t4-1];
  119551. ch[t5]=tr2+tr3;
  119552. ch[t5+=t0]=tr1-tr4;
  119553. ch[t5+=t0]=tr2-tr3;
  119554. ch[t5+=t0]=tr1+tr4;
  119555. t1+=ido;
  119556. t3+=t2;
  119557. }
  119558. if(ido<2)return;
  119559. if(ido==2)goto L105;
  119560. t1=0;
  119561. for(k=0;k<l1;k++){
  119562. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119563. t7=t1;
  119564. for(i=2;i<ido;i+=2){
  119565. t2+=2;
  119566. t3+=2;
  119567. t4-=2;
  119568. t5-=2;
  119569. t7+=2;
  119570. ti1=cc[t2]+cc[t5];
  119571. ti2=cc[t2]-cc[t5];
  119572. ti3=cc[t3]-cc[t4];
  119573. tr4=cc[t3]+cc[t4];
  119574. tr1=cc[t2-1]-cc[t5-1];
  119575. tr2=cc[t2-1]+cc[t5-1];
  119576. ti4=cc[t3-1]-cc[t4-1];
  119577. tr3=cc[t3-1]+cc[t4-1];
  119578. ch[t7-1]=tr2+tr3;
  119579. cr3=tr2-tr3;
  119580. ch[t7]=ti2+ti3;
  119581. ci3=ti2-ti3;
  119582. cr2=tr1-tr4;
  119583. cr4=tr1+tr4;
  119584. ci2=ti1+ti4;
  119585. ci4=ti1-ti4;
  119586. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119587. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119588. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119589. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119590. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119591. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119592. }
  119593. t1+=ido;
  119594. }
  119595. if(ido%2 == 1)return;
  119596. L105:
  119597. t1=ido;
  119598. t2=ido<<2;
  119599. t3=ido-1;
  119600. t4=ido+(ido<<1);
  119601. for(k=0;k<l1;k++){
  119602. t5=t3;
  119603. ti1=cc[t1]+cc[t4];
  119604. ti2=cc[t4]-cc[t1];
  119605. tr1=cc[t1-1]-cc[t4-1];
  119606. tr2=cc[t1-1]+cc[t4-1];
  119607. ch[t5]=tr2+tr2;
  119608. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119609. ch[t5+=t0]=ti2+ti2;
  119610. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119611. t3+=ido;
  119612. t1+=t2;
  119613. t4+=t2;
  119614. }
  119615. }
  119616. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119617. float *c2,float *ch,float *ch2,float *wa){
  119618. static float tpi=6.283185307179586f;
  119619. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119620. t11,t12;
  119621. float dc2,ai1,ai2,ar1,ar2,ds2;
  119622. int nbd;
  119623. float dcp,arg,dsp,ar1h,ar2h;
  119624. int ipp2;
  119625. t10=ip*ido;
  119626. t0=l1*ido;
  119627. arg=tpi/(float)ip;
  119628. dcp=cos(arg);
  119629. dsp=sin(arg);
  119630. nbd=(ido-1)>>1;
  119631. ipp2=ip;
  119632. ipph=(ip+1)>>1;
  119633. if(ido<l1)goto L103;
  119634. t1=0;
  119635. t2=0;
  119636. for(k=0;k<l1;k++){
  119637. t3=t1;
  119638. t4=t2;
  119639. for(i=0;i<ido;i++){
  119640. ch[t3]=cc[t4];
  119641. t3++;
  119642. t4++;
  119643. }
  119644. t1+=ido;
  119645. t2+=t10;
  119646. }
  119647. goto L106;
  119648. L103:
  119649. t1=0;
  119650. for(i=0;i<ido;i++){
  119651. t2=t1;
  119652. t3=t1;
  119653. for(k=0;k<l1;k++){
  119654. ch[t2]=cc[t3];
  119655. t2+=ido;
  119656. t3+=t10;
  119657. }
  119658. t1++;
  119659. }
  119660. L106:
  119661. t1=0;
  119662. t2=ipp2*t0;
  119663. t7=(t5=ido<<1);
  119664. for(j=1;j<ipph;j++){
  119665. t1+=t0;
  119666. t2-=t0;
  119667. t3=t1;
  119668. t4=t2;
  119669. t6=t5;
  119670. for(k=0;k<l1;k++){
  119671. ch[t3]=cc[t6-1]+cc[t6-1];
  119672. ch[t4]=cc[t6]+cc[t6];
  119673. t3+=ido;
  119674. t4+=ido;
  119675. t6+=t10;
  119676. }
  119677. t5+=t7;
  119678. }
  119679. if (ido == 1)goto L116;
  119680. if(nbd<l1)goto L112;
  119681. t1=0;
  119682. t2=ipp2*t0;
  119683. t7=0;
  119684. for(j=1;j<ipph;j++){
  119685. t1+=t0;
  119686. t2-=t0;
  119687. t3=t1;
  119688. t4=t2;
  119689. t7+=(ido<<1);
  119690. t8=t7;
  119691. for(k=0;k<l1;k++){
  119692. t5=t3;
  119693. t6=t4;
  119694. t9=t8;
  119695. t11=t8;
  119696. for(i=2;i<ido;i+=2){
  119697. t5+=2;
  119698. t6+=2;
  119699. t9+=2;
  119700. t11-=2;
  119701. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119702. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119703. ch[t5]=cc[t9]-cc[t11];
  119704. ch[t6]=cc[t9]+cc[t11];
  119705. }
  119706. t3+=ido;
  119707. t4+=ido;
  119708. t8+=t10;
  119709. }
  119710. }
  119711. goto L116;
  119712. L112:
  119713. t1=0;
  119714. t2=ipp2*t0;
  119715. t7=0;
  119716. for(j=1;j<ipph;j++){
  119717. t1+=t0;
  119718. t2-=t0;
  119719. t3=t1;
  119720. t4=t2;
  119721. t7+=(ido<<1);
  119722. t8=t7;
  119723. t9=t7;
  119724. for(i=2;i<ido;i+=2){
  119725. t3+=2;
  119726. t4+=2;
  119727. t8+=2;
  119728. t9-=2;
  119729. t5=t3;
  119730. t6=t4;
  119731. t11=t8;
  119732. t12=t9;
  119733. for(k=0;k<l1;k++){
  119734. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119735. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119736. ch[t5]=cc[t11]-cc[t12];
  119737. ch[t6]=cc[t11]+cc[t12];
  119738. t5+=ido;
  119739. t6+=ido;
  119740. t11+=t10;
  119741. t12+=t10;
  119742. }
  119743. }
  119744. }
  119745. L116:
  119746. ar1=1.f;
  119747. ai1=0.f;
  119748. t1=0;
  119749. t9=(t2=ipp2*idl1);
  119750. t3=(ip-1)*idl1;
  119751. for(l=1;l<ipph;l++){
  119752. t1+=idl1;
  119753. t2-=idl1;
  119754. ar1h=dcp*ar1-dsp*ai1;
  119755. ai1=dcp*ai1+dsp*ar1;
  119756. ar1=ar1h;
  119757. t4=t1;
  119758. t5=t2;
  119759. t6=0;
  119760. t7=idl1;
  119761. t8=t3;
  119762. for(ik=0;ik<idl1;ik++){
  119763. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119764. c2[t5++]=ai1*ch2[t8++];
  119765. }
  119766. dc2=ar1;
  119767. ds2=ai1;
  119768. ar2=ar1;
  119769. ai2=ai1;
  119770. t6=idl1;
  119771. t7=t9-idl1;
  119772. for(j=2;j<ipph;j++){
  119773. t6+=idl1;
  119774. t7-=idl1;
  119775. ar2h=dc2*ar2-ds2*ai2;
  119776. ai2=dc2*ai2+ds2*ar2;
  119777. ar2=ar2h;
  119778. t4=t1;
  119779. t5=t2;
  119780. t11=t6;
  119781. t12=t7;
  119782. for(ik=0;ik<idl1;ik++){
  119783. c2[t4++]+=ar2*ch2[t11++];
  119784. c2[t5++]+=ai2*ch2[t12++];
  119785. }
  119786. }
  119787. }
  119788. t1=0;
  119789. for(j=1;j<ipph;j++){
  119790. t1+=idl1;
  119791. t2=t1;
  119792. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119793. }
  119794. t1=0;
  119795. t2=ipp2*t0;
  119796. for(j=1;j<ipph;j++){
  119797. t1+=t0;
  119798. t2-=t0;
  119799. t3=t1;
  119800. t4=t2;
  119801. for(k=0;k<l1;k++){
  119802. ch[t3]=c1[t3]-c1[t4];
  119803. ch[t4]=c1[t3]+c1[t4];
  119804. t3+=ido;
  119805. t4+=ido;
  119806. }
  119807. }
  119808. if(ido==1)goto L132;
  119809. if(nbd<l1)goto L128;
  119810. t1=0;
  119811. t2=ipp2*t0;
  119812. for(j=1;j<ipph;j++){
  119813. t1+=t0;
  119814. t2-=t0;
  119815. t3=t1;
  119816. t4=t2;
  119817. for(k=0;k<l1;k++){
  119818. t5=t3;
  119819. t6=t4;
  119820. for(i=2;i<ido;i+=2){
  119821. t5+=2;
  119822. t6+=2;
  119823. ch[t5-1]=c1[t5-1]-c1[t6];
  119824. ch[t6-1]=c1[t5-1]+c1[t6];
  119825. ch[t5]=c1[t5]+c1[t6-1];
  119826. ch[t6]=c1[t5]-c1[t6-1];
  119827. }
  119828. t3+=ido;
  119829. t4+=ido;
  119830. }
  119831. }
  119832. goto L132;
  119833. L128:
  119834. t1=0;
  119835. t2=ipp2*t0;
  119836. for(j=1;j<ipph;j++){
  119837. t1+=t0;
  119838. t2-=t0;
  119839. t3=t1;
  119840. t4=t2;
  119841. for(i=2;i<ido;i+=2){
  119842. t3+=2;
  119843. t4+=2;
  119844. t5=t3;
  119845. t6=t4;
  119846. for(k=0;k<l1;k++){
  119847. ch[t5-1]=c1[t5-1]-c1[t6];
  119848. ch[t6-1]=c1[t5-1]+c1[t6];
  119849. ch[t5]=c1[t5]+c1[t6-1];
  119850. ch[t6]=c1[t5]-c1[t6-1];
  119851. t5+=ido;
  119852. t6+=ido;
  119853. }
  119854. }
  119855. }
  119856. L132:
  119857. if(ido==1)return;
  119858. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119859. t1=0;
  119860. for(j=1;j<ip;j++){
  119861. t2=(t1+=t0);
  119862. for(k=0;k<l1;k++){
  119863. c1[t2]=ch[t2];
  119864. t2+=ido;
  119865. }
  119866. }
  119867. if(nbd>l1)goto L139;
  119868. is= -ido-1;
  119869. t1=0;
  119870. for(j=1;j<ip;j++){
  119871. is+=ido;
  119872. t1+=t0;
  119873. idij=is;
  119874. t2=t1;
  119875. for(i=2;i<ido;i+=2){
  119876. t2+=2;
  119877. idij+=2;
  119878. t3=t2;
  119879. for(k=0;k<l1;k++){
  119880. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119881. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119882. t3+=ido;
  119883. }
  119884. }
  119885. }
  119886. return;
  119887. L139:
  119888. is= -ido-1;
  119889. t1=0;
  119890. for(j=1;j<ip;j++){
  119891. is+=ido;
  119892. t1+=t0;
  119893. t2=t1;
  119894. for(k=0;k<l1;k++){
  119895. idij=is;
  119896. t3=t2;
  119897. for(i=2;i<ido;i+=2){
  119898. idij+=2;
  119899. t3+=2;
  119900. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119901. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119902. }
  119903. t2+=ido;
  119904. }
  119905. }
  119906. }
  119907. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119908. int i,k1,l1,l2;
  119909. int na;
  119910. int nf,ip,iw,ix2,ix3,ido,idl1;
  119911. nf=ifac[1];
  119912. na=0;
  119913. l1=1;
  119914. iw=1;
  119915. for(k1=0;k1<nf;k1++){
  119916. ip=ifac[k1 + 2];
  119917. l2=ip*l1;
  119918. ido=n/l2;
  119919. idl1=ido*l1;
  119920. if(ip!=4)goto L103;
  119921. ix2=iw+ido;
  119922. ix3=ix2+ido;
  119923. if(na!=0)
  119924. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119925. else
  119926. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119927. na=1-na;
  119928. goto L115;
  119929. L103:
  119930. if(ip!=2)goto L106;
  119931. if(na!=0)
  119932. dradb2(ido,l1,ch,c,wa+iw-1);
  119933. else
  119934. dradb2(ido,l1,c,ch,wa+iw-1);
  119935. na=1-na;
  119936. goto L115;
  119937. L106:
  119938. if(ip!=3)goto L109;
  119939. ix2=iw+ido;
  119940. if(na!=0)
  119941. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119942. else
  119943. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119944. na=1-na;
  119945. goto L115;
  119946. L109:
  119947. /* The radix five case can be translated later..... */
  119948. /* if(ip!=5)goto L112;
  119949. ix2=iw+ido;
  119950. ix3=ix2+ido;
  119951. ix4=ix3+ido;
  119952. if(na!=0)
  119953. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119954. else
  119955. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119956. na=1-na;
  119957. goto L115;
  119958. L112:*/
  119959. if(na!=0)
  119960. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119961. else
  119962. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119963. if(ido==1)na=1-na;
  119964. L115:
  119965. l1=l2;
  119966. iw+=(ip-1)*ido;
  119967. }
  119968. if(na==0)return;
  119969. for(i=0;i<n;i++)c[i]=ch[i];
  119970. }
  119971. void drft_forward(drft_lookup *l,float *data){
  119972. if(l->n==1)return;
  119973. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119974. }
  119975. void drft_backward(drft_lookup *l,float *data){
  119976. if (l->n==1)return;
  119977. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119978. }
  119979. void drft_init(drft_lookup *l,int n){
  119980. l->n=n;
  119981. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119982. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119983. fdrffti(n, l->trigcache, l->splitcache);
  119984. }
  119985. void drft_clear(drft_lookup *l){
  119986. if(l){
  119987. if(l->trigcache)_ogg_free(l->trigcache);
  119988. if(l->splitcache)_ogg_free(l->splitcache);
  119989. memset(l,0,sizeof(*l));
  119990. }
  119991. }
  119992. #endif
  119993. /*** End of inlined file: smallft.c ***/
  119994. /*** Start of inlined file: synthesis.c ***/
  119995. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119996. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119997. // tasks..
  119998. #if JUCE_MSVC
  119999. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120000. #endif
  120001. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120002. #if JUCE_USE_OGGVORBIS
  120003. #include <stdio.h>
  120004. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120005. vorbis_dsp_state *vd=vb->vd;
  120006. private_state *b=(private_state*)vd->backend_state;
  120007. vorbis_info *vi=vd->vi;
  120008. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120009. oggpack_buffer *opb=&vb->opb;
  120010. int type,mode,i;
  120011. /* first things first. Make sure decode is ready */
  120012. _vorbis_block_ripcord(vb);
  120013. oggpack_readinit(opb,op->packet,op->bytes);
  120014. /* Check the packet type */
  120015. if(oggpack_read(opb,1)!=0){
  120016. /* Oops. This is not an audio data packet */
  120017. return(OV_ENOTAUDIO);
  120018. }
  120019. /* read our mode and pre/post windowsize */
  120020. mode=oggpack_read(opb,b->modebits);
  120021. if(mode==-1)return(OV_EBADPACKET);
  120022. vb->mode=mode;
  120023. vb->W=ci->mode_param[mode]->blockflag;
  120024. if(vb->W){
  120025. /* this doesn;t get mapped through mode selection as it's used
  120026. only for window selection */
  120027. vb->lW=oggpack_read(opb,1);
  120028. vb->nW=oggpack_read(opb,1);
  120029. if(vb->nW==-1) return(OV_EBADPACKET);
  120030. }else{
  120031. vb->lW=0;
  120032. vb->nW=0;
  120033. }
  120034. /* more setup */
  120035. vb->granulepos=op->granulepos;
  120036. vb->sequence=op->packetno;
  120037. vb->eofflag=op->e_o_s;
  120038. /* alloc pcm passback storage */
  120039. vb->pcmend=ci->blocksizes[vb->W];
  120040. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120041. for(i=0;i<vi->channels;i++)
  120042. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120043. /* unpack_header enforces range checking */
  120044. type=ci->map_type[ci->mode_param[mode]->mapping];
  120045. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120046. mapping]));
  120047. }
  120048. /* used to track pcm position without actually performing decode.
  120049. Useful for sequential 'fast forward' */
  120050. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120051. vorbis_dsp_state *vd=vb->vd;
  120052. private_state *b=(private_state*)vd->backend_state;
  120053. vorbis_info *vi=vd->vi;
  120054. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120055. oggpack_buffer *opb=&vb->opb;
  120056. int mode;
  120057. /* first things first. Make sure decode is ready */
  120058. _vorbis_block_ripcord(vb);
  120059. oggpack_readinit(opb,op->packet,op->bytes);
  120060. /* Check the packet type */
  120061. if(oggpack_read(opb,1)!=0){
  120062. /* Oops. This is not an audio data packet */
  120063. return(OV_ENOTAUDIO);
  120064. }
  120065. /* read our mode and pre/post windowsize */
  120066. mode=oggpack_read(opb,b->modebits);
  120067. if(mode==-1)return(OV_EBADPACKET);
  120068. vb->mode=mode;
  120069. vb->W=ci->mode_param[mode]->blockflag;
  120070. if(vb->W){
  120071. vb->lW=oggpack_read(opb,1);
  120072. vb->nW=oggpack_read(opb,1);
  120073. if(vb->nW==-1) return(OV_EBADPACKET);
  120074. }else{
  120075. vb->lW=0;
  120076. vb->nW=0;
  120077. }
  120078. /* more setup */
  120079. vb->granulepos=op->granulepos;
  120080. vb->sequence=op->packetno;
  120081. vb->eofflag=op->e_o_s;
  120082. /* no pcm */
  120083. vb->pcmend=0;
  120084. vb->pcm=NULL;
  120085. return(0);
  120086. }
  120087. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120088. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120089. oggpack_buffer opb;
  120090. int mode;
  120091. oggpack_readinit(&opb,op->packet,op->bytes);
  120092. /* Check the packet type */
  120093. if(oggpack_read(&opb,1)!=0){
  120094. /* Oops. This is not an audio data packet */
  120095. return(OV_ENOTAUDIO);
  120096. }
  120097. {
  120098. int modebits=0;
  120099. int v=ci->modes;
  120100. while(v>1){
  120101. modebits++;
  120102. v>>=1;
  120103. }
  120104. /* read our mode and pre/post windowsize */
  120105. mode=oggpack_read(&opb,modebits);
  120106. }
  120107. if(mode==-1)return(OV_EBADPACKET);
  120108. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120109. }
  120110. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120111. /* set / clear half-sample-rate mode */
  120112. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120113. /* right now, our MDCT can't handle < 64 sample windows. */
  120114. if(ci->blocksizes[0]<=64 && flag)return -1;
  120115. ci->halfrate_flag=(flag?1:0);
  120116. return 0;
  120117. }
  120118. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120119. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120120. return ci->halfrate_flag;
  120121. }
  120122. #endif
  120123. /*** End of inlined file: synthesis.c ***/
  120124. /*** Start of inlined file: vorbisenc.c ***/
  120125. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120126. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120127. // tasks..
  120128. #if JUCE_MSVC
  120129. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120130. #endif
  120131. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120132. #if JUCE_USE_OGGVORBIS
  120133. #include <stdlib.h>
  120134. #include <string.h>
  120135. #include <math.h>
  120136. /* careful with this; it's using static array sizing to make managing
  120137. all the modes a little less annoying. If we use a residue backend
  120138. with > 12 partition types, or a different division of iteration,
  120139. this needs to be updated. */
  120140. typedef struct {
  120141. static_codebook *books[12][3];
  120142. } static_bookblock;
  120143. typedef struct {
  120144. int res_type;
  120145. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120146. vorbis_info_residue0 *res;
  120147. static_codebook *book_aux;
  120148. static_codebook *book_aux_managed;
  120149. static_bookblock *books_base;
  120150. static_bookblock *books_base_managed;
  120151. } vorbis_residue_template;
  120152. typedef struct {
  120153. vorbis_info_mapping0 *map;
  120154. vorbis_residue_template *res;
  120155. } vorbis_mapping_template;
  120156. typedef struct vp_adjblock{
  120157. int block[P_BANDS];
  120158. } vp_adjblock;
  120159. typedef struct {
  120160. int data[NOISE_COMPAND_LEVELS];
  120161. } compandblock;
  120162. /* high level configuration information for setting things up
  120163. step-by-step with the detailed vorbis_encode_ctl interface.
  120164. There's a fair amount of redundancy such that interactive setup
  120165. does not directly deal with any vorbis_info or codec_setup_info
  120166. initialization; it's all stored (until full init) in this highlevel
  120167. setup, then flushed out to the real codec setup structs later. */
  120168. typedef struct {
  120169. int att[P_NOISECURVES];
  120170. float boost;
  120171. float decay;
  120172. } att3;
  120173. typedef struct { int data[P_NOISECURVES]; } adj3;
  120174. typedef struct {
  120175. int pre[PACKETBLOBS];
  120176. int post[PACKETBLOBS];
  120177. float kHz[PACKETBLOBS];
  120178. float lowpasskHz[PACKETBLOBS];
  120179. } adj_stereo;
  120180. typedef struct {
  120181. int lo;
  120182. int hi;
  120183. int fixed;
  120184. } noiseguard;
  120185. typedef struct {
  120186. int data[P_NOISECURVES][17];
  120187. } noise3;
  120188. typedef struct {
  120189. int mappings;
  120190. double *rate_mapping;
  120191. double *quality_mapping;
  120192. int coupling_restriction;
  120193. long samplerate_min_restriction;
  120194. long samplerate_max_restriction;
  120195. int *blocksize_short;
  120196. int *blocksize_long;
  120197. att3 *psy_tone_masteratt;
  120198. int *psy_tone_0dB;
  120199. int *psy_tone_dBsuppress;
  120200. vp_adjblock *psy_tone_adj_impulse;
  120201. vp_adjblock *psy_tone_adj_long;
  120202. vp_adjblock *psy_tone_adj_other;
  120203. noiseguard *psy_noiseguards;
  120204. noise3 *psy_noise_bias_impulse;
  120205. noise3 *psy_noise_bias_padding;
  120206. noise3 *psy_noise_bias_trans;
  120207. noise3 *psy_noise_bias_long;
  120208. int *psy_noise_dBsuppress;
  120209. compandblock *psy_noise_compand;
  120210. double *psy_noise_compand_short_mapping;
  120211. double *psy_noise_compand_long_mapping;
  120212. int *psy_noise_normal_start[2];
  120213. int *psy_noise_normal_partition[2];
  120214. double *psy_noise_normal_thresh;
  120215. int *psy_ath_float;
  120216. int *psy_ath_abs;
  120217. double *psy_lowpass;
  120218. vorbis_info_psy_global *global_params;
  120219. double *global_mapping;
  120220. adj_stereo *stereo_modes;
  120221. static_codebook ***floor_books;
  120222. vorbis_info_floor1 *floor_params;
  120223. int *floor_short_mapping;
  120224. int *floor_long_mapping;
  120225. vorbis_mapping_template *maps;
  120226. } ve_setup_data_template;
  120227. /* a few static coder conventions */
  120228. static vorbis_info_mode _mode_template[2]={
  120229. {0,0,0,0},
  120230. {1,0,0,1}
  120231. };
  120232. static vorbis_info_mapping0 _map_nominal[2]={
  120233. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120234. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120235. };
  120236. /*** Start of inlined file: setup_44.h ***/
  120237. /*** Start of inlined file: floor_all.h ***/
  120238. /*** Start of inlined file: floor_books.h ***/
  120239. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120240. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120241. };
  120242. static static_codebook _huff_book_line_256x7_0sub1 = {
  120243. 1, 9,
  120244. _huff_lengthlist_line_256x7_0sub1,
  120245. 0, 0, 0, 0, 0,
  120246. NULL,
  120247. NULL,
  120248. NULL,
  120249. NULL,
  120250. 0
  120251. };
  120252. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120254. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120255. };
  120256. static static_codebook _huff_book_line_256x7_0sub2 = {
  120257. 1, 25,
  120258. _huff_lengthlist_line_256x7_0sub2,
  120259. 0, 0, 0, 0, 0,
  120260. NULL,
  120261. NULL,
  120262. NULL,
  120263. NULL,
  120264. 0
  120265. };
  120266. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120269. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120270. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120271. };
  120272. static static_codebook _huff_book_line_256x7_0sub3 = {
  120273. 1, 64,
  120274. _huff_lengthlist_line_256x7_0sub3,
  120275. 0, 0, 0, 0, 0,
  120276. NULL,
  120277. NULL,
  120278. NULL,
  120279. NULL,
  120280. 0
  120281. };
  120282. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120283. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120284. };
  120285. static static_codebook _huff_book_line_256x7_1sub1 = {
  120286. 1, 9,
  120287. _huff_lengthlist_line_256x7_1sub1,
  120288. 0, 0, 0, 0, 0,
  120289. NULL,
  120290. NULL,
  120291. NULL,
  120292. NULL,
  120293. 0
  120294. };
  120295. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120297. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120298. };
  120299. static static_codebook _huff_book_line_256x7_1sub2 = {
  120300. 1, 25,
  120301. _huff_lengthlist_line_256x7_1sub2,
  120302. 0, 0, 0, 0, 0,
  120303. NULL,
  120304. NULL,
  120305. NULL,
  120306. NULL,
  120307. 0
  120308. };
  120309. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120312. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120313. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120314. };
  120315. static static_codebook _huff_book_line_256x7_1sub3 = {
  120316. 1, 64,
  120317. _huff_lengthlist_line_256x7_1sub3,
  120318. 0, 0, 0, 0, 0,
  120319. NULL,
  120320. NULL,
  120321. NULL,
  120322. NULL,
  120323. 0
  120324. };
  120325. static long _huff_lengthlist_line_256x7_class0[] = {
  120326. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120327. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120328. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120329. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120330. };
  120331. static static_codebook _huff_book_line_256x7_class0 = {
  120332. 1, 64,
  120333. _huff_lengthlist_line_256x7_class0,
  120334. 0, 0, 0, 0, 0,
  120335. NULL,
  120336. NULL,
  120337. NULL,
  120338. NULL,
  120339. 0
  120340. };
  120341. static long _huff_lengthlist_line_256x7_class1[] = {
  120342. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120343. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120344. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120345. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120346. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120347. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120348. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120349. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120350. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120351. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120352. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120353. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120354. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120355. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120356. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120357. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120358. };
  120359. static static_codebook _huff_book_line_256x7_class1 = {
  120360. 1, 256,
  120361. _huff_lengthlist_line_256x7_class1,
  120362. 0, 0, 0, 0, 0,
  120363. NULL,
  120364. NULL,
  120365. NULL,
  120366. NULL,
  120367. 0
  120368. };
  120369. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120370. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120371. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120372. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120373. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120374. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120375. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120376. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120377. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120378. };
  120379. static static_codebook _huff_book_line_512x17_0sub0 = {
  120380. 1, 128,
  120381. _huff_lengthlist_line_512x17_0sub0,
  120382. 0, 0, 0, 0, 0,
  120383. NULL,
  120384. NULL,
  120385. NULL,
  120386. NULL,
  120387. 0
  120388. };
  120389. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120390. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120391. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120392. };
  120393. static static_codebook _huff_book_line_512x17_1sub0 = {
  120394. 1, 32,
  120395. _huff_lengthlist_line_512x17_1sub0,
  120396. 0, 0, 0, 0, 0,
  120397. NULL,
  120398. NULL,
  120399. NULL,
  120400. NULL,
  120401. 0
  120402. };
  120403. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120406. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120407. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120408. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120409. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120410. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120411. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120412. };
  120413. static static_codebook _huff_book_line_512x17_1sub1 = {
  120414. 1, 128,
  120415. _huff_lengthlist_line_512x17_1sub1,
  120416. 0, 0, 0, 0, 0,
  120417. NULL,
  120418. NULL,
  120419. NULL,
  120420. NULL,
  120421. 0
  120422. };
  120423. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120424. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120425. 5, 3,
  120426. };
  120427. static static_codebook _huff_book_line_512x17_2sub1 = {
  120428. 1, 18,
  120429. _huff_lengthlist_line_512x17_2sub1,
  120430. 0, 0, 0, 0, 0,
  120431. NULL,
  120432. NULL,
  120433. NULL,
  120434. NULL,
  120435. 0
  120436. };
  120437. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120439. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120440. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120441. 9, 8,
  120442. };
  120443. static static_codebook _huff_book_line_512x17_2sub2 = {
  120444. 1, 50,
  120445. _huff_lengthlist_line_512x17_2sub2,
  120446. 0, 0, 0, 0, 0,
  120447. NULL,
  120448. NULL,
  120449. NULL,
  120450. NULL,
  120451. 0
  120452. };
  120453. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120457. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120458. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120459. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120460. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120461. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120462. };
  120463. static static_codebook _huff_book_line_512x17_2sub3 = {
  120464. 1, 128,
  120465. _huff_lengthlist_line_512x17_2sub3,
  120466. 0, 0, 0, 0, 0,
  120467. NULL,
  120468. NULL,
  120469. NULL,
  120470. NULL,
  120471. 0
  120472. };
  120473. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120474. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120475. 5, 5,
  120476. };
  120477. static static_codebook _huff_book_line_512x17_3sub1 = {
  120478. 1, 18,
  120479. _huff_lengthlist_line_512x17_3sub1,
  120480. 0, 0, 0, 0, 0,
  120481. NULL,
  120482. NULL,
  120483. NULL,
  120484. NULL,
  120485. 0
  120486. };
  120487. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120489. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120490. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120491. 11,14,
  120492. };
  120493. static static_codebook _huff_book_line_512x17_3sub2 = {
  120494. 1, 50,
  120495. _huff_lengthlist_line_512x17_3sub2,
  120496. 0, 0, 0, 0, 0,
  120497. NULL,
  120498. NULL,
  120499. NULL,
  120500. NULL,
  120501. 0
  120502. };
  120503. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120507. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120508. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120509. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120510. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120511. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120512. };
  120513. static static_codebook _huff_book_line_512x17_3sub3 = {
  120514. 1, 128,
  120515. _huff_lengthlist_line_512x17_3sub3,
  120516. 0, 0, 0, 0, 0,
  120517. NULL,
  120518. NULL,
  120519. NULL,
  120520. NULL,
  120521. 0
  120522. };
  120523. static long _huff_lengthlist_line_512x17_class1[] = {
  120524. 1, 2, 3, 6, 5, 4, 7, 7,
  120525. };
  120526. static static_codebook _huff_book_line_512x17_class1 = {
  120527. 1, 8,
  120528. _huff_lengthlist_line_512x17_class1,
  120529. 0, 0, 0, 0, 0,
  120530. NULL,
  120531. NULL,
  120532. NULL,
  120533. NULL,
  120534. 0
  120535. };
  120536. static long _huff_lengthlist_line_512x17_class2[] = {
  120537. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120538. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120539. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120540. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120541. };
  120542. static static_codebook _huff_book_line_512x17_class2 = {
  120543. 1, 64,
  120544. _huff_lengthlist_line_512x17_class2,
  120545. 0, 0, 0, 0, 0,
  120546. NULL,
  120547. NULL,
  120548. NULL,
  120549. NULL,
  120550. 0
  120551. };
  120552. static long _huff_lengthlist_line_512x17_class3[] = {
  120553. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120554. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120555. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120556. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120557. };
  120558. static static_codebook _huff_book_line_512x17_class3 = {
  120559. 1, 64,
  120560. _huff_lengthlist_line_512x17_class3,
  120561. 0, 0, 0, 0, 0,
  120562. NULL,
  120563. NULL,
  120564. NULL,
  120565. NULL,
  120566. 0
  120567. };
  120568. static long _huff_lengthlist_line_128x4_class0[] = {
  120569. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120570. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120571. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120572. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120573. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120574. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120575. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120576. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120577. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120578. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120579. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120580. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120581. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120582. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120583. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120584. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120585. };
  120586. static static_codebook _huff_book_line_128x4_class0 = {
  120587. 1, 256,
  120588. _huff_lengthlist_line_128x4_class0,
  120589. 0, 0, 0, 0, 0,
  120590. NULL,
  120591. NULL,
  120592. NULL,
  120593. NULL,
  120594. 0
  120595. };
  120596. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120597. 2, 2, 2, 2,
  120598. };
  120599. static static_codebook _huff_book_line_128x4_0sub0 = {
  120600. 1, 4,
  120601. _huff_lengthlist_line_128x4_0sub0,
  120602. 0, 0, 0, 0, 0,
  120603. NULL,
  120604. NULL,
  120605. NULL,
  120606. NULL,
  120607. 0
  120608. };
  120609. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120610. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120611. };
  120612. static static_codebook _huff_book_line_128x4_0sub1 = {
  120613. 1, 10,
  120614. _huff_lengthlist_line_128x4_0sub1,
  120615. 0, 0, 0, 0, 0,
  120616. NULL,
  120617. NULL,
  120618. NULL,
  120619. NULL,
  120620. 0
  120621. };
  120622. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120624. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120625. };
  120626. static static_codebook _huff_book_line_128x4_0sub2 = {
  120627. 1, 25,
  120628. _huff_lengthlist_line_128x4_0sub2,
  120629. 0, 0, 0, 0, 0,
  120630. NULL,
  120631. NULL,
  120632. NULL,
  120633. NULL,
  120634. 0
  120635. };
  120636. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120639. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120640. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120641. };
  120642. static static_codebook _huff_book_line_128x4_0sub3 = {
  120643. 1, 64,
  120644. _huff_lengthlist_line_128x4_0sub3,
  120645. 0, 0, 0, 0, 0,
  120646. NULL,
  120647. NULL,
  120648. NULL,
  120649. NULL,
  120650. 0
  120651. };
  120652. static long _huff_lengthlist_line_256x4_class0[] = {
  120653. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120654. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120655. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120656. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120657. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120658. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120659. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120660. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120661. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120662. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120663. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120664. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120665. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120666. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120667. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120668. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120669. };
  120670. static static_codebook _huff_book_line_256x4_class0 = {
  120671. 1, 256,
  120672. _huff_lengthlist_line_256x4_class0,
  120673. 0, 0, 0, 0, 0,
  120674. NULL,
  120675. NULL,
  120676. NULL,
  120677. NULL,
  120678. 0
  120679. };
  120680. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120681. 2, 2, 2, 2,
  120682. };
  120683. static static_codebook _huff_book_line_256x4_0sub0 = {
  120684. 1, 4,
  120685. _huff_lengthlist_line_256x4_0sub0,
  120686. 0, 0, 0, 0, 0,
  120687. NULL,
  120688. NULL,
  120689. NULL,
  120690. NULL,
  120691. 0
  120692. };
  120693. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120694. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120695. };
  120696. static static_codebook _huff_book_line_256x4_0sub1 = {
  120697. 1, 10,
  120698. _huff_lengthlist_line_256x4_0sub1,
  120699. 0, 0, 0, 0, 0,
  120700. NULL,
  120701. NULL,
  120702. NULL,
  120703. NULL,
  120704. 0
  120705. };
  120706. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120708. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120709. };
  120710. static static_codebook _huff_book_line_256x4_0sub2 = {
  120711. 1, 25,
  120712. _huff_lengthlist_line_256x4_0sub2,
  120713. 0, 0, 0, 0, 0,
  120714. NULL,
  120715. NULL,
  120716. NULL,
  120717. NULL,
  120718. 0
  120719. };
  120720. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120723. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120724. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120725. };
  120726. static static_codebook _huff_book_line_256x4_0sub3 = {
  120727. 1, 64,
  120728. _huff_lengthlist_line_256x4_0sub3,
  120729. 0, 0, 0, 0, 0,
  120730. NULL,
  120731. NULL,
  120732. NULL,
  120733. NULL,
  120734. 0
  120735. };
  120736. static long _huff_lengthlist_line_128x7_class0[] = {
  120737. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120738. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120739. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120740. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120741. };
  120742. static static_codebook _huff_book_line_128x7_class0 = {
  120743. 1, 64,
  120744. _huff_lengthlist_line_128x7_class0,
  120745. 0, 0, 0, 0, 0,
  120746. NULL,
  120747. NULL,
  120748. NULL,
  120749. NULL,
  120750. 0
  120751. };
  120752. static long _huff_lengthlist_line_128x7_class1[] = {
  120753. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120754. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120755. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120756. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120757. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120758. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120759. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120760. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120761. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120762. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120763. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120764. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120765. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120766. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120767. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120768. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120769. };
  120770. static static_codebook _huff_book_line_128x7_class1 = {
  120771. 1, 256,
  120772. _huff_lengthlist_line_128x7_class1,
  120773. 0, 0, 0, 0, 0,
  120774. NULL,
  120775. NULL,
  120776. NULL,
  120777. NULL,
  120778. 0
  120779. };
  120780. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120781. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120782. };
  120783. static static_codebook _huff_book_line_128x7_0sub1 = {
  120784. 1, 9,
  120785. _huff_lengthlist_line_128x7_0sub1,
  120786. 0, 0, 0, 0, 0,
  120787. NULL,
  120788. NULL,
  120789. NULL,
  120790. NULL,
  120791. 0
  120792. };
  120793. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120795. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120796. };
  120797. static static_codebook _huff_book_line_128x7_0sub2 = {
  120798. 1, 25,
  120799. _huff_lengthlist_line_128x7_0sub2,
  120800. 0, 0, 0, 0, 0,
  120801. NULL,
  120802. NULL,
  120803. NULL,
  120804. NULL,
  120805. 0
  120806. };
  120807. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120810. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120811. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120812. };
  120813. static static_codebook _huff_book_line_128x7_0sub3 = {
  120814. 1, 64,
  120815. _huff_lengthlist_line_128x7_0sub3,
  120816. 0, 0, 0, 0, 0,
  120817. NULL,
  120818. NULL,
  120819. NULL,
  120820. NULL,
  120821. 0
  120822. };
  120823. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120824. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120825. };
  120826. static static_codebook _huff_book_line_128x7_1sub1 = {
  120827. 1, 9,
  120828. _huff_lengthlist_line_128x7_1sub1,
  120829. 0, 0, 0, 0, 0,
  120830. NULL,
  120831. NULL,
  120832. NULL,
  120833. NULL,
  120834. 0
  120835. };
  120836. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120838. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120839. };
  120840. static static_codebook _huff_book_line_128x7_1sub2 = {
  120841. 1, 25,
  120842. _huff_lengthlist_line_128x7_1sub2,
  120843. 0, 0, 0, 0, 0,
  120844. NULL,
  120845. NULL,
  120846. NULL,
  120847. NULL,
  120848. 0
  120849. };
  120850. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120853. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120854. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120855. };
  120856. static static_codebook _huff_book_line_128x7_1sub3 = {
  120857. 1, 64,
  120858. _huff_lengthlist_line_128x7_1sub3,
  120859. 0, 0, 0, 0, 0,
  120860. NULL,
  120861. NULL,
  120862. NULL,
  120863. NULL,
  120864. 0
  120865. };
  120866. static long _huff_lengthlist_line_128x11_class1[] = {
  120867. 1, 6, 3, 7, 2, 4, 5, 7,
  120868. };
  120869. static static_codebook _huff_book_line_128x11_class1 = {
  120870. 1, 8,
  120871. _huff_lengthlist_line_128x11_class1,
  120872. 0, 0, 0, 0, 0,
  120873. NULL,
  120874. NULL,
  120875. NULL,
  120876. NULL,
  120877. 0
  120878. };
  120879. static long _huff_lengthlist_line_128x11_class2[] = {
  120880. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120881. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120882. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120883. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120884. };
  120885. static static_codebook _huff_book_line_128x11_class2 = {
  120886. 1, 64,
  120887. _huff_lengthlist_line_128x11_class2,
  120888. 0, 0, 0, 0, 0,
  120889. NULL,
  120890. NULL,
  120891. NULL,
  120892. NULL,
  120893. 0
  120894. };
  120895. static long _huff_lengthlist_line_128x11_class3[] = {
  120896. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120897. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120898. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120899. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120900. };
  120901. static static_codebook _huff_book_line_128x11_class3 = {
  120902. 1, 64,
  120903. _huff_lengthlist_line_128x11_class3,
  120904. 0, 0, 0, 0, 0,
  120905. NULL,
  120906. NULL,
  120907. NULL,
  120908. NULL,
  120909. 0
  120910. };
  120911. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120912. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120913. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120914. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120915. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120916. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120917. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120918. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120919. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120920. };
  120921. static static_codebook _huff_book_line_128x11_0sub0 = {
  120922. 1, 128,
  120923. _huff_lengthlist_line_128x11_0sub0,
  120924. 0, 0, 0, 0, 0,
  120925. NULL,
  120926. NULL,
  120927. NULL,
  120928. NULL,
  120929. 0
  120930. };
  120931. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120932. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120933. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120934. };
  120935. static static_codebook _huff_book_line_128x11_1sub0 = {
  120936. 1, 32,
  120937. _huff_lengthlist_line_128x11_1sub0,
  120938. 0, 0, 0, 0, 0,
  120939. NULL,
  120940. NULL,
  120941. NULL,
  120942. NULL,
  120943. 0
  120944. };
  120945. static long _huff_lengthlist_line_128x11_1sub1[] = {
  120946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120949. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120950. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120951. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120952. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120953. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120954. };
  120955. static static_codebook _huff_book_line_128x11_1sub1 = {
  120956. 1, 128,
  120957. _huff_lengthlist_line_128x11_1sub1,
  120958. 0, 0, 0, 0, 0,
  120959. NULL,
  120960. NULL,
  120961. NULL,
  120962. NULL,
  120963. 0
  120964. };
  120965. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120966. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120967. 5, 5,
  120968. };
  120969. static static_codebook _huff_book_line_128x11_2sub1 = {
  120970. 1, 18,
  120971. _huff_lengthlist_line_128x11_2sub1,
  120972. 0, 0, 0, 0, 0,
  120973. NULL,
  120974. NULL,
  120975. NULL,
  120976. NULL,
  120977. 0
  120978. };
  120979. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120981. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120982. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120983. 8,11,
  120984. };
  120985. static static_codebook _huff_book_line_128x11_2sub2 = {
  120986. 1, 50,
  120987. _huff_lengthlist_line_128x11_2sub2,
  120988. 0, 0, 0, 0, 0,
  120989. NULL,
  120990. NULL,
  120991. NULL,
  120992. NULL,
  120993. 0
  120994. };
  120995. static long _huff_lengthlist_line_128x11_2sub3[] = {
  120996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120999. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121000. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121001. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121002. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121003. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121004. };
  121005. static static_codebook _huff_book_line_128x11_2sub3 = {
  121006. 1, 128,
  121007. _huff_lengthlist_line_128x11_2sub3,
  121008. 0, 0, 0, 0, 0,
  121009. NULL,
  121010. NULL,
  121011. NULL,
  121012. NULL,
  121013. 0
  121014. };
  121015. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121016. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121017. 5, 4,
  121018. };
  121019. static static_codebook _huff_book_line_128x11_3sub1 = {
  121020. 1, 18,
  121021. _huff_lengthlist_line_128x11_3sub1,
  121022. 0, 0, 0, 0, 0,
  121023. NULL,
  121024. NULL,
  121025. NULL,
  121026. NULL,
  121027. 0
  121028. };
  121029. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121031. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121032. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121033. 12, 6,
  121034. };
  121035. static static_codebook _huff_book_line_128x11_3sub2 = {
  121036. 1, 50,
  121037. _huff_lengthlist_line_128x11_3sub2,
  121038. 0, 0, 0, 0, 0,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. 0
  121044. };
  121045. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121049. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121050. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121051. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121052. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121053. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121054. };
  121055. static static_codebook _huff_book_line_128x11_3sub3 = {
  121056. 1, 128,
  121057. _huff_lengthlist_line_128x11_3sub3,
  121058. 0, 0, 0, 0, 0,
  121059. NULL,
  121060. NULL,
  121061. NULL,
  121062. NULL,
  121063. 0
  121064. };
  121065. static long _huff_lengthlist_line_128x17_class1[] = {
  121066. 1, 3, 4, 7, 2, 5, 6, 7,
  121067. };
  121068. static static_codebook _huff_book_line_128x17_class1 = {
  121069. 1, 8,
  121070. _huff_lengthlist_line_128x17_class1,
  121071. 0, 0, 0, 0, 0,
  121072. NULL,
  121073. NULL,
  121074. NULL,
  121075. NULL,
  121076. 0
  121077. };
  121078. static long _huff_lengthlist_line_128x17_class2[] = {
  121079. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121080. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121081. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121082. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121083. };
  121084. static static_codebook _huff_book_line_128x17_class2 = {
  121085. 1, 64,
  121086. _huff_lengthlist_line_128x17_class2,
  121087. 0, 0, 0, 0, 0,
  121088. NULL,
  121089. NULL,
  121090. NULL,
  121091. NULL,
  121092. 0
  121093. };
  121094. static long _huff_lengthlist_line_128x17_class3[] = {
  121095. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121096. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121097. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121098. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121099. };
  121100. static static_codebook _huff_book_line_128x17_class3 = {
  121101. 1, 64,
  121102. _huff_lengthlist_line_128x17_class3,
  121103. 0, 0, 0, 0, 0,
  121104. NULL,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. 0
  121109. };
  121110. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121111. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121112. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121113. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121114. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121115. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121116. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121117. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121118. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121119. };
  121120. static static_codebook _huff_book_line_128x17_0sub0 = {
  121121. 1, 128,
  121122. _huff_lengthlist_line_128x17_0sub0,
  121123. 0, 0, 0, 0, 0,
  121124. NULL,
  121125. NULL,
  121126. NULL,
  121127. NULL,
  121128. 0
  121129. };
  121130. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121131. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121132. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121133. };
  121134. static static_codebook _huff_book_line_128x17_1sub0 = {
  121135. 1, 32,
  121136. _huff_lengthlist_line_128x17_1sub0,
  121137. 0, 0, 0, 0, 0,
  121138. NULL,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. 0
  121143. };
  121144. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121147. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121148. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121149. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121150. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121151. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121152. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121153. };
  121154. static static_codebook _huff_book_line_128x17_1sub1 = {
  121155. 1, 128,
  121156. _huff_lengthlist_line_128x17_1sub1,
  121157. 0, 0, 0, 0, 0,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. NULL,
  121162. 0
  121163. };
  121164. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121165. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121166. 9, 4,
  121167. };
  121168. static static_codebook _huff_book_line_128x17_2sub1 = {
  121169. 1, 18,
  121170. _huff_lengthlist_line_128x17_2sub1,
  121171. 0, 0, 0, 0, 0,
  121172. NULL,
  121173. NULL,
  121174. NULL,
  121175. NULL,
  121176. 0
  121177. };
  121178. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121180. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121181. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121182. 13,13,
  121183. };
  121184. static static_codebook _huff_book_line_128x17_2sub2 = {
  121185. 1, 50,
  121186. _huff_lengthlist_line_128x17_2sub2,
  121187. 0, 0, 0, 0, 0,
  121188. NULL,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. 0
  121193. };
  121194. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121198. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121199. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121200. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121201. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121202. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121203. };
  121204. static static_codebook _huff_book_line_128x17_2sub3 = {
  121205. 1, 128,
  121206. _huff_lengthlist_line_128x17_2sub3,
  121207. 0, 0, 0, 0, 0,
  121208. NULL,
  121209. NULL,
  121210. NULL,
  121211. NULL,
  121212. 0
  121213. };
  121214. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121215. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121216. 6, 4,
  121217. };
  121218. static static_codebook _huff_book_line_128x17_3sub1 = {
  121219. 1, 18,
  121220. _huff_lengthlist_line_128x17_3sub1,
  121221. 0, 0, 0, 0, 0,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. NULL,
  121226. 0
  121227. };
  121228. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121230. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121231. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121232. 10, 8,
  121233. };
  121234. static static_codebook _huff_book_line_128x17_3sub2 = {
  121235. 1, 50,
  121236. _huff_lengthlist_line_128x17_3sub2,
  121237. 0, 0, 0, 0, 0,
  121238. NULL,
  121239. NULL,
  121240. NULL,
  121241. NULL,
  121242. 0
  121243. };
  121244. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121249. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121250. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121253. };
  121254. static static_codebook _huff_book_line_128x17_3sub3 = {
  121255. 1, 128,
  121256. _huff_lengthlist_line_128x17_3sub3,
  121257. 0, 0, 0, 0, 0,
  121258. NULL,
  121259. NULL,
  121260. NULL,
  121261. NULL,
  121262. 0
  121263. };
  121264. static long _huff_lengthlist_line_1024x27_class1[] = {
  121265. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121266. };
  121267. static static_codebook _huff_book_line_1024x27_class1 = {
  121268. 1, 16,
  121269. _huff_lengthlist_line_1024x27_class1,
  121270. 0, 0, 0, 0, 0,
  121271. NULL,
  121272. NULL,
  121273. NULL,
  121274. NULL,
  121275. 0
  121276. };
  121277. static long _huff_lengthlist_line_1024x27_class2[] = {
  121278. 1, 4, 2, 6, 3, 7, 5, 7,
  121279. };
  121280. static static_codebook _huff_book_line_1024x27_class2 = {
  121281. 1, 8,
  121282. _huff_lengthlist_line_1024x27_class2,
  121283. 0, 0, 0, 0, 0,
  121284. NULL,
  121285. NULL,
  121286. NULL,
  121287. NULL,
  121288. 0
  121289. };
  121290. static long _huff_lengthlist_line_1024x27_class3[] = {
  121291. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121292. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121293. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121294. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121295. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121296. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121297. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121298. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121299. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121300. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121301. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121302. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121303. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121304. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121305. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121306. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121307. };
  121308. static static_codebook _huff_book_line_1024x27_class3 = {
  121309. 1, 256,
  121310. _huff_lengthlist_line_1024x27_class3,
  121311. 0, 0, 0, 0, 0,
  121312. NULL,
  121313. NULL,
  121314. NULL,
  121315. NULL,
  121316. 0
  121317. };
  121318. static long _huff_lengthlist_line_1024x27_class4[] = {
  121319. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121320. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121321. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121322. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121323. };
  121324. static static_codebook _huff_book_line_1024x27_class4 = {
  121325. 1, 64,
  121326. _huff_lengthlist_line_1024x27_class4,
  121327. 0, 0, 0, 0, 0,
  121328. NULL,
  121329. NULL,
  121330. NULL,
  121331. NULL,
  121332. 0
  121333. };
  121334. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121335. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121336. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121337. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121338. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121339. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121340. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121341. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121342. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121343. };
  121344. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121345. 1, 128,
  121346. _huff_lengthlist_line_1024x27_0sub0,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121355. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121356. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121357. };
  121358. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121359. 1, 32,
  121360. _huff_lengthlist_line_1024x27_1sub0,
  121361. 0, 0, 0, 0, 0,
  121362. NULL,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. 0
  121367. };
  121368. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121372. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121373. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121374. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121375. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121376. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121377. };
  121378. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121379. 1, 128,
  121380. _huff_lengthlist_line_1024x27_1sub1,
  121381. 0, 0, 0, 0, 0,
  121382. NULL,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. 0
  121387. };
  121388. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121389. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121390. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121391. };
  121392. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121393. 1, 32,
  121394. _huff_lengthlist_line_1024x27_2sub0,
  121395. 0, 0, 0, 0, 0,
  121396. NULL,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. 0
  121401. };
  121402. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121406. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121407. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121408. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121409. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121410. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121411. };
  121412. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121413. 1, 128,
  121414. _huff_lengthlist_line_1024x27_2sub1,
  121415. 0, 0, 0, 0, 0,
  121416. NULL,
  121417. NULL,
  121418. NULL,
  121419. NULL,
  121420. 0
  121421. };
  121422. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121423. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121424. 5, 5,
  121425. };
  121426. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121427. 1, 18,
  121428. _huff_lengthlist_line_1024x27_3sub1,
  121429. 0, 0, 0, 0, 0,
  121430. NULL,
  121431. NULL,
  121432. NULL,
  121433. NULL,
  121434. 0
  121435. };
  121436. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121438. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121439. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121440. 9,11,
  121441. };
  121442. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121443. 1, 50,
  121444. _huff_lengthlist_line_1024x27_3sub2,
  121445. 0, 0, 0, 0, 0,
  121446. NULL,
  121447. NULL,
  121448. NULL,
  121449. NULL,
  121450. 0
  121451. };
  121452. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  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, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121457. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121458. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121459. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121460. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121461. };
  121462. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121463. 1, 128,
  121464. _huff_lengthlist_line_1024x27_3sub3,
  121465. 0, 0, 0, 0, 0,
  121466. NULL,
  121467. NULL,
  121468. NULL,
  121469. NULL,
  121470. 0
  121471. };
  121472. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121473. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121474. 5, 4,
  121475. };
  121476. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121477. 1, 18,
  121478. _huff_lengthlist_line_1024x27_4sub1,
  121479. 0, 0, 0, 0, 0,
  121480. NULL,
  121481. NULL,
  121482. NULL,
  121483. NULL,
  121484. 0
  121485. };
  121486. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121489. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121490. 9,12,
  121491. };
  121492. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121493. 1, 50,
  121494. _huff_lengthlist_line_1024x27_4sub2,
  121495. 0, 0, 0, 0, 0,
  121496. NULL,
  121497. NULL,
  121498. NULL,
  121499. NULL,
  121500. 0
  121501. };
  121502. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  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, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121507. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121510. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121511. };
  121512. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121513. 1, 128,
  121514. _huff_lengthlist_line_1024x27_4sub3,
  121515. 0, 0, 0, 0, 0,
  121516. NULL,
  121517. NULL,
  121518. NULL,
  121519. NULL,
  121520. 0
  121521. };
  121522. static long _huff_lengthlist_line_2048x27_class1[] = {
  121523. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121524. };
  121525. static static_codebook _huff_book_line_2048x27_class1 = {
  121526. 1, 16,
  121527. _huff_lengthlist_line_2048x27_class1,
  121528. 0, 0, 0, 0, 0,
  121529. NULL,
  121530. NULL,
  121531. NULL,
  121532. NULL,
  121533. 0
  121534. };
  121535. static long _huff_lengthlist_line_2048x27_class2[] = {
  121536. 1, 2, 3, 6, 4, 7, 5, 7,
  121537. };
  121538. static static_codebook _huff_book_line_2048x27_class2 = {
  121539. 1, 8,
  121540. _huff_lengthlist_line_2048x27_class2,
  121541. 0, 0, 0, 0, 0,
  121542. NULL,
  121543. NULL,
  121544. NULL,
  121545. NULL,
  121546. 0
  121547. };
  121548. static long _huff_lengthlist_line_2048x27_class3[] = {
  121549. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121550. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121551. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121552. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121553. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121554. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121555. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121556. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121557. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121558. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121559. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121560. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121561. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121562. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121563. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121564. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121565. };
  121566. static static_codebook _huff_book_line_2048x27_class3 = {
  121567. 1, 256,
  121568. _huff_lengthlist_line_2048x27_class3,
  121569. 0, 0, 0, 0, 0,
  121570. NULL,
  121571. NULL,
  121572. NULL,
  121573. NULL,
  121574. 0
  121575. };
  121576. static long _huff_lengthlist_line_2048x27_class4[] = {
  121577. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121578. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121579. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121580. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121581. };
  121582. static static_codebook _huff_book_line_2048x27_class4 = {
  121583. 1, 64,
  121584. _huff_lengthlist_line_2048x27_class4,
  121585. 0, 0, 0, 0, 0,
  121586. NULL,
  121587. NULL,
  121588. NULL,
  121589. NULL,
  121590. 0
  121591. };
  121592. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121593. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121594. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121595. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121596. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121597. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121598. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121599. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121600. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121601. };
  121602. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121603. 1, 128,
  121604. _huff_lengthlist_line_2048x27_0sub0,
  121605. 0, 0, 0, 0, 0,
  121606. NULL,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. 0
  121611. };
  121612. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121613. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121614. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121615. };
  121616. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121617. 1, 32,
  121618. _huff_lengthlist_line_2048x27_1sub0,
  121619. 0, 0, 0, 0, 0,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. NULL,
  121624. 0
  121625. };
  121626. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  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. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121630. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121631. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121632. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121633. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121634. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121635. };
  121636. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121637. 1, 128,
  121638. _huff_lengthlist_line_2048x27_1sub1,
  121639. 0, 0, 0, 0, 0,
  121640. NULL,
  121641. NULL,
  121642. NULL,
  121643. NULL,
  121644. 0
  121645. };
  121646. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121647. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121648. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121649. };
  121650. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121651. 1, 32,
  121652. _huff_lengthlist_line_2048x27_2sub0,
  121653. 0, 0, 0, 0, 0,
  121654. NULL,
  121655. NULL,
  121656. NULL,
  121657. NULL,
  121658. 0
  121659. };
  121660. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  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. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121664. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121665. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121666. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121667. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121668. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121669. };
  121670. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121671. 1, 128,
  121672. _huff_lengthlist_line_2048x27_2sub1,
  121673. 0, 0, 0, 0, 0,
  121674. NULL,
  121675. NULL,
  121676. NULL,
  121677. NULL,
  121678. 0
  121679. };
  121680. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121681. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121682. 5, 5,
  121683. };
  121684. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121685. 1, 18,
  121686. _huff_lengthlist_line_2048x27_3sub1,
  121687. 0, 0, 0, 0, 0,
  121688. NULL,
  121689. NULL,
  121690. NULL,
  121691. NULL,
  121692. 0
  121693. };
  121694. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121697. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121698. 10,12,
  121699. };
  121700. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121701. 1, 50,
  121702. _huff_lengthlist_line_2048x27_3sub2,
  121703. 0, 0, 0, 0, 0,
  121704. NULL,
  121705. NULL,
  121706. NULL,
  121707. NULL,
  121708. 0
  121709. };
  121710. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  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, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121715. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121716. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121717. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121718. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121719. };
  121720. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121721. 1, 128,
  121722. _huff_lengthlist_line_2048x27_3sub3,
  121723. 0, 0, 0, 0, 0,
  121724. NULL,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. 0
  121729. };
  121730. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121731. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121732. 4, 5,
  121733. };
  121734. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121735. 1, 18,
  121736. _huff_lengthlist_line_2048x27_4sub1,
  121737. 0, 0, 0, 0, 0,
  121738. NULL,
  121739. NULL,
  121740. NULL,
  121741. NULL,
  121742. 0
  121743. };
  121744. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121747. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121748. 10,10,
  121749. };
  121750. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121751. 1, 50,
  121752. _huff_lengthlist_line_2048x27_4sub2,
  121753. 0, 0, 0, 0, 0,
  121754. NULL,
  121755. NULL,
  121756. NULL,
  121757. NULL,
  121758. 0
  121759. };
  121760. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  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, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121765. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121766. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121767. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121768. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121769. };
  121770. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121771. 1, 128,
  121772. _huff_lengthlist_line_2048x27_4sub3,
  121773. 0, 0, 0, 0, 0,
  121774. NULL,
  121775. NULL,
  121776. NULL,
  121777. NULL,
  121778. 0
  121779. };
  121780. static long _huff_lengthlist_line_256x4low_class0[] = {
  121781. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121782. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121783. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121784. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121785. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121786. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121787. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121788. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121789. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121790. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121791. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121792. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121793. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121794. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121795. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121796. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121797. };
  121798. static static_codebook _huff_book_line_256x4low_class0 = {
  121799. 1, 256,
  121800. _huff_lengthlist_line_256x4low_class0,
  121801. 0, 0, 0, 0, 0,
  121802. NULL,
  121803. NULL,
  121804. NULL,
  121805. NULL,
  121806. 0
  121807. };
  121808. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121809. 1, 3, 2, 3,
  121810. };
  121811. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121812. 1, 4,
  121813. _huff_lengthlist_line_256x4low_0sub0,
  121814. 0, 0, 0, 0, 0,
  121815. NULL,
  121816. NULL,
  121817. NULL,
  121818. NULL,
  121819. 0
  121820. };
  121821. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121822. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121823. };
  121824. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121825. 1, 10,
  121826. _huff_lengthlist_line_256x4low_0sub1,
  121827. 0, 0, 0, 0, 0,
  121828. NULL,
  121829. NULL,
  121830. NULL,
  121831. NULL,
  121832. 0
  121833. };
  121834. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121836. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121837. };
  121838. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121839. 1, 25,
  121840. _huff_lengthlist_line_256x4low_0sub2,
  121841. 0, 0, 0, 0, 0,
  121842. NULL,
  121843. NULL,
  121844. NULL,
  121845. NULL,
  121846. 0
  121847. };
  121848. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121851. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121852. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121853. };
  121854. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121855. 1, 64,
  121856. _huff_lengthlist_line_256x4low_0sub3,
  121857. 0, 0, 0, 0, 0,
  121858. NULL,
  121859. NULL,
  121860. NULL,
  121861. NULL,
  121862. 0
  121863. };
  121864. /*** End of inlined file: floor_books.h ***/
  121865. static static_codebook *_floor_128x4_books[]={
  121866. &_huff_book_line_128x4_class0,
  121867. &_huff_book_line_128x4_0sub0,
  121868. &_huff_book_line_128x4_0sub1,
  121869. &_huff_book_line_128x4_0sub2,
  121870. &_huff_book_line_128x4_0sub3,
  121871. };
  121872. static static_codebook *_floor_256x4_books[]={
  121873. &_huff_book_line_256x4_class0,
  121874. &_huff_book_line_256x4_0sub0,
  121875. &_huff_book_line_256x4_0sub1,
  121876. &_huff_book_line_256x4_0sub2,
  121877. &_huff_book_line_256x4_0sub3,
  121878. };
  121879. static static_codebook *_floor_128x7_books[]={
  121880. &_huff_book_line_128x7_class0,
  121881. &_huff_book_line_128x7_class1,
  121882. &_huff_book_line_128x7_0sub1,
  121883. &_huff_book_line_128x7_0sub2,
  121884. &_huff_book_line_128x7_0sub3,
  121885. &_huff_book_line_128x7_1sub1,
  121886. &_huff_book_line_128x7_1sub2,
  121887. &_huff_book_line_128x7_1sub3,
  121888. };
  121889. static static_codebook *_floor_256x7_books[]={
  121890. &_huff_book_line_256x7_class0,
  121891. &_huff_book_line_256x7_class1,
  121892. &_huff_book_line_256x7_0sub1,
  121893. &_huff_book_line_256x7_0sub2,
  121894. &_huff_book_line_256x7_0sub3,
  121895. &_huff_book_line_256x7_1sub1,
  121896. &_huff_book_line_256x7_1sub2,
  121897. &_huff_book_line_256x7_1sub3,
  121898. };
  121899. static static_codebook *_floor_128x11_books[]={
  121900. &_huff_book_line_128x11_class1,
  121901. &_huff_book_line_128x11_class2,
  121902. &_huff_book_line_128x11_class3,
  121903. &_huff_book_line_128x11_0sub0,
  121904. &_huff_book_line_128x11_1sub0,
  121905. &_huff_book_line_128x11_1sub1,
  121906. &_huff_book_line_128x11_2sub1,
  121907. &_huff_book_line_128x11_2sub2,
  121908. &_huff_book_line_128x11_2sub3,
  121909. &_huff_book_line_128x11_3sub1,
  121910. &_huff_book_line_128x11_3sub2,
  121911. &_huff_book_line_128x11_3sub3,
  121912. };
  121913. static static_codebook *_floor_128x17_books[]={
  121914. &_huff_book_line_128x17_class1,
  121915. &_huff_book_line_128x17_class2,
  121916. &_huff_book_line_128x17_class3,
  121917. &_huff_book_line_128x17_0sub0,
  121918. &_huff_book_line_128x17_1sub0,
  121919. &_huff_book_line_128x17_1sub1,
  121920. &_huff_book_line_128x17_2sub1,
  121921. &_huff_book_line_128x17_2sub2,
  121922. &_huff_book_line_128x17_2sub3,
  121923. &_huff_book_line_128x17_3sub1,
  121924. &_huff_book_line_128x17_3sub2,
  121925. &_huff_book_line_128x17_3sub3,
  121926. };
  121927. static static_codebook *_floor_256x4low_books[]={
  121928. &_huff_book_line_256x4low_class0,
  121929. &_huff_book_line_256x4low_0sub0,
  121930. &_huff_book_line_256x4low_0sub1,
  121931. &_huff_book_line_256x4low_0sub2,
  121932. &_huff_book_line_256x4low_0sub3,
  121933. };
  121934. static static_codebook *_floor_1024x27_books[]={
  121935. &_huff_book_line_1024x27_class1,
  121936. &_huff_book_line_1024x27_class2,
  121937. &_huff_book_line_1024x27_class3,
  121938. &_huff_book_line_1024x27_class4,
  121939. &_huff_book_line_1024x27_0sub0,
  121940. &_huff_book_line_1024x27_1sub0,
  121941. &_huff_book_line_1024x27_1sub1,
  121942. &_huff_book_line_1024x27_2sub0,
  121943. &_huff_book_line_1024x27_2sub1,
  121944. &_huff_book_line_1024x27_3sub1,
  121945. &_huff_book_line_1024x27_3sub2,
  121946. &_huff_book_line_1024x27_3sub3,
  121947. &_huff_book_line_1024x27_4sub1,
  121948. &_huff_book_line_1024x27_4sub2,
  121949. &_huff_book_line_1024x27_4sub3,
  121950. };
  121951. static static_codebook *_floor_2048x27_books[]={
  121952. &_huff_book_line_2048x27_class1,
  121953. &_huff_book_line_2048x27_class2,
  121954. &_huff_book_line_2048x27_class3,
  121955. &_huff_book_line_2048x27_class4,
  121956. &_huff_book_line_2048x27_0sub0,
  121957. &_huff_book_line_2048x27_1sub0,
  121958. &_huff_book_line_2048x27_1sub1,
  121959. &_huff_book_line_2048x27_2sub0,
  121960. &_huff_book_line_2048x27_2sub1,
  121961. &_huff_book_line_2048x27_3sub1,
  121962. &_huff_book_line_2048x27_3sub2,
  121963. &_huff_book_line_2048x27_3sub3,
  121964. &_huff_book_line_2048x27_4sub1,
  121965. &_huff_book_line_2048x27_4sub2,
  121966. &_huff_book_line_2048x27_4sub3,
  121967. };
  121968. static static_codebook *_floor_512x17_books[]={
  121969. &_huff_book_line_512x17_class1,
  121970. &_huff_book_line_512x17_class2,
  121971. &_huff_book_line_512x17_class3,
  121972. &_huff_book_line_512x17_0sub0,
  121973. &_huff_book_line_512x17_1sub0,
  121974. &_huff_book_line_512x17_1sub1,
  121975. &_huff_book_line_512x17_2sub1,
  121976. &_huff_book_line_512x17_2sub2,
  121977. &_huff_book_line_512x17_2sub3,
  121978. &_huff_book_line_512x17_3sub1,
  121979. &_huff_book_line_512x17_3sub2,
  121980. &_huff_book_line_512x17_3sub3,
  121981. };
  121982. static static_codebook **_floor_books[10]={
  121983. _floor_128x4_books,
  121984. _floor_256x4_books,
  121985. _floor_128x7_books,
  121986. _floor_256x7_books,
  121987. _floor_128x11_books,
  121988. _floor_128x17_books,
  121989. _floor_256x4low_books,
  121990. _floor_1024x27_books,
  121991. _floor_2048x27_books,
  121992. _floor_512x17_books,
  121993. };
  121994. static vorbis_info_floor1 _floor[10]={
  121995. /* 128 x 4 */
  121996. {
  121997. 1,{0},{4},{2},{0},
  121998. {{1,2,3,4}},
  121999. 4,{0,128, 33,8,16,70},
  122000. 60,30,500, 1.,18., -1
  122001. },
  122002. /* 256 x 4 */
  122003. {
  122004. 1,{0},{4},{2},{0},
  122005. {{1,2,3,4}},
  122006. 4,{0,256, 66,16,32,140},
  122007. 60,30,500, 1.,18., -1
  122008. },
  122009. /* 128 x 7 */
  122010. {
  122011. 2,{0,1},{3,4},{2,2},{0,1},
  122012. {{-1,2,3,4},{-1,5,6,7}},
  122013. 4,{0,128, 14,4,58, 2,8,28,90},
  122014. 60,30,500, 1.,18., -1
  122015. },
  122016. /* 256 x 7 */
  122017. {
  122018. 2,{0,1},{3,4},{2,2},{0,1},
  122019. {{-1,2,3,4},{-1,5,6,7}},
  122020. 4,{0,256, 28,8,116, 4,16,56,180},
  122021. 60,30,500, 1.,18., -1
  122022. },
  122023. /* 128 x 11 */
  122024. {
  122025. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122026. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122027. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122028. 60,30,500, 1,18., -1
  122029. },
  122030. /* 128 x 17 */
  122031. {
  122032. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122033. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122034. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122035. 60,30,500, 1,18., -1
  122036. },
  122037. /* 256 x 4 (low bitrate version) */
  122038. {
  122039. 1,{0},{4},{2},{0},
  122040. {{1,2,3,4}},
  122041. 4,{0,256, 66,16,32,140},
  122042. 60,30,500, 1.,18., -1
  122043. },
  122044. /* 1024 x 27 */
  122045. {
  122046. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122047. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122048. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122049. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122050. 60,30,500, 3,18., -1 /* lowpass */
  122051. },
  122052. /* 2048 x 27 */
  122053. {
  122054. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122055. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122056. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122057. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122058. 60,30,500, 3,18., -1 /* lowpass */
  122059. },
  122060. /* 512 x 17 */
  122061. {
  122062. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122063. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122064. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122065. 7,23,39, 55,79,110, 156,232,360},
  122066. 60,30,500, 1,18., -1 /* lowpass! */
  122067. },
  122068. };
  122069. /*** End of inlined file: floor_all.h ***/
  122070. /*** Start of inlined file: residue_44.h ***/
  122071. /*** Start of inlined file: res_books_stereo.h ***/
  122072. static long _vq_quantlist__16c0_s_p1_0[] = {
  122073. 1,
  122074. 0,
  122075. 2,
  122076. };
  122077. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122078. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122079. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122084. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122089. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122124. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122129. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122134. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122170. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122175. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122180. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0,
  122489. };
  122490. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122491. -0.5, 0.5,
  122492. };
  122493. static long _vq_quantmap__16c0_s_p1_0[] = {
  122494. 1, 0, 2,
  122495. };
  122496. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122497. _vq_quantthresh__16c0_s_p1_0,
  122498. _vq_quantmap__16c0_s_p1_0,
  122499. 3,
  122500. 3
  122501. };
  122502. static static_codebook _16c0_s_p1_0 = {
  122503. 8, 6561,
  122504. _vq_lengthlist__16c0_s_p1_0,
  122505. 1, -535822336, 1611661312, 2, 0,
  122506. _vq_quantlist__16c0_s_p1_0,
  122507. NULL,
  122508. &_vq_auxt__16c0_s_p1_0,
  122509. NULL,
  122510. 0
  122511. };
  122512. static long _vq_quantlist__16c0_s_p2_0[] = {
  122513. 2,
  122514. 1,
  122515. 3,
  122516. 0,
  122517. 4,
  122518. };
  122519. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 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,
  122560. };
  122561. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122562. -1.5, -0.5, 0.5, 1.5,
  122563. };
  122564. static long _vq_quantmap__16c0_s_p2_0[] = {
  122565. 3, 1, 0, 2, 4,
  122566. };
  122567. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122568. _vq_quantthresh__16c0_s_p2_0,
  122569. _vq_quantmap__16c0_s_p2_0,
  122570. 5,
  122571. 5
  122572. };
  122573. static static_codebook _16c0_s_p2_0 = {
  122574. 4, 625,
  122575. _vq_lengthlist__16c0_s_p2_0,
  122576. 1, -533725184, 1611661312, 3, 0,
  122577. _vq_quantlist__16c0_s_p2_0,
  122578. NULL,
  122579. &_vq_auxt__16c0_s_p2_0,
  122580. NULL,
  122581. 0
  122582. };
  122583. static long _vq_quantlist__16c0_s_p3_0[] = {
  122584. 2,
  122585. 1,
  122586. 3,
  122587. 0,
  122588. 4,
  122589. };
  122590. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122591. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0,
  122631. };
  122632. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122633. -1.5, -0.5, 0.5, 1.5,
  122634. };
  122635. static long _vq_quantmap__16c0_s_p3_0[] = {
  122636. 3, 1, 0, 2, 4,
  122637. };
  122638. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122639. _vq_quantthresh__16c0_s_p3_0,
  122640. _vq_quantmap__16c0_s_p3_0,
  122641. 5,
  122642. 5
  122643. };
  122644. static static_codebook _16c0_s_p3_0 = {
  122645. 4, 625,
  122646. _vq_lengthlist__16c0_s_p3_0,
  122647. 1, -533725184, 1611661312, 3, 0,
  122648. _vq_quantlist__16c0_s_p3_0,
  122649. NULL,
  122650. &_vq_auxt__16c0_s_p3_0,
  122651. NULL,
  122652. 0
  122653. };
  122654. static long _vq_quantlist__16c0_s_p4_0[] = {
  122655. 4,
  122656. 3,
  122657. 5,
  122658. 2,
  122659. 6,
  122660. 1,
  122661. 7,
  122662. 0,
  122663. 8,
  122664. };
  122665. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122666. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122667. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122668. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122669. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122670. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0,
  122672. };
  122673. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122674. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122675. };
  122676. static long _vq_quantmap__16c0_s_p4_0[] = {
  122677. 7, 5, 3, 1, 0, 2, 4, 6,
  122678. 8,
  122679. };
  122680. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122681. _vq_quantthresh__16c0_s_p4_0,
  122682. _vq_quantmap__16c0_s_p4_0,
  122683. 9,
  122684. 9
  122685. };
  122686. static static_codebook _16c0_s_p4_0 = {
  122687. 2, 81,
  122688. _vq_lengthlist__16c0_s_p4_0,
  122689. 1, -531628032, 1611661312, 4, 0,
  122690. _vq_quantlist__16c0_s_p4_0,
  122691. NULL,
  122692. &_vq_auxt__16c0_s_p4_0,
  122693. NULL,
  122694. 0
  122695. };
  122696. static long _vq_quantlist__16c0_s_p5_0[] = {
  122697. 4,
  122698. 3,
  122699. 5,
  122700. 2,
  122701. 6,
  122702. 1,
  122703. 7,
  122704. 0,
  122705. 8,
  122706. };
  122707. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122708. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122709. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122710. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122711. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122712. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122713. 10,
  122714. };
  122715. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122716. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122717. };
  122718. static long _vq_quantmap__16c0_s_p5_0[] = {
  122719. 7, 5, 3, 1, 0, 2, 4, 6,
  122720. 8,
  122721. };
  122722. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122723. _vq_quantthresh__16c0_s_p5_0,
  122724. _vq_quantmap__16c0_s_p5_0,
  122725. 9,
  122726. 9
  122727. };
  122728. static static_codebook _16c0_s_p5_0 = {
  122729. 2, 81,
  122730. _vq_lengthlist__16c0_s_p5_0,
  122731. 1, -531628032, 1611661312, 4, 0,
  122732. _vq_quantlist__16c0_s_p5_0,
  122733. NULL,
  122734. &_vq_auxt__16c0_s_p5_0,
  122735. NULL,
  122736. 0
  122737. };
  122738. static long _vq_quantlist__16c0_s_p6_0[] = {
  122739. 8,
  122740. 7,
  122741. 9,
  122742. 6,
  122743. 10,
  122744. 5,
  122745. 11,
  122746. 4,
  122747. 12,
  122748. 3,
  122749. 13,
  122750. 2,
  122751. 14,
  122752. 1,
  122753. 15,
  122754. 0,
  122755. 16,
  122756. };
  122757. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122758. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122759. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122760. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122761. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122762. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122763. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122764. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122765. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122766. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122767. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122768. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122769. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122770. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122771. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122772. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122773. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122774. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122776. 14,
  122777. };
  122778. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122779. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122780. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122781. };
  122782. static long _vq_quantmap__16c0_s_p6_0[] = {
  122783. 15, 13, 11, 9, 7, 5, 3, 1,
  122784. 0, 2, 4, 6, 8, 10, 12, 14,
  122785. 16,
  122786. };
  122787. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122788. _vq_quantthresh__16c0_s_p6_0,
  122789. _vq_quantmap__16c0_s_p6_0,
  122790. 17,
  122791. 17
  122792. };
  122793. static static_codebook _16c0_s_p6_0 = {
  122794. 2, 289,
  122795. _vq_lengthlist__16c0_s_p6_0,
  122796. 1, -529530880, 1611661312, 5, 0,
  122797. _vq_quantlist__16c0_s_p6_0,
  122798. NULL,
  122799. &_vq_auxt__16c0_s_p6_0,
  122800. NULL,
  122801. 0
  122802. };
  122803. static long _vq_quantlist__16c0_s_p7_0[] = {
  122804. 1,
  122805. 0,
  122806. 2,
  122807. };
  122808. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122809. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122810. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122811. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122812. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122813. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122814. 13,
  122815. };
  122816. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122817. -5.5, 5.5,
  122818. };
  122819. static long _vq_quantmap__16c0_s_p7_0[] = {
  122820. 1, 0, 2,
  122821. };
  122822. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122823. _vq_quantthresh__16c0_s_p7_0,
  122824. _vq_quantmap__16c0_s_p7_0,
  122825. 3,
  122826. 3
  122827. };
  122828. static static_codebook _16c0_s_p7_0 = {
  122829. 4, 81,
  122830. _vq_lengthlist__16c0_s_p7_0,
  122831. 1, -529137664, 1618345984, 2, 0,
  122832. _vq_quantlist__16c0_s_p7_0,
  122833. NULL,
  122834. &_vq_auxt__16c0_s_p7_0,
  122835. NULL,
  122836. 0
  122837. };
  122838. static long _vq_quantlist__16c0_s_p7_1[] = {
  122839. 5,
  122840. 4,
  122841. 6,
  122842. 3,
  122843. 7,
  122844. 2,
  122845. 8,
  122846. 1,
  122847. 9,
  122848. 0,
  122849. 10,
  122850. };
  122851. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122852. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122853. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122854. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122855. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122856. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122857. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122858. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122859. 11,11,11, 9, 9, 9, 9,10,10,
  122860. };
  122861. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122862. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122863. 3.5, 4.5,
  122864. };
  122865. static long _vq_quantmap__16c0_s_p7_1[] = {
  122866. 9, 7, 5, 3, 1, 0, 2, 4,
  122867. 6, 8, 10,
  122868. };
  122869. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122870. _vq_quantthresh__16c0_s_p7_1,
  122871. _vq_quantmap__16c0_s_p7_1,
  122872. 11,
  122873. 11
  122874. };
  122875. static static_codebook _16c0_s_p7_1 = {
  122876. 2, 121,
  122877. _vq_lengthlist__16c0_s_p7_1,
  122878. 1, -531365888, 1611661312, 4, 0,
  122879. _vq_quantlist__16c0_s_p7_1,
  122880. NULL,
  122881. &_vq_auxt__16c0_s_p7_1,
  122882. NULL,
  122883. 0
  122884. };
  122885. static long _vq_quantlist__16c0_s_p8_0[] = {
  122886. 6,
  122887. 5,
  122888. 7,
  122889. 4,
  122890. 8,
  122891. 3,
  122892. 9,
  122893. 2,
  122894. 10,
  122895. 1,
  122896. 11,
  122897. 0,
  122898. 12,
  122899. };
  122900. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122901. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122902. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122903. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122904. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122905. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122906. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122907. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122908. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122909. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122910. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122911. 0,12,13,13,12,13,14,14,14,
  122912. };
  122913. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122914. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122915. 12.5, 17.5, 22.5, 27.5,
  122916. };
  122917. static long _vq_quantmap__16c0_s_p8_0[] = {
  122918. 11, 9, 7, 5, 3, 1, 0, 2,
  122919. 4, 6, 8, 10, 12,
  122920. };
  122921. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122922. _vq_quantthresh__16c0_s_p8_0,
  122923. _vq_quantmap__16c0_s_p8_0,
  122924. 13,
  122925. 13
  122926. };
  122927. static static_codebook _16c0_s_p8_0 = {
  122928. 2, 169,
  122929. _vq_lengthlist__16c0_s_p8_0,
  122930. 1, -526516224, 1616117760, 4, 0,
  122931. _vq_quantlist__16c0_s_p8_0,
  122932. NULL,
  122933. &_vq_auxt__16c0_s_p8_0,
  122934. NULL,
  122935. 0
  122936. };
  122937. static long _vq_quantlist__16c0_s_p8_1[] = {
  122938. 2,
  122939. 1,
  122940. 3,
  122941. 0,
  122942. 4,
  122943. };
  122944. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122945. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122946. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122947. };
  122948. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122949. -1.5, -0.5, 0.5, 1.5,
  122950. };
  122951. static long _vq_quantmap__16c0_s_p8_1[] = {
  122952. 3, 1, 0, 2, 4,
  122953. };
  122954. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122955. _vq_quantthresh__16c0_s_p8_1,
  122956. _vq_quantmap__16c0_s_p8_1,
  122957. 5,
  122958. 5
  122959. };
  122960. static static_codebook _16c0_s_p8_1 = {
  122961. 2, 25,
  122962. _vq_lengthlist__16c0_s_p8_1,
  122963. 1, -533725184, 1611661312, 3, 0,
  122964. _vq_quantlist__16c0_s_p8_1,
  122965. NULL,
  122966. &_vq_auxt__16c0_s_p8_1,
  122967. NULL,
  122968. 0
  122969. };
  122970. static long _vq_quantlist__16c0_s_p9_0[] = {
  122971. 1,
  122972. 0,
  122973. 2,
  122974. };
  122975. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122976. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122977. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122978. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122979. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122980. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122981. 7,
  122982. };
  122983. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122984. -157.5, 157.5,
  122985. };
  122986. static long _vq_quantmap__16c0_s_p9_0[] = {
  122987. 1, 0, 2,
  122988. };
  122989. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122990. _vq_quantthresh__16c0_s_p9_0,
  122991. _vq_quantmap__16c0_s_p9_0,
  122992. 3,
  122993. 3
  122994. };
  122995. static static_codebook _16c0_s_p9_0 = {
  122996. 4, 81,
  122997. _vq_lengthlist__16c0_s_p9_0,
  122998. 1, -518803456, 1628680192, 2, 0,
  122999. _vq_quantlist__16c0_s_p9_0,
  123000. NULL,
  123001. &_vq_auxt__16c0_s_p9_0,
  123002. NULL,
  123003. 0
  123004. };
  123005. static long _vq_quantlist__16c0_s_p9_1[] = {
  123006. 7,
  123007. 6,
  123008. 8,
  123009. 5,
  123010. 9,
  123011. 4,
  123012. 10,
  123013. 3,
  123014. 11,
  123015. 2,
  123016. 12,
  123017. 1,
  123018. 13,
  123019. 0,
  123020. 14,
  123021. };
  123022. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123023. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123024. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123025. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123026. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123027. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123028. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123030. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123032. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123033. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123034. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123035. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123037. 10,
  123038. };
  123039. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123040. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123041. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123042. };
  123043. static long _vq_quantmap__16c0_s_p9_1[] = {
  123044. 13, 11, 9, 7, 5, 3, 1, 0,
  123045. 2, 4, 6, 8, 10, 12, 14,
  123046. };
  123047. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123048. _vq_quantthresh__16c0_s_p9_1,
  123049. _vq_quantmap__16c0_s_p9_1,
  123050. 15,
  123051. 15
  123052. };
  123053. static static_codebook _16c0_s_p9_1 = {
  123054. 2, 225,
  123055. _vq_lengthlist__16c0_s_p9_1,
  123056. 1, -520986624, 1620377600, 4, 0,
  123057. _vq_quantlist__16c0_s_p9_1,
  123058. NULL,
  123059. &_vq_auxt__16c0_s_p9_1,
  123060. NULL,
  123061. 0
  123062. };
  123063. static long _vq_quantlist__16c0_s_p9_2[] = {
  123064. 10,
  123065. 9,
  123066. 11,
  123067. 8,
  123068. 12,
  123069. 7,
  123070. 13,
  123071. 6,
  123072. 14,
  123073. 5,
  123074. 15,
  123075. 4,
  123076. 16,
  123077. 3,
  123078. 17,
  123079. 2,
  123080. 18,
  123081. 1,
  123082. 19,
  123083. 0,
  123084. 20,
  123085. };
  123086. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123087. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123088. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123089. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123090. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123091. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123092. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123093. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123094. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123095. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123096. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123097. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123098. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123099. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123100. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123101. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123102. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123103. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123104. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123105. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123106. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123107. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123108. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123109. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123110. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123111. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123112. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123113. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123114. 10,11,10,10,11, 9,10,10,10,
  123115. };
  123116. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123117. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123118. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123119. 6.5, 7.5, 8.5, 9.5,
  123120. };
  123121. static long _vq_quantmap__16c0_s_p9_2[] = {
  123122. 19, 17, 15, 13, 11, 9, 7, 5,
  123123. 3, 1, 0, 2, 4, 6, 8, 10,
  123124. 12, 14, 16, 18, 20,
  123125. };
  123126. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123127. _vq_quantthresh__16c0_s_p9_2,
  123128. _vq_quantmap__16c0_s_p9_2,
  123129. 21,
  123130. 21
  123131. };
  123132. static static_codebook _16c0_s_p9_2 = {
  123133. 2, 441,
  123134. _vq_lengthlist__16c0_s_p9_2,
  123135. 1, -529268736, 1611661312, 5, 0,
  123136. _vq_quantlist__16c0_s_p9_2,
  123137. NULL,
  123138. &_vq_auxt__16c0_s_p9_2,
  123139. NULL,
  123140. 0
  123141. };
  123142. static long _huff_lengthlist__16c0_s_single[] = {
  123143. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123144. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123145. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123146. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123147. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123148. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123149. 16,16,18,18,
  123150. };
  123151. static static_codebook _huff_book__16c0_s_single = {
  123152. 2, 100,
  123153. _huff_lengthlist__16c0_s_single,
  123154. 0, 0, 0, 0, 0,
  123155. NULL,
  123156. NULL,
  123157. NULL,
  123158. NULL,
  123159. 0
  123160. };
  123161. static long _huff_lengthlist__16c1_s_long[] = {
  123162. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123163. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123164. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123165. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123166. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123167. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123168. 12,11,11,13,
  123169. };
  123170. static static_codebook _huff_book__16c1_s_long = {
  123171. 2, 100,
  123172. _huff_lengthlist__16c1_s_long,
  123173. 0, 0, 0, 0, 0,
  123174. NULL,
  123175. NULL,
  123176. NULL,
  123177. NULL,
  123178. 0
  123179. };
  123180. static long _vq_quantlist__16c1_s_p1_0[] = {
  123181. 1,
  123182. 0,
  123183. 2,
  123184. };
  123185. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123186. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123187. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123192. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123197. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123232. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123237. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123242. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123278. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123283. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123288. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0,
  123597. };
  123598. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123599. -0.5, 0.5,
  123600. };
  123601. static long _vq_quantmap__16c1_s_p1_0[] = {
  123602. 1, 0, 2,
  123603. };
  123604. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123605. _vq_quantthresh__16c1_s_p1_0,
  123606. _vq_quantmap__16c1_s_p1_0,
  123607. 3,
  123608. 3
  123609. };
  123610. static static_codebook _16c1_s_p1_0 = {
  123611. 8, 6561,
  123612. _vq_lengthlist__16c1_s_p1_0,
  123613. 1, -535822336, 1611661312, 2, 0,
  123614. _vq_quantlist__16c1_s_p1_0,
  123615. NULL,
  123616. &_vq_auxt__16c1_s_p1_0,
  123617. NULL,
  123618. 0
  123619. };
  123620. static long _vq_quantlist__16c1_s_p2_0[] = {
  123621. 2,
  123622. 1,
  123623. 3,
  123624. 0,
  123625. 4,
  123626. };
  123627. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 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__16c1_s_p2_0[] = {
  123670. -1.5, -0.5, 0.5, 1.5,
  123671. };
  123672. static long _vq_quantmap__16c1_s_p2_0[] = {
  123673. 3, 1, 0, 2, 4,
  123674. };
  123675. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123676. _vq_quantthresh__16c1_s_p2_0,
  123677. _vq_quantmap__16c1_s_p2_0,
  123678. 5,
  123679. 5
  123680. };
  123681. static static_codebook _16c1_s_p2_0 = {
  123682. 4, 625,
  123683. _vq_lengthlist__16c1_s_p2_0,
  123684. 1, -533725184, 1611661312, 3, 0,
  123685. _vq_quantlist__16c1_s_p2_0,
  123686. NULL,
  123687. &_vq_auxt__16c1_s_p2_0,
  123688. NULL,
  123689. 0
  123690. };
  123691. static long _vq_quantlist__16c1_s_p3_0[] = {
  123692. 2,
  123693. 1,
  123694. 3,
  123695. 0,
  123696. 4,
  123697. };
  123698. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123699. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 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, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0,
  123739. };
  123740. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123741. -1.5, -0.5, 0.5, 1.5,
  123742. };
  123743. static long _vq_quantmap__16c1_s_p3_0[] = {
  123744. 3, 1, 0, 2, 4,
  123745. };
  123746. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123747. _vq_quantthresh__16c1_s_p3_0,
  123748. _vq_quantmap__16c1_s_p3_0,
  123749. 5,
  123750. 5
  123751. };
  123752. static static_codebook _16c1_s_p3_0 = {
  123753. 4, 625,
  123754. _vq_lengthlist__16c1_s_p3_0,
  123755. 1, -533725184, 1611661312, 3, 0,
  123756. _vq_quantlist__16c1_s_p3_0,
  123757. NULL,
  123758. &_vq_auxt__16c1_s_p3_0,
  123759. NULL,
  123760. 0
  123761. };
  123762. static long _vq_quantlist__16c1_s_p4_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__16c1_s_p4_0[] = {
  123774. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123775. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123776. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123777. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123778. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0,
  123780. };
  123781. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123782. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123783. };
  123784. static long _vq_quantmap__16c1_s_p4_0[] = {
  123785. 7, 5, 3, 1, 0, 2, 4, 6,
  123786. 8,
  123787. };
  123788. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123789. _vq_quantthresh__16c1_s_p4_0,
  123790. _vq_quantmap__16c1_s_p4_0,
  123791. 9,
  123792. 9
  123793. };
  123794. static static_codebook _16c1_s_p4_0 = {
  123795. 2, 81,
  123796. _vq_lengthlist__16c1_s_p4_0,
  123797. 1, -531628032, 1611661312, 4, 0,
  123798. _vq_quantlist__16c1_s_p4_0,
  123799. NULL,
  123800. &_vq_auxt__16c1_s_p4_0,
  123801. NULL,
  123802. 0
  123803. };
  123804. static long _vq_quantlist__16c1_s_p5_0[] = {
  123805. 4,
  123806. 3,
  123807. 5,
  123808. 2,
  123809. 6,
  123810. 1,
  123811. 7,
  123812. 0,
  123813. 8,
  123814. };
  123815. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123816. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123817. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123818. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123819. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123820. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123821. 10,
  123822. };
  123823. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123824. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123825. };
  123826. static long _vq_quantmap__16c1_s_p5_0[] = {
  123827. 7, 5, 3, 1, 0, 2, 4, 6,
  123828. 8,
  123829. };
  123830. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123831. _vq_quantthresh__16c1_s_p5_0,
  123832. _vq_quantmap__16c1_s_p5_0,
  123833. 9,
  123834. 9
  123835. };
  123836. static static_codebook _16c1_s_p5_0 = {
  123837. 2, 81,
  123838. _vq_lengthlist__16c1_s_p5_0,
  123839. 1, -531628032, 1611661312, 4, 0,
  123840. _vq_quantlist__16c1_s_p5_0,
  123841. NULL,
  123842. &_vq_auxt__16c1_s_p5_0,
  123843. NULL,
  123844. 0
  123845. };
  123846. static long _vq_quantlist__16c1_s_p6_0[] = {
  123847. 8,
  123848. 7,
  123849. 9,
  123850. 6,
  123851. 10,
  123852. 5,
  123853. 11,
  123854. 4,
  123855. 12,
  123856. 3,
  123857. 13,
  123858. 2,
  123859. 14,
  123860. 1,
  123861. 15,
  123862. 0,
  123863. 16,
  123864. };
  123865. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123866. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123867. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123868. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123869. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123870. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123871. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123872. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123873. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123874. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123875. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123876. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123877. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123878. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123879. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123880. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123881. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123882. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123884. 14,
  123885. };
  123886. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123887. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123888. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123889. };
  123890. static long _vq_quantmap__16c1_s_p6_0[] = {
  123891. 15, 13, 11, 9, 7, 5, 3, 1,
  123892. 0, 2, 4, 6, 8, 10, 12, 14,
  123893. 16,
  123894. };
  123895. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123896. _vq_quantthresh__16c1_s_p6_0,
  123897. _vq_quantmap__16c1_s_p6_0,
  123898. 17,
  123899. 17
  123900. };
  123901. static static_codebook _16c1_s_p6_0 = {
  123902. 2, 289,
  123903. _vq_lengthlist__16c1_s_p6_0,
  123904. 1, -529530880, 1611661312, 5, 0,
  123905. _vq_quantlist__16c1_s_p6_0,
  123906. NULL,
  123907. &_vq_auxt__16c1_s_p6_0,
  123908. NULL,
  123909. 0
  123910. };
  123911. static long _vq_quantlist__16c1_s_p7_0[] = {
  123912. 1,
  123913. 0,
  123914. 2,
  123915. };
  123916. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123917. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123918. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123919. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123920. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123921. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123922. 11,
  123923. };
  123924. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123925. -5.5, 5.5,
  123926. };
  123927. static long _vq_quantmap__16c1_s_p7_0[] = {
  123928. 1, 0, 2,
  123929. };
  123930. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123931. _vq_quantthresh__16c1_s_p7_0,
  123932. _vq_quantmap__16c1_s_p7_0,
  123933. 3,
  123934. 3
  123935. };
  123936. static static_codebook _16c1_s_p7_0 = {
  123937. 4, 81,
  123938. _vq_lengthlist__16c1_s_p7_0,
  123939. 1, -529137664, 1618345984, 2, 0,
  123940. _vq_quantlist__16c1_s_p7_0,
  123941. NULL,
  123942. &_vq_auxt__16c1_s_p7_0,
  123943. NULL,
  123944. 0
  123945. };
  123946. static long _vq_quantlist__16c1_s_p7_1[] = {
  123947. 5,
  123948. 4,
  123949. 6,
  123950. 3,
  123951. 7,
  123952. 2,
  123953. 8,
  123954. 1,
  123955. 9,
  123956. 0,
  123957. 10,
  123958. };
  123959. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123960. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123961. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123962. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123963. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123964. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123965. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123966. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123967. 10,10,10, 8, 8, 8, 8, 9, 9,
  123968. };
  123969. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123970. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123971. 3.5, 4.5,
  123972. };
  123973. static long _vq_quantmap__16c1_s_p7_1[] = {
  123974. 9, 7, 5, 3, 1, 0, 2, 4,
  123975. 6, 8, 10,
  123976. };
  123977. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123978. _vq_quantthresh__16c1_s_p7_1,
  123979. _vq_quantmap__16c1_s_p7_1,
  123980. 11,
  123981. 11
  123982. };
  123983. static static_codebook _16c1_s_p7_1 = {
  123984. 2, 121,
  123985. _vq_lengthlist__16c1_s_p7_1,
  123986. 1, -531365888, 1611661312, 4, 0,
  123987. _vq_quantlist__16c1_s_p7_1,
  123988. NULL,
  123989. &_vq_auxt__16c1_s_p7_1,
  123990. NULL,
  123991. 0
  123992. };
  123993. static long _vq_quantlist__16c1_s_p8_0[] = {
  123994. 6,
  123995. 5,
  123996. 7,
  123997. 4,
  123998. 8,
  123999. 3,
  124000. 9,
  124001. 2,
  124002. 10,
  124003. 1,
  124004. 11,
  124005. 0,
  124006. 12,
  124007. };
  124008. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124009. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124010. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124011. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124012. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124013. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124014. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124015. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124016. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124017. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124018. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124019. 0,12,12,12,12,13,13,14,15,
  124020. };
  124021. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124022. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124023. 12.5, 17.5, 22.5, 27.5,
  124024. };
  124025. static long _vq_quantmap__16c1_s_p8_0[] = {
  124026. 11, 9, 7, 5, 3, 1, 0, 2,
  124027. 4, 6, 8, 10, 12,
  124028. };
  124029. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124030. _vq_quantthresh__16c1_s_p8_0,
  124031. _vq_quantmap__16c1_s_p8_0,
  124032. 13,
  124033. 13
  124034. };
  124035. static static_codebook _16c1_s_p8_0 = {
  124036. 2, 169,
  124037. _vq_lengthlist__16c1_s_p8_0,
  124038. 1, -526516224, 1616117760, 4, 0,
  124039. _vq_quantlist__16c1_s_p8_0,
  124040. NULL,
  124041. &_vq_auxt__16c1_s_p8_0,
  124042. NULL,
  124043. 0
  124044. };
  124045. static long _vq_quantlist__16c1_s_p8_1[] = {
  124046. 2,
  124047. 1,
  124048. 3,
  124049. 0,
  124050. 4,
  124051. };
  124052. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124053. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124054. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124055. };
  124056. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124057. -1.5, -0.5, 0.5, 1.5,
  124058. };
  124059. static long _vq_quantmap__16c1_s_p8_1[] = {
  124060. 3, 1, 0, 2, 4,
  124061. };
  124062. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124063. _vq_quantthresh__16c1_s_p8_1,
  124064. _vq_quantmap__16c1_s_p8_1,
  124065. 5,
  124066. 5
  124067. };
  124068. static static_codebook _16c1_s_p8_1 = {
  124069. 2, 25,
  124070. _vq_lengthlist__16c1_s_p8_1,
  124071. 1, -533725184, 1611661312, 3, 0,
  124072. _vq_quantlist__16c1_s_p8_1,
  124073. NULL,
  124074. &_vq_auxt__16c1_s_p8_1,
  124075. NULL,
  124076. 0
  124077. };
  124078. static long _vq_quantlist__16c1_s_p9_0[] = {
  124079. 6,
  124080. 5,
  124081. 7,
  124082. 4,
  124083. 8,
  124084. 3,
  124085. 9,
  124086. 2,
  124087. 10,
  124088. 1,
  124089. 11,
  124090. 0,
  124091. 12,
  124092. };
  124093. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124094. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124095. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124096. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124097. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124098. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124099. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124100. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124101. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124102. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124103. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124104. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124105. };
  124106. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124107. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124108. 787.5, 1102.5, 1417.5, 1732.5,
  124109. };
  124110. static long _vq_quantmap__16c1_s_p9_0[] = {
  124111. 11, 9, 7, 5, 3, 1, 0, 2,
  124112. 4, 6, 8, 10, 12,
  124113. };
  124114. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124115. _vq_quantthresh__16c1_s_p9_0,
  124116. _vq_quantmap__16c1_s_p9_0,
  124117. 13,
  124118. 13
  124119. };
  124120. static static_codebook _16c1_s_p9_0 = {
  124121. 2, 169,
  124122. _vq_lengthlist__16c1_s_p9_0,
  124123. 1, -513964032, 1628680192, 4, 0,
  124124. _vq_quantlist__16c1_s_p9_0,
  124125. NULL,
  124126. &_vq_auxt__16c1_s_p9_0,
  124127. NULL,
  124128. 0
  124129. };
  124130. static long _vq_quantlist__16c1_s_p9_1[] = {
  124131. 7,
  124132. 6,
  124133. 8,
  124134. 5,
  124135. 9,
  124136. 4,
  124137. 10,
  124138. 3,
  124139. 11,
  124140. 2,
  124141. 12,
  124142. 1,
  124143. 13,
  124144. 0,
  124145. 14,
  124146. };
  124147. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124148. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124149. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124150. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124151. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124152. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124153. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124154. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124155. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124156. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124157. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124158. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124159. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124160. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124161. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124162. 13,
  124163. };
  124164. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124165. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124166. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124167. };
  124168. static long _vq_quantmap__16c1_s_p9_1[] = {
  124169. 13, 11, 9, 7, 5, 3, 1, 0,
  124170. 2, 4, 6, 8, 10, 12, 14,
  124171. };
  124172. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124173. _vq_quantthresh__16c1_s_p9_1,
  124174. _vq_quantmap__16c1_s_p9_1,
  124175. 15,
  124176. 15
  124177. };
  124178. static static_codebook _16c1_s_p9_1 = {
  124179. 2, 225,
  124180. _vq_lengthlist__16c1_s_p9_1,
  124181. 1, -520986624, 1620377600, 4, 0,
  124182. _vq_quantlist__16c1_s_p9_1,
  124183. NULL,
  124184. &_vq_auxt__16c1_s_p9_1,
  124185. NULL,
  124186. 0
  124187. };
  124188. static long _vq_quantlist__16c1_s_p9_2[] = {
  124189. 10,
  124190. 9,
  124191. 11,
  124192. 8,
  124193. 12,
  124194. 7,
  124195. 13,
  124196. 6,
  124197. 14,
  124198. 5,
  124199. 15,
  124200. 4,
  124201. 16,
  124202. 3,
  124203. 17,
  124204. 2,
  124205. 18,
  124206. 1,
  124207. 19,
  124208. 0,
  124209. 20,
  124210. };
  124211. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124212. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124213. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124214. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124215. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124216. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124217. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124218. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124219. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124220. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124221. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124222. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124223. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124224. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124225. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124226. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124227. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124228. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124229. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124230. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124231. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124232. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124233. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124234. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124235. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124236. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124237. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124238. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124239. 11,11,11,11,12,11,11,12,11,
  124240. };
  124241. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124242. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124243. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124244. 6.5, 7.5, 8.5, 9.5,
  124245. };
  124246. static long _vq_quantmap__16c1_s_p9_2[] = {
  124247. 19, 17, 15, 13, 11, 9, 7, 5,
  124248. 3, 1, 0, 2, 4, 6, 8, 10,
  124249. 12, 14, 16, 18, 20,
  124250. };
  124251. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124252. _vq_quantthresh__16c1_s_p9_2,
  124253. _vq_quantmap__16c1_s_p9_2,
  124254. 21,
  124255. 21
  124256. };
  124257. static static_codebook _16c1_s_p9_2 = {
  124258. 2, 441,
  124259. _vq_lengthlist__16c1_s_p9_2,
  124260. 1, -529268736, 1611661312, 5, 0,
  124261. _vq_quantlist__16c1_s_p9_2,
  124262. NULL,
  124263. &_vq_auxt__16c1_s_p9_2,
  124264. NULL,
  124265. 0
  124266. };
  124267. static long _huff_lengthlist__16c1_s_short[] = {
  124268. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124269. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124270. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124271. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124272. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124273. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124274. 9, 9,10,13,
  124275. };
  124276. static static_codebook _huff_book__16c1_s_short = {
  124277. 2, 100,
  124278. _huff_lengthlist__16c1_s_short,
  124279. 0, 0, 0, 0, 0,
  124280. NULL,
  124281. NULL,
  124282. NULL,
  124283. NULL,
  124284. 0
  124285. };
  124286. static long _huff_lengthlist__16c2_s_long[] = {
  124287. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124288. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124289. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124290. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124291. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124292. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124293. 14,14,16,18,
  124294. };
  124295. static static_codebook _huff_book__16c2_s_long = {
  124296. 2, 100,
  124297. _huff_lengthlist__16c2_s_long,
  124298. 0, 0, 0, 0, 0,
  124299. NULL,
  124300. NULL,
  124301. NULL,
  124302. NULL,
  124303. 0
  124304. };
  124305. static long _vq_quantlist__16c2_s_p1_0[] = {
  124306. 1,
  124307. 0,
  124308. 2,
  124309. };
  124310. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124311. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124312. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0,
  124317. };
  124318. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124319. -0.5, 0.5,
  124320. };
  124321. static long _vq_quantmap__16c2_s_p1_0[] = {
  124322. 1, 0, 2,
  124323. };
  124324. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124325. _vq_quantthresh__16c2_s_p1_0,
  124326. _vq_quantmap__16c2_s_p1_0,
  124327. 3,
  124328. 3
  124329. };
  124330. static static_codebook _16c2_s_p1_0 = {
  124331. 4, 81,
  124332. _vq_lengthlist__16c2_s_p1_0,
  124333. 1, -535822336, 1611661312, 2, 0,
  124334. _vq_quantlist__16c2_s_p1_0,
  124335. NULL,
  124336. &_vq_auxt__16c2_s_p1_0,
  124337. NULL,
  124338. 0
  124339. };
  124340. static long _vq_quantlist__16c2_s_p2_0[] = {
  124341. 2,
  124342. 1,
  124343. 3,
  124344. 0,
  124345. 4,
  124346. };
  124347. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124348. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124349. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124350. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124351. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124352. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124353. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124354. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124355. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124361. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124362. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124363. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124369. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124370. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124371. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124377. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124378. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124379. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124384. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124385. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124386. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124387. 13,
  124388. };
  124389. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124390. -1.5, -0.5, 0.5, 1.5,
  124391. };
  124392. static long _vq_quantmap__16c2_s_p2_0[] = {
  124393. 3, 1, 0, 2, 4,
  124394. };
  124395. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124396. _vq_quantthresh__16c2_s_p2_0,
  124397. _vq_quantmap__16c2_s_p2_0,
  124398. 5,
  124399. 5
  124400. };
  124401. static static_codebook _16c2_s_p2_0 = {
  124402. 4, 625,
  124403. _vq_lengthlist__16c2_s_p2_0,
  124404. 1, -533725184, 1611661312, 3, 0,
  124405. _vq_quantlist__16c2_s_p2_0,
  124406. NULL,
  124407. &_vq_auxt__16c2_s_p2_0,
  124408. NULL,
  124409. 0
  124410. };
  124411. static long _vq_quantlist__16c2_s_p3_0[] = {
  124412. 4,
  124413. 3,
  124414. 5,
  124415. 2,
  124416. 6,
  124417. 1,
  124418. 7,
  124419. 0,
  124420. 8,
  124421. };
  124422. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124423. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124424. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124425. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124426. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0,
  124429. };
  124430. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124431. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124432. };
  124433. static long _vq_quantmap__16c2_s_p3_0[] = {
  124434. 7, 5, 3, 1, 0, 2, 4, 6,
  124435. 8,
  124436. };
  124437. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124438. _vq_quantthresh__16c2_s_p3_0,
  124439. _vq_quantmap__16c2_s_p3_0,
  124440. 9,
  124441. 9
  124442. };
  124443. static static_codebook _16c2_s_p3_0 = {
  124444. 2, 81,
  124445. _vq_lengthlist__16c2_s_p3_0,
  124446. 1, -531628032, 1611661312, 4, 0,
  124447. _vq_quantlist__16c2_s_p3_0,
  124448. NULL,
  124449. &_vq_auxt__16c2_s_p3_0,
  124450. NULL,
  124451. 0
  124452. };
  124453. static long _vq_quantlist__16c2_s_p4_0[] = {
  124454. 8,
  124455. 7,
  124456. 9,
  124457. 6,
  124458. 10,
  124459. 5,
  124460. 11,
  124461. 4,
  124462. 12,
  124463. 3,
  124464. 13,
  124465. 2,
  124466. 14,
  124467. 1,
  124468. 15,
  124469. 0,
  124470. 16,
  124471. };
  124472. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124473. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124474. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124475. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124476. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124477. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124478. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124479. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124480. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124481. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124482. 9,10,10,11,11,12,12,12,12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0, 0, 0, 0, 0, 0, 0, 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,
  124492. };
  124493. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124494. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124495. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124496. };
  124497. static long _vq_quantmap__16c2_s_p4_0[] = {
  124498. 15, 13, 11, 9, 7, 5, 3, 1,
  124499. 0, 2, 4, 6, 8, 10, 12, 14,
  124500. 16,
  124501. };
  124502. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124503. _vq_quantthresh__16c2_s_p4_0,
  124504. _vq_quantmap__16c2_s_p4_0,
  124505. 17,
  124506. 17
  124507. };
  124508. static static_codebook _16c2_s_p4_0 = {
  124509. 2, 289,
  124510. _vq_lengthlist__16c2_s_p4_0,
  124511. 1, -529530880, 1611661312, 5, 0,
  124512. _vq_quantlist__16c2_s_p4_0,
  124513. NULL,
  124514. &_vq_auxt__16c2_s_p4_0,
  124515. NULL,
  124516. 0
  124517. };
  124518. static long _vq_quantlist__16c2_s_p5_0[] = {
  124519. 1,
  124520. 0,
  124521. 2,
  124522. };
  124523. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124524. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124525. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124526. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124527. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124528. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124529. 12,
  124530. };
  124531. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124532. -5.5, 5.5,
  124533. };
  124534. static long _vq_quantmap__16c2_s_p5_0[] = {
  124535. 1, 0, 2,
  124536. };
  124537. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124538. _vq_quantthresh__16c2_s_p5_0,
  124539. _vq_quantmap__16c2_s_p5_0,
  124540. 3,
  124541. 3
  124542. };
  124543. static static_codebook _16c2_s_p5_0 = {
  124544. 4, 81,
  124545. _vq_lengthlist__16c2_s_p5_0,
  124546. 1, -529137664, 1618345984, 2, 0,
  124547. _vq_quantlist__16c2_s_p5_0,
  124548. NULL,
  124549. &_vq_auxt__16c2_s_p5_0,
  124550. NULL,
  124551. 0
  124552. };
  124553. static long _vq_quantlist__16c2_s_p5_1[] = {
  124554. 5,
  124555. 4,
  124556. 6,
  124557. 3,
  124558. 7,
  124559. 2,
  124560. 8,
  124561. 1,
  124562. 9,
  124563. 0,
  124564. 10,
  124565. };
  124566. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124567. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124568. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124569. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124570. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124571. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124572. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124573. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124574. 11,11,11, 7, 7, 8, 8, 8, 8,
  124575. };
  124576. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124577. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124578. 3.5, 4.5,
  124579. };
  124580. static long _vq_quantmap__16c2_s_p5_1[] = {
  124581. 9, 7, 5, 3, 1, 0, 2, 4,
  124582. 6, 8, 10,
  124583. };
  124584. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124585. _vq_quantthresh__16c2_s_p5_1,
  124586. _vq_quantmap__16c2_s_p5_1,
  124587. 11,
  124588. 11
  124589. };
  124590. static static_codebook _16c2_s_p5_1 = {
  124591. 2, 121,
  124592. _vq_lengthlist__16c2_s_p5_1,
  124593. 1, -531365888, 1611661312, 4, 0,
  124594. _vq_quantlist__16c2_s_p5_1,
  124595. NULL,
  124596. &_vq_auxt__16c2_s_p5_1,
  124597. NULL,
  124598. 0
  124599. };
  124600. static long _vq_quantlist__16c2_s_p6_0[] = {
  124601. 6,
  124602. 5,
  124603. 7,
  124604. 4,
  124605. 8,
  124606. 3,
  124607. 9,
  124608. 2,
  124609. 10,
  124610. 1,
  124611. 11,
  124612. 0,
  124613. 12,
  124614. };
  124615. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124616. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124617. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124618. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124619. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124620. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124621. 12, 8, 8,10,10,11,11,12,12,13,13, 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,
  124627. };
  124628. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124629. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124630. 12.5, 17.5, 22.5, 27.5,
  124631. };
  124632. static long _vq_quantmap__16c2_s_p6_0[] = {
  124633. 11, 9, 7, 5, 3, 1, 0, 2,
  124634. 4, 6, 8, 10, 12,
  124635. };
  124636. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124637. _vq_quantthresh__16c2_s_p6_0,
  124638. _vq_quantmap__16c2_s_p6_0,
  124639. 13,
  124640. 13
  124641. };
  124642. static static_codebook _16c2_s_p6_0 = {
  124643. 2, 169,
  124644. _vq_lengthlist__16c2_s_p6_0,
  124645. 1, -526516224, 1616117760, 4, 0,
  124646. _vq_quantlist__16c2_s_p6_0,
  124647. NULL,
  124648. &_vq_auxt__16c2_s_p6_0,
  124649. NULL,
  124650. 0
  124651. };
  124652. static long _vq_quantlist__16c2_s_p6_1[] = {
  124653. 2,
  124654. 1,
  124655. 3,
  124656. 0,
  124657. 4,
  124658. };
  124659. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124660. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124661. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124662. };
  124663. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124664. -1.5, -0.5, 0.5, 1.5,
  124665. };
  124666. static long _vq_quantmap__16c2_s_p6_1[] = {
  124667. 3, 1, 0, 2, 4,
  124668. };
  124669. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124670. _vq_quantthresh__16c2_s_p6_1,
  124671. _vq_quantmap__16c2_s_p6_1,
  124672. 5,
  124673. 5
  124674. };
  124675. static static_codebook _16c2_s_p6_1 = {
  124676. 2, 25,
  124677. _vq_lengthlist__16c2_s_p6_1,
  124678. 1, -533725184, 1611661312, 3, 0,
  124679. _vq_quantlist__16c2_s_p6_1,
  124680. NULL,
  124681. &_vq_auxt__16c2_s_p6_1,
  124682. NULL,
  124683. 0
  124684. };
  124685. static long _vq_quantlist__16c2_s_p7_0[] = {
  124686. 6,
  124687. 5,
  124688. 7,
  124689. 4,
  124690. 8,
  124691. 3,
  124692. 9,
  124693. 2,
  124694. 10,
  124695. 1,
  124696. 11,
  124697. 0,
  124698. 12,
  124699. };
  124700. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124701. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124702. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124703. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124704. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124705. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124706. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124707. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124708. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124709. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124710. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124711. 18,13,14,13,13,14,13,15,14,
  124712. };
  124713. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124714. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124715. 27.5, 38.5, 49.5, 60.5,
  124716. };
  124717. static long _vq_quantmap__16c2_s_p7_0[] = {
  124718. 11, 9, 7, 5, 3, 1, 0, 2,
  124719. 4, 6, 8, 10, 12,
  124720. };
  124721. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124722. _vq_quantthresh__16c2_s_p7_0,
  124723. _vq_quantmap__16c2_s_p7_0,
  124724. 13,
  124725. 13
  124726. };
  124727. static static_codebook _16c2_s_p7_0 = {
  124728. 2, 169,
  124729. _vq_lengthlist__16c2_s_p7_0,
  124730. 1, -523206656, 1618345984, 4, 0,
  124731. _vq_quantlist__16c2_s_p7_0,
  124732. NULL,
  124733. &_vq_auxt__16c2_s_p7_0,
  124734. NULL,
  124735. 0
  124736. };
  124737. static long _vq_quantlist__16c2_s_p7_1[] = {
  124738. 5,
  124739. 4,
  124740. 6,
  124741. 3,
  124742. 7,
  124743. 2,
  124744. 8,
  124745. 1,
  124746. 9,
  124747. 0,
  124748. 10,
  124749. };
  124750. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124751. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124752. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124753. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124754. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124755. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124756. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124757. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124758. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124759. };
  124760. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124761. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124762. 3.5, 4.5,
  124763. };
  124764. static long _vq_quantmap__16c2_s_p7_1[] = {
  124765. 9, 7, 5, 3, 1, 0, 2, 4,
  124766. 6, 8, 10,
  124767. };
  124768. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124769. _vq_quantthresh__16c2_s_p7_1,
  124770. _vq_quantmap__16c2_s_p7_1,
  124771. 11,
  124772. 11
  124773. };
  124774. static static_codebook _16c2_s_p7_1 = {
  124775. 2, 121,
  124776. _vq_lengthlist__16c2_s_p7_1,
  124777. 1, -531365888, 1611661312, 4, 0,
  124778. _vq_quantlist__16c2_s_p7_1,
  124779. NULL,
  124780. &_vq_auxt__16c2_s_p7_1,
  124781. NULL,
  124782. 0
  124783. };
  124784. static long _vq_quantlist__16c2_s_p8_0[] = {
  124785. 7,
  124786. 6,
  124787. 8,
  124788. 5,
  124789. 9,
  124790. 4,
  124791. 10,
  124792. 3,
  124793. 11,
  124794. 2,
  124795. 12,
  124796. 1,
  124797. 13,
  124798. 0,
  124799. 14,
  124800. };
  124801. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124802. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124803. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124804. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124805. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124806. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124807. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124808. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124809. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124810. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124811. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124812. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124813. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124814. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124815. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124816. 13,
  124817. };
  124818. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124819. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124820. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124821. };
  124822. static long _vq_quantmap__16c2_s_p8_0[] = {
  124823. 13, 11, 9, 7, 5, 3, 1, 0,
  124824. 2, 4, 6, 8, 10, 12, 14,
  124825. };
  124826. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124827. _vq_quantthresh__16c2_s_p8_0,
  124828. _vq_quantmap__16c2_s_p8_0,
  124829. 15,
  124830. 15
  124831. };
  124832. static static_codebook _16c2_s_p8_0 = {
  124833. 2, 225,
  124834. _vq_lengthlist__16c2_s_p8_0,
  124835. 1, -520986624, 1620377600, 4, 0,
  124836. _vq_quantlist__16c2_s_p8_0,
  124837. NULL,
  124838. &_vq_auxt__16c2_s_p8_0,
  124839. NULL,
  124840. 0
  124841. };
  124842. static long _vq_quantlist__16c2_s_p8_1[] = {
  124843. 10,
  124844. 9,
  124845. 11,
  124846. 8,
  124847. 12,
  124848. 7,
  124849. 13,
  124850. 6,
  124851. 14,
  124852. 5,
  124853. 15,
  124854. 4,
  124855. 16,
  124856. 3,
  124857. 17,
  124858. 2,
  124859. 18,
  124860. 1,
  124861. 19,
  124862. 0,
  124863. 20,
  124864. };
  124865. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124866. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124867. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124868. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124869. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124870. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124871. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124872. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124873. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124874. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124875. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124876. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124877. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124878. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124879. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124880. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124881. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124882. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124883. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124884. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124885. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124886. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124887. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124888. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124889. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124890. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124891. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124892. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124893. 10,11,10,10,10,10,10,10,10,
  124894. };
  124895. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124896. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124897. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124898. 6.5, 7.5, 8.5, 9.5,
  124899. };
  124900. static long _vq_quantmap__16c2_s_p8_1[] = {
  124901. 19, 17, 15, 13, 11, 9, 7, 5,
  124902. 3, 1, 0, 2, 4, 6, 8, 10,
  124903. 12, 14, 16, 18, 20,
  124904. };
  124905. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124906. _vq_quantthresh__16c2_s_p8_1,
  124907. _vq_quantmap__16c2_s_p8_1,
  124908. 21,
  124909. 21
  124910. };
  124911. static static_codebook _16c2_s_p8_1 = {
  124912. 2, 441,
  124913. _vq_lengthlist__16c2_s_p8_1,
  124914. 1, -529268736, 1611661312, 5, 0,
  124915. _vq_quantlist__16c2_s_p8_1,
  124916. NULL,
  124917. &_vq_auxt__16c2_s_p8_1,
  124918. NULL,
  124919. 0
  124920. };
  124921. static long _vq_quantlist__16c2_s_p9_0[] = {
  124922. 6,
  124923. 5,
  124924. 7,
  124925. 4,
  124926. 8,
  124927. 3,
  124928. 9,
  124929. 2,
  124930. 10,
  124931. 1,
  124932. 11,
  124933. 0,
  124934. 12,
  124935. };
  124936. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124937. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124939. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124940. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124941. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124942. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124943. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124944. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124945. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124946. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124947. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124948. };
  124949. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124950. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124951. 2327.5, 3258.5, 4189.5, 5120.5,
  124952. };
  124953. static long _vq_quantmap__16c2_s_p9_0[] = {
  124954. 11, 9, 7, 5, 3, 1, 0, 2,
  124955. 4, 6, 8, 10, 12,
  124956. };
  124957. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124958. _vq_quantthresh__16c2_s_p9_0,
  124959. _vq_quantmap__16c2_s_p9_0,
  124960. 13,
  124961. 13
  124962. };
  124963. static static_codebook _16c2_s_p9_0 = {
  124964. 2, 169,
  124965. _vq_lengthlist__16c2_s_p9_0,
  124966. 1, -510275072, 1631393792, 4, 0,
  124967. _vq_quantlist__16c2_s_p9_0,
  124968. NULL,
  124969. &_vq_auxt__16c2_s_p9_0,
  124970. NULL,
  124971. 0
  124972. };
  124973. static long _vq_quantlist__16c2_s_p9_1[] = {
  124974. 8,
  124975. 7,
  124976. 9,
  124977. 6,
  124978. 10,
  124979. 5,
  124980. 11,
  124981. 4,
  124982. 12,
  124983. 3,
  124984. 13,
  124985. 2,
  124986. 14,
  124987. 1,
  124988. 15,
  124989. 0,
  124990. 16,
  124991. };
  124992. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124993. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124994. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124995. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124996. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124997. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124998. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124999. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125000. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125001. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125003. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125004. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125005. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125007. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125008. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125009. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125011. 10,
  125012. };
  125013. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125014. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125015. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125016. };
  125017. static long _vq_quantmap__16c2_s_p9_1[] = {
  125018. 15, 13, 11, 9, 7, 5, 3, 1,
  125019. 0, 2, 4, 6, 8, 10, 12, 14,
  125020. 16,
  125021. };
  125022. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125023. _vq_quantthresh__16c2_s_p9_1,
  125024. _vq_quantmap__16c2_s_p9_1,
  125025. 17,
  125026. 17
  125027. };
  125028. static static_codebook _16c2_s_p9_1 = {
  125029. 2, 289,
  125030. _vq_lengthlist__16c2_s_p9_1,
  125031. 1, -518488064, 1622704128, 5, 0,
  125032. _vq_quantlist__16c2_s_p9_1,
  125033. NULL,
  125034. &_vq_auxt__16c2_s_p9_1,
  125035. NULL,
  125036. 0
  125037. };
  125038. static long _vq_quantlist__16c2_s_p9_2[] = {
  125039. 13,
  125040. 12,
  125041. 14,
  125042. 11,
  125043. 15,
  125044. 10,
  125045. 16,
  125046. 9,
  125047. 17,
  125048. 8,
  125049. 18,
  125050. 7,
  125051. 19,
  125052. 6,
  125053. 20,
  125054. 5,
  125055. 21,
  125056. 4,
  125057. 22,
  125058. 3,
  125059. 23,
  125060. 2,
  125061. 24,
  125062. 1,
  125063. 25,
  125064. 0,
  125065. 26,
  125066. };
  125067. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125068. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125069. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125070. };
  125071. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125072. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125073. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125074. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125075. 11.5, 12.5,
  125076. };
  125077. static long _vq_quantmap__16c2_s_p9_2[] = {
  125078. 25, 23, 21, 19, 17, 15, 13, 11,
  125079. 9, 7, 5, 3, 1, 0, 2, 4,
  125080. 6, 8, 10, 12, 14, 16, 18, 20,
  125081. 22, 24, 26,
  125082. };
  125083. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125084. _vq_quantthresh__16c2_s_p9_2,
  125085. _vq_quantmap__16c2_s_p9_2,
  125086. 27,
  125087. 27
  125088. };
  125089. static static_codebook _16c2_s_p9_2 = {
  125090. 1, 27,
  125091. _vq_lengthlist__16c2_s_p9_2,
  125092. 1, -528875520, 1611661312, 5, 0,
  125093. _vq_quantlist__16c2_s_p9_2,
  125094. NULL,
  125095. &_vq_auxt__16c2_s_p9_2,
  125096. NULL,
  125097. 0
  125098. };
  125099. static long _huff_lengthlist__16c2_s_short[] = {
  125100. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125101. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125102. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125103. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125104. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125105. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125106. 15,12,14,14,
  125107. };
  125108. static static_codebook _huff_book__16c2_s_short = {
  125109. 2, 100,
  125110. _huff_lengthlist__16c2_s_short,
  125111. 0, 0, 0, 0, 0,
  125112. NULL,
  125113. NULL,
  125114. NULL,
  125115. NULL,
  125116. 0
  125117. };
  125118. static long _vq_quantlist__8c0_s_p1_0[] = {
  125119. 1,
  125120. 0,
  125121. 2,
  125122. };
  125123. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125124. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125125. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125130. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125135. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125170. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125175. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125180. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125215. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125216. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125221. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125226. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0,
  125535. };
  125536. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125537. -0.5, 0.5,
  125538. };
  125539. static long _vq_quantmap__8c0_s_p1_0[] = {
  125540. 1, 0, 2,
  125541. };
  125542. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125543. _vq_quantthresh__8c0_s_p1_0,
  125544. _vq_quantmap__8c0_s_p1_0,
  125545. 3,
  125546. 3
  125547. };
  125548. static static_codebook _8c0_s_p1_0 = {
  125549. 8, 6561,
  125550. _vq_lengthlist__8c0_s_p1_0,
  125551. 1, -535822336, 1611661312, 2, 0,
  125552. _vq_quantlist__8c0_s_p1_0,
  125553. NULL,
  125554. &_vq_auxt__8c0_s_p1_0,
  125555. NULL,
  125556. 0
  125557. };
  125558. static long _vq_quantlist__8c0_s_p2_0[] = {
  125559. 2,
  125560. 1,
  125561. 3,
  125562. 0,
  125563. 4,
  125564. };
  125565. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 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,
  125606. };
  125607. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125608. -1.5, -0.5, 0.5, 1.5,
  125609. };
  125610. static long _vq_quantmap__8c0_s_p2_0[] = {
  125611. 3, 1, 0, 2, 4,
  125612. };
  125613. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125614. _vq_quantthresh__8c0_s_p2_0,
  125615. _vq_quantmap__8c0_s_p2_0,
  125616. 5,
  125617. 5
  125618. };
  125619. static static_codebook _8c0_s_p2_0 = {
  125620. 4, 625,
  125621. _vq_lengthlist__8c0_s_p2_0,
  125622. 1, -533725184, 1611661312, 3, 0,
  125623. _vq_quantlist__8c0_s_p2_0,
  125624. NULL,
  125625. &_vq_auxt__8c0_s_p2_0,
  125626. NULL,
  125627. 0
  125628. };
  125629. static long _vq_quantlist__8c0_s_p3_0[] = {
  125630. 2,
  125631. 1,
  125632. 3,
  125633. 0,
  125634. 4,
  125635. };
  125636. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125637. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  125677. };
  125678. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125679. -1.5, -0.5, 0.5, 1.5,
  125680. };
  125681. static long _vq_quantmap__8c0_s_p3_0[] = {
  125682. 3, 1, 0, 2, 4,
  125683. };
  125684. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125685. _vq_quantthresh__8c0_s_p3_0,
  125686. _vq_quantmap__8c0_s_p3_0,
  125687. 5,
  125688. 5
  125689. };
  125690. static static_codebook _8c0_s_p3_0 = {
  125691. 4, 625,
  125692. _vq_lengthlist__8c0_s_p3_0,
  125693. 1, -533725184, 1611661312, 3, 0,
  125694. _vq_quantlist__8c0_s_p3_0,
  125695. NULL,
  125696. &_vq_auxt__8c0_s_p3_0,
  125697. NULL,
  125698. 0
  125699. };
  125700. static long _vq_quantlist__8c0_s_p4_0[] = {
  125701. 4,
  125702. 3,
  125703. 5,
  125704. 2,
  125705. 6,
  125706. 1,
  125707. 7,
  125708. 0,
  125709. 8,
  125710. };
  125711. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125712. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125713. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125714. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125715. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125716. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0,
  125718. };
  125719. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125720. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125721. };
  125722. static long _vq_quantmap__8c0_s_p4_0[] = {
  125723. 7, 5, 3, 1, 0, 2, 4, 6,
  125724. 8,
  125725. };
  125726. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125727. _vq_quantthresh__8c0_s_p4_0,
  125728. _vq_quantmap__8c0_s_p4_0,
  125729. 9,
  125730. 9
  125731. };
  125732. static static_codebook _8c0_s_p4_0 = {
  125733. 2, 81,
  125734. _vq_lengthlist__8c0_s_p4_0,
  125735. 1, -531628032, 1611661312, 4, 0,
  125736. _vq_quantlist__8c0_s_p4_0,
  125737. NULL,
  125738. &_vq_auxt__8c0_s_p4_0,
  125739. NULL,
  125740. 0
  125741. };
  125742. static long _vq_quantlist__8c0_s_p5_0[] = {
  125743. 4,
  125744. 3,
  125745. 5,
  125746. 2,
  125747. 6,
  125748. 1,
  125749. 7,
  125750. 0,
  125751. 8,
  125752. };
  125753. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125754. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125755. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125756. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125757. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125758. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125759. 10,
  125760. };
  125761. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125762. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125763. };
  125764. static long _vq_quantmap__8c0_s_p5_0[] = {
  125765. 7, 5, 3, 1, 0, 2, 4, 6,
  125766. 8,
  125767. };
  125768. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125769. _vq_quantthresh__8c0_s_p5_0,
  125770. _vq_quantmap__8c0_s_p5_0,
  125771. 9,
  125772. 9
  125773. };
  125774. static static_codebook _8c0_s_p5_0 = {
  125775. 2, 81,
  125776. _vq_lengthlist__8c0_s_p5_0,
  125777. 1, -531628032, 1611661312, 4, 0,
  125778. _vq_quantlist__8c0_s_p5_0,
  125779. NULL,
  125780. &_vq_auxt__8c0_s_p5_0,
  125781. NULL,
  125782. 0
  125783. };
  125784. static long _vq_quantlist__8c0_s_p6_0[] = {
  125785. 8,
  125786. 7,
  125787. 9,
  125788. 6,
  125789. 10,
  125790. 5,
  125791. 11,
  125792. 4,
  125793. 12,
  125794. 3,
  125795. 13,
  125796. 2,
  125797. 14,
  125798. 1,
  125799. 15,
  125800. 0,
  125801. 16,
  125802. };
  125803. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125804. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125805. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125806. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125807. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125808. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125809. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125810. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125811. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125812. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125813. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125814. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125815. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125816. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125817. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125818. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125819. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125820. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125822. 14,
  125823. };
  125824. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125825. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125826. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125827. };
  125828. static long _vq_quantmap__8c0_s_p6_0[] = {
  125829. 15, 13, 11, 9, 7, 5, 3, 1,
  125830. 0, 2, 4, 6, 8, 10, 12, 14,
  125831. 16,
  125832. };
  125833. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125834. _vq_quantthresh__8c0_s_p6_0,
  125835. _vq_quantmap__8c0_s_p6_0,
  125836. 17,
  125837. 17
  125838. };
  125839. static static_codebook _8c0_s_p6_0 = {
  125840. 2, 289,
  125841. _vq_lengthlist__8c0_s_p6_0,
  125842. 1, -529530880, 1611661312, 5, 0,
  125843. _vq_quantlist__8c0_s_p6_0,
  125844. NULL,
  125845. &_vq_auxt__8c0_s_p6_0,
  125846. NULL,
  125847. 0
  125848. };
  125849. static long _vq_quantlist__8c0_s_p7_0[] = {
  125850. 1,
  125851. 0,
  125852. 2,
  125853. };
  125854. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125855. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125856. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125857. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125858. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125859. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125860. 10,
  125861. };
  125862. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125863. -5.5, 5.5,
  125864. };
  125865. static long _vq_quantmap__8c0_s_p7_0[] = {
  125866. 1, 0, 2,
  125867. };
  125868. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125869. _vq_quantthresh__8c0_s_p7_0,
  125870. _vq_quantmap__8c0_s_p7_0,
  125871. 3,
  125872. 3
  125873. };
  125874. static static_codebook _8c0_s_p7_0 = {
  125875. 4, 81,
  125876. _vq_lengthlist__8c0_s_p7_0,
  125877. 1, -529137664, 1618345984, 2, 0,
  125878. _vq_quantlist__8c0_s_p7_0,
  125879. NULL,
  125880. &_vq_auxt__8c0_s_p7_0,
  125881. NULL,
  125882. 0
  125883. };
  125884. static long _vq_quantlist__8c0_s_p7_1[] = {
  125885. 5,
  125886. 4,
  125887. 6,
  125888. 3,
  125889. 7,
  125890. 2,
  125891. 8,
  125892. 1,
  125893. 9,
  125894. 0,
  125895. 10,
  125896. };
  125897. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125898. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125899. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125900. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125901. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125902. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125903. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125904. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125905. 10,10,10, 9, 9, 9,10,10,10,
  125906. };
  125907. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125908. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125909. 3.5, 4.5,
  125910. };
  125911. static long _vq_quantmap__8c0_s_p7_1[] = {
  125912. 9, 7, 5, 3, 1, 0, 2, 4,
  125913. 6, 8, 10,
  125914. };
  125915. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125916. _vq_quantthresh__8c0_s_p7_1,
  125917. _vq_quantmap__8c0_s_p7_1,
  125918. 11,
  125919. 11
  125920. };
  125921. static static_codebook _8c0_s_p7_1 = {
  125922. 2, 121,
  125923. _vq_lengthlist__8c0_s_p7_1,
  125924. 1, -531365888, 1611661312, 4, 0,
  125925. _vq_quantlist__8c0_s_p7_1,
  125926. NULL,
  125927. &_vq_auxt__8c0_s_p7_1,
  125928. NULL,
  125929. 0
  125930. };
  125931. static long _vq_quantlist__8c0_s_p8_0[] = {
  125932. 6,
  125933. 5,
  125934. 7,
  125935. 4,
  125936. 8,
  125937. 3,
  125938. 9,
  125939. 2,
  125940. 10,
  125941. 1,
  125942. 11,
  125943. 0,
  125944. 12,
  125945. };
  125946. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125947. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125948. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125949. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125950. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125951. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125952. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125953. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125954. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125955. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125956. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125957. 0, 0,13,13,11,13,13,11,12,
  125958. };
  125959. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125960. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125961. 12.5, 17.5, 22.5, 27.5,
  125962. };
  125963. static long _vq_quantmap__8c0_s_p8_0[] = {
  125964. 11, 9, 7, 5, 3, 1, 0, 2,
  125965. 4, 6, 8, 10, 12,
  125966. };
  125967. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125968. _vq_quantthresh__8c0_s_p8_0,
  125969. _vq_quantmap__8c0_s_p8_0,
  125970. 13,
  125971. 13
  125972. };
  125973. static static_codebook _8c0_s_p8_0 = {
  125974. 2, 169,
  125975. _vq_lengthlist__8c0_s_p8_0,
  125976. 1, -526516224, 1616117760, 4, 0,
  125977. _vq_quantlist__8c0_s_p8_0,
  125978. NULL,
  125979. &_vq_auxt__8c0_s_p8_0,
  125980. NULL,
  125981. 0
  125982. };
  125983. static long _vq_quantlist__8c0_s_p8_1[] = {
  125984. 2,
  125985. 1,
  125986. 3,
  125987. 0,
  125988. 4,
  125989. };
  125990. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125991. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125992. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125993. };
  125994. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125995. -1.5, -0.5, 0.5, 1.5,
  125996. };
  125997. static long _vq_quantmap__8c0_s_p8_1[] = {
  125998. 3, 1, 0, 2, 4,
  125999. };
  126000. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126001. _vq_quantthresh__8c0_s_p8_1,
  126002. _vq_quantmap__8c0_s_p8_1,
  126003. 5,
  126004. 5
  126005. };
  126006. static static_codebook _8c0_s_p8_1 = {
  126007. 2, 25,
  126008. _vq_lengthlist__8c0_s_p8_1,
  126009. 1, -533725184, 1611661312, 3, 0,
  126010. _vq_quantlist__8c0_s_p8_1,
  126011. NULL,
  126012. &_vq_auxt__8c0_s_p8_1,
  126013. NULL,
  126014. 0
  126015. };
  126016. static long _vq_quantlist__8c0_s_p9_0[] = {
  126017. 1,
  126018. 0,
  126019. 2,
  126020. };
  126021. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126022. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126023. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126024. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126025. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126026. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126027. 7,
  126028. };
  126029. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126030. -157.5, 157.5,
  126031. };
  126032. static long _vq_quantmap__8c0_s_p9_0[] = {
  126033. 1, 0, 2,
  126034. };
  126035. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126036. _vq_quantthresh__8c0_s_p9_0,
  126037. _vq_quantmap__8c0_s_p9_0,
  126038. 3,
  126039. 3
  126040. };
  126041. static static_codebook _8c0_s_p9_0 = {
  126042. 4, 81,
  126043. _vq_lengthlist__8c0_s_p9_0,
  126044. 1, -518803456, 1628680192, 2, 0,
  126045. _vq_quantlist__8c0_s_p9_0,
  126046. NULL,
  126047. &_vq_auxt__8c0_s_p9_0,
  126048. NULL,
  126049. 0
  126050. };
  126051. static long _vq_quantlist__8c0_s_p9_1[] = {
  126052. 7,
  126053. 6,
  126054. 8,
  126055. 5,
  126056. 9,
  126057. 4,
  126058. 10,
  126059. 3,
  126060. 11,
  126061. 2,
  126062. 12,
  126063. 1,
  126064. 13,
  126065. 0,
  126066. 14,
  126067. };
  126068. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126069. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126070. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126071. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126072. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126073. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126074. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126080. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126081. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126083. 11,
  126084. };
  126085. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126086. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126087. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126088. };
  126089. static long _vq_quantmap__8c0_s_p9_1[] = {
  126090. 13, 11, 9, 7, 5, 3, 1, 0,
  126091. 2, 4, 6, 8, 10, 12, 14,
  126092. };
  126093. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126094. _vq_quantthresh__8c0_s_p9_1,
  126095. _vq_quantmap__8c0_s_p9_1,
  126096. 15,
  126097. 15
  126098. };
  126099. static static_codebook _8c0_s_p9_1 = {
  126100. 2, 225,
  126101. _vq_lengthlist__8c0_s_p9_1,
  126102. 1, -520986624, 1620377600, 4, 0,
  126103. _vq_quantlist__8c0_s_p9_1,
  126104. NULL,
  126105. &_vq_auxt__8c0_s_p9_1,
  126106. NULL,
  126107. 0
  126108. };
  126109. static long _vq_quantlist__8c0_s_p9_2[] = {
  126110. 10,
  126111. 9,
  126112. 11,
  126113. 8,
  126114. 12,
  126115. 7,
  126116. 13,
  126117. 6,
  126118. 14,
  126119. 5,
  126120. 15,
  126121. 4,
  126122. 16,
  126123. 3,
  126124. 17,
  126125. 2,
  126126. 18,
  126127. 1,
  126128. 19,
  126129. 0,
  126130. 20,
  126131. };
  126132. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126133. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126134. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126135. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126136. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126137. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126138. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126139. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126140. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126141. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126142. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126143. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126144. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126145. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126146. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126147. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126148. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126149. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126150. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126151. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126152. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126153. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126154. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126155. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126156. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126157. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126158. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126159. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126160. 10,11, 9,11,10, 9,10, 9,10,
  126161. };
  126162. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126163. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126164. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126165. 6.5, 7.5, 8.5, 9.5,
  126166. };
  126167. static long _vq_quantmap__8c0_s_p9_2[] = {
  126168. 19, 17, 15, 13, 11, 9, 7, 5,
  126169. 3, 1, 0, 2, 4, 6, 8, 10,
  126170. 12, 14, 16, 18, 20,
  126171. };
  126172. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126173. _vq_quantthresh__8c0_s_p9_2,
  126174. _vq_quantmap__8c0_s_p9_2,
  126175. 21,
  126176. 21
  126177. };
  126178. static static_codebook _8c0_s_p9_2 = {
  126179. 2, 441,
  126180. _vq_lengthlist__8c0_s_p9_2,
  126181. 1, -529268736, 1611661312, 5, 0,
  126182. _vq_quantlist__8c0_s_p9_2,
  126183. NULL,
  126184. &_vq_auxt__8c0_s_p9_2,
  126185. NULL,
  126186. 0
  126187. };
  126188. static long _huff_lengthlist__8c0_s_single[] = {
  126189. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126190. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126191. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126192. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126193. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126194. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126195. 17,16,17,17,
  126196. };
  126197. static static_codebook _huff_book__8c0_s_single = {
  126198. 2, 100,
  126199. _huff_lengthlist__8c0_s_single,
  126200. 0, 0, 0, 0, 0,
  126201. NULL,
  126202. NULL,
  126203. NULL,
  126204. NULL,
  126205. 0
  126206. };
  126207. static long _vq_quantlist__8c1_s_p1_0[] = {
  126208. 1,
  126209. 0,
  126210. 2,
  126211. };
  126212. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126213. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126214. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126219. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126224. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126259. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126264. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126269. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126305. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126310. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126315. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0,
  126624. };
  126625. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126626. -0.5, 0.5,
  126627. };
  126628. static long _vq_quantmap__8c1_s_p1_0[] = {
  126629. 1, 0, 2,
  126630. };
  126631. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126632. _vq_quantthresh__8c1_s_p1_0,
  126633. _vq_quantmap__8c1_s_p1_0,
  126634. 3,
  126635. 3
  126636. };
  126637. static static_codebook _8c1_s_p1_0 = {
  126638. 8, 6561,
  126639. _vq_lengthlist__8c1_s_p1_0,
  126640. 1, -535822336, 1611661312, 2, 0,
  126641. _vq_quantlist__8c1_s_p1_0,
  126642. NULL,
  126643. &_vq_auxt__8c1_s_p1_0,
  126644. NULL,
  126645. 0
  126646. };
  126647. static long _vq_quantlist__8c1_s_p2_0[] = {
  126648. 2,
  126649. 1,
  126650. 3,
  126651. 0,
  126652. 4,
  126653. };
  126654. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 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,
  126695. };
  126696. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126697. -1.5, -0.5, 0.5, 1.5,
  126698. };
  126699. static long _vq_quantmap__8c1_s_p2_0[] = {
  126700. 3, 1, 0, 2, 4,
  126701. };
  126702. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126703. _vq_quantthresh__8c1_s_p2_0,
  126704. _vq_quantmap__8c1_s_p2_0,
  126705. 5,
  126706. 5
  126707. };
  126708. static static_codebook _8c1_s_p2_0 = {
  126709. 4, 625,
  126710. _vq_lengthlist__8c1_s_p2_0,
  126711. 1, -533725184, 1611661312, 3, 0,
  126712. _vq_quantlist__8c1_s_p2_0,
  126713. NULL,
  126714. &_vq_auxt__8c1_s_p2_0,
  126715. NULL,
  126716. 0
  126717. };
  126718. static long _vq_quantlist__8c1_s_p3_0[] = {
  126719. 2,
  126720. 1,
  126721. 3,
  126722. 0,
  126723. 4,
  126724. };
  126725. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126726. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  126766. };
  126767. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126768. -1.5, -0.5, 0.5, 1.5,
  126769. };
  126770. static long _vq_quantmap__8c1_s_p3_0[] = {
  126771. 3, 1, 0, 2, 4,
  126772. };
  126773. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126774. _vq_quantthresh__8c1_s_p3_0,
  126775. _vq_quantmap__8c1_s_p3_0,
  126776. 5,
  126777. 5
  126778. };
  126779. static static_codebook _8c1_s_p3_0 = {
  126780. 4, 625,
  126781. _vq_lengthlist__8c1_s_p3_0,
  126782. 1, -533725184, 1611661312, 3, 0,
  126783. _vq_quantlist__8c1_s_p3_0,
  126784. NULL,
  126785. &_vq_auxt__8c1_s_p3_0,
  126786. NULL,
  126787. 0
  126788. };
  126789. static long _vq_quantlist__8c1_s_p4_0[] = {
  126790. 4,
  126791. 3,
  126792. 5,
  126793. 2,
  126794. 6,
  126795. 1,
  126796. 7,
  126797. 0,
  126798. 8,
  126799. };
  126800. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126801. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126802. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126803. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126804. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126805. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0,
  126807. };
  126808. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126809. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126810. };
  126811. static long _vq_quantmap__8c1_s_p4_0[] = {
  126812. 7, 5, 3, 1, 0, 2, 4, 6,
  126813. 8,
  126814. };
  126815. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126816. _vq_quantthresh__8c1_s_p4_0,
  126817. _vq_quantmap__8c1_s_p4_0,
  126818. 9,
  126819. 9
  126820. };
  126821. static static_codebook _8c1_s_p4_0 = {
  126822. 2, 81,
  126823. _vq_lengthlist__8c1_s_p4_0,
  126824. 1, -531628032, 1611661312, 4, 0,
  126825. _vq_quantlist__8c1_s_p4_0,
  126826. NULL,
  126827. &_vq_auxt__8c1_s_p4_0,
  126828. NULL,
  126829. 0
  126830. };
  126831. static long _vq_quantlist__8c1_s_p5_0[] = {
  126832. 4,
  126833. 3,
  126834. 5,
  126835. 2,
  126836. 6,
  126837. 1,
  126838. 7,
  126839. 0,
  126840. 8,
  126841. };
  126842. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126843. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126844. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126845. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126846. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126847. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126848. 10,
  126849. };
  126850. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126851. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126852. };
  126853. static long _vq_quantmap__8c1_s_p5_0[] = {
  126854. 7, 5, 3, 1, 0, 2, 4, 6,
  126855. 8,
  126856. };
  126857. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126858. _vq_quantthresh__8c1_s_p5_0,
  126859. _vq_quantmap__8c1_s_p5_0,
  126860. 9,
  126861. 9
  126862. };
  126863. static static_codebook _8c1_s_p5_0 = {
  126864. 2, 81,
  126865. _vq_lengthlist__8c1_s_p5_0,
  126866. 1, -531628032, 1611661312, 4, 0,
  126867. _vq_quantlist__8c1_s_p5_0,
  126868. NULL,
  126869. &_vq_auxt__8c1_s_p5_0,
  126870. NULL,
  126871. 0
  126872. };
  126873. static long _vq_quantlist__8c1_s_p6_0[] = {
  126874. 8,
  126875. 7,
  126876. 9,
  126877. 6,
  126878. 10,
  126879. 5,
  126880. 11,
  126881. 4,
  126882. 12,
  126883. 3,
  126884. 13,
  126885. 2,
  126886. 14,
  126887. 1,
  126888. 15,
  126889. 0,
  126890. 16,
  126891. };
  126892. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126893. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126894. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126895. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126896. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126897. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126898. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126899. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126900. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126901. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126902. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126903. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126904. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126905. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126906. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126907. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126908. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126909. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126911. 14,
  126912. };
  126913. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126916. };
  126917. static long _vq_quantmap__8c1_s_p6_0[] = {
  126918. 15, 13, 11, 9, 7, 5, 3, 1,
  126919. 0, 2, 4, 6, 8, 10, 12, 14,
  126920. 16,
  126921. };
  126922. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126923. _vq_quantthresh__8c1_s_p6_0,
  126924. _vq_quantmap__8c1_s_p6_0,
  126925. 17,
  126926. 17
  126927. };
  126928. static static_codebook _8c1_s_p6_0 = {
  126929. 2, 289,
  126930. _vq_lengthlist__8c1_s_p6_0,
  126931. 1, -529530880, 1611661312, 5, 0,
  126932. _vq_quantlist__8c1_s_p6_0,
  126933. NULL,
  126934. &_vq_auxt__8c1_s_p6_0,
  126935. NULL,
  126936. 0
  126937. };
  126938. static long _vq_quantlist__8c1_s_p7_0[] = {
  126939. 1,
  126940. 0,
  126941. 2,
  126942. };
  126943. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126944. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126945. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126946. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126947. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126948. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126949. 9,
  126950. };
  126951. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126952. -5.5, 5.5,
  126953. };
  126954. static long _vq_quantmap__8c1_s_p7_0[] = {
  126955. 1, 0, 2,
  126956. };
  126957. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126958. _vq_quantthresh__8c1_s_p7_0,
  126959. _vq_quantmap__8c1_s_p7_0,
  126960. 3,
  126961. 3
  126962. };
  126963. static static_codebook _8c1_s_p7_0 = {
  126964. 4, 81,
  126965. _vq_lengthlist__8c1_s_p7_0,
  126966. 1, -529137664, 1618345984, 2, 0,
  126967. _vq_quantlist__8c1_s_p7_0,
  126968. NULL,
  126969. &_vq_auxt__8c1_s_p7_0,
  126970. NULL,
  126971. 0
  126972. };
  126973. static long _vq_quantlist__8c1_s_p7_1[] = {
  126974. 5,
  126975. 4,
  126976. 6,
  126977. 3,
  126978. 7,
  126979. 2,
  126980. 8,
  126981. 1,
  126982. 9,
  126983. 0,
  126984. 10,
  126985. };
  126986. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126987. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126988. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126989. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126990. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126991. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126992. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126993. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126994. 10,10,10, 8, 8, 8, 8, 8, 8,
  126995. };
  126996. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126997. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126998. 3.5, 4.5,
  126999. };
  127000. static long _vq_quantmap__8c1_s_p7_1[] = {
  127001. 9, 7, 5, 3, 1, 0, 2, 4,
  127002. 6, 8, 10,
  127003. };
  127004. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127005. _vq_quantthresh__8c1_s_p7_1,
  127006. _vq_quantmap__8c1_s_p7_1,
  127007. 11,
  127008. 11
  127009. };
  127010. static static_codebook _8c1_s_p7_1 = {
  127011. 2, 121,
  127012. _vq_lengthlist__8c1_s_p7_1,
  127013. 1, -531365888, 1611661312, 4, 0,
  127014. _vq_quantlist__8c1_s_p7_1,
  127015. NULL,
  127016. &_vq_auxt__8c1_s_p7_1,
  127017. NULL,
  127018. 0
  127019. };
  127020. static long _vq_quantlist__8c1_s_p8_0[] = {
  127021. 6,
  127022. 5,
  127023. 7,
  127024. 4,
  127025. 8,
  127026. 3,
  127027. 9,
  127028. 2,
  127029. 10,
  127030. 1,
  127031. 11,
  127032. 0,
  127033. 12,
  127034. };
  127035. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127036. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127037. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127038. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127039. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127040. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127041. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127042. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127043. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127044. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127045. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127046. 0,12,12,11,10,12,11,13,12,
  127047. };
  127048. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127049. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127050. 12.5, 17.5, 22.5, 27.5,
  127051. };
  127052. static long _vq_quantmap__8c1_s_p8_0[] = {
  127053. 11, 9, 7, 5, 3, 1, 0, 2,
  127054. 4, 6, 8, 10, 12,
  127055. };
  127056. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127057. _vq_quantthresh__8c1_s_p8_0,
  127058. _vq_quantmap__8c1_s_p8_0,
  127059. 13,
  127060. 13
  127061. };
  127062. static static_codebook _8c1_s_p8_0 = {
  127063. 2, 169,
  127064. _vq_lengthlist__8c1_s_p8_0,
  127065. 1, -526516224, 1616117760, 4, 0,
  127066. _vq_quantlist__8c1_s_p8_0,
  127067. NULL,
  127068. &_vq_auxt__8c1_s_p8_0,
  127069. NULL,
  127070. 0
  127071. };
  127072. static long _vq_quantlist__8c1_s_p8_1[] = {
  127073. 2,
  127074. 1,
  127075. 3,
  127076. 0,
  127077. 4,
  127078. };
  127079. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127080. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127081. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127082. };
  127083. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127084. -1.5, -0.5, 0.5, 1.5,
  127085. };
  127086. static long _vq_quantmap__8c1_s_p8_1[] = {
  127087. 3, 1, 0, 2, 4,
  127088. };
  127089. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127090. _vq_quantthresh__8c1_s_p8_1,
  127091. _vq_quantmap__8c1_s_p8_1,
  127092. 5,
  127093. 5
  127094. };
  127095. static static_codebook _8c1_s_p8_1 = {
  127096. 2, 25,
  127097. _vq_lengthlist__8c1_s_p8_1,
  127098. 1, -533725184, 1611661312, 3, 0,
  127099. _vq_quantlist__8c1_s_p8_1,
  127100. NULL,
  127101. &_vq_auxt__8c1_s_p8_1,
  127102. NULL,
  127103. 0
  127104. };
  127105. static long _vq_quantlist__8c1_s_p9_0[] = {
  127106. 6,
  127107. 5,
  127108. 7,
  127109. 4,
  127110. 8,
  127111. 3,
  127112. 9,
  127113. 2,
  127114. 10,
  127115. 1,
  127116. 11,
  127117. 0,
  127118. 12,
  127119. };
  127120. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127121. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127122. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127123. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127125. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127126. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127130. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127131. 10,10,10,10,10, 9, 9, 9, 9,
  127132. };
  127133. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127134. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127135. 787.5, 1102.5, 1417.5, 1732.5,
  127136. };
  127137. static long _vq_quantmap__8c1_s_p9_0[] = {
  127138. 11, 9, 7, 5, 3, 1, 0, 2,
  127139. 4, 6, 8, 10, 12,
  127140. };
  127141. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127142. _vq_quantthresh__8c1_s_p9_0,
  127143. _vq_quantmap__8c1_s_p9_0,
  127144. 13,
  127145. 13
  127146. };
  127147. static static_codebook _8c1_s_p9_0 = {
  127148. 2, 169,
  127149. _vq_lengthlist__8c1_s_p9_0,
  127150. 1, -513964032, 1628680192, 4, 0,
  127151. _vq_quantlist__8c1_s_p9_0,
  127152. NULL,
  127153. &_vq_auxt__8c1_s_p9_0,
  127154. NULL,
  127155. 0
  127156. };
  127157. static long _vq_quantlist__8c1_s_p9_1[] = {
  127158. 7,
  127159. 6,
  127160. 8,
  127161. 5,
  127162. 9,
  127163. 4,
  127164. 10,
  127165. 3,
  127166. 11,
  127167. 2,
  127168. 12,
  127169. 1,
  127170. 13,
  127171. 0,
  127172. 14,
  127173. };
  127174. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127175. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127176. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127177. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127178. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127179. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127180. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127181. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127182. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127183. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127184. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127185. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127186. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127187. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127188. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127189. 15,
  127190. };
  127191. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127192. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127193. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127194. };
  127195. static long _vq_quantmap__8c1_s_p9_1[] = {
  127196. 13, 11, 9, 7, 5, 3, 1, 0,
  127197. 2, 4, 6, 8, 10, 12, 14,
  127198. };
  127199. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127200. _vq_quantthresh__8c1_s_p9_1,
  127201. _vq_quantmap__8c1_s_p9_1,
  127202. 15,
  127203. 15
  127204. };
  127205. static static_codebook _8c1_s_p9_1 = {
  127206. 2, 225,
  127207. _vq_lengthlist__8c1_s_p9_1,
  127208. 1, -520986624, 1620377600, 4, 0,
  127209. _vq_quantlist__8c1_s_p9_1,
  127210. NULL,
  127211. &_vq_auxt__8c1_s_p9_1,
  127212. NULL,
  127213. 0
  127214. };
  127215. static long _vq_quantlist__8c1_s_p9_2[] = {
  127216. 10,
  127217. 9,
  127218. 11,
  127219. 8,
  127220. 12,
  127221. 7,
  127222. 13,
  127223. 6,
  127224. 14,
  127225. 5,
  127226. 15,
  127227. 4,
  127228. 16,
  127229. 3,
  127230. 17,
  127231. 2,
  127232. 18,
  127233. 1,
  127234. 19,
  127235. 0,
  127236. 20,
  127237. };
  127238. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127239. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127240. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127241. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127242. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127243. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127244. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127245. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127246. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127247. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127248. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127249. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127250. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127251. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127252. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127253. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127254. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127255. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127256. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127257. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127258. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127259. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127260. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127261. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127262. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127263. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127264. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127265. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127266. 10,10,10,10,10,10,10,10,10,
  127267. };
  127268. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127269. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127270. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127271. 6.5, 7.5, 8.5, 9.5,
  127272. };
  127273. static long _vq_quantmap__8c1_s_p9_2[] = {
  127274. 19, 17, 15, 13, 11, 9, 7, 5,
  127275. 3, 1, 0, 2, 4, 6, 8, 10,
  127276. 12, 14, 16, 18, 20,
  127277. };
  127278. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127279. _vq_quantthresh__8c1_s_p9_2,
  127280. _vq_quantmap__8c1_s_p9_2,
  127281. 21,
  127282. 21
  127283. };
  127284. static static_codebook _8c1_s_p9_2 = {
  127285. 2, 441,
  127286. _vq_lengthlist__8c1_s_p9_2,
  127287. 1, -529268736, 1611661312, 5, 0,
  127288. _vq_quantlist__8c1_s_p9_2,
  127289. NULL,
  127290. &_vq_auxt__8c1_s_p9_2,
  127291. NULL,
  127292. 0
  127293. };
  127294. static long _huff_lengthlist__8c1_s_single[] = {
  127295. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127296. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127297. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127298. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127299. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127300. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127301. 9, 7, 7, 8,
  127302. };
  127303. static static_codebook _huff_book__8c1_s_single = {
  127304. 2, 100,
  127305. _huff_lengthlist__8c1_s_single,
  127306. 0, 0, 0, 0, 0,
  127307. NULL,
  127308. NULL,
  127309. NULL,
  127310. NULL,
  127311. 0
  127312. };
  127313. static long _huff_lengthlist__44c2_s_long[] = {
  127314. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127315. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127316. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127317. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127318. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127319. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127320. 10, 8, 8, 9,
  127321. };
  127322. static static_codebook _huff_book__44c2_s_long = {
  127323. 2, 100,
  127324. _huff_lengthlist__44c2_s_long,
  127325. 0, 0, 0, 0, 0,
  127326. NULL,
  127327. NULL,
  127328. NULL,
  127329. NULL,
  127330. 0
  127331. };
  127332. static long _vq_quantlist__44c2_s_p1_0[] = {
  127333. 1,
  127334. 0,
  127335. 2,
  127336. };
  127337. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127338. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127339. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127344. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127349. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127384. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127389. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127394. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127430. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127435. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127440. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0,
  127749. };
  127750. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127751. -0.5, 0.5,
  127752. };
  127753. static long _vq_quantmap__44c2_s_p1_0[] = {
  127754. 1, 0, 2,
  127755. };
  127756. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127757. _vq_quantthresh__44c2_s_p1_0,
  127758. _vq_quantmap__44c2_s_p1_0,
  127759. 3,
  127760. 3
  127761. };
  127762. static static_codebook _44c2_s_p1_0 = {
  127763. 8, 6561,
  127764. _vq_lengthlist__44c2_s_p1_0,
  127765. 1, -535822336, 1611661312, 2, 0,
  127766. _vq_quantlist__44c2_s_p1_0,
  127767. NULL,
  127768. &_vq_auxt__44c2_s_p1_0,
  127769. NULL,
  127770. 0
  127771. };
  127772. static long _vq_quantlist__44c2_s_p2_0[] = {
  127773. 2,
  127774. 1,
  127775. 3,
  127776. 0,
  127777. 4,
  127778. };
  127779. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127780. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127781. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127782. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127783. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127784. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127790. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127791. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127792. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127798. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127799. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127806. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127807. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  127820. };
  127821. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127822. -1.5, -0.5, 0.5, 1.5,
  127823. };
  127824. static long _vq_quantmap__44c2_s_p2_0[] = {
  127825. 3, 1, 0, 2, 4,
  127826. };
  127827. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127828. _vq_quantthresh__44c2_s_p2_0,
  127829. _vq_quantmap__44c2_s_p2_0,
  127830. 5,
  127831. 5
  127832. };
  127833. static static_codebook _44c2_s_p2_0 = {
  127834. 4, 625,
  127835. _vq_lengthlist__44c2_s_p2_0,
  127836. 1, -533725184, 1611661312, 3, 0,
  127837. _vq_quantlist__44c2_s_p2_0,
  127838. NULL,
  127839. &_vq_auxt__44c2_s_p2_0,
  127840. NULL,
  127841. 0
  127842. };
  127843. static long _vq_quantlist__44c2_s_p3_0[] = {
  127844. 2,
  127845. 1,
  127846. 3,
  127847. 0,
  127848. 4,
  127849. };
  127850. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127851. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 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,
  127891. };
  127892. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127893. -1.5, -0.5, 0.5, 1.5,
  127894. };
  127895. static long _vq_quantmap__44c2_s_p3_0[] = {
  127896. 3, 1, 0, 2, 4,
  127897. };
  127898. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127899. _vq_quantthresh__44c2_s_p3_0,
  127900. _vq_quantmap__44c2_s_p3_0,
  127901. 5,
  127902. 5
  127903. };
  127904. static static_codebook _44c2_s_p3_0 = {
  127905. 4, 625,
  127906. _vq_lengthlist__44c2_s_p3_0,
  127907. 1, -533725184, 1611661312, 3, 0,
  127908. _vq_quantlist__44c2_s_p3_0,
  127909. NULL,
  127910. &_vq_auxt__44c2_s_p3_0,
  127911. NULL,
  127912. 0
  127913. };
  127914. static long _vq_quantlist__44c2_s_p4_0[] = {
  127915. 4,
  127916. 3,
  127917. 5,
  127918. 2,
  127919. 6,
  127920. 1,
  127921. 7,
  127922. 0,
  127923. 8,
  127924. };
  127925. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127926. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127927. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127928. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127929. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127930. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0,
  127932. };
  127933. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127935. };
  127936. static long _vq_quantmap__44c2_s_p4_0[] = {
  127937. 7, 5, 3, 1, 0, 2, 4, 6,
  127938. 8,
  127939. };
  127940. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127941. _vq_quantthresh__44c2_s_p4_0,
  127942. _vq_quantmap__44c2_s_p4_0,
  127943. 9,
  127944. 9
  127945. };
  127946. static static_codebook _44c2_s_p4_0 = {
  127947. 2, 81,
  127948. _vq_lengthlist__44c2_s_p4_0,
  127949. 1, -531628032, 1611661312, 4, 0,
  127950. _vq_quantlist__44c2_s_p4_0,
  127951. NULL,
  127952. &_vq_auxt__44c2_s_p4_0,
  127953. NULL,
  127954. 0
  127955. };
  127956. static long _vq_quantlist__44c2_s_p5_0[] = {
  127957. 4,
  127958. 3,
  127959. 5,
  127960. 2,
  127961. 6,
  127962. 1,
  127963. 7,
  127964. 0,
  127965. 8,
  127966. };
  127967. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127968. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127969. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127970. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127971. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127972. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127973. 11,
  127974. };
  127975. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127977. };
  127978. static long _vq_quantmap__44c2_s_p5_0[] = {
  127979. 7, 5, 3, 1, 0, 2, 4, 6,
  127980. 8,
  127981. };
  127982. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127983. _vq_quantthresh__44c2_s_p5_0,
  127984. _vq_quantmap__44c2_s_p5_0,
  127985. 9,
  127986. 9
  127987. };
  127988. static static_codebook _44c2_s_p5_0 = {
  127989. 2, 81,
  127990. _vq_lengthlist__44c2_s_p5_0,
  127991. 1, -531628032, 1611661312, 4, 0,
  127992. _vq_quantlist__44c2_s_p5_0,
  127993. NULL,
  127994. &_vq_auxt__44c2_s_p5_0,
  127995. NULL,
  127996. 0
  127997. };
  127998. static long _vq_quantlist__44c2_s_p6_0[] = {
  127999. 8,
  128000. 7,
  128001. 9,
  128002. 6,
  128003. 10,
  128004. 5,
  128005. 11,
  128006. 4,
  128007. 12,
  128008. 3,
  128009. 13,
  128010. 2,
  128011. 14,
  128012. 1,
  128013. 15,
  128014. 0,
  128015. 16,
  128016. };
  128017. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128018. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128019. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128020. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128021. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128022. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128023. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128024. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128025. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128026. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128027. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128028. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128029. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128030. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128031. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128032. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128033. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128034. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128036. 14,
  128037. };
  128038. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128039. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128040. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128041. };
  128042. static long _vq_quantmap__44c2_s_p6_0[] = {
  128043. 15, 13, 11, 9, 7, 5, 3, 1,
  128044. 0, 2, 4, 6, 8, 10, 12, 14,
  128045. 16,
  128046. };
  128047. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128048. _vq_quantthresh__44c2_s_p6_0,
  128049. _vq_quantmap__44c2_s_p6_0,
  128050. 17,
  128051. 17
  128052. };
  128053. static static_codebook _44c2_s_p6_0 = {
  128054. 2, 289,
  128055. _vq_lengthlist__44c2_s_p6_0,
  128056. 1, -529530880, 1611661312, 5, 0,
  128057. _vq_quantlist__44c2_s_p6_0,
  128058. NULL,
  128059. &_vq_auxt__44c2_s_p6_0,
  128060. NULL,
  128061. 0
  128062. };
  128063. static long _vq_quantlist__44c2_s_p7_0[] = {
  128064. 1,
  128065. 0,
  128066. 2,
  128067. };
  128068. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128069. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128070. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128071. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128072. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128073. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128074. 11,
  128075. };
  128076. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128077. -5.5, 5.5,
  128078. };
  128079. static long _vq_quantmap__44c2_s_p7_0[] = {
  128080. 1, 0, 2,
  128081. };
  128082. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128083. _vq_quantthresh__44c2_s_p7_0,
  128084. _vq_quantmap__44c2_s_p7_0,
  128085. 3,
  128086. 3
  128087. };
  128088. static static_codebook _44c2_s_p7_0 = {
  128089. 4, 81,
  128090. _vq_lengthlist__44c2_s_p7_0,
  128091. 1, -529137664, 1618345984, 2, 0,
  128092. _vq_quantlist__44c2_s_p7_0,
  128093. NULL,
  128094. &_vq_auxt__44c2_s_p7_0,
  128095. NULL,
  128096. 0
  128097. };
  128098. static long _vq_quantlist__44c2_s_p7_1[] = {
  128099. 5,
  128100. 4,
  128101. 6,
  128102. 3,
  128103. 7,
  128104. 2,
  128105. 8,
  128106. 1,
  128107. 9,
  128108. 0,
  128109. 10,
  128110. };
  128111. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128112. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128113. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128114. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128115. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128116. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128117. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128118. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128119. 10,10,10, 8, 8, 8, 8, 8, 8,
  128120. };
  128121. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128123. 3.5, 4.5,
  128124. };
  128125. static long _vq_quantmap__44c2_s_p7_1[] = {
  128126. 9, 7, 5, 3, 1, 0, 2, 4,
  128127. 6, 8, 10,
  128128. };
  128129. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128130. _vq_quantthresh__44c2_s_p7_1,
  128131. _vq_quantmap__44c2_s_p7_1,
  128132. 11,
  128133. 11
  128134. };
  128135. static static_codebook _44c2_s_p7_1 = {
  128136. 2, 121,
  128137. _vq_lengthlist__44c2_s_p7_1,
  128138. 1, -531365888, 1611661312, 4, 0,
  128139. _vq_quantlist__44c2_s_p7_1,
  128140. NULL,
  128141. &_vq_auxt__44c2_s_p7_1,
  128142. NULL,
  128143. 0
  128144. };
  128145. static long _vq_quantlist__44c2_s_p8_0[] = {
  128146. 6,
  128147. 5,
  128148. 7,
  128149. 4,
  128150. 8,
  128151. 3,
  128152. 9,
  128153. 2,
  128154. 10,
  128155. 1,
  128156. 11,
  128157. 0,
  128158. 12,
  128159. };
  128160. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128161. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128162. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128163. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128164. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128165. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128166. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128167. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128168. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128169. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128170. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128171. 0,12,12,12,12,13,12,14,14,
  128172. };
  128173. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128175. 12.5, 17.5, 22.5, 27.5,
  128176. };
  128177. static long _vq_quantmap__44c2_s_p8_0[] = {
  128178. 11, 9, 7, 5, 3, 1, 0, 2,
  128179. 4, 6, 8, 10, 12,
  128180. };
  128181. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128182. _vq_quantthresh__44c2_s_p8_0,
  128183. _vq_quantmap__44c2_s_p8_0,
  128184. 13,
  128185. 13
  128186. };
  128187. static static_codebook _44c2_s_p8_0 = {
  128188. 2, 169,
  128189. _vq_lengthlist__44c2_s_p8_0,
  128190. 1, -526516224, 1616117760, 4, 0,
  128191. _vq_quantlist__44c2_s_p8_0,
  128192. NULL,
  128193. &_vq_auxt__44c2_s_p8_0,
  128194. NULL,
  128195. 0
  128196. };
  128197. static long _vq_quantlist__44c2_s_p8_1[] = {
  128198. 2,
  128199. 1,
  128200. 3,
  128201. 0,
  128202. 4,
  128203. };
  128204. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128205. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128206. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128207. };
  128208. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128209. -1.5, -0.5, 0.5, 1.5,
  128210. };
  128211. static long _vq_quantmap__44c2_s_p8_1[] = {
  128212. 3, 1, 0, 2, 4,
  128213. };
  128214. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128215. _vq_quantthresh__44c2_s_p8_1,
  128216. _vq_quantmap__44c2_s_p8_1,
  128217. 5,
  128218. 5
  128219. };
  128220. static static_codebook _44c2_s_p8_1 = {
  128221. 2, 25,
  128222. _vq_lengthlist__44c2_s_p8_1,
  128223. 1, -533725184, 1611661312, 3, 0,
  128224. _vq_quantlist__44c2_s_p8_1,
  128225. NULL,
  128226. &_vq_auxt__44c2_s_p8_1,
  128227. NULL,
  128228. 0
  128229. };
  128230. static long _vq_quantlist__44c2_s_p9_0[] = {
  128231. 6,
  128232. 5,
  128233. 7,
  128234. 4,
  128235. 8,
  128236. 3,
  128237. 9,
  128238. 2,
  128239. 10,
  128240. 1,
  128241. 11,
  128242. 0,
  128243. 12,
  128244. };
  128245. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128246. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128247. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128249. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128256. 11,11,11,11,11,11,11,11,11,
  128257. };
  128258. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128259. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128260. 552.5, 773.5, 994.5, 1215.5,
  128261. };
  128262. static long _vq_quantmap__44c2_s_p9_0[] = {
  128263. 11, 9, 7, 5, 3, 1, 0, 2,
  128264. 4, 6, 8, 10, 12,
  128265. };
  128266. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128267. _vq_quantthresh__44c2_s_p9_0,
  128268. _vq_quantmap__44c2_s_p9_0,
  128269. 13,
  128270. 13
  128271. };
  128272. static static_codebook _44c2_s_p9_0 = {
  128273. 2, 169,
  128274. _vq_lengthlist__44c2_s_p9_0,
  128275. 1, -514541568, 1627103232, 4, 0,
  128276. _vq_quantlist__44c2_s_p9_0,
  128277. NULL,
  128278. &_vq_auxt__44c2_s_p9_0,
  128279. NULL,
  128280. 0
  128281. };
  128282. static long _vq_quantlist__44c2_s_p9_1[] = {
  128283. 6,
  128284. 5,
  128285. 7,
  128286. 4,
  128287. 8,
  128288. 3,
  128289. 9,
  128290. 2,
  128291. 10,
  128292. 1,
  128293. 11,
  128294. 0,
  128295. 12,
  128296. };
  128297. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128298. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128299. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128300. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128301. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128302. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128303. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128304. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128305. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128306. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128307. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128308. 17,13,12,12,10,13,11,14,14,
  128309. };
  128310. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128311. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128312. 42.5, 59.5, 76.5, 93.5,
  128313. };
  128314. static long _vq_quantmap__44c2_s_p9_1[] = {
  128315. 11, 9, 7, 5, 3, 1, 0, 2,
  128316. 4, 6, 8, 10, 12,
  128317. };
  128318. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128319. _vq_quantthresh__44c2_s_p9_1,
  128320. _vq_quantmap__44c2_s_p9_1,
  128321. 13,
  128322. 13
  128323. };
  128324. static static_codebook _44c2_s_p9_1 = {
  128325. 2, 169,
  128326. _vq_lengthlist__44c2_s_p9_1,
  128327. 1, -522616832, 1620115456, 4, 0,
  128328. _vq_quantlist__44c2_s_p9_1,
  128329. NULL,
  128330. &_vq_auxt__44c2_s_p9_1,
  128331. NULL,
  128332. 0
  128333. };
  128334. static long _vq_quantlist__44c2_s_p9_2[] = {
  128335. 8,
  128336. 7,
  128337. 9,
  128338. 6,
  128339. 10,
  128340. 5,
  128341. 11,
  128342. 4,
  128343. 12,
  128344. 3,
  128345. 13,
  128346. 2,
  128347. 14,
  128348. 1,
  128349. 15,
  128350. 0,
  128351. 16,
  128352. };
  128353. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128354. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128355. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128356. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128357. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128358. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128359. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128360. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128361. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128362. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128363. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128364. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128365. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128366. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128367. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128368. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128369. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128370. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128371. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128372. 10,
  128373. };
  128374. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128375. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128376. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128377. };
  128378. static long _vq_quantmap__44c2_s_p9_2[] = {
  128379. 15, 13, 11, 9, 7, 5, 3, 1,
  128380. 0, 2, 4, 6, 8, 10, 12, 14,
  128381. 16,
  128382. };
  128383. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128384. _vq_quantthresh__44c2_s_p9_2,
  128385. _vq_quantmap__44c2_s_p9_2,
  128386. 17,
  128387. 17
  128388. };
  128389. static static_codebook _44c2_s_p9_2 = {
  128390. 2, 289,
  128391. _vq_lengthlist__44c2_s_p9_2,
  128392. 1, -529530880, 1611661312, 5, 0,
  128393. _vq_quantlist__44c2_s_p9_2,
  128394. NULL,
  128395. &_vq_auxt__44c2_s_p9_2,
  128396. NULL,
  128397. 0
  128398. };
  128399. static long _huff_lengthlist__44c2_s_short[] = {
  128400. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128401. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128402. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128403. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128404. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128405. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128406. 6, 8, 9,12,
  128407. };
  128408. static static_codebook _huff_book__44c2_s_short = {
  128409. 2, 100,
  128410. _huff_lengthlist__44c2_s_short,
  128411. 0, 0, 0, 0, 0,
  128412. NULL,
  128413. NULL,
  128414. NULL,
  128415. NULL,
  128416. 0
  128417. };
  128418. static long _huff_lengthlist__44c3_s_long[] = {
  128419. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128420. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128421. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128422. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128423. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128424. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128425. 9, 8, 8, 8,
  128426. };
  128427. static static_codebook _huff_book__44c3_s_long = {
  128428. 2, 100,
  128429. _huff_lengthlist__44c3_s_long,
  128430. 0, 0, 0, 0, 0,
  128431. NULL,
  128432. NULL,
  128433. NULL,
  128434. NULL,
  128435. 0
  128436. };
  128437. static long _vq_quantlist__44c3_s_p1_0[] = {
  128438. 1,
  128439. 0,
  128440. 2,
  128441. };
  128442. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128443. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128444. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128449. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128454. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128489. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128494. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128499. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128535. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128540. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128545. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128853. 0,
  128854. };
  128855. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128856. -0.5, 0.5,
  128857. };
  128858. static long _vq_quantmap__44c3_s_p1_0[] = {
  128859. 1, 0, 2,
  128860. };
  128861. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128862. _vq_quantthresh__44c3_s_p1_0,
  128863. _vq_quantmap__44c3_s_p1_0,
  128864. 3,
  128865. 3
  128866. };
  128867. static static_codebook _44c3_s_p1_0 = {
  128868. 8, 6561,
  128869. _vq_lengthlist__44c3_s_p1_0,
  128870. 1, -535822336, 1611661312, 2, 0,
  128871. _vq_quantlist__44c3_s_p1_0,
  128872. NULL,
  128873. &_vq_auxt__44c3_s_p1_0,
  128874. NULL,
  128875. 0
  128876. };
  128877. static long _vq_quantlist__44c3_s_p2_0[] = {
  128878. 2,
  128879. 1,
  128880. 3,
  128881. 0,
  128882. 4,
  128883. };
  128884. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128885. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128886. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128887. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128888. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128889. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128895. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128896. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128897. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128903. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128904. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128911. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128912. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 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,
  128925. };
  128926. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128927. -1.5, -0.5, 0.5, 1.5,
  128928. };
  128929. static long _vq_quantmap__44c3_s_p2_0[] = {
  128930. 3, 1, 0, 2, 4,
  128931. };
  128932. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128933. _vq_quantthresh__44c3_s_p2_0,
  128934. _vq_quantmap__44c3_s_p2_0,
  128935. 5,
  128936. 5
  128937. };
  128938. static static_codebook _44c3_s_p2_0 = {
  128939. 4, 625,
  128940. _vq_lengthlist__44c3_s_p2_0,
  128941. 1, -533725184, 1611661312, 3, 0,
  128942. _vq_quantlist__44c3_s_p2_0,
  128943. NULL,
  128944. &_vq_auxt__44c3_s_p2_0,
  128945. NULL,
  128946. 0
  128947. };
  128948. static long _vq_quantlist__44c3_s_p3_0[] = {
  128949. 2,
  128950. 1,
  128951. 3,
  128952. 0,
  128953. 4,
  128954. };
  128955. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128956. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128996. };
  128997. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128998. -1.5, -0.5, 0.5, 1.5,
  128999. };
  129000. static long _vq_quantmap__44c3_s_p3_0[] = {
  129001. 3, 1, 0, 2, 4,
  129002. };
  129003. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129004. _vq_quantthresh__44c3_s_p3_0,
  129005. _vq_quantmap__44c3_s_p3_0,
  129006. 5,
  129007. 5
  129008. };
  129009. static static_codebook _44c3_s_p3_0 = {
  129010. 4, 625,
  129011. _vq_lengthlist__44c3_s_p3_0,
  129012. 1, -533725184, 1611661312, 3, 0,
  129013. _vq_quantlist__44c3_s_p3_0,
  129014. NULL,
  129015. &_vq_auxt__44c3_s_p3_0,
  129016. NULL,
  129017. 0
  129018. };
  129019. static long _vq_quantlist__44c3_s_p4_0[] = {
  129020. 4,
  129021. 3,
  129022. 5,
  129023. 2,
  129024. 6,
  129025. 1,
  129026. 7,
  129027. 0,
  129028. 8,
  129029. };
  129030. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129031. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129032. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129033. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129034. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129035. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0,
  129037. };
  129038. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129039. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129040. };
  129041. static long _vq_quantmap__44c3_s_p4_0[] = {
  129042. 7, 5, 3, 1, 0, 2, 4, 6,
  129043. 8,
  129044. };
  129045. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129046. _vq_quantthresh__44c3_s_p4_0,
  129047. _vq_quantmap__44c3_s_p4_0,
  129048. 9,
  129049. 9
  129050. };
  129051. static static_codebook _44c3_s_p4_0 = {
  129052. 2, 81,
  129053. _vq_lengthlist__44c3_s_p4_0,
  129054. 1, -531628032, 1611661312, 4, 0,
  129055. _vq_quantlist__44c3_s_p4_0,
  129056. NULL,
  129057. &_vq_auxt__44c3_s_p4_0,
  129058. NULL,
  129059. 0
  129060. };
  129061. static long _vq_quantlist__44c3_s_p5_0[] = {
  129062. 4,
  129063. 3,
  129064. 5,
  129065. 2,
  129066. 6,
  129067. 1,
  129068. 7,
  129069. 0,
  129070. 8,
  129071. };
  129072. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129073. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129074. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129075. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129076. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129077. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129078. 11,
  129079. };
  129080. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129081. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129082. };
  129083. static long _vq_quantmap__44c3_s_p5_0[] = {
  129084. 7, 5, 3, 1, 0, 2, 4, 6,
  129085. 8,
  129086. };
  129087. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129088. _vq_quantthresh__44c3_s_p5_0,
  129089. _vq_quantmap__44c3_s_p5_0,
  129090. 9,
  129091. 9
  129092. };
  129093. static static_codebook _44c3_s_p5_0 = {
  129094. 2, 81,
  129095. _vq_lengthlist__44c3_s_p5_0,
  129096. 1, -531628032, 1611661312, 4, 0,
  129097. _vq_quantlist__44c3_s_p5_0,
  129098. NULL,
  129099. &_vq_auxt__44c3_s_p5_0,
  129100. NULL,
  129101. 0
  129102. };
  129103. static long _vq_quantlist__44c3_s_p6_0[] = {
  129104. 8,
  129105. 7,
  129106. 9,
  129107. 6,
  129108. 10,
  129109. 5,
  129110. 11,
  129111. 4,
  129112. 12,
  129113. 3,
  129114. 13,
  129115. 2,
  129116. 14,
  129117. 1,
  129118. 15,
  129119. 0,
  129120. 16,
  129121. };
  129122. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129123. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129124. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129125. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129126. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129127. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129128. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129129. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129130. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129131. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129132. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129133. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129134. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129135. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129136. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129137. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129138. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129139. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129141. 13,
  129142. };
  129143. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129144. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129145. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129146. };
  129147. static long _vq_quantmap__44c3_s_p6_0[] = {
  129148. 15, 13, 11, 9, 7, 5, 3, 1,
  129149. 0, 2, 4, 6, 8, 10, 12, 14,
  129150. 16,
  129151. };
  129152. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129153. _vq_quantthresh__44c3_s_p6_0,
  129154. _vq_quantmap__44c3_s_p6_0,
  129155. 17,
  129156. 17
  129157. };
  129158. static static_codebook _44c3_s_p6_0 = {
  129159. 2, 289,
  129160. _vq_lengthlist__44c3_s_p6_0,
  129161. 1, -529530880, 1611661312, 5, 0,
  129162. _vq_quantlist__44c3_s_p6_0,
  129163. NULL,
  129164. &_vq_auxt__44c3_s_p6_0,
  129165. NULL,
  129166. 0
  129167. };
  129168. static long _vq_quantlist__44c3_s_p7_0[] = {
  129169. 1,
  129170. 0,
  129171. 2,
  129172. };
  129173. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129174. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129175. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129176. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129177. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129178. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129179. 10,
  129180. };
  129181. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129182. -5.5, 5.5,
  129183. };
  129184. static long _vq_quantmap__44c3_s_p7_0[] = {
  129185. 1, 0, 2,
  129186. };
  129187. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129188. _vq_quantthresh__44c3_s_p7_0,
  129189. _vq_quantmap__44c3_s_p7_0,
  129190. 3,
  129191. 3
  129192. };
  129193. static static_codebook _44c3_s_p7_0 = {
  129194. 4, 81,
  129195. _vq_lengthlist__44c3_s_p7_0,
  129196. 1, -529137664, 1618345984, 2, 0,
  129197. _vq_quantlist__44c3_s_p7_0,
  129198. NULL,
  129199. &_vq_auxt__44c3_s_p7_0,
  129200. NULL,
  129201. 0
  129202. };
  129203. static long _vq_quantlist__44c3_s_p7_1[] = {
  129204. 5,
  129205. 4,
  129206. 6,
  129207. 3,
  129208. 7,
  129209. 2,
  129210. 8,
  129211. 1,
  129212. 9,
  129213. 0,
  129214. 10,
  129215. };
  129216. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129217. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129218. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129219. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129220. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129221. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129222. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129223. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129224. 10,10,10, 8, 8, 8, 8, 8, 8,
  129225. };
  129226. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129227. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129228. 3.5, 4.5,
  129229. };
  129230. static long _vq_quantmap__44c3_s_p7_1[] = {
  129231. 9, 7, 5, 3, 1, 0, 2, 4,
  129232. 6, 8, 10,
  129233. };
  129234. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129235. _vq_quantthresh__44c3_s_p7_1,
  129236. _vq_quantmap__44c3_s_p7_1,
  129237. 11,
  129238. 11
  129239. };
  129240. static static_codebook _44c3_s_p7_1 = {
  129241. 2, 121,
  129242. _vq_lengthlist__44c3_s_p7_1,
  129243. 1, -531365888, 1611661312, 4, 0,
  129244. _vq_quantlist__44c3_s_p7_1,
  129245. NULL,
  129246. &_vq_auxt__44c3_s_p7_1,
  129247. NULL,
  129248. 0
  129249. };
  129250. static long _vq_quantlist__44c3_s_p8_0[] = {
  129251. 6,
  129252. 5,
  129253. 7,
  129254. 4,
  129255. 8,
  129256. 3,
  129257. 9,
  129258. 2,
  129259. 10,
  129260. 1,
  129261. 11,
  129262. 0,
  129263. 12,
  129264. };
  129265. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129266. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129267. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129268. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129269. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129270. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129271. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129272. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129273. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129274. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129275. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129276. 0,13,13,12,12,13,12,14,13,
  129277. };
  129278. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129279. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129280. 12.5, 17.5, 22.5, 27.5,
  129281. };
  129282. static long _vq_quantmap__44c3_s_p8_0[] = {
  129283. 11, 9, 7, 5, 3, 1, 0, 2,
  129284. 4, 6, 8, 10, 12,
  129285. };
  129286. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129287. _vq_quantthresh__44c3_s_p8_0,
  129288. _vq_quantmap__44c3_s_p8_0,
  129289. 13,
  129290. 13
  129291. };
  129292. static static_codebook _44c3_s_p8_0 = {
  129293. 2, 169,
  129294. _vq_lengthlist__44c3_s_p8_0,
  129295. 1, -526516224, 1616117760, 4, 0,
  129296. _vq_quantlist__44c3_s_p8_0,
  129297. NULL,
  129298. &_vq_auxt__44c3_s_p8_0,
  129299. NULL,
  129300. 0
  129301. };
  129302. static long _vq_quantlist__44c3_s_p8_1[] = {
  129303. 2,
  129304. 1,
  129305. 3,
  129306. 0,
  129307. 4,
  129308. };
  129309. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129310. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129311. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129312. };
  129313. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129314. -1.5, -0.5, 0.5, 1.5,
  129315. };
  129316. static long _vq_quantmap__44c3_s_p8_1[] = {
  129317. 3, 1, 0, 2, 4,
  129318. };
  129319. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129320. _vq_quantthresh__44c3_s_p8_1,
  129321. _vq_quantmap__44c3_s_p8_1,
  129322. 5,
  129323. 5
  129324. };
  129325. static static_codebook _44c3_s_p8_1 = {
  129326. 2, 25,
  129327. _vq_lengthlist__44c3_s_p8_1,
  129328. 1, -533725184, 1611661312, 3, 0,
  129329. _vq_quantlist__44c3_s_p8_1,
  129330. NULL,
  129331. &_vq_auxt__44c3_s_p8_1,
  129332. NULL,
  129333. 0
  129334. };
  129335. static long _vq_quantlist__44c3_s_p9_0[] = {
  129336. 6,
  129337. 5,
  129338. 7,
  129339. 4,
  129340. 8,
  129341. 3,
  129342. 9,
  129343. 2,
  129344. 10,
  129345. 1,
  129346. 11,
  129347. 0,
  129348. 12,
  129349. };
  129350. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129351. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129352. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129353. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129354. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129355. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129356. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129357. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129358. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129359. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129361. 11,11,11,11,11,11,11,11,11,
  129362. };
  129363. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129364. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129365. 637.5, 892.5, 1147.5, 1402.5,
  129366. };
  129367. static long _vq_quantmap__44c3_s_p9_0[] = {
  129368. 11, 9, 7, 5, 3, 1, 0, 2,
  129369. 4, 6, 8, 10, 12,
  129370. };
  129371. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129372. _vq_quantthresh__44c3_s_p9_0,
  129373. _vq_quantmap__44c3_s_p9_0,
  129374. 13,
  129375. 13
  129376. };
  129377. static static_codebook _44c3_s_p9_0 = {
  129378. 2, 169,
  129379. _vq_lengthlist__44c3_s_p9_0,
  129380. 1, -514332672, 1627381760, 4, 0,
  129381. _vq_quantlist__44c3_s_p9_0,
  129382. NULL,
  129383. &_vq_auxt__44c3_s_p9_0,
  129384. NULL,
  129385. 0
  129386. };
  129387. static long _vq_quantlist__44c3_s_p9_1[] = {
  129388. 7,
  129389. 6,
  129390. 8,
  129391. 5,
  129392. 9,
  129393. 4,
  129394. 10,
  129395. 3,
  129396. 11,
  129397. 2,
  129398. 12,
  129399. 1,
  129400. 13,
  129401. 0,
  129402. 14,
  129403. };
  129404. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129405. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129406. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129407. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129408. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129409. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129410. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129411. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129412. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129413. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129414. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129415. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129416. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129417. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129418. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129419. 15,
  129420. };
  129421. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129422. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129423. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129424. };
  129425. static long _vq_quantmap__44c3_s_p9_1[] = {
  129426. 13, 11, 9, 7, 5, 3, 1, 0,
  129427. 2, 4, 6, 8, 10, 12, 14,
  129428. };
  129429. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129430. _vq_quantthresh__44c3_s_p9_1,
  129431. _vq_quantmap__44c3_s_p9_1,
  129432. 15,
  129433. 15
  129434. };
  129435. static static_codebook _44c3_s_p9_1 = {
  129436. 2, 225,
  129437. _vq_lengthlist__44c3_s_p9_1,
  129438. 1, -522338304, 1620115456, 4, 0,
  129439. _vq_quantlist__44c3_s_p9_1,
  129440. NULL,
  129441. &_vq_auxt__44c3_s_p9_1,
  129442. NULL,
  129443. 0
  129444. };
  129445. static long _vq_quantlist__44c3_s_p9_2[] = {
  129446. 8,
  129447. 7,
  129448. 9,
  129449. 6,
  129450. 10,
  129451. 5,
  129452. 11,
  129453. 4,
  129454. 12,
  129455. 3,
  129456. 13,
  129457. 2,
  129458. 14,
  129459. 1,
  129460. 15,
  129461. 0,
  129462. 16,
  129463. };
  129464. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129465. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129466. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129467. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129468. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129469. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129470. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129471. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129472. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129473. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129474. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129475. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129476. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129477. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129478. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129479. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129480. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129481. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129482. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129483. 10,
  129484. };
  129485. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129486. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129487. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129488. };
  129489. static long _vq_quantmap__44c3_s_p9_2[] = {
  129490. 15, 13, 11, 9, 7, 5, 3, 1,
  129491. 0, 2, 4, 6, 8, 10, 12, 14,
  129492. 16,
  129493. };
  129494. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129495. _vq_quantthresh__44c3_s_p9_2,
  129496. _vq_quantmap__44c3_s_p9_2,
  129497. 17,
  129498. 17
  129499. };
  129500. static static_codebook _44c3_s_p9_2 = {
  129501. 2, 289,
  129502. _vq_lengthlist__44c3_s_p9_2,
  129503. 1, -529530880, 1611661312, 5, 0,
  129504. _vq_quantlist__44c3_s_p9_2,
  129505. NULL,
  129506. &_vq_auxt__44c3_s_p9_2,
  129507. NULL,
  129508. 0
  129509. };
  129510. static long _huff_lengthlist__44c3_s_short[] = {
  129511. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129512. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129513. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129514. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129515. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129516. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129517. 6, 8, 9,11,
  129518. };
  129519. static static_codebook _huff_book__44c3_s_short = {
  129520. 2, 100,
  129521. _huff_lengthlist__44c3_s_short,
  129522. 0, 0, 0, 0, 0,
  129523. NULL,
  129524. NULL,
  129525. NULL,
  129526. NULL,
  129527. 0
  129528. };
  129529. static long _huff_lengthlist__44c4_s_long[] = {
  129530. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129531. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129532. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129533. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129534. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129535. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129536. 9, 8, 7, 7,
  129537. };
  129538. static static_codebook _huff_book__44c4_s_long = {
  129539. 2, 100,
  129540. _huff_lengthlist__44c4_s_long,
  129541. 0, 0, 0, 0, 0,
  129542. NULL,
  129543. NULL,
  129544. NULL,
  129545. NULL,
  129546. 0
  129547. };
  129548. static long _vq_quantlist__44c4_s_p1_0[] = {
  129549. 1,
  129550. 0,
  129551. 2,
  129552. };
  129553. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129554. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129555. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129560. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129565. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129600. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129605. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129610. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129646. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129651. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129656. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0,
  129965. };
  129966. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129967. -0.5, 0.5,
  129968. };
  129969. static long _vq_quantmap__44c4_s_p1_0[] = {
  129970. 1, 0, 2,
  129971. };
  129972. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129973. _vq_quantthresh__44c4_s_p1_0,
  129974. _vq_quantmap__44c4_s_p1_0,
  129975. 3,
  129976. 3
  129977. };
  129978. static static_codebook _44c4_s_p1_0 = {
  129979. 8, 6561,
  129980. _vq_lengthlist__44c4_s_p1_0,
  129981. 1, -535822336, 1611661312, 2, 0,
  129982. _vq_quantlist__44c4_s_p1_0,
  129983. NULL,
  129984. &_vq_auxt__44c4_s_p1_0,
  129985. NULL,
  129986. 0
  129987. };
  129988. static long _vq_quantlist__44c4_s_p2_0[] = {
  129989. 2,
  129990. 1,
  129991. 3,
  129992. 0,
  129993. 4,
  129994. };
  129995. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129996. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129997. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129998. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129999. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130000. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130006. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130007. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130008. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130014. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130015. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130022. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130023. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 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,
  130036. };
  130037. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130038. -1.5, -0.5, 0.5, 1.5,
  130039. };
  130040. static long _vq_quantmap__44c4_s_p2_0[] = {
  130041. 3, 1, 0, 2, 4,
  130042. };
  130043. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130044. _vq_quantthresh__44c4_s_p2_0,
  130045. _vq_quantmap__44c4_s_p2_0,
  130046. 5,
  130047. 5
  130048. };
  130049. static static_codebook _44c4_s_p2_0 = {
  130050. 4, 625,
  130051. _vq_lengthlist__44c4_s_p2_0,
  130052. 1, -533725184, 1611661312, 3, 0,
  130053. _vq_quantlist__44c4_s_p2_0,
  130054. NULL,
  130055. &_vq_auxt__44c4_s_p2_0,
  130056. NULL,
  130057. 0
  130058. };
  130059. static long _vq_quantlist__44c4_s_p3_0[] = {
  130060. 2,
  130061. 1,
  130062. 3,
  130063. 0,
  130064. 4,
  130065. };
  130066. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130067. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  130107. };
  130108. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130109. -1.5, -0.5, 0.5, 1.5,
  130110. };
  130111. static long _vq_quantmap__44c4_s_p3_0[] = {
  130112. 3, 1, 0, 2, 4,
  130113. };
  130114. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130115. _vq_quantthresh__44c4_s_p3_0,
  130116. _vq_quantmap__44c4_s_p3_0,
  130117. 5,
  130118. 5
  130119. };
  130120. static static_codebook _44c4_s_p3_0 = {
  130121. 4, 625,
  130122. _vq_lengthlist__44c4_s_p3_0,
  130123. 1, -533725184, 1611661312, 3, 0,
  130124. _vq_quantlist__44c4_s_p3_0,
  130125. NULL,
  130126. &_vq_auxt__44c4_s_p3_0,
  130127. NULL,
  130128. 0
  130129. };
  130130. static long _vq_quantlist__44c4_s_p4_0[] = {
  130131. 4,
  130132. 3,
  130133. 5,
  130134. 2,
  130135. 6,
  130136. 1,
  130137. 7,
  130138. 0,
  130139. 8,
  130140. };
  130141. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130142. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130143. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130144. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130145. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130146. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0,
  130148. };
  130149. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130150. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130151. };
  130152. static long _vq_quantmap__44c4_s_p4_0[] = {
  130153. 7, 5, 3, 1, 0, 2, 4, 6,
  130154. 8,
  130155. };
  130156. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130157. _vq_quantthresh__44c4_s_p4_0,
  130158. _vq_quantmap__44c4_s_p4_0,
  130159. 9,
  130160. 9
  130161. };
  130162. static static_codebook _44c4_s_p4_0 = {
  130163. 2, 81,
  130164. _vq_lengthlist__44c4_s_p4_0,
  130165. 1, -531628032, 1611661312, 4, 0,
  130166. _vq_quantlist__44c4_s_p4_0,
  130167. NULL,
  130168. &_vq_auxt__44c4_s_p4_0,
  130169. NULL,
  130170. 0
  130171. };
  130172. static long _vq_quantlist__44c4_s_p5_0[] = {
  130173. 4,
  130174. 3,
  130175. 5,
  130176. 2,
  130177. 6,
  130178. 1,
  130179. 7,
  130180. 0,
  130181. 8,
  130182. };
  130183. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130184. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130185. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130186. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130187. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130188. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130189. 10,
  130190. };
  130191. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130192. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130193. };
  130194. static long _vq_quantmap__44c4_s_p5_0[] = {
  130195. 7, 5, 3, 1, 0, 2, 4, 6,
  130196. 8,
  130197. };
  130198. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130199. _vq_quantthresh__44c4_s_p5_0,
  130200. _vq_quantmap__44c4_s_p5_0,
  130201. 9,
  130202. 9
  130203. };
  130204. static static_codebook _44c4_s_p5_0 = {
  130205. 2, 81,
  130206. _vq_lengthlist__44c4_s_p5_0,
  130207. 1, -531628032, 1611661312, 4, 0,
  130208. _vq_quantlist__44c4_s_p5_0,
  130209. NULL,
  130210. &_vq_auxt__44c4_s_p5_0,
  130211. NULL,
  130212. 0
  130213. };
  130214. static long _vq_quantlist__44c4_s_p6_0[] = {
  130215. 8,
  130216. 7,
  130217. 9,
  130218. 6,
  130219. 10,
  130220. 5,
  130221. 11,
  130222. 4,
  130223. 12,
  130224. 3,
  130225. 13,
  130226. 2,
  130227. 14,
  130228. 1,
  130229. 15,
  130230. 0,
  130231. 16,
  130232. };
  130233. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130234. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130235. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130236. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130237. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130238. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130239. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130240. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130241. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130242. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130243. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130244. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130245. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130246. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130247. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130248. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130249. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130250. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130252. 13,
  130253. };
  130254. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130255. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130256. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130257. };
  130258. static long _vq_quantmap__44c4_s_p6_0[] = {
  130259. 15, 13, 11, 9, 7, 5, 3, 1,
  130260. 0, 2, 4, 6, 8, 10, 12, 14,
  130261. 16,
  130262. };
  130263. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130264. _vq_quantthresh__44c4_s_p6_0,
  130265. _vq_quantmap__44c4_s_p6_0,
  130266. 17,
  130267. 17
  130268. };
  130269. static static_codebook _44c4_s_p6_0 = {
  130270. 2, 289,
  130271. _vq_lengthlist__44c4_s_p6_0,
  130272. 1, -529530880, 1611661312, 5, 0,
  130273. _vq_quantlist__44c4_s_p6_0,
  130274. NULL,
  130275. &_vq_auxt__44c4_s_p6_0,
  130276. NULL,
  130277. 0
  130278. };
  130279. static long _vq_quantlist__44c4_s_p7_0[] = {
  130280. 1,
  130281. 0,
  130282. 2,
  130283. };
  130284. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130285. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130286. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130287. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130288. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130289. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130290. 10,
  130291. };
  130292. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130293. -5.5, 5.5,
  130294. };
  130295. static long _vq_quantmap__44c4_s_p7_0[] = {
  130296. 1, 0, 2,
  130297. };
  130298. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130299. _vq_quantthresh__44c4_s_p7_0,
  130300. _vq_quantmap__44c4_s_p7_0,
  130301. 3,
  130302. 3
  130303. };
  130304. static static_codebook _44c4_s_p7_0 = {
  130305. 4, 81,
  130306. _vq_lengthlist__44c4_s_p7_0,
  130307. 1, -529137664, 1618345984, 2, 0,
  130308. _vq_quantlist__44c4_s_p7_0,
  130309. NULL,
  130310. &_vq_auxt__44c4_s_p7_0,
  130311. NULL,
  130312. 0
  130313. };
  130314. static long _vq_quantlist__44c4_s_p7_1[] = {
  130315. 5,
  130316. 4,
  130317. 6,
  130318. 3,
  130319. 7,
  130320. 2,
  130321. 8,
  130322. 1,
  130323. 9,
  130324. 0,
  130325. 10,
  130326. };
  130327. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130328. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130329. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130330. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130331. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130332. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130333. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130334. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130335. 10,10,10, 8, 8, 8, 8, 9, 9,
  130336. };
  130337. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130338. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130339. 3.5, 4.5,
  130340. };
  130341. static long _vq_quantmap__44c4_s_p7_1[] = {
  130342. 9, 7, 5, 3, 1, 0, 2, 4,
  130343. 6, 8, 10,
  130344. };
  130345. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130346. _vq_quantthresh__44c4_s_p7_1,
  130347. _vq_quantmap__44c4_s_p7_1,
  130348. 11,
  130349. 11
  130350. };
  130351. static static_codebook _44c4_s_p7_1 = {
  130352. 2, 121,
  130353. _vq_lengthlist__44c4_s_p7_1,
  130354. 1, -531365888, 1611661312, 4, 0,
  130355. _vq_quantlist__44c4_s_p7_1,
  130356. NULL,
  130357. &_vq_auxt__44c4_s_p7_1,
  130358. NULL,
  130359. 0
  130360. };
  130361. static long _vq_quantlist__44c4_s_p8_0[] = {
  130362. 6,
  130363. 5,
  130364. 7,
  130365. 4,
  130366. 8,
  130367. 3,
  130368. 9,
  130369. 2,
  130370. 10,
  130371. 1,
  130372. 11,
  130373. 0,
  130374. 12,
  130375. };
  130376. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130377. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130378. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130379. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130380. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130381. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130382. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130383. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130384. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130385. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130386. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130387. 0,13,12,12,12,12,12,13,13,
  130388. };
  130389. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130390. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130391. 12.5, 17.5, 22.5, 27.5,
  130392. };
  130393. static long _vq_quantmap__44c4_s_p8_0[] = {
  130394. 11, 9, 7, 5, 3, 1, 0, 2,
  130395. 4, 6, 8, 10, 12,
  130396. };
  130397. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130398. _vq_quantthresh__44c4_s_p8_0,
  130399. _vq_quantmap__44c4_s_p8_0,
  130400. 13,
  130401. 13
  130402. };
  130403. static static_codebook _44c4_s_p8_0 = {
  130404. 2, 169,
  130405. _vq_lengthlist__44c4_s_p8_0,
  130406. 1, -526516224, 1616117760, 4, 0,
  130407. _vq_quantlist__44c4_s_p8_0,
  130408. NULL,
  130409. &_vq_auxt__44c4_s_p8_0,
  130410. NULL,
  130411. 0
  130412. };
  130413. static long _vq_quantlist__44c4_s_p8_1[] = {
  130414. 2,
  130415. 1,
  130416. 3,
  130417. 0,
  130418. 4,
  130419. };
  130420. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130421. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130422. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130423. };
  130424. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130425. -1.5, -0.5, 0.5, 1.5,
  130426. };
  130427. static long _vq_quantmap__44c4_s_p8_1[] = {
  130428. 3, 1, 0, 2, 4,
  130429. };
  130430. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130431. _vq_quantthresh__44c4_s_p8_1,
  130432. _vq_quantmap__44c4_s_p8_1,
  130433. 5,
  130434. 5
  130435. };
  130436. static static_codebook _44c4_s_p8_1 = {
  130437. 2, 25,
  130438. _vq_lengthlist__44c4_s_p8_1,
  130439. 1, -533725184, 1611661312, 3, 0,
  130440. _vq_quantlist__44c4_s_p8_1,
  130441. NULL,
  130442. &_vq_auxt__44c4_s_p8_1,
  130443. NULL,
  130444. 0
  130445. };
  130446. static long _vq_quantlist__44c4_s_p9_0[] = {
  130447. 6,
  130448. 5,
  130449. 7,
  130450. 4,
  130451. 8,
  130452. 3,
  130453. 9,
  130454. 2,
  130455. 10,
  130456. 1,
  130457. 11,
  130458. 0,
  130459. 12,
  130460. };
  130461. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130462. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130463. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130464. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130465. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130466. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130467. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130468. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130469. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130470. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130471. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130472. 12,12,12,12,12,12,12,12,12,
  130473. };
  130474. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130475. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130476. 787.5, 1102.5, 1417.5, 1732.5,
  130477. };
  130478. static long _vq_quantmap__44c4_s_p9_0[] = {
  130479. 11, 9, 7, 5, 3, 1, 0, 2,
  130480. 4, 6, 8, 10, 12,
  130481. };
  130482. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130483. _vq_quantthresh__44c4_s_p9_0,
  130484. _vq_quantmap__44c4_s_p9_0,
  130485. 13,
  130486. 13
  130487. };
  130488. static static_codebook _44c4_s_p9_0 = {
  130489. 2, 169,
  130490. _vq_lengthlist__44c4_s_p9_0,
  130491. 1, -513964032, 1628680192, 4, 0,
  130492. _vq_quantlist__44c4_s_p9_0,
  130493. NULL,
  130494. &_vq_auxt__44c4_s_p9_0,
  130495. NULL,
  130496. 0
  130497. };
  130498. static long _vq_quantlist__44c4_s_p9_1[] = {
  130499. 7,
  130500. 6,
  130501. 8,
  130502. 5,
  130503. 9,
  130504. 4,
  130505. 10,
  130506. 3,
  130507. 11,
  130508. 2,
  130509. 12,
  130510. 1,
  130511. 13,
  130512. 0,
  130513. 14,
  130514. };
  130515. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130516. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130517. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130518. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130519. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130520. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130521. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130522. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130523. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130524. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130525. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130526. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130527. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130528. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130529. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130530. 15,
  130531. };
  130532. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130533. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130534. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130535. };
  130536. static long _vq_quantmap__44c4_s_p9_1[] = {
  130537. 13, 11, 9, 7, 5, 3, 1, 0,
  130538. 2, 4, 6, 8, 10, 12, 14,
  130539. };
  130540. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130541. _vq_quantthresh__44c4_s_p9_1,
  130542. _vq_quantmap__44c4_s_p9_1,
  130543. 15,
  130544. 15
  130545. };
  130546. static static_codebook _44c4_s_p9_1 = {
  130547. 2, 225,
  130548. _vq_lengthlist__44c4_s_p9_1,
  130549. 1, -520986624, 1620377600, 4, 0,
  130550. _vq_quantlist__44c4_s_p9_1,
  130551. NULL,
  130552. &_vq_auxt__44c4_s_p9_1,
  130553. NULL,
  130554. 0
  130555. };
  130556. static long _vq_quantlist__44c4_s_p9_2[] = {
  130557. 10,
  130558. 9,
  130559. 11,
  130560. 8,
  130561. 12,
  130562. 7,
  130563. 13,
  130564. 6,
  130565. 14,
  130566. 5,
  130567. 15,
  130568. 4,
  130569. 16,
  130570. 3,
  130571. 17,
  130572. 2,
  130573. 18,
  130574. 1,
  130575. 19,
  130576. 0,
  130577. 20,
  130578. };
  130579. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130580. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130581. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130582. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130583. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130584. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130585. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130586. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130587. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130588. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130589. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130590. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130591. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130592. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130593. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130594. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130595. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130596. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130597. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130598. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130599. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130600. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130601. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130602. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130603. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130604. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130605. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130606. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130607. 10,10,10,10,10,10,10,10,10,
  130608. };
  130609. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130610. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130611. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130612. 6.5, 7.5, 8.5, 9.5,
  130613. };
  130614. static long _vq_quantmap__44c4_s_p9_2[] = {
  130615. 19, 17, 15, 13, 11, 9, 7, 5,
  130616. 3, 1, 0, 2, 4, 6, 8, 10,
  130617. 12, 14, 16, 18, 20,
  130618. };
  130619. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130620. _vq_quantthresh__44c4_s_p9_2,
  130621. _vq_quantmap__44c4_s_p9_2,
  130622. 21,
  130623. 21
  130624. };
  130625. static static_codebook _44c4_s_p9_2 = {
  130626. 2, 441,
  130627. _vq_lengthlist__44c4_s_p9_2,
  130628. 1, -529268736, 1611661312, 5, 0,
  130629. _vq_quantlist__44c4_s_p9_2,
  130630. NULL,
  130631. &_vq_auxt__44c4_s_p9_2,
  130632. NULL,
  130633. 0
  130634. };
  130635. static long _huff_lengthlist__44c4_s_short[] = {
  130636. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130637. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130638. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130639. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130640. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130641. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130642. 7, 9,12,17,
  130643. };
  130644. static static_codebook _huff_book__44c4_s_short = {
  130645. 2, 100,
  130646. _huff_lengthlist__44c4_s_short,
  130647. 0, 0, 0, 0, 0,
  130648. NULL,
  130649. NULL,
  130650. NULL,
  130651. NULL,
  130652. 0
  130653. };
  130654. static long _huff_lengthlist__44c5_s_long[] = {
  130655. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130656. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130657. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130658. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130659. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130660. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130661. 9, 8, 7, 7,
  130662. };
  130663. static static_codebook _huff_book__44c5_s_long = {
  130664. 2, 100,
  130665. _huff_lengthlist__44c5_s_long,
  130666. 0, 0, 0, 0, 0,
  130667. NULL,
  130668. NULL,
  130669. NULL,
  130670. NULL,
  130671. 0
  130672. };
  130673. static long _vq_quantlist__44c5_s_p1_0[] = {
  130674. 1,
  130675. 0,
  130676. 2,
  130677. };
  130678. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130679. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130680. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130685. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130690. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130725. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130730. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130735. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130771. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130776. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130781. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0,
  131090. };
  131091. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131092. -0.5, 0.5,
  131093. };
  131094. static long _vq_quantmap__44c5_s_p1_0[] = {
  131095. 1, 0, 2,
  131096. };
  131097. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131098. _vq_quantthresh__44c5_s_p1_0,
  131099. _vq_quantmap__44c5_s_p1_0,
  131100. 3,
  131101. 3
  131102. };
  131103. static static_codebook _44c5_s_p1_0 = {
  131104. 8, 6561,
  131105. _vq_lengthlist__44c5_s_p1_0,
  131106. 1, -535822336, 1611661312, 2, 0,
  131107. _vq_quantlist__44c5_s_p1_0,
  131108. NULL,
  131109. &_vq_auxt__44c5_s_p1_0,
  131110. NULL,
  131111. 0
  131112. };
  131113. static long _vq_quantlist__44c5_s_p2_0[] = {
  131114. 2,
  131115. 1,
  131116. 3,
  131117. 0,
  131118. 4,
  131119. };
  131120. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131121. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131122. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131123. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131124. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131125. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131131. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131132. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131133. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131139. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131140. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131147. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131148. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0,
  131161. };
  131162. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131163. -1.5, -0.5, 0.5, 1.5,
  131164. };
  131165. static long _vq_quantmap__44c5_s_p2_0[] = {
  131166. 3, 1, 0, 2, 4,
  131167. };
  131168. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131169. _vq_quantthresh__44c5_s_p2_0,
  131170. _vq_quantmap__44c5_s_p2_0,
  131171. 5,
  131172. 5
  131173. };
  131174. static static_codebook _44c5_s_p2_0 = {
  131175. 4, 625,
  131176. _vq_lengthlist__44c5_s_p2_0,
  131177. 1, -533725184, 1611661312, 3, 0,
  131178. _vq_quantlist__44c5_s_p2_0,
  131179. NULL,
  131180. &_vq_auxt__44c5_s_p2_0,
  131181. NULL,
  131182. 0
  131183. };
  131184. static long _vq_quantlist__44c5_s_p3_0[] = {
  131185. 2,
  131186. 1,
  131187. 3,
  131188. 0,
  131189. 4,
  131190. };
  131191. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131192. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0,
  131232. };
  131233. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131234. -1.5, -0.5, 0.5, 1.5,
  131235. };
  131236. static long _vq_quantmap__44c5_s_p3_0[] = {
  131237. 3, 1, 0, 2, 4,
  131238. };
  131239. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131240. _vq_quantthresh__44c5_s_p3_0,
  131241. _vq_quantmap__44c5_s_p3_0,
  131242. 5,
  131243. 5
  131244. };
  131245. static static_codebook _44c5_s_p3_0 = {
  131246. 4, 625,
  131247. _vq_lengthlist__44c5_s_p3_0,
  131248. 1, -533725184, 1611661312, 3, 0,
  131249. _vq_quantlist__44c5_s_p3_0,
  131250. NULL,
  131251. &_vq_auxt__44c5_s_p3_0,
  131252. NULL,
  131253. 0
  131254. };
  131255. static long _vq_quantlist__44c5_s_p4_0[] = {
  131256. 4,
  131257. 3,
  131258. 5,
  131259. 2,
  131260. 6,
  131261. 1,
  131262. 7,
  131263. 0,
  131264. 8,
  131265. };
  131266. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131267. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131268. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131269. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131270. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131271. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0,
  131273. };
  131274. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131275. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131276. };
  131277. static long _vq_quantmap__44c5_s_p4_0[] = {
  131278. 7, 5, 3, 1, 0, 2, 4, 6,
  131279. 8,
  131280. };
  131281. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131282. _vq_quantthresh__44c5_s_p4_0,
  131283. _vq_quantmap__44c5_s_p4_0,
  131284. 9,
  131285. 9
  131286. };
  131287. static static_codebook _44c5_s_p4_0 = {
  131288. 2, 81,
  131289. _vq_lengthlist__44c5_s_p4_0,
  131290. 1, -531628032, 1611661312, 4, 0,
  131291. _vq_quantlist__44c5_s_p4_0,
  131292. NULL,
  131293. &_vq_auxt__44c5_s_p4_0,
  131294. NULL,
  131295. 0
  131296. };
  131297. static long _vq_quantlist__44c5_s_p5_0[] = {
  131298. 4,
  131299. 3,
  131300. 5,
  131301. 2,
  131302. 6,
  131303. 1,
  131304. 7,
  131305. 0,
  131306. 8,
  131307. };
  131308. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131309. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131310. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131311. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131312. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131313. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131314. 10,
  131315. };
  131316. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131317. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131318. };
  131319. static long _vq_quantmap__44c5_s_p5_0[] = {
  131320. 7, 5, 3, 1, 0, 2, 4, 6,
  131321. 8,
  131322. };
  131323. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131324. _vq_quantthresh__44c5_s_p5_0,
  131325. _vq_quantmap__44c5_s_p5_0,
  131326. 9,
  131327. 9
  131328. };
  131329. static static_codebook _44c5_s_p5_0 = {
  131330. 2, 81,
  131331. _vq_lengthlist__44c5_s_p5_0,
  131332. 1, -531628032, 1611661312, 4, 0,
  131333. _vq_quantlist__44c5_s_p5_0,
  131334. NULL,
  131335. &_vq_auxt__44c5_s_p5_0,
  131336. NULL,
  131337. 0
  131338. };
  131339. static long _vq_quantlist__44c5_s_p6_0[] = {
  131340. 8,
  131341. 7,
  131342. 9,
  131343. 6,
  131344. 10,
  131345. 5,
  131346. 11,
  131347. 4,
  131348. 12,
  131349. 3,
  131350. 13,
  131351. 2,
  131352. 14,
  131353. 1,
  131354. 15,
  131355. 0,
  131356. 16,
  131357. };
  131358. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131359. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131360. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131361. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131362. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131363. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131364. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131365. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131366. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131367. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131368. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131369. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131370. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131371. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131372. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131373. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131374. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131375. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131377. 13,
  131378. };
  131379. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131380. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131381. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131382. };
  131383. static long _vq_quantmap__44c5_s_p6_0[] = {
  131384. 15, 13, 11, 9, 7, 5, 3, 1,
  131385. 0, 2, 4, 6, 8, 10, 12, 14,
  131386. 16,
  131387. };
  131388. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131389. _vq_quantthresh__44c5_s_p6_0,
  131390. _vq_quantmap__44c5_s_p6_0,
  131391. 17,
  131392. 17
  131393. };
  131394. static static_codebook _44c5_s_p6_0 = {
  131395. 2, 289,
  131396. _vq_lengthlist__44c5_s_p6_0,
  131397. 1, -529530880, 1611661312, 5, 0,
  131398. _vq_quantlist__44c5_s_p6_0,
  131399. NULL,
  131400. &_vq_auxt__44c5_s_p6_0,
  131401. NULL,
  131402. 0
  131403. };
  131404. static long _vq_quantlist__44c5_s_p7_0[] = {
  131405. 1,
  131406. 0,
  131407. 2,
  131408. };
  131409. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131410. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131411. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131412. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131413. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131414. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131415. 10,
  131416. };
  131417. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131418. -5.5, 5.5,
  131419. };
  131420. static long _vq_quantmap__44c5_s_p7_0[] = {
  131421. 1, 0, 2,
  131422. };
  131423. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131424. _vq_quantthresh__44c5_s_p7_0,
  131425. _vq_quantmap__44c5_s_p7_0,
  131426. 3,
  131427. 3
  131428. };
  131429. static static_codebook _44c5_s_p7_0 = {
  131430. 4, 81,
  131431. _vq_lengthlist__44c5_s_p7_0,
  131432. 1, -529137664, 1618345984, 2, 0,
  131433. _vq_quantlist__44c5_s_p7_0,
  131434. NULL,
  131435. &_vq_auxt__44c5_s_p7_0,
  131436. NULL,
  131437. 0
  131438. };
  131439. static long _vq_quantlist__44c5_s_p7_1[] = {
  131440. 5,
  131441. 4,
  131442. 6,
  131443. 3,
  131444. 7,
  131445. 2,
  131446. 8,
  131447. 1,
  131448. 9,
  131449. 0,
  131450. 10,
  131451. };
  131452. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131453. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131454. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131455. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131456. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131457. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131458. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131459. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131460. 10,10,10, 8, 8, 8, 8, 8, 8,
  131461. };
  131462. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131463. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131464. 3.5, 4.5,
  131465. };
  131466. static long _vq_quantmap__44c5_s_p7_1[] = {
  131467. 9, 7, 5, 3, 1, 0, 2, 4,
  131468. 6, 8, 10,
  131469. };
  131470. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131471. _vq_quantthresh__44c5_s_p7_1,
  131472. _vq_quantmap__44c5_s_p7_1,
  131473. 11,
  131474. 11
  131475. };
  131476. static static_codebook _44c5_s_p7_1 = {
  131477. 2, 121,
  131478. _vq_lengthlist__44c5_s_p7_1,
  131479. 1, -531365888, 1611661312, 4, 0,
  131480. _vq_quantlist__44c5_s_p7_1,
  131481. NULL,
  131482. &_vq_auxt__44c5_s_p7_1,
  131483. NULL,
  131484. 0
  131485. };
  131486. static long _vq_quantlist__44c5_s_p8_0[] = {
  131487. 6,
  131488. 5,
  131489. 7,
  131490. 4,
  131491. 8,
  131492. 3,
  131493. 9,
  131494. 2,
  131495. 10,
  131496. 1,
  131497. 11,
  131498. 0,
  131499. 12,
  131500. };
  131501. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131502. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131503. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131504. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131505. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131506. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131507. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131508. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131509. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131510. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131511. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131512. 0,12,12,12,12,12,12,13,13,
  131513. };
  131514. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131515. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131516. 12.5, 17.5, 22.5, 27.5,
  131517. };
  131518. static long _vq_quantmap__44c5_s_p8_0[] = {
  131519. 11, 9, 7, 5, 3, 1, 0, 2,
  131520. 4, 6, 8, 10, 12,
  131521. };
  131522. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131523. _vq_quantthresh__44c5_s_p8_0,
  131524. _vq_quantmap__44c5_s_p8_0,
  131525. 13,
  131526. 13
  131527. };
  131528. static static_codebook _44c5_s_p8_0 = {
  131529. 2, 169,
  131530. _vq_lengthlist__44c5_s_p8_0,
  131531. 1, -526516224, 1616117760, 4, 0,
  131532. _vq_quantlist__44c5_s_p8_0,
  131533. NULL,
  131534. &_vq_auxt__44c5_s_p8_0,
  131535. NULL,
  131536. 0
  131537. };
  131538. static long _vq_quantlist__44c5_s_p8_1[] = {
  131539. 2,
  131540. 1,
  131541. 3,
  131542. 0,
  131543. 4,
  131544. };
  131545. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131546. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131547. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131548. };
  131549. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131550. -1.5, -0.5, 0.5, 1.5,
  131551. };
  131552. static long _vq_quantmap__44c5_s_p8_1[] = {
  131553. 3, 1, 0, 2, 4,
  131554. };
  131555. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131556. _vq_quantthresh__44c5_s_p8_1,
  131557. _vq_quantmap__44c5_s_p8_1,
  131558. 5,
  131559. 5
  131560. };
  131561. static static_codebook _44c5_s_p8_1 = {
  131562. 2, 25,
  131563. _vq_lengthlist__44c5_s_p8_1,
  131564. 1, -533725184, 1611661312, 3, 0,
  131565. _vq_quantlist__44c5_s_p8_1,
  131566. NULL,
  131567. &_vq_auxt__44c5_s_p8_1,
  131568. NULL,
  131569. 0
  131570. };
  131571. static long _vq_quantlist__44c5_s_p9_0[] = {
  131572. 7,
  131573. 6,
  131574. 8,
  131575. 5,
  131576. 9,
  131577. 4,
  131578. 10,
  131579. 3,
  131580. 11,
  131581. 2,
  131582. 12,
  131583. 1,
  131584. 13,
  131585. 0,
  131586. 14,
  131587. };
  131588. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131589. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131590. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131591. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131592. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131593. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131594. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131595. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131596. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131597. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131598. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131599. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131600. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131601. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131602. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131603. 12,
  131604. };
  131605. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131606. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131607. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131608. };
  131609. static long _vq_quantmap__44c5_s_p9_0[] = {
  131610. 13, 11, 9, 7, 5, 3, 1, 0,
  131611. 2, 4, 6, 8, 10, 12, 14,
  131612. };
  131613. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131614. _vq_quantthresh__44c5_s_p9_0,
  131615. _vq_quantmap__44c5_s_p9_0,
  131616. 15,
  131617. 15
  131618. };
  131619. static static_codebook _44c5_s_p9_0 = {
  131620. 2, 225,
  131621. _vq_lengthlist__44c5_s_p9_0,
  131622. 1, -512522752, 1628852224, 4, 0,
  131623. _vq_quantlist__44c5_s_p9_0,
  131624. NULL,
  131625. &_vq_auxt__44c5_s_p9_0,
  131626. NULL,
  131627. 0
  131628. };
  131629. static long _vq_quantlist__44c5_s_p9_1[] = {
  131630. 8,
  131631. 7,
  131632. 9,
  131633. 6,
  131634. 10,
  131635. 5,
  131636. 11,
  131637. 4,
  131638. 12,
  131639. 3,
  131640. 13,
  131641. 2,
  131642. 14,
  131643. 1,
  131644. 15,
  131645. 0,
  131646. 16,
  131647. };
  131648. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131649. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131650. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131651. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131652. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131653. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131654. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131655. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131656. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131657. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131658. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131659. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131660. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131661. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131662. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131663. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131664. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131665. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131666. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131667. 15,
  131668. };
  131669. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131670. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131671. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131672. };
  131673. static long _vq_quantmap__44c5_s_p9_1[] = {
  131674. 15, 13, 11, 9, 7, 5, 3, 1,
  131675. 0, 2, 4, 6, 8, 10, 12, 14,
  131676. 16,
  131677. };
  131678. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131679. _vq_quantthresh__44c5_s_p9_1,
  131680. _vq_quantmap__44c5_s_p9_1,
  131681. 17,
  131682. 17
  131683. };
  131684. static static_codebook _44c5_s_p9_1 = {
  131685. 2, 289,
  131686. _vq_lengthlist__44c5_s_p9_1,
  131687. 1, -520814592, 1620377600, 5, 0,
  131688. _vq_quantlist__44c5_s_p9_1,
  131689. NULL,
  131690. &_vq_auxt__44c5_s_p9_1,
  131691. NULL,
  131692. 0
  131693. };
  131694. static long _vq_quantlist__44c5_s_p9_2[] = {
  131695. 10,
  131696. 9,
  131697. 11,
  131698. 8,
  131699. 12,
  131700. 7,
  131701. 13,
  131702. 6,
  131703. 14,
  131704. 5,
  131705. 15,
  131706. 4,
  131707. 16,
  131708. 3,
  131709. 17,
  131710. 2,
  131711. 18,
  131712. 1,
  131713. 19,
  131714. 0,
  131715. 20,
  131716. };
  131717. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131718. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131719. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131720. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131721. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131722. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131723. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131724. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131725. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131726. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131727. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131728. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131729. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131730. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131731. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131732. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131733. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131734. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131735. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131736. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131737. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131738. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131739. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131740. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131741. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131742. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131743. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131744. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131745. 10,10,10,10,10,10,10,10,10,
  131746. };
  131747. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131748. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131749. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131750. 6.5, 7.5, 8.5, 9.5,
  131751. };
  131752. static long _vq_quantmap__44c5_s_p9_2[] = {
  131753. 19, 17, 15, 13, 11, 9, 7, 5,
  131754. 3, 1, 0, 2, 4, 6, 8, 10,
  131755. 12, 14, 16, 18, 20,
  131756. };
  131757. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131758. _vq_quantthresh__44c5_s_p9_2,
  131759. _vq_quantmap__44c5_s_p9_2,
  131760. 21,
  131761. 21
  131762. };
  131763. static static_codebook _44c5_s_p9_2 = {
  131764. 2, 441,
  131765. _vq_lengthlist__44c5_s_p9_2,
  131766. 1, -529268736, 1611661312, 5, 0,
  131767. _vq_quantlist__44c5_s_p9_2,
  131768. NULL,
  131769. &_vq_auxt__44c5_s_p9_2,
  131770. NULL,
  131771. 0
  131772. };
  131773. static long _huff_lengthlist__44c5_s_short[] = {
  131774. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131775. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131776. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131777. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131778. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131779. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131780. 6, 8,11,16,
  131781. };
  131782. static static_codebook _huff_book__44c5_s_short = {
  131783. 2, 100,
  131784. _huff_lengthlist__44c5_s_short,
  131785. 0, 0, 0, 0, 0,
  131786. NULL,
  131787. NULL,
  131788. NULL,
  131789. NULL,
  131790. 0
  131791. };
  131792. static long _huff_lengthlist__44c6_s_long[] = {
  131793. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131794. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131795. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131796. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131797. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131798. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131799. 11,10,10,12,
  131800. };
  131801. static static_codebook _huff_book__44c6_s_long = {
  131802. 2, 100,
  131803. _huff_lengthlist__44c6_s_long,
  131804. 0, 0, 0, 0, 0,
  131805. NULL,
  131806. NULL,
  131807. NULL,
  131808. NULL,
  131809. 0
  131810. };
  131811. static long _vq_quantlist__44c6_s_p1_0[] = {
  131812. 1,
  131813. 0,
  131814. 2,
  131815. };
  131816. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131817. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131818. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131820. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131821. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131822. 8,
  131823. };
  131824. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131825. -0.5, 0.5,
  131826. };
  131827. static long _vq_quantmap__44c6_s_p1_0[] = {
  131828. 1, 0, 2,
  131829. };
  131830. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131831. _vq_quantthresh__44c6_s_p1_0,
  131832. _vq_quantmap__44c6_s_p1_0,
  131833. 3,
  131834. 3
  131835. };
  131836. static static_codebook _44c6_s_p1_0 = {
  131837. 4, 81,
  131838. _vq_lengthlist__44c6_s_p1_0,
  131839. 1, -535822336, 1611661312, 2, 0,
  131840. _vq_quantlist__44c6_s_p1_0,
  131841. NULL,
  131842. &_vq_auxt__44c6_s_p1_0,
  131843. NULL,
  131844. 0
  131845. };
  131846. static long _vq_quantlist__44c6_s_p2_0[] = {
  131847. 2,
  131848. 1,
  131849. 3,
  131850. 0,
  131851. 4,
  131852. };
  131853. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131854. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131855. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131856. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131857. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131858. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131859. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131860. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131861. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131864. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131865. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131866. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131867. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131868. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131869. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131872. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131873. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131874. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131875. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131876. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131877. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131879. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131880. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131881. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131882. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131883. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131884. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131885. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131890. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131891. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131892. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131893. 13,
  131894. };
  131895. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131896. -1.5, -0.5, 0.5, 1.5,
  131897. };
  131898. static long _vq_quantmap__44c6_s_p2_0[] = {
  131899. 3, 1, 0, 2, 4,
  131900. };
  131901. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131902. _vq_quantthresh__44c6_s_p2_0,
  131903. _vq_quantmap__44c6_s_p2_0,
  131904. 5,
  131905. 5
  131906. };
  131907. static static_codebook _44c6_s_p2_0 = {
  131908. 4, 625,
  131909. _vq_lengthlist__44c6_s_p2_0,
  131910. 1, -533725184, 1611661312, 3, 0,
  131911. _vq_quantlist__44c6_s_p2_0,
  131912. NULL,
  131913. &_vq_auxt__44c6_s_p2_0,
  131914. NULL,
  131915. 0
  131916. };
  131917. static long _vq_quantlist__44c6_s_p3_0[] = {
  131918. 4,
  131919. 3,
  131920. 5,
  131921. 2,
  131922. 6,
  131923. 1,
  131924. 7,
  131925. 0,
  131926. 8,
  131927. };
  131928. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131929. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131930. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131931. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131932. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0,
  131935. };
  131936. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131937. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131938. };
  131939. static long _vq_quantmap__44c6_s_p3_0[] = {
  131940. 7, 5, 3, 1, 0, 2, 4, 6,
  131941. 8,
  131942. };
  131943. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131944. _vq_quantthresh__44c6_s_p3_0,
  131945. _vq_quantmap__44c6_s_p3_0,
  131946. 9,
  131947. 9
  131948. };
  131949. static static_codebook _44c6_s_p3_0 = {
  131950. 2, 81,
  131951. _vq_lengthlist__44c6_s_p3_0,
  131952. 1, -531628032, 1611661312, 4, 0,
  131953. _vq_quantlist__44c6_s_p3_0,
  131954. NULL,
  131955. &_vq_auxt__44c6_s_p3_0,
  131956. NULL,
  131957. 0
  131958. };
  131959. static long _vq_quantlist__44c6_s_p4_0[] = {
  131960. 8,
  131961. 7,
  131962. 9,
  131963. 6,
  131964. 10,
  131965. 5,
  131966. 11,
  131967. 4,
  131968. 12,
  131969. 3,
  131970. 13,
  131971. 2,
  131972. 14,
  131973. 1,
  131974. 15,
  131975. 0,
  131976. 16,
  131977. };
  131978. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131979. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131980. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131981. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131982. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131983. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131984. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131985. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131986. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131987. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131988. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0,
  131998. };
  131999. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132000. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132001. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132002. };
  132003. static long _vq_quantmap__44c6_s_p4_0[] = {
  132004. 15, 13, 11, 9, 7, 5, 3, 1,
  132005. 0, 2, 4, 6, 8, 10, 12, 14,
  132006. 16,
  132007. };
  132008. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132009. _vq_quantthresh__44c6_s_p4_0,
  132010. _vq_quantmap__44c6_s_p4_0,
  132011. 17,
  132012. 17
  132013. };
  132014. static static_codebook _44c6_s_p4_0 = {
  132015. 2, 289,
  132016. _vq_lengthlist__44c6_s_p4_0,
  132017. 1, -529530880, 1611661312, 5, 0,
  132018. _vq_quantlist__44c6_s_p4_0,
  132019. NULL,
  132020. &_vq_auxt__44c6_s_p4_0,
  132021. NULL,
  132022. 0
  132023. };
  132024. static long _vq_quantlist__44c6_s_p5_0[] = {
  132025. 1,
  132026. 0,
  132027. 2,
  132028. };
  132029. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132030. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132031. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132032. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132033. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132034. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132035. 12,
  132036. };
  132037. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132038. -5.5, 5.5,
  132039. };
  132040. static long _vq_quantmap__44c6_s_p5_0[] = {
  132041. 1, 0, 2,
  132042. };
  132043. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132044. _vq_quantthresh__44c6_s_p5_0,
  132045. _vq_quantmap__44c6_s_p5_0,
  132046. 3,
  132047. 3
  132048. };
  132049. static static_codebook _44c6_s_p5_0 = {
  132050. 4, 81,
  132051. _vq_lengthlist__44c6_s_p5_0,
  132052. 1, -529137664, 1618345984, 2, 0,
  132053. _vq_quantlist__44c6_s_p5_0,
  132054. NULL,
  132055. &_vq_auxt__44c6_s_p5_0,
  132056. NULL,
  132057. 0
  132058. };
  132059. static long _vq_quantlist__44c6_s_p5_1[] = {
  132060. 5,
  132061. 4,
  132062. 6,
  132063. 3,
  132064. 7,
  132065. 2,
  132066. 8,
  132067. 1,
  132068. 9,
  132069. 0,
  132070. 10,
  132071. };
  132072. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132073. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132074. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132075. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132076. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132077. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132078. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132079. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132080. 11,10,10, 7, 7, 8, 8, 8, 8,
  132081. };
  132082. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132083. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132084. 3.5, 4.5,
  132085. };
  132086. static long _vq_quantmap__44c6_s_p5_1[] = {
  132087. 9, 7, 5, 3, 1, 0, 2, 4,
  132088. 6, 8, 10,
  132089. };
  132090. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132091. _vq_quantthresh__44c6_s_p5_1,
  132092. _vq_quantmap__44c6_s_p5_1,
  132093. 11,
  132094. 11
  132095. };
  132096. static static_codebook _44c6_s_p5_1 = {
  132097. 2, 121,
  132098. _vq_lengthlist__44c6_s_p5_1,
  132099. 1, -531365888, 1611661312, 4, 0,
  132100. _vq_quantlist__44c6_s_p5_1,
  132101. NULL,
  132102. &_vq_auxt__44c6_s_p5_1,
  132103. NULL,
  132104. 0
  132105. };
  132106. static long _vq_quantlist__44c6_s_p6_0[] = {
  132107. 6,
  132108. 5,
  132109. 7,
  132110. 4,
  132111. 8,
  132112. 3,
  132113. 9,
  132114. 2,
  132115. 10,
  132116. 1,
  132117. 11,
  132118. 0,
  132119. 12,
  132120. };
  132121. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132122. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132123. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132124. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132125. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132126. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132127. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. };
  132134. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132135. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132136. 12.5, 17.5, 22.5, 27.5,
  132137. };
  132138. static long _vq_quantmap__44c6_s_p6_0[] = {
  132139. 11, 9, 7, 5, 3, 1, 0, 2,
  132140. 4, 6, 8, 10, 12,
  132141. };
  132142. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132143. _vq_quantthresh__44c6_s_p6_0,
  132144. _vq_quantmap__44c6_s_p6_0,
  132145. 13,
  132146. 13
  132147. };
  132148. static static_codebook _44c6_s_p6_0 = {
  132149. 2, 169,
  132150. _vq_lengthlist__44c6_s_p6_0,
  132151. 1, -526516224, 1616117760, 4, 0,
  132152. _vq_quantlist__44c6_s_p6_0,
  132153. NULL,
  132154. &_vq_auxt__44c6_s_p6_0,
  132155. NULL,
  132156. 0
  132157. };
  132158. static long _vq_quantlist__44c6_s_p6_1[] = {
  132159. 2,
  132160. 1,
  132161. 3,
  132162. 0,
  132163. 4,
  132164. };
  132165. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132166. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132167. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132168. };
  132169. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132170. -1.5, -0.5, 0.5, 1.5,
  132171. };
  132172. static long _vq_quantmap__44c6_s_p6_1[] = {
  132173. 3, 1, 0, 2, 4,
  132174. };
  132175. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132176. _vq_quantthresh__44c6_s_p6_1,
  132177. _vq_quantmap__44c6_s_p6_1,
  132178. 5,
  132179. 5
  132180. };
  132181. static static_codebook _44c6_s_p6_1 = {
  132182. 2, 25,
  132183. _vq_lengthlist__44c6_s_p6_1,
  132184. 1, -533725184, 1611661312, 3, 0,
  132185. _vq_quantlist__44c6_s_p6_1,
  132186. NULL,
  132187. &_vq_auxt__44c6_s_p6_1,
  132188. NULL,
  132189. 0
  132190. };
  132191. static long _vq_quantlist__44c6_s_p7_0[] = {
  132192. 6,
  132193. 5,
  132194. 7,
  132195. 4,
  132196. 8,
  132197. 3,
  132198. 9,
  132199. 2,
  132200. 10,
  132201. 1,
  132202. 11,
  132203. 0,
  132204. 12,
  132205. };
  132206. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132207. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132208. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132209. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132210. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132211. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132212. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132213. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132214. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132215. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132216. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132217. 20,13,13,13,13,13,13,14,14,
  132218. };
  132219. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132220. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132221. 27.5, 38.5, 49.5, 60.5,
  132222. };
  132223. static long _vq_quantmap__44c6_s_p7_0[] = {
  132224. 11, 9, 7, 5, 3, 1, 0, 2,
  132225. 4, 6, 8, 10, 12,
  132226. };
  132227. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132228. _vq_quantthresh__44c6_s_p7_0,
  132229. _vq_quantmap__44c6_s_p7_0,
  132230. 13,
  132231. 13
  132232. };
  132233. static static_codebook _44c6_s_p7_0 = {
  132234. 2, 169,
  132235. _vq_lengthlist__44c6_s_p7_0,
  132236. 1, -523206656, 1618345984, 4, 0,
  132237. _vq_quantlist__44c6_s_p7_0,
  132238. NULL,
  132239. &_vq_auxt__44c6_s_p7_0,
  132240. NULL,
  132241. 0
  132242. };
  132243. static long _vq_quantlist__44c6_s_p7_1[] = {
  132244. 5,
  132245. 4,
  132246. 6,
  132247. 3,
  132248. 7,
  132249. 2,
  132250. 8,
  132251. 1,
  132252. 9,
  132253. 0,
  132254. 10,
  132255. };
  132256. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132257. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132258. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132259. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132260. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132261. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132262. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132263. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132264. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132265. };
  132266. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132267. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132268. 3.5, 4.5,
  132269. };
  132270. static long _vq_quantmap__44c6_s_p7_1[] = {
  132271. 9, 7, 5, 3, 1, 0, 2, 4,
  132272. 6, 8, 10,
  132273. };
  132274. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132275. _vq_quantthresh__44c6_s_p7_1,
  132276. _vq_quantmap__44c6_s_p7_1,
  132277. 11,
  132278. 11
  132279. };
  132280. static static_codebook _44c6_s_p7_1 = {
  132281. 2, 121,
  132282. _vq_lengthlist__44c6_s_p7_1,
  132283. 1, -531365888, 1611661312, 4, 0,
  132284. _vq_quantlist__44c6_s_p7_1,
  132285. NULL,
  132286. &_vq_auxt__44c6_s_p7_1,
  132287. NULL,
  132288. 0
  132289. };
  132290. static long _vq_quantlist__44c6_s_p8_0[] = {
  132291. 7,
  132292. 6,
  132293. 8,
  132294. 5,
  132295. 9,
  132296. 4,
  132297. 10,
  132298. 3,
  132299. 11,
  132300. 2,
  132301. 12,
  132302. 1,
  132303. 13,
  132304. 0,
  132305. 14,
  132306. };
  132307. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132308. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132309. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132310. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132311. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132312. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132313. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132314. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132315. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132316. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132317. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132318. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132319. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132320. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132321. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132322. 14,
  132323. };
  132324. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132325. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132326. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132327. };
  132328. static long _vq_quantmap__44c6_s_p8_0[] = {
  132329. 13, 11, 9, 7, 5, 3, 1, 0,
  132330. 2, 4, 6, 8, 10, 12, 14,
  132331. };
  132332. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132333. _vq_quantthresh__44c6_s_p8_0,
  132334. _vq_quantmap__44c6_s_p8_0,
  132335. 15,
  132336. 15
  132337. };
  132338. static static_codebook _44c6_s_p8_0 = {
  132339. 2, 225,
  132340. _vq_lengthlist__44c6_s_p8_0,
  132341. 1, -520986624, 1620377600, 4, 0,
  132342. _vq_quantlist__44c6_s_p8_0,
  132343. NULL,
  132344. &_vq_auxt__44c6_s_p8_0,
  132345. NULL,
  132346. 0
  132347. };
  132348. static long _vq_quantlist__44c6_s_p8_1[] = {
  132349. 10,
  132350. 9,
  132351. 11,
  132352. 8,
  132353. 12,
  132354. 7,
  132355. 13,
  132356. 6,
  132357. 14,
  132358. 5,
  132359. 15,
  132360. 4,
  132361. 16,
  132362. 3,
  132363. 17,
  132364. 2,
  132365. 18,
  132366. 1,
  132367. 19,
  132368. 0,
  132369. 20,
  132370. };
  132371. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132372. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132373. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132374. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132375. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132376. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132377. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132378. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132379. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132380. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132381. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132382. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132383. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132384. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132385. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132386. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132387. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132388. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132389. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132390. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132391. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132392. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132393. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132394. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132395. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132396. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132397. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132398. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132399. 10,10,10,10,10,10,10,10,10,
  132400. };
  132401. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132402. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132403. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132404. 6.5, 7.5, 8.5, 9.5,
  132405. };
  132406. static long _vq_quantmap__44c6_s_p8_1[] = {
  132407. 19, 17, 15, 13, 11, 9, 7, 5,
  132408. 3, 1, 0, 2, 4, 6, 8, 10,
  132409. 12, 14, 16, 18, 20,
  132410. };
  132411. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132412. _vq_quantthresh__44c6_s_p8_1,
  132413. _vq_quantmap__44c6_s_p8_1,
  132414. 21,
  132415. 21
  132416. };
  132417. static static_codebook _44c6_s_p8_1 = {
  132418. 2, 441,
  132419. _vq_lengthlist__44c6_s_p8_1,
  132420. 1, -529268736, 1611661312, 5, 0,
  132421. _vq_quantlist__44c6_s_p8_1,
  132422. NULL,
  132423. &_vq_auxt__44c6_s_p8_1,
  132424. NULL,
  132425. 0
  132426. };
  132427. static long _vq_quantlist__44c6_s_p9_0[] = {
  132428. 6,
  132429. 5,
  132430. 7,
  132431. 4,
  132432. 8,
  132433. 3,
  132434. 9,
  132435. 2,
  132436. 10,
  132437. 1,
  132438. 11,
  132439. 0,
  132440. 12,
  132441. };
  132442. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132443. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132444. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132445. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132446. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132447. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132448. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132449. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132450. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132451. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132452. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132453. 10,10,10,10,10,10,10,10,10,
  132454. };
  132455. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132456. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132457. 1592.5, 2229.5, 2866.5, 3503.5,
  132458. };
  132459. static long _vq_quantmap__44c6_s_p9_0[] = {
  132460. 11, 9, 7, 5, 3, 1, 0, 2,
  132461. 4, 6, 8, 10, 12,
  132462. };
  132463. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132464. _vq_quantthresh__44c6_s_p9_0,
  132465. _vq_quantmap__44c6_s_p9_0,
  132466. 13,
  132467. 13
  132468. };
  132469. static static_codebook _44c6_s_p9_0 = {
  132470. 2, 169,
  132471. _vq_lengthlist__44c6_s_p9_0,
  132472. 1, -511845376, 1630791680, 4, 0,
  132473. _vq_quantlist__44c6_s_p9_0,
  132474. NULL,
  132475. &_vq_auxt__44c6_s_p9_0,
  132476. NULL,
  132477. 0
  132478. };
  132479. static long _vq_quantlist__44c6_s_p9_1[] = {
  132480. 6,
  132481. 5,
  132482. 7,
  132483. 4,
  132484. 8,
  132485. 3,
  132486. 9,
  132487. 2,
  132488. 10,
  132489. 1,
  132490. 11,
  132491. 0,
  132492. 12,
  132493. };
  132494. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132495. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132496. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132497. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132498. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132499. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132500. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132501. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132502. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132503. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132504. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132505. 15,12,10,11,11,13,11,12,13,
  132506. };
  132507. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132508. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132509. 122.5, 171.5, 220.5, 269.5,
  132510. };
  132511. static long _vq_quantmap__44c6_s_p9_1[] = {
  132512. 11, 9, 7, 5, 3, 1, 0, 2,
  132513. 4, 6, 8, 10, 12,
  132514. };
  132515. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132516. _vq_quantthresh__44c6_s_p9_1,
  132517. _vq_quantmap__44c6_s_p9_1,
  132518. 13,
  132519. 13
  132520. };
  132521. static static_codebook _44c6_s_p9_1 = {
  132522. 2, 169,
  132523. _vq_lengthlist__44c6_s_p9_1,
  132524. 1, -518889472, 1622704128, 4, 0,
  132525. _vq_quantlist__44c6_s_p9_1,
  132526. NULL,
  132527. &_vq_auxt__44c6_s_p9_1,
  132528. NULL,
  132529. 0
  132530. };
  132531. static long _vq_quantlist__44c6_s_p9_2[] = {
  132532. 24,
  132533. 23,
  132534. 25,
  132535. 22,
  132536. 26,
  132537. 21,
  132538. 27,
  132539. 20,
  132540. 28,
  132541. 19,
  132542. 29,
  132543. 18,
  132544. 30,
  132545. 17,
  132546. 31,
  132547. 16,
  132548. 32,
  132549. 15,
  132550. 33,
  132551. 14,
  132552. 34,
  132553. 13,
  132554. 35,
  132555. 12,
  132556. 36,
  132557. 11,
  132558. 37,
  132559. 10,
  132560. 38,
  132561. 9,
  132562. 39,
  132563. 8,
  132564. 40,
  132565. 7,
  132566. 41,
  132567. 6,
  132568. 42,
  132569. 5,
  132570. 43,
  132571. 4,
  132572. 44,
  132573. 3,
  132574. 45,
  132575. 2,
  132576. 46,
  132577. 1,
  132578. 47,
  132579. 0,
  132580. 48,
  132581. };
  132582. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132583. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132584. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132585. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132586. 7,
  132587. };
  132588. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132589. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132590. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132591. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132592. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132593. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132594. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132595. };
  132596. static long _vq_quantmap__44c6_s_p9_2[] = {
  132597. 47, 45, 43, 41, 39, 37, 35, 33,
  132598. 31, 29, 27, 25, 23, 21, 19, 17,
  132599. 15, 13, 11, 9, 7, 5, 3, 1,
  132600. 0, 2, 4, 6, 8, 10, 12, 14,
  132601. 16, 18, 20, 22, 24, 26, 28, 30,
  132602. 32, 34, 36, 38, 40, 42, 44, 46,
  132603. 48,
  132604. };
  132605. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132606. _vq_quantthresh__44c6_s_p9_2,
  132607. _vq_quantmap__44c6_s_p9_2,
  132608. 49,
  132609. 49
  132610. };
  132611. static static_codebook _44c6_s_p9_2 = {
  132612. 1, 49,
  132613. _vq_lengthlist__44c6_s_p9_2,
  132614. 1, -526909440, 1611661312, 6, 0,
  132615. _vq_quantlist__44c6_s_p9_2,
  132616. NULL,
  132617. &_vq_auxt__44c6_s_p9_2,
  132618. NULL,
  132619. 0
  132620. };
  132621. static long _huff_lengthlist__44c6_s_short[] = {
  132622. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132623. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132624. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132625. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132626. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132627. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132628. 9,10,17,18,
  132629. };
  132630. static static_codebook _huff_book__44c6_s_short = {
  132631. 2, 100,
  132632. _huff_lengthlist__44c6_s_short,
  132633. 0, 0, 0, 0, 0,
  132634. NULL,
  132635. NULL,
  132636. NULL,
  132637. NULL,
  132638. 0
  132639. };
  132640. static long _huff_lengthlist__44c7_s_long[] = {
  132641. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132642. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132643. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132644. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132645. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132646. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132647. 11,10,10,12,
  132648. };
  132649. static static_codebook _huff_book__44c7_s_long = {
  132650. 2, 100,
  132651. _huff_lengthlist__44c7_s_long,
  132652. 0, 0, 0, 0, 0,
  132653. NULL,
  132654. NULL,
  132655. NULL,
  132656. NULL,
  132657. 0
  132658. };
  132659. static long _vq_quantlist__44c7_s_p1_0[] = {
  132660. 1,
  132661. 0,
  132662. 2,
  132663. };
  132664. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132665. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132666. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132667. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132668. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132669. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132670. 8,
  132671. };
  132672. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132673. -0.5, 0.5,
  132674. };
  132675. static long _vq_quantmap__44c7_s_p1_0[] = {
  132676. 1, 0, 2,
  132677. };
  132678. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132679. _vq_quantthresh__44c7_s_p1_0,
  132680. _vq_quantmap__44c7_s_p1_0,
  132681. 3,
  132682. 3
  132683. };
  132684. static static_codebook _44c7_s_p1_0 = {
  132685. 4, 81,
  132686. _vq_lengthlist__44c7_s_p1_0,
  132687. 1, -535822336, 1611661312, 2, 0,
  132688. _vq_quantlist__44c7_s_p1_0,
  132689. NULL,
  132690. &_vq_auxt__44c7_s_p1_0,
  132691. NULL,
  132692. 0
  132693. };
  132694. static long _vq_quantlist__44c7_s_p2_0[] = {
  132695. 2,
  132696. 1,
  132697. 3,
  132698. 0,
  132699. 4,
  132700. };
  132701. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132702. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132703. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132704. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132705. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132706. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132707. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132708. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132709. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132711. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132712. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132713. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132714. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132715. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132716. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132717. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132719. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132720. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132721. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132722. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132723. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132724. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132725. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132728. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132729. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132730. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132731. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132732. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132733. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132738. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132739. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132740. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132741. 13,
  132742. };
  132743. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132744. -1.5, -0.5, 0.5, 1.5,
  132745. };
  132746. static long _vq_quantmap__44c7_s_p2_0[] = {
  132747. 3, 1, 0, 2, 4,
  132748. };
  132749. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132750. _vq_quantthresh__44c7_s_p2_0,
  132751. _vq_quantmap__44c7_s_p2_0,
  132752. 5,
  132753. 5
  132754. };
  132755. static static_codebook _44c7_s_p2_0 = {
  132756. 4, 625,
  132757. _vq_lengthlist__44c7_s_p2_0,
  132758. 1, -533725184, 1611661312, 3, 0,
  132759. _vq_quantlist__44c7_s_p2_0,
  132760. NULL,
  132761. &_vq_auxt__44c7_s_p2_0,
  132762. NULL,
  132763. 0
  132764. };
  132765. static long _vq_quantlist__44c7_s_p3_0[] = {
  132766. 4,
  132767. 3,
  132768. 5,
  132769. 2,
  132770. 6,
  132771. 1,
  132772. 7,
  132773. 0,
  132774. 8,
  132775. };
  132776. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132777. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132778. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132779. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132780. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132782. 0,
  132783. };
  132784. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132785. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132786. };
  132787. static long _vq_quantmap__44c7_s_p3_0[] = {
  132788. 7, 5, 3, 1, 0, 2, 4, 6,
  132789. 8,
  132790. };
  132791. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132792. _vq_quantthresh__44c7_s_p3_0,
  132793. _vq_quantmap__44c7_s_p3_0,
  132794. 9,
  132795. 9
  132796. };
  132797. static static_codebook _44c7_s_p3_0 = {
  132798. 2, 81,
  132799. _vq_lengthlist__44c7_s_p3_0,
  132800. 1, -531628032, 1611661312, 4, 0,
  132801. _vq_quantlist__44c7_s_p3_0,
  132802. NULL,
  132803. &_vq_auxt__44c7_s_p3_0,
  132804. NULL,
  132805. 0
  132806. };
  132807. static long _vq_quantlist__44c7_s_p4_0[] = {
  132808. 8,
  132809. 7,
  132810. 9,
  132811. 6,
  132812. 10,
  132813. 5,
  132814. 11,
  132815. 4,
  132816. 12,
  132817. 3,
  132818. 13,
  132819. 2,
  132820. 14,
  132821. 1,
  132822. 15,
  132823. 0,
  132824. 16,
  132825. };
  132826. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132827. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132828. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132829. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132830. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132831. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132832. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132833. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132834. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132835. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132836. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132845. 0,
  132846. };
  132847. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132848. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132849. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132850. };
  132851. static long _vq_quantmap__44c7_s_p4_0[] = {
  132852. 15, 13, 11, 9, 7, 5, 3, 1,
  132853. 0, 2, 4, 6, 8, 10, 12, 14,
  132854. 16,
  132855. };
  132856. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132857. _vq_quantthresh__44c7_s_p4_0,
  132858. _vq_quantmap__44c7_s_p4_0,
  132859. 17,
  132860. 17
  132861. };
  132862. static static_codebook _44c7_s_p4_0 = {
  132863. 2, 289,
  132864. _vq_lengthlist__44c7_s_p4_0,
  132865. 1, -529530880, 1611661312, 5, 0,
  132866. _vq_quantlist__44c7_s_p4_0,
  132867. NULL,
  132868. &_vq_auxt__44c7_s_p4_0,
  132869. NULL,
  132870. 0
  132871. };
  132872. static long _vq_quantlist__44c7_s_p5_0[] = {
  132873. 1,
  132874. 0,
  132875. 2,
  132876. };
  132877. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132878. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132879. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132880. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132881. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132882. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132883. 12,
  132884. };
  132885. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132886. -5.5, 5.5,
  132887. };
  132888. static long _vq_quantmap__44c7_s_p5_0[] = {
  132889. 1, 0, 2,
  132890. };
  132891. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132892. _vq_quantthresh__44c7_s_p5_0,
  132893. _vq_quantmap__44c7_s_p5_0,
  132894. 3,
  132895. 3
  132896. };
  132897. static static_codebook _44c7_s_p5_0 = {
  132898. 4, 81,
  132899. _vq_lengthlist__44c7_s_p5_0,
  132900. 1, -529137664, 1618345984, 2, 0,
  132901. _vq_quantlist__44c7_s_p5_0,
  132902. NULL,
  132903. &_vq_auxt__44c7_s_p5_0,
  132904. NULL,
  132905. 0
  132906. };
  132907. static long _vq_quantlist__44c7_s_p5_1[] = {
  132908. 5,
  132909. 4,
  132910. 6,
  132911. 3,
  132912. 7,
  132913. 2,
  132914. 8,
  132915. 1,
  132916. 9,
  132917. 0,
  132918. 10,
  132919. };
  132920. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132921. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132922. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132923. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132924. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132925. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132926. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132927. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132928. 11,11,11, 7, 7, 8, 8, 8, 8,
  132929. };
  132930. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132931. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132932. 3.5, 4.5,
  132933. };
  132934. static long _vq_quantmap__44c7_s_p5_1[] = {
  132935. 9, 7, 5, 3, 1, 0, 2, 4,
  132936. 6, 8, 10,
  132937. };
  132938. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132939. _vq_quantthresh__44c7_s_p5_1,
  132940. _vq_quantmap__44c7_s_p5_1,
  132941. 11,
  132942. 11
  132943. };
  132944. static static_codebook _44c7_s_p5_1 = {
  132945. 2, 121,
  132946. _vq_lengthlist__44c7_s_p5_1,
  132947. 1, -531365888, 1611661312, 4, 0,
  132948. _vq_quantlist__44c7_s_p5_1,
  132949. NULL,
  132950. &_vq_auxt__44c7_s_p5_1,
  132951. NULL,
  132952. 0
  132953. };
  132954. static long _vq_quantlist__44c7_s_p6_0[] = {
  132955. 6,
  132956. 5,
  132957. 7,
  132958. 4,
  132959. 8,
  132960. 3,
  132961. 9,
  132962. 2,
  132963. 10,
  132964. 1,
  132965. 11,
  132966. 0,
  132967. 12,
  132968. };
  132969. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132970. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132971. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132972. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132973. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132974. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132975. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  132976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132980. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132981. };
  132982. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132983. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132984. 12.5, 17.5, 22.5, 27.5,
  132985. };
  132986. static long _vq_quantmap__44c7_s_p6_0[] = {
  132987. 11, 9, 7, 5, 3, 1, 0, 2,
  132988. 4, 6, 8, 10, 12,
  132989. };
  132990. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132991. _vq_quantthresh__44c7_s_p6_0,
  132992. _vq_quantmap__44c7_s_p6_0,
  132993. 13,
  132994. 13
  132995. };
  132996. static static_codebook _44c7_s_p6_0 = {
  132997. 2, 169,
  132998. _vq_lengthlist__44c7_s_p6_0,
  132999. 1, -526516224, 1616117760, 4, 0,
  133000. _vq_quantlist__44c7_s_p6_0,
  133001. NULL,
  133002. &_vq_auxt__44c7_s_p6_0,
  133003. NULL,
  133004. 0
  133005. };
  133006. static long _vq_quantlist__44c7_s_p6_1[] = {
  133007. 2,
  133008. 1,
  133009. 3,
  133010. 0,
  133011. 4,
  133012. };
  133013. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133014. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133015. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133016. };
  133017. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133018. -1.5, -0.5, 0.5, 1.5,
  133019. };
  133020. static long _vq_quantmap__44c7_s_p6_1[] = {
  133021. 3, 1, 0, 2, 4,
  133022. };
  133023. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133024. _vq_quantthresh__44c7_s_p6_1,
  133025. _vq_quantmap__44c7_s_p6_1,
  133026. 5,
  133027. 5
  133028. };
  133029. static static_codebook _44c7_s_p6_1 = {
  133030. 2, 25,
  133031. _vq_lengthlist__44c7_s_p6_1,
  133032. 1, -533725184, 1611661312, 3, 0,
  133033. _vq_quantlist__44c7_s_p6_1,
  133034. NULL,
  133035. &_vq_auxt__44c7_s_p6_1,
  133036. NULL,
  133037. 0
  133038. };
  133039. static long _vq_quantlist__44c7_s_p7_0[] = {
  133040. 6,
  133041. 5,
  133042. 7,
  133043. 4,
  133044. 8,
  133045. 3,
  133046. 9,
  133047. 2,
  133048. 10,
  133049. 1,
  133050. 11,
  133051. 0,
  133052. 12,
  133053. };
  133054. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133055. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133056. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133057. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133058. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133059. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133060. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133061. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133062. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133063. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133064. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133065. 19,13,13,13,13,14,14,15,15,
  133066. };
  133067. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133068. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133069. 27.5, 38.5, 49.5, 60.5,
  133070. };
  133071. static long _vq_quantmap__44c7_s_p7_0[] = {
  133072. 11, 9, 7, 5, 3, 1, 0, 2,
  133073. 4, 6, 8, 10, 12,
  133074. };
  133075. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133076. _vq_quantthresh__44c7_s_p7_0,
  133077. _vq_quantmap__44c7_s_p7_0,
  133078. 13,
  133079. 13
  133080. };
  133081. static static_codebook _44c7_s_p7_0 = {
  133082. 2, 169,
  133083. _vq_lengthlist__44c7_s_p7_0,
  133084. 1, -523206656, 1618345984, 4, 0,
  133085. _vq_quantlist__44c7_s_p7_0,
  133086. NULL,
  133087. &_vq_auxt__44c7_s_p7_0,
  133088. NULL,
  133089. 0
  133090. };
  133091. static long _vq_quantlist__44c7_s_p7_1[] = {
  133092. 5,
  133093. 4,
  133094. 6,
  133095. 3,
  133096. 7,
  133097. 2,
  133098. 8,
  133099. 1,
  133100. 9,
  133101. 0,
  133102. 10,
  133103. };
  133104. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133105. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133106. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133107. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133108. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133109. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133110. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133111. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133112. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133113. };
  133114. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133115. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133116. 3.5, 4.5,
  133117. };
  133118. static long _vq_quantmap__44c7_s_p7_1[] = {
  133119. 9, 7, 5, 3, 1, 0, 2, 4,
  133120. 6, 8, 10,
  133121. };
  133122. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133123. _vq_quantthresh__44c7_s_p7_1,
  133124. _vq_quantmap__44c7_s_p7_1,
  133125. 11,
  133126. 11
  133127. };
  133128. static static_codebook _44c7_s_p7_1 = {
  133129. 2, 121,
  133130. _vq_lengthlist__44c7_s_p7_1,
  133131. 1, -531365888, 1611661312, 4, 0,
  133132. _vq_quantlist__44c7_s_p7_1,
  133133. NULL,
  133134. &_vq_auxt__44c7_s_p7_1,
  133135. NULL,
  133136. 0
  133137. };
  133138. static long _vq_quantlist__44c7_s_p8_0[] = {
  133139. 7,
  133140. 6,
  133141. 8,
  133142. 5,
  133143. 9,
  133144. 4,
  133145. 10,
  133146. 3,
  133147. 11,
  133148. 2,
  133149. 12,
  133150. 1,
  133151. 13,
  133152. 0,
  133153. 14,
  133154. };
  133155. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133156. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133157. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133158. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133159. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133160. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133161. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133162. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133163. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133164. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133165. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133166. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133167. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133168. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133169. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133170. 14,
  133171. };
  133172. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133173. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133174. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133175. };
  133176. static long _vq_quantmap__44c7_s_p8_0[] = {
  133177. 13, 11, 9, 7, 5, 3, 1, 0,
  133178. 2, 4, 6, 8, 10, 12, 14,
  133179. };
  133180. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133181. _vq_quantthresh__44c7_s_p8_0,
  133182. _vq_quantmap__44c7_s_p8_0,
  133183. 15,
  133184. 15
  133185. };
  133186. static static_codebook _44c7_s_p8_0 = {
  133187. 2, 225,
  133188. _vq_lengthlist__44c7_s_p8_0,
  133189. 1, -520986624, 1620377600, 4, 0,
  133190. _vq_quantlist__44c7_s_p8_0,
  133191. NULL,
  133192. &_vq_auxt__44c7_s_p8_0,
  133193. NULL,
  133194. 0
  133195. };
  133196. static long _vq_quantlist__44c7_s_p8_1[] = {
  133197. 10,
  133198. 9,
  133199. 11,
  133200. 8,
  133201. 12,
  133202. 7,
  133203. 13,
  133204. 6,
  133205. 14,
  133206. 5,
  133207. 15,
  133208. 4,
  133209. 16,
  133210. 3,
  133211. 17,
  133212. 2,
  133213. 18,
  133214. 1,
  133215. 19,
  133216. 0,
  133217. 20,
  133218. };
  133219. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133220. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133221. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133222. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133223. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133224. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133225. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133226. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133227. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133228. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133229. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133230. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133231. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133232. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133233. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133234. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133235. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133236. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133237. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133238. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133239. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133240. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133241. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133242. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133243. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133244. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133245. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133246. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133247. 10,10,10,10,10,10,10,10,10,
  133248. };
  133249. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133250. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133251. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133252. 6.5, 7.5, 8.5, 9.5,
  133253. };
  133254. static long _vq_quantmap__44c7_s_p8_1[] = {
  133255. 19, 17, 15, 13, 11, 9, 7, 5,
  133256. 3, 1, 0, 2, 4, 6, 8, 10,
  133257. 12, 14, 16, 18, 20,
  133258. };
  133259. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133260. _vq_quantthresh__44c7_s_p8_1,
  133261. _vq_quantmap__44c7_s_p8_1,
  133262. 21,
  133263. 21
  133264. };
  133265. static static_codebook _44c7_s_p8_1 = {
  133266. 2, 441,
  133267. _vq_lengthlist__44c7_s_p8_1,
  133268. 1, -529268736, 1611661312, 5, 0,
  133269. _vq_quantlist__44c7_s_p8_1,
  133270. NULL,
  133271. &_vq_auxt__44c7_s_p8_1,
  133272. NULL,
  133273. 0
  133274. };
  133275. static long _vq_quantlist__44c7_s_p9_0[] = {
  133276. 6,
  133277. 5,
  133278. 7,
  133279. 4,
  133280. 8,
  133281. 3,
  133282. 9,
  133283. 2,
  133284. 10,
  133285. 1,
  133286. 11,
  133287. 0,
  133288. 12,
  133289. };
  133290. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133291. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133292. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133299. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133300. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133301. 11,11,11,11,11,11,11,11,11,
  133302. };
  133303. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133304. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133305. 1592.5, 2229.5, 2866.5, 3503.5,
  133306. };
  133307. static long _vq_quantmap__44c7_s_p9_0[] = {
  133308. 11, 9, 7, 5, 3, 1, 0, 2,
  133309. 4, 6, 8, 10, 12,
  133310. };
  133311. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133312. _vq_quantthresh__44c7_s_p9_0,
  133313. _vq_quantmap__44c7_s_p9_0,
  133314. 13,
  133315. 13
  133316. };
  133317. static static_codebook _44c7_s_p9_0 = {
  133318. 2, 169,
  133319. _vq_lengthlist__44c7_s_p9_0,
  133320. 1, -511845376, 1630791680, 4, 0,
  133321. _vq_quantlist__44c7_s_p9_0,
  133322. NULL,
  133323. &_vq_auxt__44c7_s_p9_0,
  133324. NULL,
  133325. 0
  133326. };
  133327. static long _vq_quantlist__44c7_s_p9_1[] = {
  133328. 6,
  133329. 5,
  133330. 7,
  133331. 4,
  133332. 8,
  133333. 3,
  133334. 9,
  133335. 2,
  133336. 10,
  133337. 1,
  133338. 11,
  133339. 0,
  133340. 12,
  133341. };
  133342. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133343. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133344. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133345. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133346. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133347. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133348. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133349. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133350. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133351. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133352. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133353. 15,11,11,10,10,12,12,12,12,
  133354. };
  133355. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133356. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133357. 122.5, 171.5, 220.5, 269.5,
  133358. };
  133359. static long _vq_quantmap__44c7_s_p9_1[] = {
  133360. 11, 9, 7, 5, 3, 1, 0, 2,
  133361. 4, 6, 8, 10, 12,
  133362. };
  133363. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133364. _vq_quantthresh__44c7_s_p9_1,
  133365. _vq_quantmap__44c7_s_p9_1,
  133366. 13,
  133367. 13
  133368. };
  133369. static static_codebook _44c7_s_p9_1 = {
  133370. 2, 169,
  133371. _vq_lengthlist__44c7_s_p9_1,
  133372. 1, -518889472, 1622704128, 4, 0,
  133373. _vq_quantlist__44c7_s_p9_1,
  133374. NULL,
  133375. &_vq_auxt__44c7_s_p9_1,
  133376. NULL,
  133377. 0
  133378. };
  133379. static long _vq_quantlist__44c7_s_p9_2[] = {
  133380. 24,
  133381. 23,
  133382. 25,
  133383. 22,
  133384. 26,
  133385. 21,
  133386. 27,
  133387. 20,
  133388. 28,
  133389. 19,
  133390. 29,
  133391. 18,
  133392. 30,
  133393. 17,
  133394. 31,
  133395. 16,
  133396. 32,
  133397. 15,
  133398. 33,
  133399. 14,
  133400. 34,
  133401. 13,
  133402. 35,
  133403. 12,
  133404. 36,
  133405. 11,
  133406. 37,
  133407. 10,
  133408. 38,
  133409. 9,
  133410. 39,
  133411. 8,
  133412. 40,
  133413. 7,
  133414. 41,
  133415. 6,
  133416. 42,
  133417. 5,
  133418. 43,
  133419. 4,
  133420. 44,
  133421. 3,
  133422. 45,
  133423. 2,
  133424. 46,
  133425. 1,
  133426. 47,
  133427. 0,
  133428. 48,
  133429. };
  133430. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133431. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133432. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133433. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133434. 7,
  133435. };
  133436. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133437. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133438. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133439. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133440. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133441. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133442. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133443. };
  133444. static long _vq_quantmap__44c7_s_p9_2[] = {
  133445. 47, 45, 43, 41, 39, 37, 35, 33,
  133446. 31, 29, 27, 25, 23, 21, 19, 17,
  133447. 15, 13, 11, 9, 7, 5, 3, 1,
  133448. 0, 2, 4, 6, 8, 10, 12, 14,
  133449. 16, 18, 20, 22, 24, 26, 28, 30,
  133450. 32, 34, 36, 38, 40, 42, 44, 46,
  133451. 48,
  133452. };
  133453. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133454. _vq_quantthresh__44c7_s_p9_2,
  133455. _vq_quantmap__44c7_s_p9_2,
  133456. 49,
  133457. 49
  133458. };
  133459. static static_codebook _44c7_s_p9_2 = {
  133460. 1, 49,
  133461. _vq_lengthlist__44c7_s_p9_2,
  133462. 1, -526909440, 1611661312, 6, 0,
  133463. _vq_quantlist__44c7_s_p9_2,
  133464. NULL,
  133465. &_vq_auxt__44c7_s_p9_2,
  133466. NULL,
  133467. 0
  133468. };
  133469. static long _huff_lengthlist__44c7_s_short[] = {
  133470. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133471. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133472. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133473. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133474. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133475. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133476. 10, 9,11,14,
  133477. };
  133478. static static_codebook _huff_book__44c7_s_short = {
  133479. 2, 100,
  133480. _huff_lengthlist__44c7_s_short,
  133481. 0, 0, 0, 0, 0,
  133482. NULL,
  133483. NULL,
  133484. NULL,
  133485. NULL,
  133486. 0
  133487. };
  133488. static long _huff_lengthlist__44c8_s_long[] = {
  133489. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133490. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133491. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133492. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133493. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133494. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133495. 11, 9, 9,10,
  133496. };
  133497. static static_codebook _huff_book__44c8_s_long = {
  133498. 2, 100,
  133499. _huff_lengthlist__44c8_s_long,
  133500. 0, 0, 0, 0, 0,
  133501. NULL,
  133502. NULL,
  133503. NULL,
  133504. NULL,
  133505. 0
  133506. };
  133507. static long _vq_quantlist__44c8_s_p1_0[] = {
  133508. 1,
  133509. 0,
  133510. 2,
  133511. };
  133512. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133513. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133514. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133515. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133516. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133517. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133518. 8,
  133519. };
  133520. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133521. -0.5, 0.5,
  133522. };
  133523. static long _vq_quantmap__44c8_s_p1_0[] = {
  133524. 1, 0, 2,
  133525. };
  133526. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133527. _vq_quantthresh__44c8_s_p1_0,
  133528. _vq_quantmap__44c8_s_p1_0,
  133529. 3,
  133530. 3
  133531. };
  133532. static static_codebook _44c8_s_p1_0 = {
  133533. 4, 81,
  133534. _vq_lengthlist__44c8_s_p1_0,
  133535. 1, -535822336, 1611661312, 2, 0,
  133536. _vq_quantlist__44c8_s_p1_0,
  133537. NULL,
  133538. &_vq_auxt__44c8_s_p1_0,
  133539. NULL,
  133540. 0
  133541. };
  133542. static long _vq_quantlist__44c8_s_p2_0[] = {
  133543. 2,
  133544. 1,
  133545. 3,
  133546. 0,
  133547. 4,
  133548. };
  133549. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133550. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133551. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133552. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133553. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133554. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133555. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133556. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133557. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133559. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133560. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133561. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133562. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133563. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133564. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133565. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133567. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133568. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133569. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133570. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133571. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133572. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133573. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133575. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133576. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133577. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133578. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133579. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133580. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133581. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133586. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133587. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133588. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133589. 13,
  133590. };
  133591. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133592. -1.5, -0.5, 0.5, 1.5,
  133593. };
  133594. static long _vq_quantmap__44c8_s_p2_0[] = {
  133595. 3, 1, 0, 2, 4,
  133596. };
  133597. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133598. _vq_quantthresh__44c8_s_p2_0,
  133599. _vq_quantmap__44c8_s_p2_0,
  133600. 5,
  133601. 5
  133602. };
  133603. static static_codebook _44c8_s_p2_0 = {
  133604. 4, 625,
  133605. _vq_lengthlist__44c8_s_p2_0,
  133606. 1, -533725184, 1611661312, 3, 0,
  133607. _vq_quantlist__44c8_s_p2_0,
  133608. NULL,
  133609. &_vq_auxt__44c8_s_p2_0,
  133610. NULL,
  133611. 0
  133612. };
  133613. static long _vq_quantlist__44c8_s_p3_0[] = {
  133614. 4,
  133615. 3,
  133616. 5,
  133617. 2,
  133618. 6,
  133619. 1,
  133620. 7,
  133621. 0,
  133622. 8,
  133623. };
  133624. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133625. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133626. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133627. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133628. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133630. 0,
  133631. };
  133632. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133633. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133634. };
  133635. static long _vq_quantmap__44c8_s_p3_0[] = {
  133636. 7, 5, 3, 1, 0, 2, 4, 6,
  133637. 8,
  133638. };
  133639. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133640. _vq_quantthresh__44c8_s_p3_0,
  133641. _vq_quantmap__44c8_s_p3_0,
  133642. 9,
  133643. 9
  133644. };
  133645. static static_codebook _44c8_s_p3_0 = {
  133646. 2, 81,
  133647. _vq_lengthlist__44c8_s_p3_0,
  133648. 1, -531628032, 1611661312, 4, 0,
  133649. _vq_quantlist__44c8_s_p3_0,
  133650. NULL,
  133651. &_vq_auxt__44c8_s_p3_0,
  133652. NULL,
  133653. 0
  133654. };
  133655. static long _vq_quantlist__44c8_s_p4_0[] = {
  133656. 8,
  133657. 7,
  133658. 9,
  133659. 6,
  133660. 10,
  133661. 5,
  133662. 11,
  133663. 4,
  133664. 12,
  133665. 3,
  133666. 13,
  133667. 2,
  133668. 14,
  133669. 1,
  133670. 15,
  133671. 0,
  133672. 16,
  133673. };
  133674. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133675. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133676. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133677. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133678. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133679. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133680. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133681. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133682. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133683. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133684. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133693. 0,
  133694. };
  133695. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133696. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133697. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133698. };
  133699. static long _vq_quantmap__44c8_s_p4_0[] = {
  133700. 15, 13, 11, 9, 7, 5, 3, 1,
  133701. 0, 2, 4, 6, 8, 10, 12, 14,
  133702. 16,
  133703. };
  133704. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133705. _vq_quantthresh__44c8_s_p4_0,
  133706. _vq_quantmap__44c8_s_p4_0,
  133707. 17,
  133708. 17
  133709. };
  133710. static static_codebook _44c8_s_p4_0 = {
  133711. 2, 289,
  133712. _vq_lengthlist__44c8_s_p4_0,
  133713. 1, -529530880, 1611661312, 5, 0,
  133714. _vq_quantlist__44c8_s_p4_0,
  133715. NULL,
  133716. &_vq_auxt__44c8_s_p4_0,
  133717. NULL,
  133718. 0
  133719. };
  133720. static long _vq_quantlist__44c8_s_p5_0[] = {
  133721. 1,
  133722. 0,
  133723. 2,
  133724. };
  133725. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133726. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133727. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133728. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133729. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133730. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133731. 12,
  133732. };
  133733. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133734. -5.5, 5.5,
  133735. };
  133736. static long _vq_quantmap__44c8_s_p5_0[] = {
  133737. 1, 0, 2,
  133738. };
  133739. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133740. _vq_quantthresh__44c8_s_p5_0,
  133741. _vq_quantmap__44c8_s_p5_0,
  133742. 3,
  133743. 3
  133744. };
  133745. static static_codebook _44c8_s_p5_0 = {
  133746. 4, 81,
  133747. _vq_lengthlist__44c8_s_p5_0,
  133748. 1, -529137664, 1618345984, 2, 0,
  133749. _vq_quantlist__44c8_s_p5_0,
  133750. NULL,
  133751. &_vq_auxt__44c8_s_p5_0,
  133752. NULL,
  133753. 0
  133754. };
  133755. static long _vq_quantlist__44c8_s_p5_1[] = {
  133756. 5,
  133757. 4,
  133758. 6,
  133759. 3,
  133760. 7,
  133761. 2,
  133762. 8,
  133763. 1,
  133764. 9,
  133765. 0,
  133766. 10,
  133767. };
  133768. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133769. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133770. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133771. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133772. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133773. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133774. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133775. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133776. 11,11,11, 7, 7, 7, 7, 8, 8,
  133777. };
  133778. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133779. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133780. 3.5, 4.5,
  133781. };
  133782. static long _vq_quantmap__44c8_s_p5_1[] = {
  133783. 9, 7, 5, 3, 1, 0, 2, 4,
  133784. 6, 8, 10,
  133785. };
  133786. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133787. _vq_quantthresh__44c8_s_p5_1,
  133788. _vq_quantmap__44c8_s_p5_1,
  133789. 11,
  133790. 11
  133791. };
  133792. static static_codebook _44c8_s_p5_1 = {
  133793. 2, 121,
  133794. _vq_lengthlist__44c8_s_p5_1,
  133795. 1, -531365888, 1611661312, 4, 0,
  133796. _vq_quantlist__44c8_s_p5_1,
  133797. NULL,
  133798. &_vq_auxt__44c8_s_p5_1,
  133799. NULL,
  133800. 0
  133801. };
  133802. static long _vq_quantlist__44c8_s_p6_0[] = {
  133803. 6,
  133804. 5,
  133805. 7,
  133806. 4,
  133807. 8,
  133808. 3,
  133809. 9,
  133810. 2,
  133811. 10,
  133812. 1,
  133813. 11,
  133814. 0,
  133815. 12,
  133816. };
  133817. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133818. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133819. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133820. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133821. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133822. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133823. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133828. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133829. };
  133830. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133831. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133832. 12.5, 17.5, 22.5, 27.5,
  133833. };
  133834. static long _vq_quantmap__44c8_s_p6_0[] = {
  133835. 11, 9, 7, 5, 3, 1, 0, 2,
  133836. 4, 6, 8, 10, 12,
  133837. };
  133838. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133839. _vq_quantthresh__44c8_s_p6_0,
  133840. _vq_quantmap__44c8_s_p6_0,
  133841. 13,
  133842. 13
  133843. };
  133844. static static_codebook _44c8_s_p6_0 = {
  133845. 2, 169,
  133846. _vq_lengthlist__44c8_s_p6_0,
  133847. 1, -526516224, 1616117760, 4, 0,
  133848. _vq_quantlist__44c8_s_p6_0,
  133849. NULL,
  133850. &_vq_auxt__44c8_s_p6_0,
  133851. NULL,
  133852. 0
  133853. };
  133854. static long _vq_quantlist__44c8_s_p6_1[] = {
  133855. 2,
  133856. 1,
  133857. 3,
  133858. 0,
  133859. 4,
  133860. };
  133861. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133862. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133863. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133864. };
  133865. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133866. -1.5, -0.5, 0.5, 1.5,
  133867. };
  133868. static long _vq_quantmap__44c8_s_p6_1[] = {
  133869. 3, 1, 0, 2, 4,
  133870. };
  133871. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133872. _vq_quantthresh__44c8_s_p6_1,
  133873. _vq_quantmap__44c8_s_p6_1,
  133874. 5,
  133875. 5
  133876. };
  133877. static static_codebook _44c8_s_p6_1 = {
  133878. 2, 25,
  133879. _vq_lengthlist__44c8_s_p6_1,
  133880. 1, -533725184, 1611661312, 3, 0,
  133881. _vq_quantlist__44c8_s_p6_1,
  133882. NULL,
  133883. &_vq_auxt__44c8_s_p6_1,
  133884. NULL,
  133885. 0
  133886. };
  133887. static long _vq_quantlist__44c8_s_p7_0[] = {
  133888. 6,
  133889. 5,
  133890. 7,
  133891. 4,
  133892. 8,
  133893. 3,
  133894. 9,
  133895. 2,
  133896. 10,
  133897. 1,
  133898. 11,
  133899. 0,
  133900. 12,
  133901. };
  133902. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133903. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133904. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133905. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133906. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133907. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133908. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133909. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133910. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133911. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133912. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133913. 20,13,13,13,13,14,13,15,15,
  133914. };
  133915. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133916. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133917. 27.5, 38.5, 49.5, 60.5,
  133918. };
  133919. static long _vq_quantmap__44c8_s_p7_0[] = {
  133920. 11, 9, 7, 5, 3, 1, 0, 2,
  133921. 4, 6, 8, 10, 12,
  133922. };
  133923. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133924. _vq_quantthresh__44c8_s_p7_0,
  133925. _vq_quantmap__44c8_s_p7_0,
  133926. 13,
  133927. 13
  133928. };
  133929. static static_codebook _44c8_s_p7_0 = {
  133930. 2, 169,
  133931. _vq_lengthlist__44c8_s_p7_0,
  133932. 1, -523206656, 1618345984, 4, 0,
  133933. _vq_quantlist__44c8_s_p7_0,
  133934. NULL,
  133935. &_vq_auxt__44c8_s_p7_0,
  133936. NULL,
  133937. 0
  133938. };
  133939. static long _vq_quantlist__44c8_s_p7_1[] = {
  133940. 5,
  133941. 4,
  133942. 6,
  133943. 3,
  133944. 7,
  133945. 2,
  133946. 8,
  133947. 1,
  133948. 9,
  133949. 0,
  133950. 10,
  133951. };
  133952. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133953. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133954. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133955. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133956. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133957. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133958. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133959. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133960. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133961. };
  133962. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133963. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133964. 3.5, 4.5,
  133965. };
  133966. static long _vq_quantmap__44c8_s_p7_1[] = {
  133967. 9, 7, 5, 3, 1, 0, 2, 4,
  133968. 6, 8, 10,
  133969. };
  133970. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133971. _vq_quantthresh__44c8_s_p7_1,
  133972. _vq_quantmap__44c8_s_p7_1,
  133973. 11,
  133974. 11
  133975. };
  133976. static static_codebook _44c8_s_p7_1 = {
  133977. 2, 121,
  133978. _vq_lengthlist__44c8_s_p7_1,
  133979. 1, -531365888, 1611661312, 4, 0,
  133980. _vq_quantlist__44c8_s_p7_1,
  133981. NULL,
  133982. &_vq_auxt__44c8_s_p7_1,
  133983. NULL,
  133984. 0
  133985. };
  133986. static long _vq_quantlist__44c8_s_p8_0[] = {
  133987. 7,
  133988. 6,
  133989. 8,
  133990. 5,
  133991. 9,
  133992. 4,
  133993. 10,
  133994. 3,
  133995. 11,
  133996. 2,
  133997. 12,
  133998. 1,
  133999. 13,
  134000. 0,
  134001. 14,
  134002. };
  134003. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134004. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134005. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134006. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134007. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134008. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134009. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134010. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134011. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134012. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134013. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134014. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134015. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134016. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134017. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134018. 15,
  134019. };
  134020. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134021. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134022. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134023. };
  134024. static long _vq_quantmap__44c8_s_p8_0[] = {
  134025. 13, 11, 9, 7, 5, 3, 1, 0,
  134026. 2, 4, 6, 8, 10, 12, 14,
  134027. };
  134028. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134029. _vq_quantthresh__44c8_s_p8_0,
  134030. _vq_quantmap__44c8_s_p8_0,
  134031. 15,
  134032. 15
  134033. };
  134034. static static_codebook _44c8_s_p8_0 = {
  134035. 2, 225,
  134036. _vq_lengthlist__44c8_s_p8_0,
  134037. 1, -520986624, 1620377600, 4, 0,
  134038. _vq_quantlist__44c8_s_p8_0,
  134039. NULL,
  134040. &_vq_auxt__44c8_s_p8_0,
  134041. NULL,
  134042. 0
  134043. };
  134044. static long _vq_quantlist__44c8_s_p8_1[] = {
  134045. 10,
  134046. 9,
  134047. 11,
  134048. 8,
  134049. 12,
  134050. 7,
  134051. 13,
  134052. 6,
  134053. 14,
  134054. 5,
  134055. 15,
  134056. 4,
  134057. 16,
  134058. 3,
  134059. 17,
  134060. 2,
  134061. 18,
  134062. 1,
  134063. 19,
  134064. 0,
  134065. 20,
  134066. };
  134067. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134068. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134069. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134070. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134071. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134072. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134073. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134074. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134076. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134077. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134078. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134080. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134081. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134082. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134083. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134084. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134085. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134086. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134087. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134088. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134089. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134090. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134091. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134092. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134093. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134094. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134095. 10, 9, 9,10,10, 9,10, 9, 9,
  134096. };
  134097. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134098. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134099. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134100. 6.5, 7.5, 8.5, 9.5,
  134101. };
  134102. static long _vq_quantmap__44c8_s_p8_1[] = {
  134103. 19, 17, 15, 13, 11, 9, 7, 5,
  134104. 3, 1, 0, 2, 4, 6, 8, 10,
  134105. 12, 14, 16, 18, 20,
  134106. };
  134107. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134108. _vq_quantthresh__44c8_s_p8_1,
  134109. _vq_quantmap__44c8_s_p8_1,
  134110. 21,
  134111. 21
  134112. };
  134113. static static_codebook _44c8_s_p8_1 = {
  134114. 2, 441,
  134115. _vq_lengthlist__44c8_s_p8_1,
  134116. 1, -529268736, 1611661312, 5, 0,
  134117. _vq_quantlist__44c8_s_p8_1,
  134118. NULL,
  134119. &_vq_auxt__44c8_s_p8_1,
  134120. NULL,
  134121. 0
  134122. };
  134123. static long _vq_quantlist__44c8_s_p9_0[] = {
  134124. 8,
  134125. 7,
  134126. 9,
  134127. 6,
  134128. 10,
  134129. 5,
  134130. 11,
  134131. 4,
  134132. 12,
  134133. 3,
  134134. 13,
  134135. 2,
  134136. 14,
  134137. 1,
  134138. 15,
  134139. 0,
  134140. 16,
  134141. };
  134142. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134143. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134144. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134145. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134148. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134157. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134158. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134159. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134161. 10,
  134162. };
  134163. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134164. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134165. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134166. };
  134167. static long _vq_quantmap__44c8_s_p9_0[] = {
  134168. 15, 13, 11, 9, 7, 5, 3, 1,
  134169. 0, 2, 4, 6, 8, 10, 12, 14,
  134170. 16,
  134171. };
  134172. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134173. _vq_quantthresh__44c8_s_p9_0,
  134174. _vq_quantmap__44c8_s_p9_0,
  134175. 17,
  134176. 17
  134177. };
  134178. static static_codebook _44c8_s_p9_0 = {
  134179. 2, 289,
  134180. _vq_lengthlist__44c8_s_p9_0,
  134181. 1, -509798400, 1631393792, 5, 0,
  134182. _vq_quantlist__44c8_s_p9_0,
  134183. NULL,
  134184. &_vq_auxt__44c8_s_p9_0,
  134185. NULL,
  134186. 0
  134187. };
  134188. static long _vq_quantlist__44c8_s_p9_1[] = {
  134189. 9,
  134190. 8,
  134191. 10,
  134192. 7,
  134193. 11,
  134194. 6,
  134195. 12,
  134196. 5,
  134197. 13,
  134198. 4,
  134199. 14,
  134200. 3,
  134201. 15,
  134202. 2,
  134203. 16,
  134204. 1,
  134205. 17,
  134206. 0,
  134207. 18,
  134208. };
  134209. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134210. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134211. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134212. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134213. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134214. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134215. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134216. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134217. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134218. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134219. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134220. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134221. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134222. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134223. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134224. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134225. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134226. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134227. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134228. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134229. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134230. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134231. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134232. 14,13,13,14,14,15,14,15,14,
  134233. };
  134234. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134235. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134236. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134237. 367.5, 416.5,
  134238. };
  134239. static long _vq_quantmap__44c8_s_p9_1[] = {
  134240. 17, 15, 13, 11, 9, 7, 5, 3,
  134241. 1, 0, 2, 4, 6, 8, 10, 12,
  134242. 14, 16, 18,
  134243. };
  134244. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134245. _vq_quantthresh__44c8_s_p9_1,
  134246. _vq_quantmap__44c8_s_p9_1,
  134247. 19,
  134248. 19
  134249. };
  134250. static static_codebook _44c8_s_p9_1 = {
  134251. 2, 361,
  134252. _vq_lengthlist__44c8_s_p9_1,
  134253. 1, -518287360, 1622704128, 5, 0,
  134254. _vq_quantlist__44c8_s_p9_1,
  134255. NULL,
  134256. &_vq_auxt__44c8_s_p9_1,
  134257. NULL,
  134258. 0
  134259. };
  134260. static long _vq_quantlist__44c8_s_p9_2[] = {
  134261. 24,
  134262. 23,
  134263. 25,
  134264. 22,
  134265. 26,
  134266. 21,
  134267. 27,
  134268. 20,
  134269. 28,
  134270. 19,
  134271. 29,
  134272. 18,
  134273. 30,
  134274. 17,
  134275. 31,
  134276. 16,
  134277. 32,
  134278. 15,
  134279. 33,
  134280. 14,
  134281. 34,
  134282. 13,
  134283. 35,
  134284. 12,
  134285. 36,
  134286. 11,
  134287. 37,
  134288. 10,
  134289. 38,
  134290. 9,
  134291. 39,
  134292. 8,
  134293. 40,
  134294. 7,
  134295. 41,
  134296. 6,
  134297. 42,
  134298. 5,
  134299. 43,
  134300. 4,
  134301. 44,
  134302. 3,
  134303. 45,
  134304. 2,
  134305. 46,
  134306. 1,
  134307. 47,
  134308. 0,
  134309. 48,
  134310. };
  134311. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134312. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134313. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134314. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134315. 7,
  134316. };
  134317. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134318. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134319. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134322. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134323. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134324. };
  134325. static long _vq_quantmap__44c8_s_p9_2[] = {
  134326. 47, 45, 43, 41, 39, 37, 35, 33,
  134327. 31, 29, 27, 25, 23, 21, 19, 17,
  134328. 15, 13, 11, 9, 7, 5, 3, 1,
  134329. 0, 2, 4, 6, 8, 10, 12, 14,
  134330. 16, 18, 20, 22, 24, 26, 28, 30,
  134331. 32, 34, 36, 38, 40, 42, 44, 46,
  134332. 48,
  134333. };
  134334. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134335. _vq_quantthresh__44c8_s_p9_2,
  134336. _vq_quantmap__44c8_s_p9_2,
  134337. 49,
  134338. 49
  134339. };
  134340. static static_codebook _44c8_s_p9_2 = {
  134341. 1, 49,
  134342. _vq_lengthlist__44c8_s_p9_2,
  134343. 1, -526909440, 1611661312, 6, 0,
  134344. _vq_quantlist__44c8_s_p9_2,
  134345. NULL,
  134346. &_vq_auxt__44c8_s_p9_2,
  134347. NULL,
  134348. 0
  134349. };
  134350. static long _huff_lengthlist__44c8_s_short[] = {
  134351. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134352. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134353. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134354. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134355. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134356. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134357. 10, 9,11,14,
  134358. };
  134359. static static_codebook _huff_book__44c8_s_short = {
  134360. 2, 100,
  134361. _huff_lengthlist__44c8_s_short,
  134362. 0, 0, 0, 0, 0,
  134363. NULL,
  134364. NULL,
  134365. NULL,
  134366. NULL,
  134367. 0
  134368. };
  134369. static long _huff_lengthlist__44c9_s_long[] = {
  134370. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134371. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134372. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134373. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134374. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134375. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134376. 10, 9, 8, 9,
  134377. };
  134378. static static_codebook _huff_book__44c9_s_long = {
  134379. 2, 100,
  134380. _huff_lengthlist__44c9_s_long,
  134381. 0, 0, 0, 0, 0,
  134382. NULL,
  134383. NULL,
  134384. NULL,
  134385. NULL,
  134386. 0
  134387. };
  134388. static long _vq_quantlist__44c9_s_p1_0[] = {
  134389. 1,
  134390. 0,
  134391. 2,
  134392. };
  134393. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134394. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134395. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134397. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134398. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134399. 7,
  134400. };
  134401. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134402. -0.5, 0.5,
  134403. };
  134404. static long _vq_quantmap__44c9_s_p1_0[] = {
  134405. 1, 0, 2,
  134406. };
  134407. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134408. _vq_quantthresh__44c9_s_p1_0,
  134409. _vq_quantmap__44c9_s_p1_0,
  134410. 3,
  134411. 3
  134412. };
  134413. static static_codebook _44c9_s_p1_0 = {
  134414. 4, 81,
  134415. _vq_lengthlist__44c9_s_p1_0,
  134416. 1, -535822336, 1611661312, 2, 0,
  134417. _vq_quantlist__44c9_s_p1_0,
  134418. NULL,
  134419. &_vq_auxt__44c9_s_p1_0,
  134420. NULL,
  134421. 0
  134422. };
  134423. static long _vq_quantlist__44c9_s_p2_0[] = {
  134424. 2,
  134425. 1,
  134426. 3,
  134427. 0,
  134428. 4,
  134429. };
  134430. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134431. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134432. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134433. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134434. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134435. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134436. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134437. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134438. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134441. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134442. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134443. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134444. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134445. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134446. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134448. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134449. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134450. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134451. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134452. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134453. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134454. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134457. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134458. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134459. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134460. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134461. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134462. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134467. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134468. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134469. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134470. 12,
  134471. };
  134472. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134473. -1.5, -0.5, 0.5, 1.5,
  134474. };
  134475. static long _vq_quantmap__44c9_s_p2_0[] = {
  134476. 3, 1, 0, 2, 4,
  134477. };
  134478. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134479. _vq_quantthresh__44c9_s_p2_0,
  134480. _vq_quantmap__44c9_s_p2_0,
  134481. 5,
  134482. 5
  134483. };
  134484. static static_codebook _44c9_s_p2_0 = {
  134485. 4, 625,
  134486. _vq_lengthlist__44c9_s_p2_0,
  134487. 1, -533725184, 1611661312, 3, 0,
  134488. _vq_quantlist__44c9_s_p2_0,
  134489. NULL,
  134490. &_vq_auxt__44c9_s_p2_0,
  134491. NULL,
  134492. 0
  134493. };
  134494. static long _vq_quantlist__44c9_s_p3_0[] = {
  134495. 4,
  134496. 3,
  134497. 5,
  134498. 2,
  134499. 6,
  134500. 1,
  134501. 7,
  134502. 0,
  134503. 8,
  134504. };
  134505. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134506. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134507. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134508. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134509. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134511. 0,
  134512. };
  134513. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134514. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134515. };
  134516. static long _vq_quantmap__44c9_s_p3_0[] = {
  134517. 7, 5, 3, 1, 0, 2, 4, 6,
  134518. 8,
  134519. };
  134520. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134521. _vq_quantthresh__44c9_s_p3_0,
  134522. _vq_quantmap__44c9_s_p3_0,
  134523. 9,
  134524. 9
  134525. };
  134526. static static_codebook _44c9_s_p3_0 = {
  134527. 2, 81,
  134528. _vq_lengthlist__44c9_s_p3_0,
  134529. 1, -531628032, 1611661312, 4, 0,
  134530. _vq_quantlist__44c9_s_p3_0,
  134531. NULL,
  134532. &_vq_auxt__44c9_s_p3_0,
  134533. NULL,
  134534. 0
  134535. };
  134536. static long _vq_quantlist__44c9_s_p4_0[] = {
  134537. 8,
  134538. 7,
  134539. 9,
  134540. 6,
  134541. 10,
  134542. 5,
  134543. 11,
  134544. 4,
  134545. 12,
  134546. 3,
  134547. 13,
  134548. 2,
  134549. 14,
  134550. 1,
  134551. 15,
  134552. 0,
  134553. 16,
  134554. };
  134555. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134556. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134557. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134558. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134559. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134560. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134561. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134562. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134563. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134564. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134565. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134574. 0,
  134575. };
  134576. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134577. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134578. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134579. };
  134580. static long _vq_quantmap__44c9_s_p4_0[] = {
  134581. 15, 13, 11, 9, 7, 5, 3, 1,
  134582. 0, 2, 4, 6, 8, 10, 12, 14,
  134583. 16,
  134584. };
  134585. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134586. _vq_quantthresh__44c9_s_p4_0,
  134587. _vq_quantmap__44c9_s_p4_0,
  134588. 17,
  134589. 17
  134590. };
  134591. static static_codebook _44c9_s_p4_0 = {
  134592. 2, 289,
  134593. _vq_lengthlist__44c9_s_p4_0,
  134594. 1, -529530880, 1611661312, 5, 0,
  134595. _vq_quantlist__44c9_s_p4_0,
  134596. NULL,
  134597. &_vq_auxt__44c9_s_p4_0,
  134598. NULL,
  134599. 0
  134600. };
  134601. static long _vq_quantlist__44c9_s_p5_0[] = {
  134602. 1,
  134603. 0,
  134604. 2,
  134605. };
  134606. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134607. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134608. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134609. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134610. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134611. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134612. 12,
  134613. };
  134614. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134615. -5.5, 5.5,
  134616. };
  134617. static long _vq_quantmap__44c9_s_p5_0[] = {
  134618. 1, 0, 2,
  134619. };
  134620. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134621. _vq_quantthresh__44c9_s_p5_0,
  134622. _vq_quantmap__44c9_s_p5_0,
  134623. 3,
  134624. 3
  134625. };
  134626. static static_codebook _44c9_s_p5_0 = {
  134627. 4, 81,
  134628. _vq_lengthlist__44c9_s_p5_0,
  134629. 1, -529137664, 1618345984, 2, 0,
  134630. _vq_quantlist__44c9_s_p5_0,
  134631. NULL,
  134632. &_vq_auxt__44c9_s_p5_0,
  134633. NULL,
  134634. 0
  134635. };
  134636. static long _vq_quantlist__44c9_s_p5_1[] = {
  134637. 5,
  134638. 4,
  134639. 6,
  134640. 3,
  134641. 7,
  134642. 2,
  134643. 8,
  134644. 1,
  134645. 9,
  134646. 0,
  134647. 10,
  134648. };
  134649. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134650. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134651. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134652. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134653. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134654. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134655. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134656. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134657. 11,11,11, 7, 7, 7, 7, 7, 7,
  134658. };
  134659. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134660. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134661. 3.5, 4.5,
  134662. };
  134663. static long _vq_quantmap__44c9_s_p5_1[] = {
  134664. 9, 7, 5, 3, 1, 0, 2, 4,
  134665. 6, 8, 10,
  134666. };
  134667. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134668. _vq_quantthresh__44c9_s_p5_1,
  134669. _vq_quantmap__44c9_s_p5_1,
  134670. 11,
  134671. 11
  134672. };
  134673. static static_codebook _44c9_s_p5_1 = {
  134674. 2, 121,
  134675. _vq_lengthlist__44c9_s_p5_1,
  134676. 1, -531365888, 1611661312, 4, 0,
  134677. _vq_quantlist__44c9_s_p5_1,
  134678. NULL,
  134679. &_vq_auxt__44c9_s_p5_1,
  134680. NULL,
  134681. 0
  134682. };
  134683. static long _vq_quantlist__44c9_s_p6_0[] = {
  134684. 6,
  134685. 5,
  134686. 7,
  134687. 4,
  134688. 8,
  134689. 3,
  134690. 9,
  134691. 2,
  134692. 10,
  134693. 1,
  134694. 11,
  134695. 0,
  134696. 12,
  134697. };
  134698. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134699. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134700. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134701. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134702. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134703. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134704. 11, 8, 8, 9, 9,10,10,11,11,12,12, 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,
  134710. };
  134711. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134712. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134713. 12.5, 17.5, 22.5, 27.5,
  134714. };
  134715. static long _vq_quantmap__44c9_s_p6_0[] = {
  134716. 11, 9, 7, 5, 3, 1, 0, 2,
  134717. 4, 6, 8, 10, 12,
  134718. };
  134719. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134720. _vq_quantthresh__44c9_s_p6_0,
  134721. _vq_quantmap__44c9_s_p6_0,
  134722. 13,
  134723. 13
  134724. };
  134725. static static_codebook _44c9_s_p6_0 = {
  134726. 2, 169,
  134727. _vq_lengthlist__44c9_s_p6_0,
  134728. 1, -526516224, 1616117760, 4, 0,
  134729. _vq_quantlist__44c9_s_p6_0,
  134730. NULL,
  134731. &_vq_auxt__44c9_s_p6_0,
  134732. NULL,
  134733. 0
  134734. };
  134735. static long _vq_quantlist__44c9_s_p6_1[] = {
  134736. 2,
  134737. 1,
  134738. 3,
  134739. 0,
  134740. 4,
  134741. };
  134742. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134743. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134744. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134745. };
  134746. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134747. -1.5, -0.5, 0.5, 1.5,
  134748. };
  134749. static long _vq_quantmap__44c9_s_p6_1[] = {
  134750. 3, 1, 0, 2, 4,
  134751. };
  134752. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134753. _vq_quantthresh__44c9_s_p6_1,
  134754. _vq_quantmap__44c9_s_p6_1,
  134755. 5,
  134756. 5
  134757. };
  134758. static static_codebook _44c9_s_p6_1 = {
  134759. 2, 25,
  134760. _vq_lengthlist__44c9_s_p6_1,
  134761. 1, -533725184, 1611661312, 3, 0,
  134762. _vq_quantlist__44c9_s_p6_1,
  134763. NULL,
  134764. &_vq_auxt__44c9_s_p6_1,
  134765. NULL,
  134766. 0
  134767. };
  134768. static long _vq_quantlist__44c9_s_p7_0[] = {
  134769. 6,
  134770. 5,
  134771. 7,
  134772. 4,
  134773. 8,
  134774. 3,
  134775. 9,
  134776. 2,
  134777. 10,
  134778. 1,
  134779. 11,
  134780. 0,
  134781. 12,
  134782. };
  134783. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134784. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134785. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134786. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134787. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134788. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134789. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134790. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134791. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134792. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134793. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134794. 19,12,12,12,12,13,13,14,14,
  134795. };
  134796. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134797. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134798. 27.5, 38.5, 49.5, 60.5,
  134799. };
  134800. static long _vq_quantmap__44c9_s_p7_0[] = {
  134801. 11, 9, 7, 5, 3, 1, 0, 2,
  134802. 4, 6, 8, 10, 12,
  134803. };
  134804. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134805. _vq_quantthresh__44c9_s_p7_0,
  134806. _vq_quantmap__44c9_s_p7_0,
  134807. 13,
  134808. 13
  134809. };
  134810. static static_codebook _44c9_s_p7_0 = {
  134811. 2, 169,
  134812. _vq_lengthlist__44c9_s_p7_0,
  134813. 1, -523206656, 1618345984, 4, 0,
  134814. _vq_quantlist__44c9_s_p7_0,
  134815. NULL,
  134816. &_vq_auxt__44c9_s_p7_0,
  134817. NULL,
  134818. 0
  134819. };
  134820. static long _vq_quantlist__44c9_s_p7_1[] = {
  134821. 5,
  134822. 4,
  134823. 6,
  134824. 3,
  134825. 7,
  134826. 2,
  134827. 8,
  134828. 1,
  134829. 9,
  134830. 0,
  134831. 10,
  134832. };
  134833. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134834. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134835. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134836. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134837. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134838. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134839. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134840. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134841. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134842. };
  134843. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134844. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134845. 3.5, 4.5,
  134846. };
  134847. static long _vq_quantmap__44c9_s_p7_1[] = {
  134848. 9, 7, 5, 3, 1, 0, 2, 4,
  134849. 6, 8, 10,
  134850. };
  134851. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134852. _vq_quantthresh__44c9_s_p7_1,
  134853. _vq_quantmap__44c9_s_p7_1,
  134854. 11,
  134855. 11
  134856. };
  134857. static static_codebook _44c9_s_p7_1 = {
  134858. 2, 121,
  134859. _vq_lengthlist__44c9_s_p7_1,
  134860. 1, -531365888, 1611661312, 4, 0,
  134861. _vq_quantlist__44c9_s_p7_1,
  134862. NULL,
  134863. &_vq_auxt__44c9_s_p7_1,
  134864. NULL,
  134865. 0
  134866. };
  134867. static long _vq_quantlist__44c9_s_p8_0[] = {
  134868. 7,
  134869. 6,
  134870. 8,
  134871. 5,
  134872. 9,
  134873. 4,
  134874. 10,
  134875. 3,
  134876. 11,
  134877. 2,
  134878. 12,
  134879. 1,
  134880. 13,
  134881. 0,
  134882. 14,
  134883. };
  134884. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134885. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134886. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134887. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134888. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134889. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134890. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134891. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134892. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134893. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134894. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134895. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134896. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134897. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134898. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134899. 14,
  134900. };
  134901. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134902. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134903. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134904. };
  134905. static long _vq_quantmap__44c9_s_p8_0[] = {
  134906. 13, 11, 9, 7, 5, 3, 1, 0,
  134907. 2, 4, 6, 8, 10, 12, 14,
  134908. };
  134909. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134910. _vq_quantthresh__44c9_s_p8_0,
  134911. _vq_quantmap__44c9_s_p8_0,
  134912. 15,
  134913. 15
  134914. };
  134915. static static_codebook _44c9_s_p8_0 = {
  134916. 2, 225,
  134917. _vq_lengthlist__44c9_s_p8_0,
  134918. 1, -520986624, 1620377600, 4, 0,
  134919. _vq_quantlist__44c9_s_p8_0,
  134920. NULL,
  134921. &_vq_auxt__44c9_s_p8_0,
  134922. NULL,
  134923. 0
  134924. };
  134925. static long _vq_quantlist__44c9_s_p8_1[] = {
  134926. 10,
  134927. 9,
  134928. 11,
  134929. 8,
  134930. 12,
  134931. 7,
  134932. 13,
  134933. 6,
  134934. 14,
  134935. 5,
  134936. 15,
  134937. 4,
  134938. 16,
  134939. 3,
  134940. 17,
  134941. 2,
  134942. 18,
  134943. 1,
  134944. 19,
  134945. 0,
  134946. 20,
  134947. };
  134948. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134949. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134950. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134951. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134952. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134953. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134954. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134955. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134956. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134957. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134958. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134959. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134960. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134961. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134962. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134963. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134964. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134965. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134966. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134967. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134968. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134969. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134970. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134971. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134972. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134973. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134974. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134975. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134976. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134977. };
  134978. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134979. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134980. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134981. 6.5, 7.5, 8.5, 9.5,
  134982. };
  134983. static long _vq_quantmap__44c9_s_p8_1[] = {
  134984. 19, 17, 15, 13, 11, 9, 7, 5,
  134985. 3, 1, 0, 2, 4, 6, 8, 10,
  134986. 12, 14, 16, 18, 20,
  134987. };
  134988. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134989. _vq_quantthresh__44c9_s_p8_1,
  134990. _vq_quantmap__44c9_s_p8_1,
  134991. 21,
  134992. 21
  134993. };
  134994. static static_codebook _44c9_s_p8_1 = {
  134995. 2, 441,
  134996. _vq_lengthlist__44c9_s_p8_1,
  134997. 1, -529268736, 1611661312, 5, 0,
  134998. _vq_quantlist__44c9_s_p8_1,
  134999. NULL,
  135000. &_vq_auxt__44c9_s_p8_1,
  135001. NULL,
  135002. 0
  135003. };
  135004. static long _vq_quantlist__44c9_s_p9_0[] = {
  135005. 9,
  135006. 8,
  135007. 10,
  135008. 7,
  135009. 11,
  135010. 6,
  135011. 12,
  135012. 5,
  135013. 13,
  135014. 4,
  135015. 14,
  135016. 3,
  135017. 15,
  135018. 2,
  135019. 16,
  135020. 1,
  135021. 17,
  135022. 0,
  135023. 18,
  135024. };
  135025. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135026. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135027. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135028. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135029. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135030. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135031. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135032. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135033. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135034. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135035. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135036. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135037. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135038. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135039. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135040. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135041. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135042. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135048. 11,11,11,11,11,11,11,11,11,
  135049. };
  135050. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135051. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135052. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135053. 6982.5, 7913.5,
  135054. };
  135055. static long _vq_quantmap__44c9_s_p9_0[] = {
  135056. 17, 15, 13, 11, 9, 7, 5, 3,
  135057. 1, 0, 2, 4, 6, 8, 10, 12,
  135058. 14, 16, 18,
  135059. };
  135060. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135061. _vq_quantthresh__44c9_s_p9_0,
  135062. _vq_quantmap__44c9_s_p9_0,
  135063. 19,
  135064. 19
  135065. };
  135066. static static_codebook _44c9_s_p9_0 = {
  135067. 2, 361,
  135068. _vq_lengthlist__44c9_s_p9_0,
  135069. 1, -508535424, 1631393792, 5, 0,
  135070. _vq_quantlist__44c9_s_p9_0,
  135071. NULL,
  135072. &_vq_auxt__44c9_s_p9_0,
  135073. NULL,
  135074. 0
  135075. };
  135076. static long _vq_quantlist__44c9_s_p9_1[] = {
  135077. 9,
  135078. 8,
  135079. 10,
  135080. 7,
  135081. 11,
  135082. 6,
  135083. 12,
  135084. 5,
  135085. 13,
  135086. 4,
  135087. 14,
  135088. 3,
  135089. 15,
  135090. 2,
  135091. 16,
  135092. 1,
  135093. 17,
  135094. 0,
  135095. 18,
  135096. };
  135097. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135098. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135099. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135100. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135101. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135102. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135103. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135104. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135105. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135106. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135107. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135108. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135109. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135110. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135111. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135112. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135113. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135114. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135115. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135116. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135117. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135118. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135119. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135120. 13,13,13,14,13,14,15,15,15,
  135121. };
  135122. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135123. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135124. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135125. 367.5, 416.5,
  135126. };
  135127. static long _vq_quantmap__44c9_s_p9_1[] = {
  135128. 17, 15, 13, 11, 9, 7, 5, 3,
  135129. 1, 0, 2, 4, 6, 8, 10, 12,
  135130. 14, 16, 18,
  135131. };
  135132. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135133. _vq_quantthresh__44c9_s_p9_1,
  135134. _vq_quantmap__44c9_s_p9_1,
  135135. 19,
  135136. 19
  135137. };
  135138. static static_codebook _44c9_s_p9_1 = {
  135139. 2, 361,
  135140. _vq_lengthlist__44c9_s_p9_1,
  135141. 1, -518287360, 1622704128, 5, 0,
  135142. _vq_quantlist__44c9_s_p9_1,
  135143. NULL,
  135144. &_vq_auxt__44c9_s_p9_1,
  135145. NULL,
  135146. 0
  135147. };
  135148. static long _vq_quantlist__44c9_s_p9_2[] = {
  135149. 24,
  135150. 23,
  135151. 25,
  135152. 22,
  135153. 26,
  135154. 21,
  135155. 27,
  135156. 20,
  135157. 28,
  135158. 19,
  135159. 29,
  135160. 18,
  135161. 30,
  135162. 17,
  135163. 31,
  135164. 16,
  135165. 32,
  135166. 15,
  135167. 33,
  135168. 14,
  135169. 34,
  135170. 13,
  135171. 35,
  135172. 12,
  135173. 36,
  135174. 11,
  135175. 37,
  135176. 10,
  135177. 38,
  135178. 9,
  135179. 39,
  135180. 8,
  135181. 40,
  135182. 7,
  135183. 41,
  135184. 6,
  135185. 42,
  135186. 5,
  135187. 43,
  135188. 4,
  135189. 44,
  135190. 3,
  135191. 45,
  135192. 2,
  135193. 46,
  135194. 1,
  135195. 47,
  135196. 0,
  135197. 48,
  135198. };
  135199. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135200. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135201. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135202. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135203. 7,
  135204. };
  135205. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135206. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135207. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135208. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135209. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135210. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135211. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135212. };
  135213. static long _vq_quantmap__44c9_s_p9_2[] = {
  135214. 47, 45, 43, 41, 39, 37, 35, 33,
  135215. 31, 29, 27, 25, 23, 21, 19, 17,
  135216. 15, 13, 11, 9, 7, 5, 3, 1,
  135217. 0, 2, 4, 6, 8, 10, 12, 14,
  135218. 16, 18, 20, 22, 24, 26, 28, 30,
  135219. 32, 34, 36, 38, 40, 42, 44, 46,
  135220. 48,
  135221. };
  135222. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135223. _vq_quantthresh__44c9_s_p9_2,
  135224. _vq_quantmap__44c9_s_p9_2,
  135225. 49,
  135226. 49
  135227. };
  135228. static static_codebook _44c9_s_p9_2 = {
  135229. 1, 49,
  135230. _vq_lengthlist__44c9_s_p9_2,
  135231. 1, -526909440, 1611661312, 6, 0,
  135232. _vq_quantlist__44c9_s_p9_2,
  135233. NULL,
  135234. &_vq_auxt__44c9_s_p9_2,
  135235. NULL,
  135236. 0
  135237. };
  135238. static long _huff_lengthlist__44c9_s_short[] = {
  135239. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135240. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135241. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135242. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135243. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135244. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135245. 9, 8,10,13,
  135246. };
  135247. static static_codebook _huff_book__44c9_s_short = {
  135248. 2, 100,
  135249. _huff_lengthlist__44c9_s_short,
  135250. 0, 0, 0, 0, 0,
  135251. NULL,
  135252. NULL,
  135253. NULL,
  135254. NULL,
  135255. 0
  135256. };
  135257. static long _huff_lengthlist__44c0_s_long[] = {
  135258. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135259. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135260. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135261. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135262. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135263. 12,
  135264. };
  135265. static static_codebook _huff_book__44c0_s_long = {
  135266. 2, 81,
  135267. _huff_lengthlist__44c0_s_long,
  135268. 0, 0, 0, 0, 0,
  135269. NULL,
  135270. NULL,
  135271. NULL,
  135272. NULL,
  135273. 0
  135274. };
  135275. static long _vq_quantlist__44c0_s_p1_0[] = {
  135276. 1,
  135277. 0,
  135278. 2,
  135279. };
  135280. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135281. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135282. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135287. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135292. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135327. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135332. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135337. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135372. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135373. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135377. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135378. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135382. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135383. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 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,
  135692. };
  135693. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135694. -0.5, 0.5,
  135695. };
  135696. static long _vq_quantmap__44c0_s_p1_0[] = {
  135697. 1, 0, 2,
  135698. };
  135699. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135700. _vq_quantthresh__44c0_s_p1_0,
  135701. _vq_quantmap__44c0_s_p1_0,
  135702. 3,
  135703. 3
  135704. };
  135705. static static_codebook _44c0_s_p1_0 = {
  135706. 8, 6561,
  135707. _vq_lengthlist__44c0_s_p1_0,
  135708. 1, -535822336, 1611661312, 2, 0,
  135709. _vq_quantlist__44c0_s_p1_0,
  135710. NULL,
  135711. &_vq_auxt__44c0_s_p1_0,
  135712. NULL,
  135713. 0
  135714. };
  135715. static long _vq_quantlist__44c0_s_p2_0[] = {
  135716. 2,
  135717. 1,
  135718. 3,
  135719. 0,
  135720. 4,
  135721. };
  135722. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135723. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  135763. };
  135764. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135765. -1.5, -0.5, 0.5, 1.5,
  135766. };
  135767. static long _vq_quantmap__44c0_s_p2_0[] = {
  135768. 3, 1, 0, 2, 4,
  135769. };
  135770. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135771. _vq_quantthresh__44c0_s_p2_0,
  135772. _vq_quantmap__44c0_s_p2_0,
  135773. 5,
  135774. 5
  135775. };
  135776. static static_codebook _44c0_s_p2_0 = {
  135777. 4, 625,
  135778. _vq_lengthlist__44c0_s_p2_0,
  135779. 1, -533725184, 1611661312, 3, 0,
  135780. _vq_quantlist__44c0_s_p2_0,
  135781. NULL,
  135782. &_vq_auxt__44c0_s_p2_0,
  135783. NULL,
  135784. 0
  135785. };
  135786. static long _vq_quantlist__44c0_s_p3_0[] = {
  135787. 4,
  135788. 3,
  135789. 5,
  135790. 2,
  135791. 6,
  135792. 1,
  135793. 7,
  135794. 0,
  135795. 8,
  135796. };
  135797. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135798. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135799. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135800. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135801. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135802. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0,
  135804. };
  135805. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135806. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135807. };
  135808. static long _vq_quantmap__44c0_s_p3_0[] = {
  135809. 7, 5, 3, 1, 0, 2, 4, 6,
  135810. 8,
  135811. };
  135812. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135813. _vq_quantthresh__44c0_s_p3_0,
  135814. _vq_quantmap__44c0_s_p3_0,
  135815. 9,
  135816. 9
  135817. };
  135818. static static_codebook _44c0_s_p3_0 = {
  135819. 2, 81,
  135820. _vq_lengthlist__44c0_s_p3_0,
  135821. 1, -531628032, 1611661312, 4, 0,
  135822. _vq_quantlist__44c0_s_p3_0,
  135823. NULL,
  135824. &_vq_auxt__44c0_s_p3_0,
  135825. NULL,
  135826. 0
  135827. };
  135828. static long _vq_quantlist__44c0_s_p4_0[] = {
  135829. 4,
  135830. 3,
  135831. 5,
  135832. 2,
  135833. 6,
  135834. 1,
  135835. 7,
  135836. 0,
  135837. 8,
  135838. };
  135839. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135840. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135841. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135842. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135843. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135844. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135845. 10,
  135846. };
  135847. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135848. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135849. };
  135850. static long _vq_quantmap__44c0_s_p4_0[] = {
  135851. 7, 5, 3, 1, 0, 2, 4, 6,
  135852. 8,
  135853. };
  135854. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135855. _vq_quantthresh__44c0_s_p4_0,
  135856. _vq_quantmap__44c0_s_p4_0,
  135857. 9,
  135858. 9
  135859. };
  135860. static static_codebook _44c0_s_p4_0 = {
  135861. 2, 81,
  135862. _vq_lengthlist__44c0_s_p4_0,
  135863. 1, -531628032, 1611661312, 4, 0,
  135864. _vq_quantlist__44c0_s_p4_0,
  135865. NULL,
  135866. &_vq_auxt__44c0_s_p4_0,
  135867. NULL,
  135868. 0
  135869. };
  135870. static long _vq_quantlist__44c0_s_p5_0[] = {
  135871. 8,
  135872. 7,
  135873. 9,
  135874. 6,
  135875. 10,
  135876. 5,
  135877. 11,
  135878. 4,
  135879. 12,
  135880. 3,
  135881. 13,
  135882. 2,
  135883. 14,
  135884. 1,
  135885. 15,
  135886. 0,
  135887. 16,
  135888. };
  135889. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135890. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135891. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135892. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135893. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135894. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135895. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135896. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135897. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135898. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135899. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135900. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135901. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135902. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135903. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135904. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135905. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135906. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135908. 14,
  135909. };
  135910. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135911. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135912. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135913. };
  135914. static long _vq_quantmap__44c0_s_p5_0[] = {
  135915. 15, 13, 11, 9, 7, 5, 3, 1,
  135916. 0, 2, 4, 6, 8, 10, 12, 14,
  135917. 16,
  135918. };
  135919. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135920. _vq_quantthresh__44c0_s_p5_0,
  135921. _vq_quantmap__44c0_s_p5_0,
  135922. 17,
  135923. 17
  135924. };
  135925. static static_codebook _44c0_s_p5_0 = {
  135926. 2, 289,
  135927. _vq_lengthlist__44c0_s_p5_0,
  135928. 1, -529530880, 1611661312, 5, 0,
  135929. _vq_quantlist__44c0_s_p5_0,
  135930. NULL,
  135931. &_vq_auxt__44c0_s_p5_0,
  135932. NULL,
  135933. 0
  135934. };
  135935. static long _vq_quantlist__44c0_s_p6_0[] = {
  135936. 1,
  135937. 0,
  135938. 2,
  135939. };
  135940. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135941. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135942. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135943. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135944. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135945. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135946. 10,
  135947. };
  135948. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135949. -5.5, 5.5,
  135950. };
  135951. static long _vq_quantmap__44c0_s_p6_0[] = {
  135952. 1, 0, 2,
  135953. };
  135954. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135955. _vq_quantthresh__44c0_s_p6_0,
  135956. _vq_quantmap__44c0_s_p6_0,
  135957. 3,
  135958. 3
  135959. };
  135960. static static_codebook _44c0_s_p6_0 = {
  135961. 4, 81,
  135962. _vq_lengthlist__44c0_s_p6_0,
  135963. 1, -529137664, 1618345984, 2, 0,
  135964. _vq_quantlist__44c0_s_p6_0,
  135965. NULL,
  135966. &_vq_auxt__44c0_s_p6_0,
  135967. NULL,
  135968. 0
  135969. };
  135970. static long _vq_quantlist__44c0_s_p6_1[] = {
  135971. 5,
  135972. 4,
  135973. 6,
  135974. 3,
  135975. 7,
  135976. 2,
  135977. 8,
  135978. 1,
  135979. 9,
  135980. 0,
  135981. 10,
  135982. };
  135983. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135984. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135985. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135986. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135987. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135988. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135989. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135990. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135991. 10,10,10, 8, 8, 8, 8, 8, 8,
  135992. };
  135993. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135994. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135995. 3.5, 4.5,
  135996. };
  135997. static long _vq_quantmap__44c0_s_p6_1[] = {
  135998. 9, 7, 5, 3, 1, 0, 2, 4,
  135999. 6, 8, 10,
  136000. };
  136001. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136002. _vq_quantthresh__44c0_s_p6_1,
  136003. _vq_quantmap__44c0_s_p6_1,
  136004. 11,
  136005. 11
  136006. };
  136007. static static_codebook _44c0_s_p6_1 = {
  136008. 2, 121,
  136009. _vq_lengthlist__44c0_s_p6_1,
  136010. 1, -531365888, 1611661312, 4, 0,
  136011. _vq_quantlist__44c0_s_p6_1,
  136012. NULL,
  136013. &_vq_auxt__44c0_s_p6_1,
  136014. NULL,
  136015. 0
  136016. };
  136017. static long _vq_quantlist__44c0_s_p7_0[] = {
  136018. 6,
  136019. 5,
  136020. 7,
  136021. 4,
  136022. 8,
  136023. 3,
  136024. 9,
  136025. 2,
  136026. 10,
  136027. 1,
  136028. 11,
  136029. 0,
  136030. 12,
  136031. };
  136032. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136033. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136034. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136035. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136036. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136037. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136038. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136039. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136040. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136041. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136042. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136043. 0,12,12,11,11,12,12,13,13,
  136044. };
  136045. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136046. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136047. 12.5, 17.5, 22.5, 27.5,
  136048. };
  136049. static long _vq_quantmap__44c0_s_p7_0[] = {
  136050. 11, 9, 7, 5, 3, 1, 0, 2,
  136051. 4, 6, 8, 10, 12,
  136052. };
  136053. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136054. _vq_quantthresh__44c0_s_p7_0,
  136055. _vq_quantmap__44c0_s_p7_0,
  136056. 13,
  136057. 13
  136058. };
  136059. static static_codebook _44c0_s_p7_0 = {
  136060. 2, 169,
  136061. _vq_lengthlist__44c0_s_p7_0,
  136062. 1, -526516224, 1616117760, 4, 0,
  136063. _vq_quantlist__44c0_s_p7_0,
  136064. NULL,
  136065. &_vq_auxt__44c0_s_p7_0,
  136066. NULL,
  136067. 0
  136068. };
  136069. static long _vq_quantlist__44c0_s_p7_1[] = {
  136070. 2,
  136071. 1,
  136072. 3,
  136073. 0,
  136074. 4,
  136075. };
  136076. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136077. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136078. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136079. };
  136080. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136081. -1.5, -0.5, 0.5, 1.5,
  136082. };
  136083. static long _vq_quantmap__44c0_s_p7_1[] = {
  136084. 3, 1, 0, 2, 4,
  136085. };
  136086. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136087. _vq_quantthresh__44c0_s_p7_1,
  136088. _vq_quantmap__44c0_s_p7_1,
  136089. 5,
  136090. 5
  136091. };
  136092. static static_codebook _44c0_s_p7_1 = {
  136093. 2, 25,
  136094. _vq_lengthlist__44c0_s_p7_1,
  136095. 1, -533725184, 1611661312, 3, 0,
  136096. _vq_quantlist__44c0_s_p7_1,
  136097. NULL,
  136098. &_vq_auxt__44c0_s_p7_1,
  136099. NULL,
  136100. 0
  136101. };
  136102. static long _vq_quantlist__44c0_s_p8_0[] = {
  136103. 2,
  136104. 1,
  136105. 3,
  136106. 0,
  136107. 4,
  136108. };
  136109. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136110. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136111. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136112. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136113. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136114. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136115. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136116. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136117. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136118. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136119. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136121. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136122. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136124. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136125. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136131. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136132. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136134. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136137. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136138. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136140. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136141. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136142. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136143. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136144. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136148. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136149. 11,
  136150. };
  136151. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136152. -331.5, -110.5, 110.5, 331.5,
  136153. };
  136154. static long _vq_quantmap__44c0_s_p8_0[] = {
  136155. 3, 1, 0, 2, 4,
  136156. };
  136157. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136158. _vq_quantthresh__44c0_s_p8_0,
  136159. _vq_quantmap__44c0_s_p8_0,
  136160. 5,
  136161. 5
  136162. };
  136163. static static_codebook _44c0_s_p8_0 = {
  136164. 4, 625,
  136165. _vq_lengthlist__44c0_s_p8_0,
  136166. 1, -518283264, 1627103232, 3, 0,
  136167. _vq_quantlist__44c0_s_p8_0,
  136168. NULL,
  136169. &_vq_auxt__44c0_s_p8_0,
  136170. NULL,
  136171. 0
  136172. };
  136173. static long _vq_quantlist__44c0_s_p8_1[] = {
  136174. 6,
  136175. 5,
  136176. 7,
  136177. 4,
  136178. 8,
  136179. 3,
  136180. 9,
  136181. 2,
  136182. 10,
  136183. 1,
  136184. 11,
  136185. 0,
  136186. 12,
  136187. };
  136188. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136189. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136190. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136191. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136192. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136193. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136194. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136195. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136196. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136197. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136198. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136199. 16,13,13,12,12,14,14,15,13,
  136200. };
  136201. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136202. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136203. 42.5, 59.5, 76.5, 93.5,
  136204. };
  136205. static long _vq_quantmap__44c0_s_p8_1[] = {
  136206. 11, 9, 7, 5, 3, 1, 0, 2,
  136207. 4, 6, 8, 10, 12,
  136208. };
  136209. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136210. _vq_quantthresh__44c0_s_p8_1,
  136211. _vq_quantmap__44c0_s_p8_1,
  136212. 13,
  136213. 13
  136214. };
  136215. static static_codebook _44c0_s_p8_1 = {
  136216. 2, 169,
  136217. _vq_lengthlist__44c0_s_p8_1,
  136218. 1, -522616832, 1620115456, 4, 0,
  136219. _vq_quantlist__44c0_s_p8_1,
  136220. NULL,
  136221. &_vq_auxt__44c0_s_p8_1,
  136222. NULL,
  136223. 0
  136224. };
  136225. static long _vq_quantlist__44c0_s_p8_2[] = {
  136226. 8,
  136227. 7,
  136228. 9,
  136229. 6,
  136230. 10,
  136231. 5,
  136232. 11,
  136233. 4,
  136234. 12,
  136235. 3,
  136236. 13,
  136237. 2,
  136238. 14,
  136239. 1,
  136240. 15,
  136241. 0,
  136242. 16,
  136243. };
  136244. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136245. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136246. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136247. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136248. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136249. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136250. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136251. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136252. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136253. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136254. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136255. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136256. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136257. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136258. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136259. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136260. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136261. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136262. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136263. 10,
  136264. };
  136265. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136266. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136267. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136268. };
  136269. static long _vq_quantmap__44c0_s_p8_2[] = {
  136270. 15, 13, 11, 9, 7, 5, 3, 1,
  136271. 0, 2, 4, 6, 8, 10, 12, 14,
  136272. 16,
  136273. };
  136274. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136275. _vq_quantthresh__44c0_s_p8_2,
  136276. _vq_quantmap__44c0_s_p8_2,
  136277. 17,
  136278. 17
  136279. };
  136280. static static_codebook _44c0_s_p8_2 = {
  136281. 2, 289,
  136282. _vq_lengthlist__44c0_s_p8_2,
  136283. 1, -529530880, 1611661312, 5, 0,
  136284. _vq_quantlist__44c0_s_p8_2,
  136285. NULL,
  136286. &_vq_auxt__44c0_s_p8_2,
  136287. NULL,
  136288. 0
  136289. };
  136290. static long _huff_lengthlist__44c0_s_short[] = {
  136291. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136292. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136293. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136294. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136295. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136296. 12,
  136297. };
  136298. static static_codebook _huff_book__44c0_s_short = {
  136299. 2, 81,
  136300. _huff_lengthlist__44c0_s_short,
  136301. 0, 0, 0, 0, 0,
  136302. NULL,
  136303. NULL,
  136304. NULL,
  136305. NULL,
  136306. 0
  136307. };
  136308. static long _huff_lengthlist__44c0_sm_long[] = {
  136309. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136310. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136311. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136312. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136313. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136314. 13,
  136315. };
  136316. static static_codebook _huff_book__44c0_sm_long = {
  136317. 2, 81,
  136318. _huff_lengthlist__44c0_sm_long,
  136319. 0, 0, 0, 0, 0,
  136320. NULL,
  136321. NULL,
  136322. NULL,
  136323. NULL,
  136324. 0
  136325. };
  136326. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136327. 1,
  136328. 0,
  136329. 2,
  136330. };
  136331. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136332. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136333. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136338. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136343. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136378. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136383. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136388. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136424. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136429. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136434. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 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,
  136743. };
  136744. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136745. -0.5, 0.5,
  136746. };
  136747. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136748. 1, 0, 2,
  136749. };
  136750. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136751. _vq_quantthresh__44c0_sm_p1_0,
  136752. _vq_quantmap__44c0_sm_p1_0,
  136753. 3,
  136754. 3
  136755. };
  136756. static static_codebook _44c0_sm_p1_0 = {
  136757. 8, 6561,
  136758. _vq_lengthlist__44c0_sm_p1_0,
  136759. 1, -535822336, 1611661312, 2, 0,
  136760. _vq_quantlist__44c0_sm_p1_0,
  136761. NULL,
  136762. &_vq_auxt__44c0_sm_p1_0,
  136763. NULL,
  136764. 0
  136765. };
  136766. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136767. 2,
  136768. 1,
  136769. 3,
  136770. 0,
  136771. 4,
  136772. };
  136773. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136774. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  136814. };
  136815. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136816. -1.5, -0.5, 0.5, 1.5,
  136817. };
  136818. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136819. 3, 1, 0, 2, 4,
  136820. };
  136821. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136822. _vq_quantthresh__44c0_sm_p2_0,
  136823. _vq_quantmap__44c0_sm_p2_0,
  136824. 5,
  136825. 5
  136826. };
  136827. static static_codebook _44c0_sm_p2_0 = {
  136828. 4, 625,
  136829. _vq_lengthlist__44c0_sm_p2_0,
  136830. 1, -533725184, 1611661312, 3, 0,
  136831. _vq_quantlist__44c0_sm_p2_0,
  136832. NULL,
  136833. &_vq_auxt__44c0_sm_p2_0,
  136834. NULL,
  136835. 0
  136836. };
  136837. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136838. 4,
  136839. 3,
  136840. 5,
  136841. 2,
  136842. 6,
  136843. 1,
  136844. 7,
  136845. 0,
  136846. 8,
  136847. };
  136848. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136849. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136850. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136851. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136852. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136853. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0,
  136855. };
  136856. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136857. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136858. };
  136859. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136860. 7, 5, 3, 1, 0, 2, 4, 6,
  136861. 8,
  136862. };
  136863. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136864. _vq_quantthresh__44c0_sm_p3_0,
  136865. _vq_quantmap__44c0_sm_p3_0,
  136866. 9,
  136867. 9
  136868. };
  136869. static static_codebook _44c0_sm_p3_0 = {
  136870. 2, 81,
  136871. _vq_lengthlist__44c0_sm_p3_0,
  136872. 1, -531628032, 1611661312, 4, 0,
  136873. _vq_quantlist__44c0_sm_p3_0,
  136874. NULL,
  136875. &_vq_auxt__44c0_sm_p3_0,
  136876. NULL,
  136877. 0
  136878. };
  136879. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136880. 4,
  136881. 3,
  136882. 5,
  136883. 2,
  136884. 6,
  136885. 1,
  136886. 7,
  136887. 0,
  136888. 8,
  136889. };
  136890. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136891. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136892. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136893. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136894. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136895. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136896. 11,
  136897. };
  136898. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136899. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136900. };
  136901. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136902. 7, 5, 3, 1, 0, 2, 4, 6,
  136903. 8,
  136904. };
  136905. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136906. _vq_quantthresh__44c0_sm_p4_0,
  136907. _vq_quantmap__44c0_sm_p4_0,
  136908. 9,
  136909. 9
  136910. };
  136911. static static_codebook _44c0_sm_p4_0 = {
  136912. 2, 81,
  136913. _vq_lengthlist__44c0_sm_p4_0,
  136914. 1, -531628032, 1611661312, 4, 0,
  136915. _vq_quantlist__44c0_sm_p4_0,
  136916. NULL,
  136917. &_vq_auxt__44c0_sm_p4_0,
  136918. NULL,
  136919. 0
  136920. };
  136921. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136922. 8,
  136923. 7,
  136924. 9,
  136925. 6,
  136926. 10,
  136927. 5,
  136928. 11,
  136929. 4,
  136930. 12,
  136931. 3,
  136932. 13,
  136933. 2,
  136934. 14,
  136935. 1,
  136936. 15,
  136937. 0,
  136938. 16,
  136939. };
  136940. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136941. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136942. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136943. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136944. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136945. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136946. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136947. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136948. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136949. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136950. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136951. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136952. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136953. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136954. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136955. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136956. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136957. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136959. 14,
  136960. };
  136961. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136962. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136963. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136964. };
  136965. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136966. 15, 13, 11, 9, 7, 5, 3, 1,
  136967. 0, 2, 4, 6, 8, 10, 12, 14,
  136968. 16,
  136969. };
  136970. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136971. _vq_quantthresh__44c0_sm_p5_0,
  136972. _vq_quantmap__44c0_sm_p5_0,
  136973. 17,
  136974. 17
  136975. };
  136976. static static_codebook _44c0_sm_p5_0 = {
  136977. 2, 289,
  136978. _vq_lengthlist__44c0_sm_p5_0,
  136979. 1, -529530880, 1611661312, 5, 0,
  136980. _vq_quantlist__44c0_sm_p5_0,
  136981. NULL,
  136982. &_vq_auxt__44c0_sm_p5_0,
  136983. NULL,
  136984. 0
  136985. };
  136986. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136987. 1,
  136988. 0,
  136989. 2,
  136990. };
  136991. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136992. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136993. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136994. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136995. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136996. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136997. 11,
  136998. };
  136999. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137000. -5.5, 5.5,
  137001. };
  137002. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137003. 1, 0, 2,
  137004. };
  137005. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137006. _vq_quantthresh__44c0_sm_p6_0,
  137007. _vq_quantmap__44c0_sm_p6_0,
  137008. 3,
  137009. 3
  137010. };
  137011. static static_codebook _44c0_sm_p6_0 = {
  137012. 4, 81,
  137013. _vq_lengthlist__44c0_sm_p6_0,
  137014. 1, -529137664, 1618345984, 2, 0,
  137015. _vq_quantlist__44c0_sm_p6_0,
  137016. NULL,
  137017. &_vq_auxt__44c0_sm_p6_0,
  137018. NULL,
  137019. 0
  137020. };
  137021. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137022. 5,
  137023. 4,
  137024. 6,
  137025. 3,
  137026. 7,
  137027. 2,
  137028. 8,
  137029. 1,
  137030. 9,
  137031. 0,
  137032. 10,
  137033. };
  137034. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137035. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137036. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137037. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137038. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137039. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137040. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137041. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137042. 10,10,10, 8, 8, 8, 8, 8, 8,
  137043. };
  137044. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137045. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137046. 3.5, 4.5,
  137047. };
  137048. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137049. 9, 7, 5, 3, 1, 0, 2, 4,
  137050. 6, 8, 10,
  137051. };
  137052. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137053. _vq_quantthresh__44c0_sm_p6_1,
  137054. _vq_quantmap__44c0_sm_p6_1,
  137055. 11,
  137056. 11
  137057. };
  137058. static static_codebook _44c0_sm_p6_1 = {
  137059. 2, 121,
  137060. _vq_lengthlist__44c0_sm_p6_1,
  137061. 1, -531365888, 1611661312, 4, 0,
  137062. _vq_quantlist__44c0_sm_p6_1,
  137063. NULL,
  137064. &_vq_auxt__44c0_sm_p6_1,
  137065. NULL,
  137066. 0
  137067. };
  137068. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137069. 6,
  137070. 5,
  137071. 7,
  137072. 4,
  137073. 8,
  137074. 3,
  137075. 9,
  137076. 2,
  137077. 10,
  137078. 1,
  137079. 11,
  137080. 0,
  137081. 12,
  137082. };
  137083. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137084. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137085. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137086. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137087. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137088. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137089. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137090. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137091. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137092. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137093. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137094. 0,12,12,11,11,13,12,14,14,
  137095. };
  137096. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137097. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137098. 12.5, 17.5, 22.5, 27.5,
  137099. };
  137100. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137101. 11, 9, 7, 5, 3, 1, 0, 2,
  137102. 4, 6, 8, 10, 12,
  137103. };
  137104. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137105. _vq_quantthresh__44c0_sm_p7_0,
  137106. _vq_quantmap__44c0_sm_p7_0,
  137107. 13,
  137108. 13
  137109. };
  137110. static static_codebook _44c0_sm_p7_0 = {
  137111. 2, 169,
  137112. _vq_lengthlist__44c0_sm_p7_0,
  137113. 1, -526516224, 1616117760, 4, 0,
  137114. _vq_quantlist__44c0_sm_p7_0,
  137115. NULL,
  137116. &_vq_auxt__44c0_sm_p7_0,
  137117. NULL,
  137118. 0
  137119. };
  137120. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137121. 2,
  137122. 1,
  137123. 3,
  137124. 0,
  137125. 4,
  137126. };
  137127. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137128. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137129. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137130. };
  137131. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137132. -1.5, -0.5, 0.5, 1.5,
  137133. };
  137134. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137135. 3, 1, 0, 2, 4,
  137136. };
  137137. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137138. _vq_quantthresh__44c0_sm_p7_1,
  137139. _vq_quantmap__44c0_sm_p7_1,
  137140. 5,
  137141. 5
  137142. };
  137143. static static_codebook _44c0_sm_p7_1 = {
  137144. 2, 25,
  137145. _vq_lengthlist__44c0_sm_p7_1,
  137146. 1, -533725184, 1611661312, 3, 0,
  137147. _vq_quantlist__44c0_sm_p7_1,
  137148. NULL,
  137149. &_vq_auxt__44c0_sm_p7_1,
  137150. NULL,
  137151. 0
  137152. };
  137153. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137154. 4,
  137155. 3,
  137156. 5,
  137157. 2,
  137158. 6,
  137159. 1,
  137160. 7,
  137161. 0,
  137162. 8,
  137163. };
  137164. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137165. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137166. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137168. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137169. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137170. 12,
  137171. };
  137172. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137173. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137174. };
  137175. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137176. 7, 5, 3, 1, 0, 2, 4, 6,
  137177. 8,
  137178. };
  137179. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137180. _vq_quantthresh__44c0_sm_p8_0,
  137181. _vq_quantmap__44c0_sm_p8_0,
  137182. 9,
  137183. 9
  137184. };
  137185. static static_codebook _44c0_sm_p8_0 = {
  137186. 2, 81,
  137187. _vq_lengthlist__44c0_sm_p8_0,
  137188. 1, -516186112, 1627103232, 4, 0,
  137189. _vq_quantlist__44c0_sm_p8_0,
  137190. NULL,
  137191. &_vq_auxt__44c0_sm_p8_0,
  137192. NULL,
  137193. 0
  137194. };
  137195. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137196. 6,
  137197. 5,
  137198. 7,
  137199. 4,
  137200. 8,
  137201. 3,
  137202. 9,
  137203. 2,
  137204. 10,
  137205. 1,
  137206. 11,
  137207. 0,
  137208. 12,
  137209. };
  137210. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137211. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137212. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137213. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137214. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137215. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137216. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137217. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137218. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137219. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137220. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137221. 20,13,13,12,12,16,13,15,13,
  137222. };
  137223. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137224. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137225. 42.5, 59.5, 76.5, 93.5,
  137226. };
  137227. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137228. 11, 9, 7, 5, 3, 1, 0, 2,
  137229. 4, 6, 8, 10, 12,
  137230. };
  137231. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137232. _vq_quantthresh__44c0_sm_p8_1,
  137233. _vq_quantmap__44c0_sm_p8_1,
  137234. 13,
  137235. 13
  137236. };
  137237. static static_codebook _44c0_sm_p8_1 = {
  137238. 2, 169,
  137239. _vq_lengthlist__44c0_sm_p8_1,
  137240. 1, -522616832, 1620115456, 4, 0,
  137241. _vq_quantlist__44c0_sm_p8_1,
  137242. NULL,
  137243. &_vq_auxt__44c0_sm_p8_1,
  137244. NULL,
  137245. 0
  137246. };
  137247. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137248. 8,
  137249. 7,
  137250. 9,
  137251. 6,
  137252. 10,
  137253. 5,
  137254. 11,
  137255. 4,
  137256. 12,
  137257. 3,
  137258. 13,
  137259. 2,
  137260. 14,
  137261. 1,
  137262. 15,
  137263. 0,
  137264. 16,
  137265. };
  137266. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137267. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137268. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137269. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137270. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137271. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137272. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137273. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137274. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137275. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137276. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137277. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137278. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137279. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137280. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137281. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137282. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137283. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137284. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137285. 9,
  137286. };
  137287. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137288. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137289. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137290. };
  137291. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137292. 15, 13, 11, 9, 7, 5, 3, 1,
  137293. 0, 2, 4, 6, 8, 10, 12, 14,
  137294. 16,
  137295. };
  137296. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137297. _vq_quantthresh__44c0_sm_p8_2,
  137298. _vq_quantmap__44c0_sm_p8_2,
  137299. 17,
  137300. 17
  137301. };
  137302. static static_codebook _44c0_sm_p8_2 = {
  137303. 2, 289,
  137304. _vq_lengthlist__44c0_sm_p8_2,
  137305. 1, -529530880, 1611661312, 5, 0,
  137306. _vq_quantlist__44c0_sm_p8_2,
  137307. NULL,
  137308. &_vq_auxt__44c0_sm_p8_2,
  137309. NULL,
  137310. 0
  137311. };
  137312. static long _huff_lengthlist__44c0_sm_short[] = {
  137313. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137314. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137315. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137316. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137317. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137318. 12,
  137319. };
  137320. static static_codebook _huff_book__44c0_sm_short = {
  137321. 2, 81,
  137322. _huff_lengthlist__44c0_sm_short,
  137323. 0, 0, 0, 0, 0,
  137324. NULL,
  137325. NULL,
  137326. NULL,
  137327. NULL,
  137328. 0
  137329. };
  137330. static long _huff_lengthlist__44c1_s_long[] = {
  137331. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137332. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137333. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137334. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137335. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137336. 11,
  137337. };
  137338. static static_codebook _huff_book__44c1_s_long = {
  137339. 2, 81,
  137340. _huff_lengthlist__44c1_s_long,
  137341. 0, 0, 0, 0, 0,
  137342. NULL,
  137343. NULL,
  137344. NULL,
  137345. NULL,
  137346. 0
  137347. };
  137348. static long _vq_quantlist__44c1_s_p1_0[] = {
  137349. 1,
  137350. 0,
  137351. 2,
  137352. };
  137353. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137354. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137355. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137360. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137365. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137400. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137405. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137410. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137446. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137451. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137456. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 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,
  137765. };
  137766. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137767. -0.5, 0.5,
  137768. };
  137769. static long _vq_quantmap__44c1_s_p1_0[] = {
  137770. 1, 0, 2,
  137771. };
  137772. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137773. _vq_quantthresh__44c1_s_p1_0,
  137774. _vq_quantmap__44c1_s_p1_0,
  137775. 3,
  137776. 3
  137777. };
  137778. static static_codebook _44c1_s_p1_0 = {
  137779. 8, 6561,
  137780. _vq_lengthlist__44c1_s_p1_0,
  137781. 1, -535822336, 1611661312, 2, 0,
  137782. _vq_quantlist__44c1_s_p1_0,
  137783. NULL,
  137784. &_vq_auxt__44c1_s_p1_0,
  137785. NULL,
  137786. 0
  137787. };
  137788. static long _vq_quantlist__44c1_s_p2_0[] = {
  137789. 2,
  137790. 1,
  137791. 3,
  137792. 0,
  137793. 4,
  137794. };
  137795. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137796. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0,
  137836. };
  137837. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137838. -1.5, -0.5, 0.5, 1.5,
  137839. };
  137840. static long _vq_quantmap__44c1_s_p2_0[] = {
  137841. 3, 1, 0, 2, 4,
  137842. };
  137843. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137844. _vq_quantthresh__44c1_s_p2_0,
  137845. _vq_quantmap__44c1_s_p2_0,
  137846. 5,
  137847. 5
  137848. };
  137849. static static_codebook _44c1_s_p2_0 = {
  137850. 4, 625,
  137851. _vq_lengthlist__44c1_s_p2_0,
  137852. 1, -533725184, 1611661312, 3, 0,
  137853. _vq_quantlist__44c1_s_p2_0,
  137854. NULL,
  137855. &_vq_auxt__44c1_s_p2_0,
  137856. NULL,
  137857. 0
  137858. };
  137859. static long _vq_quantlist__44c1_s_p3_0[] = {
  137860. 4,
  137861. 3,
  137862. 5,
  137863. 2,
  137864. 6,
  137865. 1,
  137866. 7,
  137867. 0,
  137868. 8,
  137869. };
  137870. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137871. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137872. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137873. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137874. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137875. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0,
  137877. };
  137878. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137879. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137880. };
  137881. static long _vq_quantmap__44c1_s_p3_0[] = {
  137882. 7, 5, 3, 1, 0, 2, 4, 6,
  137883. 8,
  137884. };
  137885. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137886. _vq_quantthresh__44c1_s_p3_0,
  137887. _vq_quantmap__44c1_s_p3_0,
  137888. 9,
  137889. 9
  137890. };
  137891. static static_codebook _44c1_s_p3_0 = {
  137892. 2, 81,
  137893. _vq_lengthlist__44c1_s_p3_0,
  137894. 1, -531628032, 1611661312, 4, 0,
  137895. _vq_quantlist__44c1_s_p3_0,
  137896. NULL,
  137897. &_vq_auxt__44c1_s_p3_0,
  137898. NULL,
  137899. 0
  137900. };
  137901. static long _vq_quantlist__44c1_s_p4_0[] = {
  137902. 4,
  137903. 3,
  137904. 5,
  137905. 2,
  137906. 6,
  137907. 1,
  137908. 7,
  137909. 0,
  137910. 8,
  137911. };
  137912. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137913. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137914. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137915. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137916. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137917. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137918. 11,
  137919. };
  137920. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137921. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137922. };
  137923. static long _vq_quantmap__44c1_s_p4_0[] = {
  137924. 7, 5, 3, 1, 0, 2, 4, 6,
  137925. 8,
  137926. };
  137927. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137928. _vq_quantthresh__44c1_s_p4_0,
  137929. _vq_quantmap__44c1_s_p4_0,
  137930. 9,
  137931. 9
  137932. };
  137933. static static_codebook _44c1_s_p4_0 = {
  137934. 2, 81,
  137935. _vq_lengthlist__44c1_s_p4_0,
  137936. 1, -531628032, 1611661312, 4, 0,
  137937. _vq_quantlist__44c1_s_p4_0,
  137938. NULL,
  137939. &_vq_auxt__44c1_s_p4_0,
  137940. NULL,
  137941. 0
  137942. };
  137943. static long _vq_quantlist__44c1_s_p5_0[] = {
  137944. 8,
  137945. 7,
  137946. 9,
  137947. 6,
  137948. 10,
  137949. 5,
  137950. 11,
  137951. 4,
  137952. 12,
  137953. 3,
  137954. 13,
  137955. 2,
  137956. 14,
  137957. 1,
  137958. 15,
  137959. 0,
  137960. 16,
  137961. };
  137962. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137963. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137964. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137965. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137966. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137967. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137968. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137969. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137970. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137971. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137972. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137973. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137974. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137975. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137976. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137977. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137978. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137979. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137981. 14,
  137982. };
  137983. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137984. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137985. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137986. };
  137987. static long _vq_quantmap__44c1_s_p5_0[] = {
  137988. 15, 13, 11, 9, 7, 5, 3, 1,
  137989. 0, 2, 4, 6, 8, 10, 12, 14,
  137990. 16,
  137991. };
  137992. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137993. _vq_quantthresh__44c1_s_p5_0,
  137994. _vq_quantmap__44c1_s_p5_0,
  137995. 17,
  137996. 17
  137997. };
  137998. static static_codebook _44c1_s_p5_0 = {
  137999. 2, 289,
  138000. _vq_lengthlist__44c1_s_p5_0,
  138001. 1, -529530880, 1611661312, 5, 0,
  138002. _vq_quantlist__44c1_s_p5_0,
  138003. NULL,
  138004. &_vq_auxt__44c1_s_p5_0,
  138005. NULL,
  138006. 0
  138007. };
  138008. static long _vq_quantlist__44c1_s_p6_0[] = {
  138009. 1,
  138010. 0,
  138011. 2,
  138012. };
  138013. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138014. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138015. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138016. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138017. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138018. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138019. 11,
  138020. };
  138021. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138022. -5.5, 5.5,
  138023. };
  138024. static long _vq_quantmap__44c1_s_p6_0[] = {
  138025. 1, 0, 2,
  138026. };
  138027. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138028. _vq_quantthresh__44c1_s_p6_0,
  138029. _vq_quantmap__44c1_s_p6_0,
  138030. 3,
  138031. 3
  138032. };
  138033. static static_codebook _44c1_s_p6_0 = {
  138034. 4, 81,
  138035. _vq_lengthlist__44c1_s_p6_0,
  138036. 1, -529137664, 1618345984, 2, 0,
  138037. _vq_quantlist__44c1_s_p6_0,
  138038. NULL,
  138039. &_vq_auxt__44c1_s_p6_0,
  138040. NULL,
  138041. 0
  138042. };
  138043. static long _vq_quantlist__44c1_s_p6_1[] = {
  138044. 5,
  138045. 4,
  138046. 6,
  138047. 3,
  138048. 7,
  138049. 2,
  138050. 8,
  138051. 1,
  138052. 9,
  138053. 0,
  138054. 10,
  138055. };
  138056. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138057. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138058. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138059. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138060. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138061. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138062. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138063. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138064. 10,10,10, 8, 8, 8, 8, 8, 8,
  138065. };
  138066. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138067. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138068. 3.5, 4.5,
  138069. };
  138070. static long _vq_quantmap__44c1_s_p6_1[] = {
  138071. 9, 7, 5, 3, 1, 0, 2, 4,
  138072. 6, 8, 10,
  138073. };
  138074. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138075. _vq_quantthresh__44c1_s_p6_1,
  138076. _vq_quantmap__44c1_s_p6_1,
  138077. 11,
  138078. 11
  138079. };
  138080. static static_codebook _44c1_s_p6_1 = {
  138081. 2, 121,
  138082. _vq_lengthlist__44c1_s_p6_1,
  138083. 1, -531365888, 1611661312, 4, 0,
  138084. _vq_quantlist__44c1_s_p6_1,
  138085. NULL,
  138086. &_vq_auxt__44c1_s_p6_1,
  138087. NULL,
  138088. 0
  138089. };
  138090. static long _vq_quantlist__44c1_s_p7_0[] = {
  138091. 6,
  138092. 5,
  138093. 7,
  138094. 4,
  138095. 8,
  138096. 3,
  138097. 9,
  138098. 2,
  138099. 10,
  138100. 1,
  138101. 11,
  138102. 0,
  138103. 12,
  138104. };
  138105. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138106. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138107. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138108. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138109. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138110. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138111. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138112. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138113. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138114. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138115. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138116. 0,12,11,11,11,13,10,14,13,
  138117. };
  138118. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138119. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138120. 12.5, 17.5, 22.5, 27.5,
  138121. };
  138122. static long _vq_quantmap__44c1_s_p7_0[] = {
  138123. 11, 9, 7, 5, 3, 1, 0, 2,
  138124. 4, 6, 8, 10, 12,
  138125. };
  138126. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138127. _vq_quantthresh__44c1_s_p7_0,
  138128. _vq_quantmap__44c1_s_p7_0,
  138129. 13,
  138130. 13
  138131. };
  138132. static static_codebook _44c1_s_p7_0 = {
  138133. 2, 169,
  138134. _vq_lengthlist__44c1_s_p7_0,
  138135. 1, -526516224, 1616117760, 4, 0,
  138136. _vq_quantlist__44c1_s_p7_0,
  138137. NULL,
  138138. &_vq_auxt__44c1_s_p7_0,
  138139. NULL,
  138140. 0
  138141. };
  138142. static long _vq_quantlist__44c1_s_p7_1[] = {
  138143. 2,
  138144. 1,
  138145. 3,
  138146. 0,
  138147. 4,
  138148. };
  138149. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138150. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138151. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138152. };
  138153. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138154. -1.5, -0.5, 0.5, 1.5,
  138155. };
  138156. static long _vq_quantmap__44c1_s_p7_1[] = {
  138157. 3, 1, 0, 2, 4,
  138158. };
  138159. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138160. _vq_quantthresh__44c1_s_p7_1,
  138161. _vq_quantmap__44c1_s_p7_1,
  138162. 5,
  138163. 5
  138164. };
  138165. static static_codebook _44c1_s_p7_1 = {
  138166. 2, 25,
  138167. _vq_lengthlist__44c1_s_p7_1,
  138168. 1, -533725184, 1611661312, 3, 0,
  138169. _vq_quantlist__44c1_s_p7_1,
  138170. NULL,
  138171. &_vq_auxt__44c1_s_p7_1,
  138172. NULL,
  138173. 0
  138174. };
  138175. static long _vq_quantlist__44c1_s_p8_0[] = {
  138176. 6,
  138177. 5,
  138178. 7,
  138179. 4,
  138180. 8,
  138181. 3,
  138182. 9,
  138183. 2,
  138184. 10,
  138185. 1,
  138186. 11,
  138187. 0,
  138188. 12,
  138189. };
  138190. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138191. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138192. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138198. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138199. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138200. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138201. 10,10,10,10,10,10,10,10,10,
  138202. };
  138203. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138204. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138205. 552.5, 773.5, 994.5, 1215.5,
  138206. };
  138207. static long _vq_quantmap__44c1_s_p8_0[] = {
  138208. 11, 9, 7, 5, 3, 1, 0, 2,
  138209. 4, 6, 8, 10, 12,
  138210. };
  138211. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138212. _vq_quantthresh__44c1_s_p8_0,
  138213. _vq_quantmap__44c1_s_p8_0,
  138214. 13,
  138215. 13
  138216. };
  138217. static static_codebook _44c1_s_p8_0 = {
  138218. 2, 169,
  138219. _vq_lengthlist__44c1_s_p8_0,
  138220. 1, -514541568, 1627103232, 4, 0,
  138221. _vq_quantlist__44c1_s_p8_0,
  138222. NULL,
  138223. &_vq_auxt__44c1_s_p8_0,
  138224. NULL,
  138225. 0
  138226. };
  138227. static long _vq_quantlist__44c1_s_p8_1[] = {
  138228. 6,
  138229. 5,
  138230. 7,
  138231. 4,
  138232. 8,
  138233. 3,
  138234. 9,
  138235. 2,
  138236. 10,
  138237. 1,
  138238. 11,
  138239. 0,
  138240. 12,
  138241. };
  138242. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138243. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138244. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138245. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138246. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138247. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138248. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138249. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138250. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138251. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138252. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138253. 16,13,12,12,11,14,12,15,13,
  138254. };
  138255. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138256. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138257. 42.5, 59.5, 76.5, 93.5,
  138258. };
  138259. static long _vq_quantmap__44c1_s_p8_1[] = {
  138260. 11, 9, 7, 5, 3, 1, 0, 2,
  138261. 4, 6, 8, 10, 12,
  138262. };
  138263. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138264. _vq_quantthresh__44c1_s_p8_1,
  138265. _vq_quantmap__44c1_s_p8_1,
  138266. 13,
  138267. 13
  138268. };
  138269. static static_codebook _44c1_s_p8_1 = {
  138270. 2, 169,
  138271. _vq_lengthlist__44c1_s_p8_1,
  138272. 1, -522616832, 1620115456, 4, 0,
  138273. _vq_quantlist__44c1_s_p8_1,
  138274. NULL,
  138275. &_vq_auxt__44c1_s_p8_1,
  138276. NULL,
  138277. 0
  138278. };
  138279. static long _vq_quantlist__44c1_s_p8_2[] = {
  138280. 8,
  138281. 7,
  138282. 9,
  138283. 6,
  138284. 10,
  138285. 5,
  138286. 11,
  138287. 4,
  138288. 12,
  138289. 3,
  138290. 13,
  138291. 2,
  138292. 14,
  138293. 1,
  138294. 15,
  138295. 0,
  138296. 16,
  138297. };
  138298. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138299. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138300. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138301. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138302. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138303. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138304. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138305. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138306. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138307. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138308. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138309. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138310. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138311. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138312. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138313. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138314. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138315. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138316. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138317. 9,
  138318. };
  138319. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138322. };
  138323. static long _vq_quantmap__44c1_s_p8_2[] = {
  138324. 15, 13, 11, 9, 7, 5, 3, 1,
  138325. 0, 2, 4, 6, 8, 10, 12, 14,
  138326. 16,
  138327. };
  138328. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138329. _vq_quantthresh__44c1_s_p8_2,
  138330. _vq_quantmap__44c1_s_p8_2,
  138331. 17,
  138332. 17
  138333. };
  138334. static static_codebook _44c1_s_p8_2 = {
  138335. 2, 289,
  138336. _vq_lengthlist__44c1_s_p8_2,
  138337. 1, -529530880, 1611661312, 5, 0,
  138338. _vq_quantlist__44c1_s_p8_2,
  138339. NULL,
  138340. &_vq_auxt__44c1_s_p8_2,
  138341. NULL,
  138342. 0
  138343. };
  138344. static long _huff_lengthlist__44c1_s_short[] = {
  138345. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138346. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138347. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138348. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138349. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138350. 11,
  138351. };
  138352. static static_codebook _huff_book__44c1_s_short = {
  138353. 2, 81,
  138354. _huff_lengthlist__44c1_s_short,
  138355. 0, 0, 0, 0, 0,
  138356. NULL,
  138357. NULL,
  138358. NULL,
  138359. NULL,
  138360. 0
  138361. };
  138362. static long _huff_lengthlist__44c1_sm_long[] = {
  138363. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138364. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138365. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138366. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138367. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138368. 11,
  138369. };
  138370. static static_codebook _huff_book__44c1_sm_long = {
  138371. 2, 81,
  138372. _huff_lengthlist__44c1_sm_long,
  138373. 0, 0, 0, 0, 0,
  138374. NULL,
  138375. NULL,
  138376. NULL,
  138377. NULL,
  138378. 0
  138379. };
  138380. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138381. 1,
  138382. 0,
  138383. 2,
  138384. };
  138385. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138386. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138387. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138392. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138397. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138432. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138437. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138442. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138478. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138483. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138488. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138770. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138775. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138780. 0, 0, 0, 0, 0, 0, 0, 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,
  138797. };
  138798. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138799. -0.5, 0.5,
  138800. };
  138801. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138802. 1, 0, 2,
  138803. };
  138804. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138805. _vq_quantthresh__44c1_sm_p1_0,
  138806. _vq_quantmap__44c1_sm_p1_0,
  138807. 3,
  138808. 3
  138809. };
  138810. static static_codebook _44c1_sm_p1_0 = {
  138811. 8, 6561,
  138812. _vq_lengthlist__44c1_sm_p1_0,
  138813. 1, -535822336, 1611661312, 2, 0,
  138814. _vq_quantlist__44c1_sm_p1_0,
  138815. NULL,
  138816. &_vq_auxt__44c1_sm_p1_0,
  138817. NULL,
  138818. 0
  138819. };
  138820. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138821. 2,
  138822. 1,
  138823. 3,
  138824. 0,
  138825. 4,
  138826. };
  138827. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138828. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0,
  138868. };
  138869. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138870. -1.5, -0.5, 0.5, 1.5,
  138871. };
  138872. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138873. 3, 1, 0, 2, 4,
  138874. };
  138875. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138876. _vq_quantthresh__44c1_sm_p2_0,
  138877. _vq_quantmap__44c1_sm_p2_0,
  138878. 5,
  138879. 5
  138880. };
  138881. static static_codebook _44c1_sm_p2_0 = {
  138882. 4, 625,
  138883. _vq_lengthlist__44c1_sm_p2_0,
  138884. 1, -533725184, 1611661312, 3, 0,
  138885. _vq_quantlist__44c1_sm_p2_0,
  138886. NULL,
  138887. &_vq_auxt__44c1_sm_p2_0,
  138888. NULL,
  138889. 0
  138890. };
  138891. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138892. 4,
  138893. 3,
  138894. 5,
  138895. 2,
  138896. 6,
  138897. 1,
  138898. 7,
  138899. 0,
  138900. 8,
  138901. };
  138902. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138903. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138904. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138905. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138906. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138907. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0,
  138909. };
  138910. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138911. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138912. };
  138913. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138914. 7, 5, 3, 1, 0, 2, 4, 6,
  138915. 8,
  138916. };
  138917. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138918. _vq_quantthresh__44c1_sm_p3_0,
  138919. _vq_quantmap__44c1_sm_p3_0,
  138920. 9,
  138921. 9
  138922. };
  138923. static static_codebook _44c1_sm_p3_0 = {
  138924. 2, 81,
  138925. _vq_lengthlist__44c1_sm_p3_0,
  138926. 1, -531628032, 1611661312, 4, 0,
  138927. _vq_quantlist__44c1_sm_p3_0,
  138928. NULL,
  138929. &_vq_auxt__44c1_sm_p3_0,
  138930. NULL,
  138931. 0
  138932. };
  138933. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138934. 4,
  138935. 3,
  138936. 5,
  138937. 2,
  138938. 6,
  138939. 1,
  138940. 7,
  138941. 0,
  138942. 8,
  138943. };
  138944. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138945. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138946. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138947. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138948. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138949. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138950. 11,
  138951. };
  138952. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138953. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138954. };
  138955. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138956. 7, 5, 3, 1, 0, 2, 4, 6,
  138957. 8,
  138958. };
  138959. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138960. _vq_quantthresh__44c1_sm_p4_0,
  138961. _vq_quantmap__44c1_sm_p4_0,
  138962. 9,
  138963. 9
  138964. };
  138965. static static_codebook _44c1_sm_p4_0 = {
  138966. 2, 81,
  138967. _vq_lengthlist__44c1_sm_p4_0,
  138968. 1, -531628032, 1611661312, 4, 0,
  138969. _vq_quantlist__44c1_sm_p4_0,
  138970. NULL,
  138971. &_vq_auxt__44c1_sm_p4_0,
  138972. NULL,
  138973. 0
  138974. };
  138975. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138976. 8,
  138977. 7,
  138978. 9,
  138979. 6,
  138980. 10,
  138981. 5,
  138982. 11,
  138983. 4,
  138984. 12,
  138985. 3,
  138986. 13,
  138987. 2,
  138988. 14,
  138989. 1,
  138990. 15,
  138991. 0,
  138992. 16,
  138993. };
  138994. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138995. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138996. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138997. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138998. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138999. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139000. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139001. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139002. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139003. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139004. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139005. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139006. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139007. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139008. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139009. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139010. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139011. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139013. 14,
  139014. };
  139015. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139016. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139017. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139018. };
  139019. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139020. 15, 13, 11, 9, 7, 5, 3, 1,
  139021. 0, 2, 4, 6, 8, 10, 12, 14,
  139022. 16,
  139023. };
  139024. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139025. _vq_quantthresh__44c1_sm_p5_0,
  139026. _vq_quantmap__44c1_sm_p5_0,
  139027. 17,
  139028. 17
  139029. };
  139030. static static_codebook _44c1_sm_p5_0 = {
  139031. 2, 289,
  139032. _vq_lengthlist__44c1_sm_p5_0,
  139033. 1, -529530880, 1611661312, 5, 0,
  139034. _vq_quantlist__44c1_sm_p5_0,
  139035. NULL,
  139036. &_vq_auxt__44c1_sm_p5_0,
  139037. NULL,
  139038. 0
  139039. };
  139040. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139041. 1,
  139042. 0,
  139043. 2,
  139044. };
  139045. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139046. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139047. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139048. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139049. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139050. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139051. 11,
  139052. };
  139053. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139054. -5.5, 5.5,
  139055. };
  139056. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139057. 1, 0, 2,
  139058. };
  139059. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139060. _vq_quantthresh__44c1_sm_p6_0,
  139061. _vq_quantmap__44c1_sm_p6_0,
  139062. 3,
  139063. 3
  139064. };
  139065. static static_codebook _44c1_sm_p6_0 = {
  139066. 4, 81,
  139067. _vq_lengthlist__44c1_sm_p6_0,
  139068. 1, -529137664, 1618345984, 2, 0,
  139069. _vq_quantlist__44c1_sm_p6_0,
  139070. NULL,
  139071. &_vq_auxt__44c1_sm_p6_0,
  139072. NULL,
  139073. 0
  139074. };
  139075. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139076. 5,
  139077. 4,
  139078. 6,
  139079. 3,
  139080. 7,
  139081. 2,
  139082. 8,
  139083. 1,
  139084. 9,
  139085. 0,
  139086. 10,
  139087. };
  139088. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139089. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139090. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139091. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139092. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139093. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139094. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139095. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139096. 10,10,10, 8, 8, 8, 8, 8, 8,
  139097. };
  139098. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139099. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139100. 3.5, 4.5,
  139101. };
  139102. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139103. 9, 7, 5, 3, 1, 0, 2, 4,
  139104. 6, 8, 10,
  139105. };
  139106. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139107. _vq_quantthresh__44c1_sm_p6_1,
  139108. _vq_quantmap__44c1_sm_p6_1,
  139109. 11,
  139110. 11
  139111. };
  139112. static static_codebook _44c1_sm_p6_1 = {
  139113. 2, 121,
  139114. _vq_lengthlist__44c1_sm_p6_1,
  139115. 1, -531365888, 1611661312, 4, 0,
  139116. _vq_quantlist__44c1_sm_p6_1,
  139117. NULL,
  139118. &_vq_auxt__44c1_sm_p6_1,
  139119. NULL,
  139120. 0
  139121. };
  139122. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139123. 6,
  139124. 5,
  139125. 7,
  139126. 4,
  139127. 8,
  139128. 3,
  139129. 9,
  139130. 2,
  139131. 10,
  139132. 1,
  139133. 11,
  139134. 0,
  139135. 12,
  139136. };
  139137. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139138. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139139. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139140. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139141. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139142. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139143. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139144. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139145. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139146. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139147. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139148. 0,12,12,11,11,13,12,14,13,
  139149. };
  139150. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139151. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139152. 12.5, 17.5, 22.5, 27.5,
  139153. };
  139154. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139155. 11, 9, 7, 5, 3, 1, 0, 2,
  139156. 4, 6, 8, 10, 12,
  139157. };
  139158. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139159. _vq_quantthresh__44c1_sm_p7_0,
  139160. _vq_quantmap__44c1_sm_p7_0,
  139161. 13,
  139162. 13
  139163. };
  139164. static static_codebook _44c1_sm_p7_0 = {
  139165. 2, 169,
  139166. _vq_lengthlist__44c1_sm_p7_0,
  139167. 1, -526516224, 1616117760, 4, 0,
  139168. _vq_quantlist__44c1_sm_p7_0,
  139169. NULL,
  139170. &_vq_auxt__44c1_sm_p7_0,
  139171. NULL,
  139172. 0
  139173. };
  139174. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139175. 2,
  139176. 1,
  139177. 3,
  139178. 0,
  139179. 4,
  139180. };
  139181. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139182. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139183. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139184. };
  139185. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139186. -1.5, -0.5, 0.5, 1.5,
  139187. };
  139188. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139189. 3, 1, 0, 2, 4,
  139190. };
  139191. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139192. _vq_quantthresh__44c1_sm_p7_1,
  139193. _vq_quantmap__44c1_sm_p7_1,
  139194. 5,
  139195. 5
  139196. };
  139197. static static_codebook _44c1_sm_p7_1 = {
  139198. 2, 25,
  139199. _vq_lengthlist__44c1_sm_p7_1,
  139200. 1, -533725184, 1611661312, 3, 0,
  139201. _vq_quantlist__44c1_sm_p7_1,
  139202. NULL,
  139203. &_vq_auxt__44c1_sm_p7_1,
  139204. NULL,
  139205. 0
  139206. };
  139207. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139208. 6,
  139209. 5,
  139210. 7,
  139211. 4,
  139212. 8,
  139213. 3,
  139214. 9,
  139215. 2,
  139216. 10,
  139217. 1,
  139218. 11,
  139219. 0,
  139220. 12,
  139221. };
  139222. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139223. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139224. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139225. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139226. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139227. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139228. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139229. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139230. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139231. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139232. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139233. 13,13,13,13,13,13,13,13,13,
  139234. };
  139235. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139236. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139237. 552.5, 773.5, 994.5, 1215.5,
  139238. };
  139239. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139240. 11, 9, 7, 5, 3, 1, 0, 2,
  139241. 4, 6, 8, 10, 12,
  139242. };
  139243. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139244. _vq_quantthresh__44c1_sm_p8_0,
  139245. _vq_quantmap__44c1_sm_p8_0,
  139246. 13,
  139247. 13
  139248. };
  139249. static static_codebook _44c1_sm_p8_0 = {
  139250. 2, 169,
  139251. _vq_lengthlist__44c1_sm_p8_0,
  139252. 1, -514541568, 1627103232, 4, 0,
  139253. _vq_quantlist__44c1_sm_p8_0,
  139254. NULL,
  139255. &_vq_auxt__44c1_sm_p8_0,
  139256. NULL,
  139257. 0
  139258. };
  139259. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139260. 6,
  139261. 5,
  139262. 7,
  139263. 4,
  139264. 8,
  139265. 3,
  139266. 9,
  139267. 2,
  139268. 10,
  139269. 1,
  139270. 11,
  139271. 0,
  139272. 12,
  139273. };
  139274. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139275. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139276. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139277. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139278. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139279. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139280. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139281. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139282. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139283. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139284. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139285. 20,13,12,12,12,14,12,14,13,
  139286. };
  139287. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139288. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139289. 42.5, 59.5, 76.5, 93.5,
  139290. };
  139291. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139292. 11, 9, 7, 5, 3, 1, 0, 2,
  139293. 4, 6, 8, 10, 12,
  139294. };
  139295. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139296. _vq_quantthresh__44c1_sm_p8_1,
  139297. _vq_quantmap__44c1_sm_p8_1,
  139298. 13,
  139299. 13
  139300. };
  139301. static static_codebook _44c1_sm_p8_1 = {
  139302. 2, 169,
  139303. _vq_lengthlist__44c1_sm_p8_1,
  139304. 1, -522616832, 1620115456, 4, 0,
  139305. _vq_quantlist__44c1_sm_p8_1,
  139306. NULL,
  139307. &_vq_auxt__44c1_sm_p8_1,
  139308. NULL,
  139309. 0
  139310. };
  139311. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139312. 8,
  139313. 7,
  139314. 9,
  139315. 6,
  139316. 10,
  139317. 5,
  139318. 11,
  139319. 4,
  139320. 12,
  139321. 3,
  139322. 13,
  139323. 2,
  139324. 14,
  139325. 1,
  139326. 15,
  139327. 0,
  139328. 16,
  139329. };
  139330. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139331. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139332. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139333. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139334. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139335. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139336. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139337. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139338. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139339. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139340. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139341. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139342. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139343. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139344. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139345. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139346. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139347. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139348. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139349. 9,
  139350. };
  139351. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139352. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139353. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139354. };
  139355. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139356. 15, 13, 11, 9, 7, 5, 3, 1,
  139357. 0, 2, 4, 6, 8, 10, 12, 14,
  139358. 16,
  139359. };
  139360. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139361. _vq_quantthresh__44c1_sm_p8_2,
  139362. _vq_quantmap__44c1_sm_p8_2,
  139363. 17,
  139364. 17
  139365. };
  139366. static static_codebook _44c1_sm_p8_2 = {
  139367. 2, 289,
  139368. _vq_lengthlist__44c1_sm_p8_2,
  139369. 1, -529530880, 1611661312, 5, 0,
  139370. _vq_quantlist__44c1_sm_p8_2,
  139371. NULL,
  139372. &_vq_auxt__44c1_sm_p8_2,
  139373. NULL,
  139374. 0
  139375. };
  139376. static long _huff_lengthlist__44c1_sm_short[] = {
  139377. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139378. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139379. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139380. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139381. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139382. 11,
  139383. };
  139384. static static_codebook _huff_book__44c1_sm_short = {
  139385. 2, 81,
  139386. _huff_lengthlist__44c1_sm_short,
  139387. 0, 0, 0, 0, 0,
  139388. NULL,
  139389. NULL,
  139390. NULL,
  139391. NULL,
  139392. 0
  139393. };
  139394. static long _huff_lengthlist__44cn1_s_long[] = {
  139395. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139396. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139397. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139398. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139399. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139400. 20,
  139401. };
  139402. static static_codebook _huff_book__44cn1_s_long = {
  139403. 2, 81,
  139404. _huff_lengthlist__44cn1_s_long,
  139405. 0, 0, 0, 0, 0,
  139406. NULL,
  139407. NULL,
  139408. NULL,
  139409. NULL,
  139410. 0
  139411. };
  139412. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139413. 1,
  139414. 0,
  139415. 2,
  139416. };
  139417. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139418. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139419. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139424. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139429. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139464. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139469. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139474. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139510. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139515. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139520. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139821. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139826. 0, 0, 0, 0, 0, 0, 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,
  139829. };
  139830. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139831. -0.5, 0.5,
  139832. };
  139833. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139834. 1, 0, 2,
  139835. };
  139836. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139837. _vq_quantthresh__44cn1_s_p1_0,
  139838. _vq_quantmap__44cn1_s_p1_0,
  139839. 3,
  139840. 3
  139841. };
  139842. static static_codebook _44cn1_s_p1_0 = {
  139843. 8, 6561,
  139844. _vq_lengthlist__44cn1_s_p1_0,
  139845. 1, -535822336, 1611661312, 2, 0,
  139846. _vq_quantlist__44cn1_s_p1_0,
  139847. NULL,
  139848. &_vq_auxt__44cn1_s_p1_0,
  139849. NULL,
  139850. 0
  139851. };
  139852. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139853. 2,
  139854. 1,
  139855. 3,
  139856. 0,
  139857. 4,
  139858. };
  139859. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139860. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  139871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  139876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  139900. };
  139901. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139902. -1.5, -0.5, 0.5, 1.5,
  139903. };
  139904. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139905. 3, 1, 0, 2, 4,
  139906. };
  139907. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139908. _vq_quantthresh__44cn1_s_p2_0,
  139909. _vq_quantmap__44cn1_s_p2_0,
  139910. 5,
  139911. 5
  139912. };
  139913. static static_codebook _44cn1_s_p2_0 = {
  139914. 4, 625,
  139915. _vq_lengthlist__44cn1_s_p2_0,
  139916. 1, -533725184, 1611661312, 3, 0,
  139917. _vq_quantlist__44cn1_s_p2_0,
  139918. NULL,
  139919. &_vq_auxt__44cn1_s_p2_0,
  139920. NULL,
  139921. 0
  139922. };
  139923. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139924. 4,
  139925. 3,
  139926. 5,
  139927. 2,
  139928. 6,
  139929. 1,
  139930. 7,
  139931. 0,
  139932. 8,
  139933. };
  139934. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139935. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139936. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139937. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139938. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139939. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0,
  139941. };
  139942. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139943. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139944. };
  139945. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139946. 7, 5, 3, 1, 0, 2, 4, 6,
  139947. 8,
  139948. };
  139949. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139950. _vq_quantthresh__44cn1_s_p3_0,
  139951. _vq_quantmap__44cn1_s_p3_0,
  139952. 9,
  139953. 9
  139954. };
  139955. static static_codebook _44cn1_s_p3_0 = {
  139956. 2, 81,
  139957. _vq_lengthlist__44cn1_s_p3_0,
  139958. 1, -531628032, 1611661312, 4, 0,
  139959. _vq_quantlist__44cn1_s_p3_0,
  139960. NULL,
  139961. &_vq_auxt__44cn1_s_p3_0,
  139962. NULL,
  139963. 0
  139964. };
  139965. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139966. 4,
  139967. 3,
  139968. 5,
  139969. 2,
  139970. 6,
  139971. 1,
  139972. 7,
  139973. 0,
  139974. 8,
  139975. };
  139976. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139977. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139978. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139979. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139980. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139981. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139982. 11,
  139983. };
  139984. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139985. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139986. };
  139987. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139988. 7, 5, 3, 1, 0, 2, 4, 6,
  139989. 8,
  139990. };
  139991. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139992. _vq_quantthresh__44cn1_s_p4_0,
  139993. _vq_quantmap__44cn1_s_p4_0,
  139994. 9,
  139995. 9
  139996. };
  139997. static static_codebook _44cn1_s_p4_0 = {
  139998. 2, 81,
  139999. _vq_lengthlist__44cn1_s_p4_0,
  140000. 1, -531628032, 1611661312, 4, 0,
  140001. _vq_quantlist__44cn1_s_p4_0,
  140002. NULL,
  140003. &_vq_auxt__44cn1_s_p4_0,
  140004. NULL,
  140005. 0
  140006. };
  140007. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140008. 8,
  140009. 7,
  140010. 9,
  140011. 6,
  140012. 10,
  140013. 5,
  140014. 11,
  140015. 4,
  140016. 12,
  140017. 3,
  140018. 13,
  140019. 2,
  140020. 14,
  140021. 1,
  140022. 15,
  140023. 0,
  140024. 16,
  140025. };
  140026. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140027. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140028. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140029. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140030. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140031. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140032. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140033. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140034. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140035. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140036. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140037. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140038. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140039. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140040. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140041. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140042. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140043. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140045. 14,
  140046. };
  140047. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140048. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140049. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140050. };
  140051. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140052. 15, 13, 11, 9, 7, 5, 3, 1,
  140053. 0, 2, 4, 6, 8, 10, 12, 14,
  140054. 16,
  140055. };
  140056. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140057. _vq_quantthresh__44cn1_s_p5_0,
  140058. _vq_quantmap__44cn1_s_p5_0,
  140059. 17,
  140060. 17
  140061. };
  140062. static static_codebook _44cn1_s_p5_0 = {
  140063. 2, 289,
  140064. _vq_lengthlist__44cn1_s_p5_0,
  140065. 1, -529530880, 1611661312, 5, 0,
  140066. _vq_quantlist__44cn1_s_p5_0,
  140067. NULL,
  140068. &_vq_auxt__44cn1_s_p5_0,
  140069. NULL,
  140070. 0
  140071. };
  140072. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140073. 1,
  140074. 0,
  140075. 2,
  140076. };
  140077. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140078. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140079. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140080. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140081. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140082. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140083. 10,
  140084. };
  140085. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140086. -5.5, 5.5,
  140087. };
  140088. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140089. 1, 0, 2,
  140090. };
  140091. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140092. _vq_quantthresh__44cn1_s_p6_0,
  140093. _vq_quantmap__44cn1_s_p6_0,
  140094. 3,
  140095. 3
  140096. };
  140097. static static_codebook _44cn1_s_p6_0 = {
  140098. 4, 81,
  140099. _vq_lengthlist__44cn1_s_p6_0,
  140100. 1, -529137664, 1618345984, 2, 0,
  140101. _vq_quantlist__44cn1_s_p6_0,
  140102. NULL,
  140103. &_vq_auxt__44cn1_s_p6_0,
  140104. NULL,
  140105. 0
  140106. };
  140107. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140108. 5,
  140109. 4,
  140110. 6,
  140111. 3,
  140112. 7,
  140113. 2,
  140114. 8,
  140115. 1,
  140116. 9,
  140117. 0,
  140118. 10,
  140119. };
  140120. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140121. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140122. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140123. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140124. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140125. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140126. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140127. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140128. 10,10,10, 9, 9, 9, 9, 9, 9,
  140129. };
  140130. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140131. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140132. 3.5, 4.5,
  140133. };
  140134. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140135. 9, 7, 5, 3, 1, 0, 2, 4,
  140136. 6, 8, 10,
  140137. };
  140138. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140139. _vq_quantthresh__44cn1_s_p6_1,
  140140. _vq_quantmap__44cn1_s_p6_1,
  140141. 11,
  140142. 11
  140143. };
  140144. static static_codebook _44cn1_s_p6_1 = {
  140145. 2, 121,
  140146. _vq_lengthlist__44cn1_s_p6_1,
  140147. 1, -531365888, 1611661312, 4, 0,
  140148. _vq_quantlist__44cn1_s_p6_1,
  140149. NULL,
  140150. &_vq_auxt__44cn1_s_p6_1,
  140151. NULL,
  140152. 0
  140153. };
  140154. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140155. 6,
  140156. 5,
  140157. 7,
  140158. 4,
  140159. 8,
  140160. 3,
  140161. 9,
  140162. 2,
  140163. 10,
  140164. 1,
  140165. 11,
  140166. 0,
  140167. 12,
  140168. };
  140169. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140170. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140171. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140172. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140173. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140174. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140175. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140176. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140177. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140178. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140179. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140180. 0,13,13,12,12,13,13,13,14,
  140181. };
  140182. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140183. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140184. 12.5, 17.5, 22.5, 27.5,
  140185. };
  140186. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140187. 11, 9, 7, 5, 3, 1, 0, 2,
  140188. 4, 6, 8, 10, 12,
  140189. };
  140190. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140191. _vq_quantthresh__44cn1_s_p7_0,
  140192. _vq_quantmap__44cn1_s_p7_0,
  140193. 13,
  140194. 13
  140195. };
  140196. static static_codebook _44cn1_s_p7_0 = {
  140197. 2, 169,
  140198. _vq_lengthlist__44cn1_s_p7_0,
  140199. 1, -526516224, 1616117760, 4, 0,
  140200. _vq_quantlist__44cn1_s_p7_0,
  140201. NULL,
  140202. &_vq_auxt__44cn1_s_p7_0,
  140203. NULL,
  140204. 0
  140205. };
  140206. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140207. 2,
  140208. 1,
  140209. 3,
  140210. 0,
  140211. 4,
  140212. };
  140213. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140214. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140215. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140216. };
  140217. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140218. -1.5, -0.5, 0.5, 1.5,
  140219. };
  140220. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140221. 3, 1, 0, 2, 4,
  140222. };
  140223. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140224. _vq_quantthresh__44cn1_s_p7_1,
  140225. _vq_quantmap__44cn1_s_p7_1,
  140226. 5,
  140227. 5
  140228. };
  140229. static static_codebook _44cn1_s_p7_1 = {
  140230. 2, 25,
  140231. _vq_lengthlist__44cn1_s_p7_1,
  140232. 1, -533725184, 1611661312, 3, 0,
  140233. _vq_quantlist__44cn1_s_p7_1,
  140234. NULL,
  140235. &_vq_auxt__44cn1_s_p7_1,
  140236. NULL,
  140237. 0
  140238. };
  140239. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140240. 2,
  140241. 1,
  140242. 3,
  140243. 0,
  140244. 4,
  140245. };
  140246. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140247. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140248. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140250. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140254. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140256. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140262. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140280. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140281. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140282. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140283. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140284. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140285. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140286. 12,
  140287. };
  140288. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140289. -331.5, -110.5, 110.5, 331.5,
  140290. };
  140291. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140292. 3, 1, 0, 2, 4,
  140293. };
  140294. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140295. _vq_quantthresh__44cn1_s_p8_0,
  140296. _vq_quantmap__44cn1_s_p8_0,
  140297. 5,
  140298. 5
  140299. };
  140300. static static_codebook _44cn1_s_p8_0 = {
  140301. 4, 625,
  140302. _vq_lengthlist__44cn1_s_p8_0,
  140303. 1, -518283264, 1627103232, 3, 0,
  140304. _vq_quantlist__44cn1_s_p8_0,
  140305. NULL,
  140306. &_vq_auxt__44cn1_s_p8_0,
  140307. NULL,
  140308. 0
  140309. };
  140310. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140311. 6,
  140312. 5,
  140313. 7,
  140314. 4,
  140315. 8,
  140316. 3,
  140317. 9,
  140318. 2,
  140319. 10,
  140320. 1,
  140321. 11,
  140322. 0,
  140323. 12,
  140324. };
  140325. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140326. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140327. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140328. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140329. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140330. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140331. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140332. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140333. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140334. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140335. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140336. 15,12,12,11,11,14,12,13,14,
  140337. };
  140338. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140339. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140340. 42.5, 59.5, 76.5, 93.5,
  140341. };
  140342. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140343. 11, 9, 7, 5, 3, 1, 0, 2,
  140344. 4, 6, 8, 10, 12,
  140345. };
  140346. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140347. _vq_quantthresh__44cn1_s_p8_1,
  140348. _vq_quantmap__44cn1_s_p8_1,
  140349. 13,
  140350. 13
  140351. };
  140352. static static_codebook _44cn1_s_p8_1 = {
  140353. 2, 169,
  140354. _vq_lengthlist__44cn1_s_p8_1,
  140355. 1, -522616832, 1620115456, 4, 0,
  140356. _vq_quantlist__44cn1_s_p8_1,
  140357. NULL,
  140358. &_vq_auxt__44cn1_s_p8_1,
  140359. NULL,
  140360. 0
  140361. };
  140362. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140363. 8,
  140364. 7,
  140365. 9,
  140366. 6,
  140367. 10,
  140368. 5,
  140369. 11,
  140370. 4,
  140371. 12,
  140372. 3,
  140373. 13,
  140374. 2,
  140375. 14,
  140376. 1,
  140377. 15,
  140378. 0,
  140379. 16,
  140380. };
  140381. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140382. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140383. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140384. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140385. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140386. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140387. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140388. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140389. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140390. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140391. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140392. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140393. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140394. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140395. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140396. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140397. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140398. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140399. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140400. 9,
  140401. };
  140402. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140403. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140404. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140405. };
  140406. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140407. 15, 13, 11, 9, 7, 5, 3, 1,
  140408. 0, 2, 4, 6, 8, 10, 12, 14,
  140409. 16,
  140410. };
  140411. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140412. _vq_quantthresh__44cn1_s_p8_2,
  140413. _vq_quantmap__44cn1_s_p8_2,
  140414. 17,
  140415. 17
  140416. };
  140417. static static_codebook _44cn1_s_p8_2 = {
  140418. 2, 289,
  140419. _vq_lengthlist__44cn1_s_p8_2,
  140420. 1, -529530880, 1611661312, 5, 0,
  140421. _vq_quantlist__44cn1_s_p8_2,
  140422. NULL,
  140423. &_vq_auxt__44cn1_s_p8_2,
  140424. NULL,
  140425. 0
  140426. };
  140427. static long _huff_lengthlist__44cn1_s_short[] = {
  140428. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140429. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140430. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140431. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140432. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140433. 10,
  140434. };
  140435. static static_codebook _huff_book__44cn1_s_short = {
  140436. 2, 81,
  140437. _huff_lengthlist__44cn1_s_short,
  140438. 0, 0, 0, 0, 0,
  140439. NULL,
  140440. NULL,
  140441. NULL,
  140442. NULL,
  140443. 0
  140444. };
  140445. static long _huff_lengthlist__44cn1_sm_long[] = {
  140446. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140447. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140448. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140449. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140450. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140451. 17,
  140452. };
  140453. static static_codebook _huff_book__44cn1_sm_long = {
  140454. 2, 81,
  140455. _huff_lengthlist__44cn1_sm_long,
  140456. 0, 0, 0, 0, 0,
  140457. NULL,
  140458. NULL,
  140459. NULL,
  140460. NULL,
  140461. 0
  140462. };
  140463. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140464. 1,
  140465. 0,
  140466. 2,
  140467. };
  140468. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140469. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140470. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140475. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140480. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140515. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140520. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140525. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140561. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140566. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140571. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0,
  140880. };
  140881. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140882. -0.5, 0.5,
  140883. };
  140884. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140885. 1, 0, 2,
  140886. };
  140887. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140888. _vq_quantthresh__44cn1_sm_p1_0,
  140889. _vq_quantmap__44cn1_sm_p1_0,
  140890. 3,
  140891. 3
  140892. };
  140893. static static_codebook _44cn1_sm_p1_0 = {
  140894. 8, 6561,
  140895. _vq_lengthlist__44cn1_sm_p1_0,
  140896. 1, -535822336, 1611661312, 2, 0,
  140897. _vq_quantlist__44cn1_sm_p1_0,
  140898. NULL,
  140899. &_vq_auxt__44cn1_sm_p1_0,
  140900. NULL,
  140901. 0
  140902. };
  140903. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140904. 2,
  140905. 1,
  140906. 3,
  140907. 0,
  140908. 4,
  140909. };
  140910. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140911. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0,
  140951. };
  140952. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140953. -1.5, -0.5, 0.5, 1.5,
  140954. };
  140955. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140956. 3, 1, 0, 2, 4,
  140957. };
  140958. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140959. _vq_quantthresh__44cn1_sm_p2_0,
  140960. _vq_quantmap__44cn1_sm_p2_0,
  140961. 5,
  140962. 5
  140963. };
  140964. static static_codebook _44cn1_sm_p2_0 = {
  140965. 4, 625,
  140966. _vq_lengthlist__44cn1_sm_p2_0,
  140967. 1, -533725184, 1611661312, 3, 0,
  140968. _vq_quantlist__44cn1_sm_p2_0,
  140969. NULL,
  140970. &_vq_auxt__44cn1_sm_p2_0,
  140971. NULL,
  140972. 0
  140973. };
  140974. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140975. 4,
  140976. 3,
  140977. 5,
  140978. 2,
  140979. 6,
  140980. 1,
  140981. 7,
  140982. 0,
  140983. 8,
  140984. };
  140985. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140986. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140987. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140988. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140989. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140990. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0,
  140992. };
  140993. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140994. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140995. };
  140996. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140997. 7, 5, 3, 1, 0, 2, 4, 6,
  140998. 8,
  140999. };
  141000. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141001. _vq_quantthresh__44cn1_sm_p3_0,
  141002. _vq_quantmap__44cn1_sm_p3_0,
  141003. 9,
  141004. 9
  141005. };
  141006. static static_codebook _44cn1_sm_p3_0 = {
  141007. 2, 81,
  141008. _vq_lengthlist__44cn1_sm_p3_0,
  141009. 1, -531628032, 1611661312, 4, 0,
  141010. _vq_quantlist__44cn1_sm_p3_0,
  141011. NULL,
  141012. &_vq_auxt__44cn1_sm_p3_0,
  141013. NULL,
  141014. 0
  141015. };
  141016. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141017. 4,
  141018. 3,
  141019. 5,
  141020. 2,
  141021. 6,
  141022. 1,
  141023. 7,
  141024. 0,
  141025. 8,
  141026. };
  141027. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141028. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141029. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141030. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141031. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141032. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141033. 11,
  141034. };
  141035. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141036. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141037. };
  141038. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141039. 7, 5, 3, 1, 0, 2, 4, 6,
  141040. 8,
  141041. };
  141042. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141043. _vq_quantthresh__44cn1_sm_p4_0,
  141044. _vq_quantmap__44cn1_sm_p4_0,
  141045. 9,
  141046. 9
  141047. };
  141048. static static_codebook _44cn1_sm_p4_0 = {
  141049. 2, 81,
  141050. _vq_lengthlist__44cn1_sm_p4_0,
  141051. 1, -531628032, 1611661312, 4, 0,
  141052. _vq_quantlist__44cn1_sm_p4_0,
  141053. NULL,
  141054. &_vq_auxt__44cn1_sm_p4_0,
  141055. NULL,
  141056. 0
  141057. };
  141058. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141059. 8,
  141060. 7,
  141061. 9,
  141062. 6,
  141063. 10,
  141064. 5,
  141065. 11,
  141066. 4,
  141067. 12,
  141068. 3,
  141069. 13,
  141070. 2,
  141071. 14,
  141072. 1,
  141073. 15,
  141074. 0,
  141075. 16,
  141076. };
  141077. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141078. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141079. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141080. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141081. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141082. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141083. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141084. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141085. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141086. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141087. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141088. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141089. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141090. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141091. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141092. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141093. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141094. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141096. 14,
  141097. };
  141098. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141099. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141100. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141101. };
  141102. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141103. 15, 13, 11, 9, 7, 5, 3, 1,
  141104. 0, 2, 4, 6, 8, 10, 12, 14,
  141105. 16,
  141106. };
  141107. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141108. _vq_quantthresh__44cn1_sm_p5_0,
  141109. _vq_quantmap__44cn1_sm_p5_0,
  141110. 17,
  141111. 17
  141112. };
  141113. static static_codebook _44cn1_sm_p5_0 = {
  141114. 2, 289,
  141115. _vq_lengthlist__44cn1_sm_p5_0,
  141116. 1, -529530880, 1611661312, 5, 0,
  141117. _vq_quantlist__44cn1_sm_p5_0,
  141118. NULL,
  141119. &_vq_auxt__44cn1_sm_p5_0,
  141120. NULL,
  141121. 0
  141122. };
  141123. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141124. 1,
  141125. 0,
  141126. 2,
  141127. };
  141128. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141129. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141130. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141131. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141132. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141133. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141134. 10,
  141135. };
  141136. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141137. -5.5, 5.5,
  141138. };
  141139. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141140. 1, 0, 2,
  141141. };
  141142. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141143. _vq_quantthresh__44cn1_sm_p6_0,
  141144. _vq_quantmap__44cn1_sm_p6_0,
  141145. 3,
  141146. 3
  141147. };
  141148. static static_codebook _44cn1_sm_p6_0 = {
  141149. 4, 81,
  141150. _vq_lengthlist__44cn1_sm_p6_0,
  141151. 1, -529137664, 1618345984, 2, 0,
  141152. _vq_quantlist__44cn1_sm_p6_0,
  141153. NULL,
  141154. &_vq_auxt__44cn1_sm_p6_0,
  141155. NULL,
  141156. 0
  141157. };
  141158. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141159. 5,
  141160. 4,
  141161. 6,
  141162. 3,
  141163. 7,
  141164. 2,
  141165. 8,
  141166. 1,
  141167. 9,
  141168. 0,
  141169. 10,
  141170. };
  141171. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141172. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141173. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141174. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141175. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141176. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141177. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141178. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141179. 10,10,10, 8, 9, 8, 8, 9, 8,
  141180. };
  141181. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141182. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141183. 3.5, 4.5,
  141184. };
  141185. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141186. 9, 7, 5, 3, 1, 0, 2, 4,
  141187. 6, 8, 10,
  141188. };
  141189. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141190. _vq_quantthresh__44cn1_sm_p6_1,
  141191. _vq_quantmap__44cn1_sm_p6_1,
  141192. 11,
  141193. 11
  141194. };
  141195. static static_codebook _44cn1_sm_p6_1 = {
  141196. 2, 121,
  141197. _vq_lengthlist__44cn1_sm_p6_1,
  141198. 1, -531365888, 1611661312, 4, 0,
  141199. _vq_quantlist__44cn1_sm_p6_1,
  141200. NULL,
  141201. &_vq_auxt__44cn1_sm_p6_1,
  141202. NULL,
  141203. 0
  141204. };
  141205. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141206. 6,
  141207. 5,
  141208. 7,
  141209. 4,
  141210. 8,
  141211. 3,
  141212. 9,
  141213. 2,
  141214. 10,
  141215. 1,
  141216. 11,
  141217. 0,
  141218. 12,
  141219. };
  141220. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141221. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141222. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141223. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141224. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141225. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141226. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141227. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141228. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141229. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141230. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141231. 0,13,12,12,12,13,13,13,14,
  141232. };
  141233. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141234. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141235. 12.5, 17.5, 22.5, 27.5,
  141236. };
  141237. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141238. 11, 9, 7, 5, 3, 1, 0, 2,
  141239. 4, 6, 8, 10, 12,
  141240. };
  141241. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141242. _vq_quantthresh__44cn1_sm_p7_0,
  141243. _vq_quantmap__44cn1_sm_p7_0,
  141244. 13,
  141245. 13
  141246. };
  141247. static static_codebook _44cn1_sm_p7_0 = {
  141248. 2, 169,
  141249. _vq_lengthlist__44cn1_sm_p7_0,
  141250. 1, -526516224, 1616117760, 4, 0,
  141251. _vq_quantlist__44cn1_sm_p7_0,
  141252. NULL,
  141253. &_vq_auxt__44cn1_sm_p7_0,
  141254. NULL,
  141255. 0
  141256. };
  141257. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141258. 2,
  141259. 1,
  141260. 3,
  141261. 0,
  141262. 4,
  141263. };
  141264. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141265. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141266. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141267. };
  141268. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141269. -1.5, -0.5, 0.5, 1.5,
  141270. };
  141271. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141272. 3, 1, 0, 2, 4,
  141273. };
  141274. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141275. _vq_quantthresh__44cn1_sm_p7_1,
  141276. _vq_quantmap__44cn1_sm_p7_1,
  141277. 5,
  141278. 5
  141279. };
  141280. static static_codebook _44cn1_sm_p7_1 = {
  141281. 2, 25,
  141282. _vq_lengthlist__44cn1_sm_p7_1,
  141283. 1, -533725184, 1611661312, 3, 0,
  141284. _vq_quantlist__44cn1_sm_p7_1,
  141285. NULL,
  141286. &_vq_auxt__44cn1_sm_p7_1,
  141287. NULL,
  141288. 0
  141289. };
  141290. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141291. 4,
  141292. 3,
  141293. 5,
  141294. 2,
  141295. 6,
  141296. 1,
  141297. 7,
  141298. 0,
  141299. 8,
  141300. };
  141301. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141302. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141303. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141304. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141305. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141306. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141307. 14,
  141308. };
  141309. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141310. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141311. };
  141312. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141313. 7, 5, 3, 1, 0, 2, 4, 6,
  141314. 8,
  141315. };
  141316. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141317. _vq_quantthresh__44cn1_sm_p8_0,
  141318. _vq_quantmap__44cn1_sm_p8_0,
  141319. 9,
  141320. 9
  141321. };
  141322. static static_codebook _44cn1_sm_p8_0 = {
  141323. 2, 81,
  141324. _vq_lengthlist__44cn1_sm_p8_0,
  141325. 1, -516186112, 1627103232, 4, 0,
  141326. _vq_quantlist__44cn1_sm_p8_0,
  141327. NULL,
  141328. &_vq_auxt__44cn1_sm_p8_0,
  141329. NULL,
  141330. 0
  141331. };
  141332. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141333. 6,
  141334. 5,
  141335. 7,
  141336. 4,
  141337. 8,
  141338. 3,
  141339. 9,
  141340. 2,
  141341. 10,
  141342. 1,
  141343. 11,
  141344. 0,
  141345. 12,
  141346. };
  141347. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141348. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141349. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141350. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141351. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141352. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141353. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141354. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141355. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141356. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141357. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141358. 17,12,12,11,10,13,11,13,13,
  141359. };
  141360. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141361. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141362. 42.5, 59.5, 76.5, 93.5,
  141363. };
  141364. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141365. 11, 9, 7, 5, 3, 1, 0, 2,
  141366. 4, 6, 8, 10, 12,
  141367. };
  141368. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141369. _vq_quantthresh__44cn1_sm_p8_1,
  141370. _vq_quantmap__44cn1_sm_p8_1,
  141371. 13,
  141372. 13
  141373. };
  141374. static static_codebook _44cn1_sm_p8_1 = {
  141375. 2, 169,
  141376. _vq_lengthlist__44cn1_sm_p8_1,
  141377. 1, -522616832, 1620115456, 4, 0,
  141378. _vq_quantlist__44cn1_sm_p8_1,
  141379. NULL,
  141380. &_vq_auxt__44cn1_sm_p8_1,
  141381. NULL,
  141382. 0
  141383. };
  141384. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141385. 8,
  141386. 7,
  141387. 9,
  141388. 6,
  141389. 10,
  141390. 5,
  141391. 11,
  141392. 4,
  141393. 12,
  141394. 3,
  141395. 13,
  141396. 2,
  141397. 14,
  141398. 1,
  141399. 15,
  141400. 0,
  141401. 16,
  141402. };
  141403. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141404. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141405. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141406. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141407. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141408. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141409. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141410. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141411. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141412. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141413. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141414. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141417. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141418. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141419. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141420. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141421. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141422. 9,
  141423. };
  141424. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141425. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141426. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141427. };
  141428. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141429. 15, 13, 11, 9, 7, 5, 3, 1,
  141430. 0, 2, 4, 6, 8, 10, 12, 14,
  141431. 16,
  141432. };
  141433. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141434. _vq_quantthresh__44cn1_sm_p8_2,
  141435. _vq_quantmap__44cn1_sm_p8_2,
  141436. 17,
  141437. 17
  141438. };
  141439. static static_codebook _44cn1_sm_p8_2 = {
  141440. 2, 289,
  141441. _vq_lengthlist__44cn1_sm_p8_2,
  141442. 1, -529530880, 1611661312, 5, 0,
  141443. _vq_quantlist__44cn1_sm_p8_2,
  141444. NULL,
  141445. &_vq_auxt__44cn1_sm_p8_2,
  141446. NULL,
  141447. 0
  141448. };
  141449. static long _huff_lengthlist__44cn1_sm_short[] = {
  141450. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141451. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141452. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141453. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141454. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141455. 9,
  141456. };
  141457. static static_codebook _huff_book__44cn1_sm_short = {
  141458. 2, 81,
  141459. _huff_lengthlist__44cn1_sm_short,
  141460. 0, 0, 0, 0, 0,
  141461. NULL,
  141462. NULL,
  141463. NULL,
  141464. NULL,
  141465. 0
  141466. };
  141467. /*** End of inlined file: res_books_stereo.h ***/
  141468. /***** residue backends *********************************************/
  141469. static vorbis_info_residue0 _residue_44_low={
  141470. 0,-1, -1, 9,-1,
  141471. /* 0 1 2 3 4 5 6 7 */
  141472. {0},
  141473. {-1},
  141474. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141475. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141476. };
  141477. static vorbis_info_residue0 _residue_44_mid={
  141478. 0,-1, -1, 10,-1,
  141479. /* 0 1 2 3 4 5 6 7 8 */
  141480. {0},
  141481. {-1},
  141482. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141483. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141484. };
  141485. static vorbis_info_residue0 _residue_44_high={
  141486. 0,-1, -1, 10,-1,
  141487. /* 0 1 2 3 4 5 6 7 8 */
  141488. {0},
  141489. {-1},
  141490. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141491. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141492. };
  141493. static static_bookblock _resbook_44s_n1={
  141494. {
  141495. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141496. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141497. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141498. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141499. }
  141500. };
  141501. static static_bookblock _resbook_44sm_n1={
  141502. {
  141503. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141504. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141505. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141506. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141507. }
  141508. };
  141509. static static_bookblock _resbook_44s_0={
  141510. {
  141511. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141512. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141513. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141514. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141515. }
  141516. };
  141517. static static_bookblock _resbook_44sm_0={
  141518. {
  141519. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141520. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141521. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141522. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141523. }
  141524. };
  141525. static static_bookblock _resbook_44s_1={
  141526. {
  141527. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141528. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141529. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141530. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141531. }
  141532. };
  141533. static static_bookblock _resbook_44sm_1={
  141534. {
  141535. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141536. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141537. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141538. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141539. }
  141540. };
  141541. static static_bookblock _resbook_44s_2={
  141542. {
  141543. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141544. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141545. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141546. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141547. }
  141548. };
  141549. static static_bookblock _resbook_44s_3={
  141550. {
  141551. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141552. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141553. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141554. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141555. }
  141556. };
  141557. static static_bookblock _resbook_44s_4={
  141558. {
  141559. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141560. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141561. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141562. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141563. }
  141564. };
  141565. static static_bookblock _resbook_44s_5={
  141566. {
  141567. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141568. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141569. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141570. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141571. }
  141572. };
  141573. static static_bookblock _resbook_44s_6={
  141574. {
  141575. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141576. {0,0,&_44c6_s_p4_0},
  141577. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141578. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141579. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141580. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141581. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141582. }
  141583. };
  141584. static static_bookblock _resbook_44s_7={
  141585. {
  141586. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141587. {0,0,&_44c7_s_p4_0},
  141588. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141589. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141590. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141591. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141592. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141593. }
  141594. };
  141595. static static_bookblock _resbook_44s_8={
  141596. {
  141597. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141598. {0,0,&_44c8_s_p4_0},
  141599. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141600. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141601. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141602. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141603. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141604. }
  141605. };
  141606. static static_bookblock _resbook_44s_9={
  141607. {
  141608. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141609. {0,0,&_44c9_s_p4_0},
  141610. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141611. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141612. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141613. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141614. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141615. }
  141616. };
  141617. static vorbis_residue_template _res_44s_n1[]={
  141618. {2,0, &_residue_44_low,
  141619. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141620. &_resbook_44s_n1,&_resbook_44sm_n1},
  141621. {2,0, &_residue_44_low,
  141622. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141623. &_resbook_44s_n1,&_resbook_44sm_n1}
  141624. };
  141625. static vorbis_residue_template _res_44s_0[]={
  141626. {2,0, &_residue_44_low,
  141627. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141628. &_resbook_44s_0,&_resbook_44sm_0},
  141629. {2,0, &_residue_44_low,
  141630. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141631. &_resbook_44s_0,&_resbook_44sm_0}
  141632. };
  141633. static vorbis_residue_template _res_44s_1[]={
  141634. {2,0, &_residue_44_low,
  141635. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141636. &_resbook_44s_1,&_resbook_44sm_1},
  141637. {2,0, &_residue_44_low,
  141638. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141639. &_resbook_44s_1,&_resbook_44sm_1}
  141640. };
  141641. static vorbis_residue_template _res_44s_2[]={
  141642. {2,0, &_residue_44_mid,
  141643. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141644. &_resbook_44s_2,&_resbook_44s_2},
  141645. {2,0, &_residue_44_mid,
  141646. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141647. &_resbook_44s_2,&_resbook_44s_2}
  141648. };
  141649. static vorbis_residue_template _res_44s_3[]={
  141650. {2,0, &_residue_44_mid,
  141651. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141652. &_resbook_44s_3,&_resbook_44s_3},
  141653. {2,0, &_residue_44_mid,
  141654. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141655. &_resbook_44s_3,&_resbook_44s_3}
  141656. };
  141657. static vorbis_residue_template _res_44s_4[]={
  141658. {2,0, &_residue_44_mid,
  141659. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141660. &_resbook_44s_4,&_resbook_44s_4},
  141661. {2,0, &_residue_44_mid,
  141662. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141663. &_resbook_44s_4,&_resbook_44s_4}
  141664. };
  141665. static vorbis_residue_template _res_44s_5[]={
  141666. {2,0, &_residue_44_mid,
  141667. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141668. &_resbook_44s_5,&_resbook_44s_5},
  141669. {2,0, &_residue_44_mid,
  141670. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141671. &_resbook_44s_5,&_resbook_44s_5}
  141672. };
  141673. static vorbis_residue_template _res_44s_6[]={
  141674. {2,0, &_residue_44_high,
  141675. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141676. &_resbook_44s_6,&_resbook_44s_6},
  141677. {2,0, &_residue_44_high,
  141678. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141679. &_resbook_44s_6,&_resbook_44s_6}
  141680. };
  141681. static vorbis_residue_template _res_44s_7[]={
  141682. {2,0, &_residue_44_high,
  141683. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141684. &_resbook_44s_7,&_resbook_44s_7},
  141685. {2,0, &_residue_44_high,
  141686. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141687. &_resbook_44s_7,&_resbook_44s_7}
  141688. };
  141689. static vorbis_residue_template _res_44s_8[]={
  141690. {2,0, &_residue_44_high,
  141691. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141692. &_resbook_44s_8,&_resbook_44s_8},
  141693. {2,0, &_residue_44_high,
  141694. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141695. &_resbook_44s_8,&_resbook_44s_8}
  141696. };
  141697. static vorbis_residue_template _res_44s_9[]={
  141698. {2,0, &_residue_44_high,
  141699. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141700. &_resbook_44s_9,&_resbook_44s_9},
  141701. {2,0, &_residue_44_high,
  141702. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141703. &_resbook_44s_9,&_resbook_44s_9}
  141704. };
  141705. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141706. { _map_nominal, _res_44s_n1 }, /* -1 */
  141707. { _map_nominal, _res_44s_0 }, /* 0 */
  141708. { _map_nominal, _res_44s_1 }, /* 1 */
  141709. { _map_nominal, _res_44s_2 }, /* 2 */
  141710. { _map_nominal, _res_44s_3 }, /* 3 */
  141711. { _map_nominal, _res_44s_4 }, /* 4 */
  141712. { _map_nominal, _res_44s_5 }, /* 5 */
  141713. { _map_nominal, _res_44s_6 }, /* 6 */
  141714. { _map_nominal, _res_44s_7 }, /* 7 */
  141715. { _map_nominal, _res_44s_8 }, /* 8 */
  141716. { _map_nominal, _res_44s_9 }, /* 9 */
  141717. };
  141718. /*** End of inlined file: residue_44.h ***/
  141719. /*** Start of inlined file: psych_44.h ***/
  141720. /* preecho trigger settings *****************************************/
  141721. static vorbis_info_psy_global _psy_global_44[5]={
  141722. {8, /* lines per eighth octave */
  141723. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141724. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141725. -6.f,
  141726. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141727. },
  141728. {8, /* lines per eighth octave */
  141729. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141730. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141731. -6.f,
  141732. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141733. },
  141734. {8, /* lines per eighth octave */
  141735. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141736. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141737. -6.f,
  141738. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141739. },
  141740. {8, /* lines per eighth octave */
  141741. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141742. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141743. -6.f,
  141744. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141745. },
  141746. {8, /* lines per eighth octave */
  141747. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141748. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141749. -6.f,
  141750. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141751. },
  141752. };
  141753. /* noise compander lookups * low, mid, high quality ****************/
  141754. static compandblock _psy_compand_44[6]={
  141755. /* sub-mode Z short */
  141756. {{
  141757. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141758. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141759. 16,17,18,19,20,21,22, 23, /* 23dB */
  141760. 24,25,26,27,28,29,30, 31, /* 31dB */
  141761. 32,33,34,35,36,37,38, 39, /* 39dB */
  141762. }},
  141763. /* mode_Z nominal short */
  141764. {{
  141765. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141766. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141767. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141768. 15,16,17,17,17,18,18, 19, /* 31dB */
  141769. 19,19,20,21,22,23,24, 25, /* 39dB */
  141770. }},
  141771. /* mode A short */
  141772. {{
  141773. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141774. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141775. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141776. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141777. 11,12,13,14,15,16,17, 18, /* 39dB */
  141778. }},
  141779. /* sub-mode Z long */
  141780. {{
  141781. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141782. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141783. 16,17,18,19,20,21,22, 23, /* 23dB */
  141784. 24,25,26,27,28,29,30, 31, /* 31dB */
  141785. 32,33,34,35,36,37,38, 39, /* 39dB */
  141786. }},
  141787. /* mode_Z nominal long */
  141788. {{
  141789. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141790. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141791. 13,14,14,14,15,15,15, 15, /* 23dB */
  141792. 16,16,17,17,17,18,18, 19, /* 31dB */
  141793. 19,19,20,21,22,23,24, 25, /* 39dB */
  141794. }},
  141795. /* mode A long */
  141796. {{
  141797. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141798. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141799. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141800. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141801. 11,12,13,14,15,16,17, 18, /* 39dB */
  141802. }}
  141803. };
  141804. /* tonal masking curve level adjustments *************************/
  141805. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141806. /* 63 125 250 500 1 2 4 8 16 */
  141807. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141808. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141809. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141810. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141811. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141812. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141813. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141814. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141815. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141816. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141817. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141818. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141819. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141820. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141821. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141822. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141823. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141824. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141825. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141826. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141827. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141828. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141829. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141830. };
  141831. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141832. /* 63 125 250 500 1 2 4 8 16 */
  141833. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141834. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141835. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141836. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141837. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141838. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141839. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141840. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141841. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141842. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141843. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141844. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141845. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141846. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141847. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141848. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141849. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141850. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141851. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141852. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141853. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141854. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141855. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141856. };
  141857. /* noise bias (transition block) */
  141858. static noise3 _psy_noisebias_trans[12]={
  141859. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141860. /* -1 */
  141861. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141862. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141863. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141864. /* 0
  141865. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141866. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141867. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141868. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141869. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141870. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141871. /* 1
  141872. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141873. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141874. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141875. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141876. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141877. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141878. /* 2
  141879. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141880. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141881. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141882. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141883. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141884. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141885. /* 3
  141886. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141887. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141888. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141889. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141890. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141891. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141892. /* 4
  141893. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141894. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141895. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141896. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141897. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141898. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141899. /* 5
  141900. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141901. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141902. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141903. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141904. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141905. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141906. /* 6
  141907. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141908. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141909. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141910. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141911. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141912. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141913. /* 7
  141914. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141915. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141916. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141917. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141918. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141919. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141920. /* 8
  141921. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141922. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141923. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141924. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141925. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141926. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141927. /* 9
  141928. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141929. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141930. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141931. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141932. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141933. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141934. /* 10 */
  141935. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141936. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141937. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141938. };
  141939. /* noise bias (long block) */
  141940. static noise3 _psy_noisebias_long[12]={
  141941. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141942. /* -1 */
  141943. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141944. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141945. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141946. /* 0 */
  141947. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141948. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141949. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141950. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141951. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141952. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141953. /* 1 */
  141954. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141955. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141956. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141957. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141958. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141959. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141960. /* 2 */
  141961. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141962. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141963. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141964. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141965. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141966. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141967. /* 3 */
  141968. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141969. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141970. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141971. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141972. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141973. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141974. /* 4 */
  141975. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141976. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141977. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141978. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141979. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141980. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141981. /* 5 */
  141982. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141983. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141984. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141985. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141986. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141987. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141988. /* 6 */
  141989. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141990. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141991. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141992. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141993. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141994. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141995. /* 7 */
  141996. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141997. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141998. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141999. /* 8 */
  142000. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142001. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142002. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142003. /* 9 */
  142004. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142005. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142006. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142007. /* 10 */
  142008. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142009. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142010. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142011. };
  142012. /* noise bias (impulse block) */
  142013. static noise3 _psy_noisebias_impulse[12]={
  142014. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142015. /* -1 */
  142016. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142017. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142018. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142019. /* 0 */
  142020. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142021. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142022. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142023. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142024. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142025. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142026. /* 1 */
  142027. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142028. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142029. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142030. /* 2 */
  142031. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142032. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142033. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142034. /* 3 */
  142035. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142036. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142037. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142038. /* 4 */
  142039. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142040. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142041. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142042. /* 5 */
  142043. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142044. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142045. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142046. /* 6
  142047. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142048. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142049. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142050. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142051. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142052. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142053. /* 7 */
  142054. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142055. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142056. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142057. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142058. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142059. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142060. /* 8 */
  142061. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142062. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142063. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142064. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142065. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142066. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142067. /* 9 */
  142068. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142069. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142070. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142071. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142072. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142073. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142074. /* 10 */
  142075. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142076. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142077. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142078. };
  142079. /* noise bias (padding block) */
  142080. static noise3 _psy_noisebias_padding[12]={
  142081. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142082. /* -1 */
  142083. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142084. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142085. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142086. /* 0 */
  142087. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142088. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142089. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142090. /* 1 */
  142091. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142092. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142093. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142094. /* 2 */
  142095. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142096. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142097. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142098. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142099. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142100. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142101. /* 3 */
  142102. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142103. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142104. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142105. /* 4 */
  142106. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142107. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142108. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142109. /* 5 */
  142110. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142111. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142112. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142113. /* 6 */
  142114. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142115. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142116. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142117. /* 7 */
  142118. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142119. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142120. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142121. /* 8 */
  142122. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142123. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142124. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142125. /* 9 */
  142126. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142127. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142128. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142129. /* 10 */
  142130. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142131. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142132. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142133. };
  142134. static noiseguard _psy_noiseguards_44[4]={
  142135. {3,3,15},
  142136. {3,3,15},
  142137. {10,10,100},
  142138. {10,10,100},
  142139. };
  142140. static int _psy_tone_suppress[12]={
  142141. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142142. };
  142143. static int _psy_tone_0dB[12]={
  142144. 90,90,95,95,95,95,105,105,105,105,105,105,
  142145. };
  142146. static int _psy_noise_suppress[12]={
  142147. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142148. };
  142149. static vorbis_info_psy _psy_info_template={
  142150. /* blockflag */
  142151. -1,
  142152. /* ath_adjatt, ath_maxatt */
  142153. -140.,-140.,
  142154. /* tonemask att boost/decay,suppr,curves */
  142155. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142156. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142157. 1, -0.f, .5f, .5f, 0,0,0,
  142158. /* noiseoffset*3, noisecompand, max_curve_dB */
  142159. {{-1},{-1},{-1}},{-1},105.f,
  142160. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142161. 0,0,-1,-1,0.,
  142162. };
  142163. /* ath ****************/
  142164. static int _psy_ath_floater[12]={
  142165. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142166. };
  142167. static int _psy_ath_abs[12]={
  142168. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142169. };
  142170. /* stereo setup. These don't map directly to quality level, there's
  142171. an additional indirection as several of the below may be used in a
  142172. single bitmanaged stream
  142173. ****************/
  142174. /* various stereo possibilities */
  142175. /* stereo mode by base quality level */
  142176. static adj_stereo _psy_stereo_modes_44[12]={
  142177. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142178. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142179. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142180. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142181. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142182. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142183. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142184. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142185. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142186. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142187. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142188. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142189. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142190. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142191. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142192. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142193. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142194. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142195. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142196. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142197. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142198. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142199. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142200. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142201. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142202. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142203. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142204. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142205. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142206. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142207. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142208. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142209. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142210. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142211. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142212. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142213. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142214. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142215. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142216. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142217. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142218. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142219. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142220. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142221. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142222. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142223. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142224. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142225. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142226. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142227. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142228. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142229. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142230. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142231. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142232. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142233. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142234. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142235. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142236. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142237. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142238. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142239. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142240. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142241. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142242. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142243. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142244. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142245. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142246. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142247. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142248. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142249. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142250. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142251. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142252. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142253. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142254. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142255. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142256. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142257. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142258. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142259. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142260. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142261. };
  142262. /* tone master attenuation by base quality mode and bitrate tweak */
  142263. static att3 _psy_tone_masteratt_44[12]={
  142264. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142265. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142266. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142267. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142268. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142269. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142270. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142271. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142272. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142273. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142274. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142275. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142276. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142277. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142278. };
  142279. /* lowpass by mode **************/
  142280. static double _psy_lowpass_44[12]={
  142281. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142282. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142283. };
  142284. /* noise normalization **********/
  142285. static int _noise_start_short_44[11]={
  142286. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142287. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142288. };
  142289. static int _noise_start_long_44[11]={
  142290. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142291. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142292. };
  142293. static int _noise_part_short_44[11]={
  142294. 8,8,8,8,8,8,8,8,8,8,8
  142295. };
  142296. static int _noise_part_long_44[11]={
  142297. 32,32,32,32,32,32,32,32,32,32,32
  142298. };
  142299. static double _noise_thresh_44[11]={
  142300. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142301. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142302. };
  142303. static double _noise_thresh_5only[2]={
  142304. .5,.5,
  142305. };
  142306. /*** End of inlined file: psych_44.h ***/
  142307. static double rate_mapping_44_stereo[12]={
  142308. 22500.,32000.,40000.,48000.,56000.,64000.,
  142309. 80000.,96000.,112000.,128000.,160000.,250001.
  142310. };
  142311. static double quality_mapping_44[12]={
  142312. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142313. };
  142314. static int blocksize_short_44[11]={
  142315. 512,256,256,256,256,256,256,256,256,256,256
  142316. };
  142317. static int blocksize_long_44[11]={
  142318. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142319. };
  142320. static double _psy_compand_short_mapping[12]={
  142321. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142322. };
  142323. static double _psy_compand_long_mapping[12]={
  142324. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142325. };
  142326. static double _global_mapping_44[12]={
  142327. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142328. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142329. };
  142330. static int _floor_short_mapping_44[11]={
  142331. 1,0,0,2,2,4,5,5,5,5,5
  142332. };
  142333. static int _floor_long_mapping_44[11]={
  142334. 8,7,7,7,7,7,7,7,7,7,7
  142335. };
  142336. ve_setup_data_template ve_setup_44_stereo={
  142337. 11,
  142338. rate_mapping_44_stereo,
  142339. quality_mapping_44,
  142340. 2,
  142341. 40000,
  142342. 50000,
  142343. blocksize_short_44,
  142344. blocksize_long_44,
  142345. _psy_tone_masteratt_44,
  142346. _psy_tone_0dB,
  142347. _psy_tone_suppress,
  142348. _vp_tonemask_adj_otherblock,
  142349. _vp_tonemask_adj_longblock,
  142350. _vp_tonemask_adj_otherblock,
  142351. _psy_noiseguards_44,
  142352. _psy_noisebias_impulse,
  142353. _psy_noisebias_padding,
  142354. _psy_noisebias_trans,
  142355. _psy_noisebias_long,
  142356. _psy_noise_suppress,
  142357. _psy_compand_44,
  142358. _psy_compand_short_mapping,
  142359. _psy_compand_long_mapping,
  142360. {_noise_start_short_44,_noise_start_long_44},
  142361. {_noise_part_short_44,_noise_part_long_44},
  142362. _noise_thresh_44,
  142363. _psy_ath_floater,
  142364. _psy_ath_abs,
  142365. _psy_lowpass_44,
  142366. _psy_global_44,
  142367. _global_mapping_44,
  142368. _psy_stereo_modes_44,
  142369. _floor_books,
  142370. _floor,
  142371. _floor_short_mapping_44,
  142372. _floor_long_mapping_44,
  142373. _mapres_template_44_stereo
  142374. };
  142375. /*** End of inlined file: setup_44.h ***/
  142376. /*** Start of inlined file: setup_44u.h ***/
  142377. /*** Start of inlined file: residue_44u.h ***/
  142378. /*** Start of inlined file: res_books_uncoupled.h ***/
  142379. static long _vq_quantlist__16u0__p1_0[] = {
  142380. 1,
  142381. 0,
  142382. 2,
  142383. };
  142384. static long _vq_lengthlist__16u0__p1_0[] = {
  142385. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142386. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142387. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142388. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142389. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142390. 12,
  142391. };
  142392. static float _vq_quantthresh__16u0__p1_0[] = {
  142393. -0.5, 0.5,
  142394. };
  142395. static long _vq_quantmap__16u0__p1_0[] = {
  142396. 1, 0, 2,
  142397. };
  142398. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142399. _vq_quantthresh__16u0__p1_0,
  142400. _vq_quantmap__16u0__p1_0,
  142401. 3,
  142402. 3
  142403. };
  142404. static static_codebook _16u0__p1_0 = {
  142405. 4, 81,
  142406. _vq_lengthlist__16u0__p1_0,
  142407. 1, -535822336, 1611661312, 2, 0,
  142408. _vq_quantlist__16u0__p1_0,
  142409. NULL,
  142410. &_vq_auxt__16u0__p1_0,
  142411. NULL,
  142412. 0
  142413. };
  142414. static long _vq_quantlist__16u0__p2_0[] = {
  142415. 1,
  142416. 0,
  142417. 2,
  142418. };
  142419. static long _vq_lengthlist__16u0__p2_0[] = {
  142420. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142421. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142422. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142423. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142424. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142425. 8,
  142426. };
  142427. static float _vq_quantthresh__16u0__p2_0[] = {
  142428. -0.5, 0.5,
  142429. };
  142430. static long _vq_quantmap__16u0__p2_0[] = {
  142431. 1, 0, 2,
  142432. };
  142433. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142434. _vq_quantthresh__16u0__p2_0,
  142435. _vq_quantmap__16u0__p2_0,
  142436. 3,
  142437. 3
  142438. };
  142439. static static_codebook _16u0__p2_0 = {
  142440. 4, 81,
  142441. _vq_lengthlist__16u0__p2_0,
  142442. 1, -535822336, 1611661312, 2, 0,
  142443. _vq_quantlist__16u0__p2_0,
  142444. NULL,
  142445. &_vq_auxt__16u0__p2_0,
  142446. NULL,
  142447. 0
  142448. };
  142449. static long _vq_quantlist__16u0__p3_0[] = {
  142450. 2,
  142451. 1,
  142452. 3,
  142453. 0,
  142454. 4,
  142455. };
  142456. static long _vq_lengthlist__16u0__p3_0[] = {
  142457. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142458. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142459. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142460. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142461. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142462. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142463. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142464. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142465. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142466. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142467. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142468. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142469. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142470. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142471. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142472. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142473. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142474. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142475. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142476. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142477. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142478. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142479. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142480. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142481. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142482. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142483. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142484. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142485. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142486. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142487. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142488. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142489. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142490. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142491. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142492. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142493. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142494. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142495. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142496. 18,
  142497. };
  142498. static float _vq_quantthresh__16u0__p3_0[] = {
  142499. -1.5, -0.5, 0.5, 1.5,
  142500. };
  142501. static long _vq_quantmap__16u0__p3_0[] = {
  142502. 3, 1, 0, 2, 4,
  142503. };
  142504. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142505. _vq_quantthresh__16u0__p3_0,
  142506. _vq_quantmap__16u0__p3_0,
  142507. 5,
  142508. 5
  142509. };
  142510. static static_codebook _16u0__p3_0 = {
  142511. 4, 625,
  142512. _vq_lengthlist__16u0__p3_0,
  142513. 1, -533725184, 1611661312, 3, 0,
  142514. _vq_quantlist__16u0__p3_0,
  142515. NULL,
  142516. &_vq_auxt__16u0__p3_0,
  142517. NULL,
  142518. 0
  142519. };
  142520. static long _vq_quantlist__16u0__p4_0[] = {
  142521. 2,
  142522. 1,
  142523. 3,
  142524. 0,
  142525. 4,
  142526. };
  142527. static long _vq_lengthlist__16u0__p4_0[] = {
  142528. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142529. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142530. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142531. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142532. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142533. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142534. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142535. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142536. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142537. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142538. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142539. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142540. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142541. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142542. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142543. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142544. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142545. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142546. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142547. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142548. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142549. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142550. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142551. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142552. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142553. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142554. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142555. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142556. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142557. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142558. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142559. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142560. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142561. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142562. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142563. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142564. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142565. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142566. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142567. 11,
  142568. };
  142569. static float _vq_quantthresh__16u0__p4_0[] = {
  142570. -1.5, -0.5, 0.5, 1.5,
  142571. };
  142572. static long _vq_quantmap__16u0__p4_0[] = {
  142573. 3, 1, 0, 2, 4,
  142574. };
  142575. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142576. _vq_quantthresh__16u0__p4_0,
  142577. _vq_quantmap__16u0__p4_0,
  142578. 5,
  142579. 5
  142580. };
  142581. static static_codebook _16u0__p4_0 = {
  142582. 4, 625,
  142583. _vq_lengthlist__16u0__p4_0,
  142584. 1, -533725184, 1611661312, 3, 0,
  142585. _vq_quantlist__16u0__p4_0,
  142586. NULL,
  142587. &_vq_auxt__16u0__p4_0,
  142588. NULL,
  142589. 0
  142590. };
  142591. static long _vq_quantlist__16u0__p5_0[] = {
  142592. 4,
  142593. 3,
  142594. 5,
  142595. 2,
  142596. 6,
  142597. 1,
  142598. 7,
  142599. 0,
  142600. 8,
  142601. };
  142602. static long _vq_lengthlist__16u0__p5_0[] = {
  142603. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142604. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142605. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142606. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142607. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142608. 12,
  142609. };
  142610. static float _vq_quantthresh__16u0__p5_0[] = {
  142611. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142612. };
  142613. static long _vq_quantmap__16u0__p5_0[] = {
  142614. 7, 5, 3, 1, 0, 2, 4, 6,
  142615. 8,
  142616. };
  142617. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142618. _vq_quantthresh__16u0__p5_0,
  142619. _vq_quantmap__16u0__p5_0,
  142620. 9,
  142621. 9
  142622. };
  142623. static static_codebook _16u0__p5_0 = {
  142624. 2, 81,
  142625. _vq_lengthlist__16u0__p5_0,
  142626. 1, -531628032, 1611661312, 4, 0,
  142627. _vq_quantlist__16u0__p5_0,
  142628. NULL,
  142629. &_vq_auxt__16u0__p5_0,
  142630. NULL,
  142631. 0
  142632. };
  142633. static long _vq_quantlist__16u0__p6_0[] = {
  142634. 6,
  142635. 5,
  142636. 7,
  142637. 4,
  142638. 8,
  142639. 3,
  142640. 9,
  142641. 2,
  142642. 10,
  142643. 1,
  142644. 11,
  142645. 0,
  142646. 12,
  142647. };
  142648. static long _vq_lengthlist__16u0__p6_0[] = {
  142649. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142650. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142651. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142652. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142653. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142654. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142655. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142656. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142657. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142658. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142659. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142660. };
  142661. static float _vq_quantthresh__16u0__p6_0[] = {
  142662. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142663. 12.5, 17.5, 22.5, 27.5,
  142664. };
  142665. static long _vq_quantmap__16u0__p6_0[] = {
  142666. 11, 9, 7, 5, 3, 1, 0, 2,
  142667. 4, 6, 8, 10, 12,
  142668. };
  142669. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142670. _vq_quantthresh__16u0__p6_0,
  142671. _vq_quantmap__16u0__p6_0,
  142672. 13,
  142673. 13
  142674. };
  142675. static static_codebook _16u0__p6_0 = {
  142676. 2, 169,
  142677. _vq_lengthlist__16u0__p6_0,
  142678. 1, -526516224, 1616117760, 4, 0,
  142679. _vq_quantlist__16u0__p6_0,
  142680. NULL,
  142681. &_vq_auxt__16u0__p6_0,
  142682. NULL,
  142683. 0
  142684. };
  142685. static long _vq_quantlist__16u0__p6_1[] = {
  142686. 2,
  142687. 1,
  142688. 3,
  142689. 0,
  142690. 4,
  142691. };
  142692. static long _vq_lengthlist__16u0__p6_1[] = {
  142693. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142694. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142695. };
  142696. static float _vq_quantthresh__16u0__p6_1[] = {
  142697. -1.5, -0.5, 0.5, 1.5,
  142698. };
  142699. static long _vq_quantmap__16u0__p6_1[] = {
  142700. 3, 1, 0, 2, 4,
  142701. };
  142702. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142703. _vq_quantthresh__16u0__p6_1,
  142704. _vq_quantmap__16u0__p6_1,
  142705. 5,
  142706. 5
  142707. };
  142708. static static_codebook _16u0__p6_1 = {
  142709. 2, 25,
  142710. _vq_lengthlist__16u0__p6_1,
  142711. 1, -533725184, 1611661312, 3, 0,
  142712. _vq_quantlist__16u0__p6_1,
  142713. NULL,
  142714. &_vq_auxt__16u0__p6_1,
  142715. NULL,
  142716. 0
  142717. };
  142718. static long _vq_quantlist__16u0__p7_0[] = {
  142719. 1,
  142720. 0,
  142721. 2,
  142722. };
  142723. static long _vq_lengthlist__16u0__p7_0[] = {
  142724. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142725. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142726. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142727. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142728. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142729. 7,
  142730. };
  142731. static float _vq_quantthresh__16u0__p7_0[] = {
  142732. -157.5, 157.5,
  142733. };
  142734. static long _vq_quantmap__16u0__p7_0[] = {
  142735. 1, 0, 2,
  142736. };
  142737. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142738. _vq_quantthresh__16u0__p7_0,
  142739. _vq_quantmap__16u0__p7_0,
  142740. 3,
  142741. 3
  142742. };
  142743. static static_codebook _16u0__p7_0 = {
  142744. 4, 81,
  142745. _vq_lengthlist__16u0__p7_0,
  142746. 1, -518803456, 1628680192, 2, 0,
  142747. _vq_quantlist__16u0__p7_0,
  142748. NULL,
  142749. &_vq_auxt__16u0__p7_0,
  142750. NULL,
  142751. 0
  142752. };
  142753. static long _vq_quantlist__16u0__p7_1[] = {
  142754. 7,
  142755. 6,
  142756. 8,
  142757. 5,
  142758. 9,
  142759. 4,
  142760. 10,
  142761. 3,
  142762. 11,
  142763. 2,
  142764. 12,
  142765. 1,
  142766. 13,
  142767. 0,
  142768. 14,
  142769. };
  142770. static long _vq_lengthlist__16u0__p7_1[] = {
  142771. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142772. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142773. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142774. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142775. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142776. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142781. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142784. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142785. 10,
  142786. };
  142787. static float _vq_quantthresh__16u0__p7_1[] = {
  142788. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142789. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142790. };
  142791. static long _vq_quantmap__16u0__p7_1[] = {
  142792. 13, 11, 9, 7, 5, 3, 1, 0,
  142793. 2, 4, 6, 8, 10, 12, 14,
  142794. };
  142795. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142796. _vq_quantthresh__16u0__p7_1,
  142797. _vq_quantmap__16u0__p7_1,
  142798. 15,
  142799. 15
  142800. };
  142801. static static_codebook _16u0__p7_1 = {
  142802. 2, 225,
  142803. _vq_lengthlist__16u0__p7_1,
  142804. 1, -520986624, 1620377600, 4, 0,
  142805. _vq_quantlist__16u0__p7_1,
  142806. NULL,
  142807. &_vq_auxt__16u0__p7_1,
  142808. NULL,
  142809. 0
  142810. };
  142811. static long _vq_quantlist__16u0__p7_2[] = {
  142812. 10,
  142813. 9,
  142814. 11,
  142815. 8,
  142816. 12,
  142817. 7,
  142818. 13,
  142819. 6,
  142820. 14,
  142821. 5,
  142822. 15,
  142823. 4,
  142824. 16,
  142825. 3,
  142826. 17,
  142827. 2,
  142828. 18,
  142829. 1,
  142830. 19,
  142831. 0,
  142832. 20,
  142833. };
  142834. static long _vq_lengthlist__16u0__p7_2[] = {
  142835. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142836. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142837. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142838. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142839. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142840. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142841. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142842. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142843. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142844. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142845. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142846. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142847. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142848. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142849. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142850. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142851. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142852. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142853. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142854. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142855. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142856. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142857. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142858. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142859. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142860. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142861. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142862. 10,10,12,11,10,11,11,11,10,
  142863. };
  142864. static float _vq_quantthresh__16u0__p7_2[] = {
  142865. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142866. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142867. 6.5, 7.5, 8.5, 9.5,
  142868. };
  142869. static long _vq_quantmap__16u0__p7_2[] = {
  142870. 19, 17, 15, 13, 11, 9, 7, 5,
  142871. 3, 1, 0, 2, 4, 6, 8, 10,
  142872. 12, 14, 16, 18, 20,
  142873. };
  142874. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142875. _vq_quantthresh__16u0__p7_2,
  142876. _vq_quantmap__16u0__p7_2,
  142877. 21,
  142878. 21
  142879. };
  142880. static static_codebook _16u0__p7_2 = {
  142881. 2, 441,
  142882. _vq_lengthlist__16u0__p7_2,
  142883. 1, -529268736, 1611661312, 5, 0,
  142884. _vq_quantlist__16u0__p7_2,
  142885. NULL,
  142886. &_vq_auxt__16u0__p7_2,
  142887. NULL,
  142888. 0
  142889. };
  142890. static long _huff_lengthlist__16u0__single[] = {
  142891. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142892. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142893. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142894. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142895. };
  142896. static static_codebook _huff_book__16u0__single = {
  142897. 2, 64,
  142898. _huff_lengthlist__16u0__single,
  142899. 0, 0, 0, 0, 0,
  142900. NULL,
  142901. NULL,
  142902. NULL,
  142903. NULL,
  142904. 0
  142905. };
  142906. static long _huff_lengthlist__16u1__long[] = {
  142907. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142908. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142909. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142910. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142911. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142912. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142913. 16,13,16,18,
  142914. };
  142915. static static_codebook _huff_book__16u1__long = {
  142916. 2, 100,
  142917. _huff_lengthlist__16u1__long,
  142918. 0, 0, 0, 0, 0,
  142919. NULL,
  142920. NULL,
  142921. NULL,
  142922. NULL,
  142923. 0
  142924. };
  142925. static long _vq_quantlist__16u1__p1_0[] = {
  142926. 1,
  142927. 0,
  142928. 2,
  142929. };
  142930. static long _vq_lengthlist__16u1__p1_0[] = {
  142931. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142932. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142933. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142934. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142935. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142936. 11,
  142937. };
  142938. static float _vq_quantthresh__16u1__p1_0[] = {
  142939. -0.5, 0.5,
  142940. };
  142941. static long _vq_quantmap__16u1__p1_0[] = {
  142942. 1, 0, 2,
  142943. };
  142944. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142945. _vq_quantthresh__16u1__p1_0,
  142946. _vq_quantmap__16u1__p1_0,
  142947. 3,
  142948. 3
  142949. };
  142950. static static_codebook _16u1__p1_0 = {
  142951. 4, 81,
  142952. _vq_lengthlist__16u1__p1_0,
  142953. 1, -535822336, 1611661312, 2, 0,
  142954. _vq_quantlist__16u1__p1_0,
  142955. NULL,
  142956. &_vq_auxt__16u1__p1_0,
  142957. NULL,
  142958. 0
  142959. };
  142960. static long _vq_quantlist__16u1__p2_0[] = {
  142961. 1,
  142962. 0,
  142963. 2,
  142964. };
  142965. static long _vq_lengthlist__16u1__p2_0[] = {
  142966. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142967. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142968. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142969. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142970. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142971. 8,
  142972. };
  142973. static float _vq_quantthresh__16u1__p2_0[] = {
  142974. -0.5, 0.5,
  142975. };
  142976. static long _vq_quantmap__16u1__p2_0[] = {
  142977. 1, 0, 2,
  142978. };
  142979. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142980. _vq_quantthresh__16u1__p2_0,
  142981. _vq_quantmap__16u1__p2_0,
  142982. 3,
  142983. 3
  142984. };
  142985. static static_codebook _16u1__p2_0 = {
  142986. 4, 81,
  142987. _vq_lengthlist__16u1__p2_0,
  142988. 1, -535822336, 1611661312, 2, 0,
  142989. _vq_quantlist__16u1__p2_0,
  142990. NULL,
  142991. &_vq_auxt__16u1__p2_0,
  142992. NULL,
  142993. 0
  142994. };
  142995. static long _vq_quantlist__16u1__p3_0[] = {
  142996. 2,
  142997. 1,
  142998. 3,
  142999. 0,
  143000. 4,
  143001. };
  143002. static long _vq_lengthlist__16u1__p3_0[] = {
  143003. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143004. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143005. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143006. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143007. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143008. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143009. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143010. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143011. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143012. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143013. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143014. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143015. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143016. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143017. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143018. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143019. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143020. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143021. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143022. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143023. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143024. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143025. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143026. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143027. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143028. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143029. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143030. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143031. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143032. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143033. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143034. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143035. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143036. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143037. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143038. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143039. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143040. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143041. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143042. 16,
  143043. };
  143044. static float _vq_quantthresh__16u1__p3_0[] = {
  143045. -1.5, -0.5, 0.5, 1.5,
  143046. };
  143047. static long _vq_quantmap__16u1__p3_0[] = {
  143048. 3, 1, 0, 2, 4,
  143049. };
  143050. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143051. _vq_quantthresh__16u1__p3_0,
  143052. _vq_quantmap__16u1__p3_0,
  143053. 5,
  143054. 5
  143055. };
  143056. static static_codebook _16u1__p3_0 = {
  143057. 4, 625,
  143058. _vq_lengthlist__16u1__p3_0,
  143059. 1, -533725184, 1611661312, 3, 0,
  143060. _vq_quantlist__16u1__p3_0,
  143061. NULL,
  143062. &_vq_auxt__16u1__p3_0,
  143063. NULL,
  143064. 0
  143065. };
  143066. static long _vq_quantlist__16u1__p4_0[] = {
  143067. 2,
  143068. 1,
  143069. 3,
  143070. 0,
  143071. 4,
  143072. };
  143073. static long _vq_lengthlist__16u1__p4_0[] = {
  143074. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143075. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143076. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143077. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143078. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143079. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143080. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143081. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143082. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143083. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143084. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143085. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143086. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143087. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143088. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143089. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143090. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143091. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143092. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143093. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143094. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143095. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143096. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143097. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143098. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143099. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143100. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143101. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143102. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143103. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143104. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143105. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143106. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143107. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143108. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143109. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143110. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143111. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143112. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143113. 11,
  143114. };
  143115. static float _vq_quantthresh__16u1__p4_0[] = {
  143116. -1.5, -0.5, 0.5, 1.5,
  143117. };
  143118. static long _vq_quantmap__16u1__p4_0[] = {
  143119. 3, 1, 0, 2, 4,
  143120. };
  143121. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143122. _vq_quantthresh__16u1__p4_0,
  143123. _vq_quantmap__16u1__p4_0,
  143124. 5,
  143125. 5
  143126. };
  143127. static static_codebook _16u1__p4_0 = {
  143128. 4, 625,
  143129. _vq_lengthlist__16u1__p4_0,
  143130. 1, -533725184, 1611661312, 3, 0,
  143131. _vq_quantlist__16u1__p4_0,
  143132. NULL,
  143133. &_vq_auxt__16u1__p4_0,
  143134. NULL,
  143135. 0
  143136. };
  143137. static long _vq_quantlist__16u1__p5_0[] = {
  143138. 4,
  143139. 3,
  143140. 5,
  143141. 2,
  143142. 6,
  143143. 1,
  143144. 7,
  143145. 0,
  143146. 8,
  143147. };
  143148. static long _vq_lengthlist__16u1__p5_0[] = {
  143149. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143150. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143151. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143152. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143153. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143154. 13,
  143155. };
  143156. static float _vq_quantthresh__16u1__p5_0[] = {
  143157. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143158. };
  143159. static long _vq_quantmap__16u1__p5_0[] = {
  143160. 7, 5, 3, 1, 0, 2, 4, 6,
  143161. 8,
  143162. };
  143163. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143164. _vq_quantthresh__16u1__p5_0,
  143165. _vq_quantmap__16u1__p5_0,
  143166. 9,
  143167. 9
  143168. };
  143169. static static_codebook _16u1__p5_0 = {
  143170. 2, 81,
  143171. _vq_lengthlist__16u1__p5_0,
  143172. 1, -531628032, 1611661312, 4, 0,
  143173. _vq_quantlist__16u1__p5_0,
  143174. NULL,
  143175. &_vq_auxt__16u1__p5_0,
  143176. NULL,
  143177. 0
  143178. };
  143179. static long _vq_quantlist__16u1__p6_0[] = {
  143180. 4,
  143181. 3,
  143182. 5,
  143183. 2,
  143184. 6,
  143185. 1,
  143186. 7,
  143187. 0,
  143188. 8,
  143189. };
  143190. static long _vq_lengthlist__16u1__p6_0[] = {
  143191. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143192. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143193. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143194. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143195. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143196. 11,
  143197. };
  143198. static float _vq_quantthresh__16u1__p6_0[] = {
  143199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143200. };
  143201. static long _vq_quantmap__16u1__p6_0[] = {
  143202. 7, 5, 3, 1, 0, 2, 4, 6,
  143203. 8,
  143204. };
  143205. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143206. _vq_quantthresh__16u1__p6_0,
  143207. _vq_quantmap__16u1__p6_0,
  143208. 9,
  143209. 9
  143210. };
  143211. static static_codebook _16u1__p6_0 = {
  143212. 2, 81,
  143213. _vq_lengthlist__16u1__p6_0,
  143214. 1, -531628032, 1611661312, 4, 0,
  143215. _vq_quantlist__16u1__p6_0,
  143216. NULL,
  143217. &_vq_auxt__16u1__p6_0,
  143218. NULL,
  143219. 0
  143220. };
  143221. static long _vq_quantlist__16u1__p7_0[] = {
  143222. 1,
  143223. 0,
  143224. 2,
  143225. };
  143226. static long _vq_lengthlist__16u1__p7_0[] = {
  143227. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143228. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143229. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143230. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143231. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143232. 13,
  143233. };
  143234. static float _vq_quantthresh__16u1__p7_0[] = {
  143235. -5.5, 5.5,
  143236. };
  143237. static long _vq_quantmap__16u1__p7_0[] = {
  143238. 1, 0, 2,
  143239. };
  143240. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143241. _vq_quantthresh__16u1__p7_0,
  143242. _vq_quantmap__16u1__p7_0,
  143243. 3,
  143244. 3
  143245. };
  143246. static static_codebook _16u1__p7_0 = {
  143247. 4, 81,
  143248. _vq_lengthlist__16u1__p7_0,
  143249. 1, -529137664, 1618345984, 2, 0,
  143250. _vq_quantlist__16u1__p7_0,
  143251. NULL,
  143252. &_vq_auxt__16u1__p7_0,
  143253. NULL,
  143254. 0
  143255. };
  143256. static long _vq_quantlist__16u1__p7_1[] = {
  143257. 5,
  143258. 4,
  143259. 6,
  143260. 3,
  143261. 7,
  143262. 2,
  143263. 8,
  143264. 1,
  143265. 9,
  143266. 0,
  143267. 10,
  143268. };
  143269. static long _vq_lengthlist__16u1__p7_1[] = {
  143270. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143271. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143272. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143273. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143274. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143275. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143276. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143277. 8, 9, 9,10,10,10,10,10,10,
  143278. };
  143279. static float _vq_quantthresh__16u1__p7_1[] = {
  143280. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143281. 3.5, 4.5,
  143282. };
  143283. static long _vq_quantmap__16u1__p7_1[] = {
  143284. 9, 7, 5, 3, 1, 0, 2, 4,
  143285. 6, 8, 10,
  143286. };
  143287. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143288. _vq_quantthresh__16u1__p7_1,
  143289. _vq_quantmap__16u1__p7_1,
  143290. 11,
  143291. 11
  143292. };
  143293. static static_codebook _16u1__p7_1 = {
  143294. 2, 121,
  143295. _vq_lengthlist__16u1__p7_1,
  143296. 1, -531365888, 1611661312, 4, 0,
  143297. _vq_quantlist__16u1__p7_1,
  143298. NULL,
  143299. &_vq_auxt__16u1__p7_1,
  143300. NULL,
  143301. 0
  143302. };
  143303. static long _vq_quantlist__16u1__p8_0[] = {
  143304. 5,
  143305. 4,
  143306. 6,
  143307. 3,
  143308. 7,
  143309. 2,
  143310. 8,
  143311. 1,
  143312. 9,
  143313. 0,
  143314. 10,
  143315. };
  143316. static long _vq_lengthlist__16u1__p8_0[] = {
  143317. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143318. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143319. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143320. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143321. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143322. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143323. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143324. 13,14,14,15,15,16,16,15,16,
  143325. };
  143326. static float _vq_quantthresh__16u1__p8_0[] = {
  143327. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143328. 38.5, 49.5,
  143329. };
  143330. static long _vq_quantmap__16u1__p8_0[] = {
  143331. 9, 7, 5, 3, 1, 0, 2, 4,
  143332. 6, 8, 10,
  143333. };
  143334. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143335. _vq_quantthresh__16u1__p8_0,
  143336. _vq_quantmap__16u1__p8_0,
  143337. 11,
  143338. 11
  143339. };
  143340. static static_codebook _16u1__p8_0 = {
  143341. 2, 121,
  143342. _vq_lengthlist__16u1__p8_0,
  143343. 1, -524582912, 1618345984, 4, 0,
  143344. _vq_quantlist__16u1__p8_0,
  143345. NULL,
  143346. &_vq_auxt__16u1__p8_0,
  143347. NULL,
  143348. 0
  143349. };
  143350. static long _vq_quantlist__16u1__p8_1[] = {
  143351. 5,
  143352. 4,
  143353. 6,
  143354. 3,
  143355. 7,
  143356. 2,
  143357. 8,
  143358. 1,
  143359. 9,
  143360. 0,
  143361. 10,
  143362. };
  143363. static long _vq_lengthlist__16u1__p8_1[] = {
  143364. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143365. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143366. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143367. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143368. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143369. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143370. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143371. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143372. };
  143373. static float _vq_quantthresh__16u1__p8_1[] = {
  143374. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143375. 3.5, 4.5,
  143376. };
  143377. static long _vq_quantmap__16u1__p8_1[] = {
  143378. 9, 7, 5, 3, 1, 0, 2, 4,
  143379. 6, 8, 10,
  143380. };
  143381. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143382. _vq_quantthresh__16u1__p8_1,
  143383. _vq_quantmap__16u1__p8_1,
  143384. 11,
  143385. 11
  143386. };
  143387. static static_codebook _16u1__p8_1 = {
  143388. 2, 121,
  143389. _vq_lengthlist__16u1__p8_1,
  143390. 1, -531365888, 1611661312, 4, 0,
  143391. _vq_quantlist__16u1__p8_1,
  143392. NULL,
  143393. &_vq_auxt__16u1__p8_1,
  143394. NULL,
  143395. 0
  143396. };
  143397. static long _vq_quantlist__16u1__p9_0[] = {
  143398. 7,
  143399. 6,
  143400. 8,
  143401. 5,
  143402. 9,
  143403. 4,
  143404. 10,
  143405. 3,
  143406. 11,
  143407. 2,
  143408. 12,
  143409. 1,
  143410. 13,
  143411. 0,
  143412. 14,
  143413. };
  143414. static long _vq_lengthlist__16u1__p9_0[] = {
  143415. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143417. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143418. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143419. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143420. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143421. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143422. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143423. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143424. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143425. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143426. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143427. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143428. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143429. 8,
  143430. };
  143431. static float _vq_quantthresh__16u1__p9_0[] = {
  143432. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143433. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143434. };
  143435. static long _vq_quantmap__16u1__p9_0[] = {
  143436. 13, 11, 9, 7, 5, 3, 1, 0,
  143437. 2, 4, 6, 8, 10, 12, 14,
  143438. };
  143439. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143440. _vq_quantthresh__16u1__p9_0,
  143441. _vq_quantmap__16u1__p9_0,
  143442. 15,
  143443. 15
  143444. };
  143445. static static_codebook _16u1__p9_0 = {
  143446. 2, 225,
  143447. _vq_lengthlist__16u1__p9_0,
  143448. 1, -514071552, 1627381760, 4, 0,
  143449. _vq_quantlist__16u1__p9_0,
  143450. NULL,
  143451. &_vq_auxt__16u1__p9_0,
  143452. NULL,
  143453. 0
  143454. };
  143455. static long _vq_quantlist__16u1__p9_1[] = {
  143456. 7,
  143457. 6,
  143458. 8,
  143459. 5,
  143460. 9,
  143461. 4,
  143462. 10,
  143463. 3,
  143464. 11,
  143465. 2,
  143466. 12,
  143467. 1,
  143468. 13,
  143469. 0,
  143470. 14,
  143471. };
  143472. static long _vq_lengthlist__16u1__p9_1[] = {
  143473. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143474. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143475. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143476. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143477. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143478. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143479. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143480. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143481. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143483. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143484. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143485. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143486. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143487. 9,
  143488. };
  143489. static float _vq_quantthresh__16u1__p9_1[] = {
  143490. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143491. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143492. };
  143493. static long _vq_quantmap__16u1__p9_1[] = {
  143494. 13, 11, 9, 7, 5, 3, 1, 0,
  143495. 2, 4, 6, 8, 10, 12, 14,
  143496. };
  143497. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143498. _vq_quantthresh__16u1__p9_1,
  143499. _vq_quantmap__16u1__p9_1,
  143500. 15,
  143501. 15
  143502. };
  143503. static static_codebook _16u1__p9_1 = {
  143504. 2, 225,
  143505. _vq_lengthlist__16u1__p9_1,
  143506. 1, -522338304, 1620115456, 4, 0,
  143507. _vq_quantlist__16u1__p9_1,
  143508. NULL,
  143509. &_vq_auxt__16u1__p9_1,
  143510. NULL,
  143511. 0
  143512. };
  143513. static long _vq_quantlist__16u1__p9_2[] = {
  143514. 8,
  143515. 7,
  143516. 9,
  143517. 6,
  143518. 10,
  143519. 5,
  143520. 11,
  143521. 4,
  143522. 12,
  143523. 3,
  143524. 13,
  143525. 2,
  143526. 14,
  143527. 1,
  143528. 15,
  143529. 0,
  143530. 16,
  143531. };
  143532. static long _vq_lengthlist__16u1__p9_2[] = {
  143533. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143534. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143535. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143536. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143537. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143538. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143539. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143540. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143541. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143542. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143543. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143544. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143545. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143546. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143547. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143548. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143549. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143550. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143551. 10,
  143552. };
  143553. static float _vq_quantthresh__16u1__p9_2[] = {
  143554. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143555. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143556. };
  143557. static long _vq_quantmap__16u1__p9_2[] = {
  143558. 15, 13, 11, 9, 7, 5, 3, 1,
  143559. 0, 2, 4, 6, 8, 10, 12, 14,
  143560. 16,
  143561. };
  143562. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143563. _vq_quantthresh__16u1__p9_2,
  143564. _vq_quantmap__16u1__p9_2,
  143565. 17,
  143566. 17
  143567. };
  143568. static static_codebook _16u1__p9_2 = {
  143569. 2, 289,
  143570. _vq_lengthlist__16u1__p9_2,
  143571. 1, -529530880, 1611661312, 5, 0,
  143572. _vq_quantlist__16u1__p9_2,
  143573. NULL,
  143574. &_vq_auxt__16u1__p9_2,
  143575. NULL,
  143576. 0
  143577. };
  143578. static long _huff_lengthlist__16u1__short[] = {
  143579. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143580. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143581. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143582. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143583. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143584. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143585. 16,16,16,16,
  143586. };
  143587. static static_codebook _huff_book__16u1__short = {
  143588. 2, 100,
  143589. _huff_lengthlist__16u1__short,
  143590. 0, 0, 0, 0, 0,
  143591. NULL,
  143592. NULL,
  143593. NULL,
  143594. NULL,
  143595. 0
  143596. };
  143597. static long _huff_lengthlist__16u2__long[] = {
  143598. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143599. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143600. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143601. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143602. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143603. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143604. 13,14,18,18,
  143605. };
  143606. static static_codebook _huff_book__16u2__long = {
  143607. 2, 100,
  143608. _huff_lengthlist__16u2__long,
  143609. 0, 0, 0, 0, 0,
  143610. NULL,
  143611. NULL,
  143612. NULL,
  143613. NULL,
  143614. 0
  143615. };
  143616. static long _huff_lengthlist__16u2__short[] = {
  143617. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143618. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143619. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143620. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143621. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143622. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143623. 16,16,16,16,
  143624. };
  143625. static static_codebook _huff_book__16u2__short = {
  143626. 2, 100,
  143627. _huff_lengthlist__16u2__short,
  143628. 0, 0, 0, 0, 0,
  143629. NULL,
  143630. NULL,
  143631. NULL,
  143632. NULL,
  143633. 0
  143634. };
  143635. static long _vq_quantlist__16u2_p1_0[] = {
  143636. 1,
  143637. 0,
  143638. 2,
  143639. };
  143640. static long _vq_lengthlist__16u2_p1_0[] = {
  143641. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143642. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143643. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143644. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143645. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143646. 10,
  143647. };
  143648. static float _vq_quantthresh__16u2_p1_0[] = {
  143649. -0.5, 0.5,
  143650. };
  143651. static long _vq_quantmap__16u2_p1_0[] = {
  143652. 1, 0, 2,
  143653. };
  143654. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143655. _vq_quantthresh__16u2_p1_0,
  143656. _vq_quantmap__16u2_p1_0,
  143657. 3,
  143658. 3
  143659. };
  143660. static static_codebook _16u2_p1_0 = {
  143661. 4, 81,
  143662. _vq_lengthlist__16u2_p1_0,
  143663. 1, -535822336, 1611661312, 2, 0,
  143664. _vq_quantlist__16u2_p1_0,
  143665. NULL,
  143666. &_vq_auxt__16u2_p1_0,
  143667. NULL,
  143668. 0
  143669. };
  143670. static long _vq_quantlist__16u2_p2_0[] = {
  143671. 2,
  143672. 1,
  143673. 3,
  143674. 0,
  143675. 4,
  143676. };
  143677. static long _vq_lengthlist__16u2_p2_0[] = {
  143678. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143679. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143680. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143681. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143682. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143683. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143684. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143685. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143686. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143687. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143688. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143689. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143690. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143691. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143692. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143693. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143694. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143695. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143696. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143697. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143698. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143699. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143700. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143701. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143702. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143703. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143704. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143705. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143706. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143707. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143708. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143709. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143710. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143711. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143712. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143713. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143714. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143715. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143716. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143717. 13,
  143718. };
  143719. static float _vq_quantthresh__16u2_p2_0[] = {
  143720. -1.5, -0.5, 0.5, 1.5,
  143721. };
  143722. static long _vq_quantmap__16u2_p2_0[] = {
  143723. 3, 1, 0, 2, 4,
  143724. };
  143725. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143726. _vq_quantthresh__16u2_p2_0,
  143727. _vq_quantmap__16u2_p2_0,
  143728. 5,
  143729. 5
  143730. };
  143731. static static_codebook _16u2_p2_0 = {
  143732. 4, 625,
  143733. _vq_lengthlist__16u2_p2_0,
  143734. 1, -533725184, 1611661312, 3, 0,
  143735. _vq_quantlist__16u2_p2_0,
  143736. NULL,
  143737. &_vq_auxt__16u2_p2_0,
  143738. NULL,
  143739. 0
  143740. };
  143741. static long _vq_quantlist__16u2_p3_0[] = {
  143742. 4,
  143743. 3,
  143744. 5,
  143745. 2,
  143746. 6,
  143747. 1,
  143748. 7,
  143749. 0,
  143750. 8,
  143751. };
  143752. static long _vq_lengthlist__16u2_p3_0[] = {
  143753. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143754. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143755. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143756. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143757. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143758. 11,
  143759. };
  143760. static float _vq_quantthresh__16u2_p3_0[] = {
  143761. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143762. };
  143763. static long _vq_quantmap__16u2_p3_0[] = {
  143764. 7, 5, 3, 1, 0, 2, 4, 6,
  143765. 8,
  143766. };
  143767. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143768. _vq_quantthresh__16u2_p3_0,
  143769. _vq_quantmap__16u2_p3_0,
  143770. 9,
  143771. 9
  143772. };
  143773. static static_codebook _16u2_p3_0 = {
  143774. 2, 81,
  143775. _vq_lengthlist__16u2_p3_0,
  143776. 1, -531628032, 1611661312, 4, 0,
  143777. _vq_quantlist__16u2_p3_0,
  143778. NULL,
  143779. &_vq_auxt__16u2_p3_0,
  143780. NULL,
  143781. 0
  143782. };
  143783. static long _vq_quantlist__16u2_p4_0[] = {
  143784. 8,
  143785. 7,
  143786. 9,
  143787. 6,
  143788. 10,
  143789. 5,
  143790. 11,
  143791. 4,
  143792. 12,
  143793. 3,
  143794. 13,
  143795. 2,
  143796. 14,
  143797. 1,
  143798. 15,
  143799. 0,
  143800. 16,
  143801. };
  143802. static long _vq_lengthlist__16u2_p4_0[] = {
  143803. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143804. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143805. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143806. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143807. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143808. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143809. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143810. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143811. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143812. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143813. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143814. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143815. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143816. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143817. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143818. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143819. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143820. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143821. 14,
  143822. };
  143823. static float _vq_quantthresh__16u2_p4_0[] = {
  143824. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143825. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143826. };
  143827. static long _vq_quantmap__16u2_p4_0[] = {
  143828. 15, 13, 11, 9, 7, 5, 3, 1,
  143829. 0, 2, 4, 6, 8, 10, 12, 14,
  143830. 16,
  143831. };
  143832. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143833. _vq_quantthresh__16u2_p4_0,
  143834. _vq_quantmap__16u2_p4_0,
  143835. 17,
  143836. 17
  143837. };
  143838. static static_codebook _16u2_p4_0 = {
  143839. 2, 289,
  143840. _vq_lengthlist__16u2_p4_0,
  143841. 1, -529530880, 1611661312, 5, 0,
  143842. _vq_quantlist__16u2_p4_0,
  143843. NULL,
  143844. &_vq_auxt__16u2_p4_0,
  143845. NULL,
  143846. 0
  143847. };
  143848. static long _vq_quantlist__16u2_p5_0[] = {
  143849. 1,
  143850. 0,
  143851. 2,
  143852. };
  143853. static long _vq_lengthlist__16u2_p5_0[] = {
  143854. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143855. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143856. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143857. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143858. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143859. 10,
  143860. };
  143861. static float _vq_quantthresh__16u2_p5_0[] = {
  143862. -5.5, 5.5,
  143863. };
  143864. static long _vq_quantmap__16u2_p5_0[] = {
  143865. 1, 0, 2,
  143866. };
  143867. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143868. _vq_quantthresh__16u2_p5_0,
  143869. _vq_quantmap__16u2_p5_0,
  143870. 3,
  143871. 3
  143872. };
  143873. static static_codebook _16u2_p5_0 = {
  143874. 4, 81,
  143875. _vq_lengthlist__16u2_p5_0,
  143876. 1, -529137664, 1618345984, 2, 0,
  143877. _vq_quantlist__16u2_p5_0,
  143878. NULL,
  143879. &_vq_auxt__16u2_p5_0,
  143880. NULL,
  143881. 0
  143882. };
  143883. static long _vq_quantlist__16u2_p5_1[] = {
  143884. 5,
  143885. 4,
  143886. 6,
  143887. 3,
  143888. 7,
  143889. 2,
  143890. 8,
  143891. 1,
  143892. 9,
  143893. 0,
  143894. 10,
  143895. };
  143896. static long _vq_lengthlist__16u2_p5_1[] = {
  143897. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143898. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143899. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143900. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143901. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143902. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143903. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143904. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143905. };
  143906. static float _vq_quantthresh__16u2_p5_1[] = {
  143907. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143908. 3.5, 4.5,
  143909. };
  143910. static long _vq_quantmap__16u2_p5_1[] = {
  143911. 9, 7, 5, 3, 1, 0, 2, 4,
  143912. 6, 8, 10,
  143913. };
  143914. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143915. _vq_quantthresh__16u2_p5_1,
  143916. _vq_quantmap__16u2_p5_1,
  143917. 11,
  143918. 11
  143919. };
  143920. static static_codebook _16u2_p5_1 = {
  143921. 2, 121,
  143922. _vq_lengthlist__16u2_p5_1,
  143923. 1, -531365888, 1611661312, 4, 0,
  143924. _vq_quantlist__16u2_p5_1,
  143925. NULL,
  143926. &_vq_auxt__16u2_p5_1,
  143927. NULL,
  143928. 0
  143929. };
  143930. static long _vq_quantlist__16u2_p6_0[] = {
  143931. 6,
  143932. 5,
  143933. 7,
  143934. 4,
  143935. 8,
  143936. 3,
  143937. 9,
  143938. 2,
  143939. 10,
  143940. 1,
  143941. 11,
  143942. 0,
  143943. 12,
  143944. };
  143945. static long _vq_lengthlist__16u2_p6_0[] = {
  143946. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143947. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143948. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143949. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143950. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143951. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143952. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143953. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143954. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143955. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143956. 12,13,13,14,14,14,14,15,15,
  143957. };
  143958. static float _vq_quantthresh__16u2_p6_0[] = {
  143959. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143960. 12.5, 17.5, 22.5, 27.5,
  143961. };
  143962. static long _vq_quantmap__16u2_p6_0[] = {
  143963. 11, 9, 7, 5, 3, 1, 0, 2,
  143964. 4, 6, 8, 10, 12,
  143965. };
  143966. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143967. _vq_quantthresh__16u2_p6_0,
  143968. _vq_quantmap__16u2_p6_0,
  143969. 13,
  143970. 13
  143971. };
  143972. static static_codebook _16u2_p6_0 = {
  143973. 2, 169,
  143974. _vq_lengthlist__16u2_p6_0,
  143975. 1, -526516224, 1616117760, 4, 0,
  143976. _vq_quantlist__16u2_p6_0,
  143977. NULL,
  143978. &_vq_auxt__16u2_p6_0,
  143979. NULL,
  143980. 0
  143981. };
  143982. static long _vq_quantlist__16u2_p6_1[] = {
  143983. 2,
  143984. 1,
  143985. 3,
  143986. 0,
  143987. 4,
  143988. };
  143989. static long _vq_lengthlist__16u2_p6_1[] = {
  143990. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143991. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143992. };
  143993. static float _vq_quantthresh__16u2_p6_1[] = {
  143994. -1.5, -0.5, 0.5, 1.5,
  143995. };
  143996. static long _vq_quantmap__16u2_p6_1[] = {
  143997. 3, 1, 0, 2, 4,
  143998. };
  143999. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144000. _vq_quantthresh__16u2_p6_1,
  144001. _vq_quantmap__16u2_p6_1,
  144002. 5,
  144003. 5
  144004. };
  144005. static static_codebook _16u2_p6_1 = {
  144006. 2, 25,
  144007. _vq_lengthlist__16u2_p6_1,
  144008. 1, -533725184, 1611661312, 3, 0,
  144009. _vq_quantlist__16u2_p6_1,
  144010. NULL,
  144011. &_vq_auxt__16u2_p6_1,
  144012. NULL,
  144013. 0
  144014. };
  144015. static long _vq_quantlist__16u2_p7_0[] = {
  144016. 6,
  144017. 5,
  144018. 7,
  144019. 4,
  144020. 8,
  144021. 3,
  144022. 9,
  144023. 2,
  144024. 10,
  144025. 1,
  144026. 11,
  144027. 0,
  144028. 12,
  144029. };
  144030. static long _vq_lengthlist__16u2_p7_0[] = {
  144031. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144032. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144033. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144034. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144035. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144036. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144037. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144038. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144039. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144040. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144041. 12,13,13,13,14,14,14,15,14,
  144042. };
  144043. static float _vq_quantthresh__16u2_p7_0[] = {
  144044. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144045. 27.5, 38.5, 49.5, 60.5,
  144046. };
  144047. static long _vq_quantmap__16u2_p7_0[] = {
  144048. 11, 9, 7, 5, 3, 1, 0, 2,
  144049. 4, 6, 8, 10, 12,
  144050. };
  144051. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144052. _vq_quantthresh__16u2_p7_0,
  144053. _vq_quantmap__16u2_p7_0,
  144054. 13,
  144055. 13
  144056. };
  144057. static static_codebook _16u2_p7_0 = {
  144058. 2, 169,
  144059. _vq_lengthlist__16u2_p7_0,
  144060. 1, -523206656, 1618345984, 4, 0,
  144061. _vq_quantlist__16u2_p7_0,
  144062. NULL,
  144063. &_vq_auxt__16u2_p7_0,
  144064. NULL,
  144065. 0
  144066. };
  144067. static long _vq_quantlist__16u2_p7_1[] = {
  144068. 5,
  144069. 4,
  144070. 6,
  144071. 3,
  144072. 7,
  144073. 2,
  144074. 8,
  144075. 1,
  144076. 9,
  144077. 0,
  144078. 10,
  144079. };
  144080. static long _vq_lengthlist__16u2_p7_1[] = {
  144081. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144082. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144083. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144084. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144085. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144086. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144087. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144088. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144089. };
  144090. static float _vq_quantthresh__16u2_p7_1[] = {
  144091. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144092. 3.5, 4.5,
  144093. };
  144094. static long _vq_quantmap__16u2_p7_1[] = {
  144095. 9, 7, 5, 3, 1, 0, 2, 4,
  144096. 6, 8, 10,
  144097. };
  144098. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144099. _vq_quantthresh__16u2_p7_1,
  144100. _vq_quantmap__16u2_p7_1,
  144101. 11,
  144102. 11
  144103. };
  144104. static static_codebook _16u2_p7_1 = {
  144105. 2, 121,
  144106. _vq_lengthlist__16u2_p7_1,
  144107. 1, -531365888, 1611661312, 4, 0,
  144108. _vq_quantlist__16u2_p7_1,
  144109. NULL,
  144110. &_vq_auxt__16u2_p7_1,
  144111. NULL,
  144112. 0
  144113. };
  144114. static long _vq_quantlist__16u2_p8_0[] = {
  144115. 7,
  144116. 6,
  144117. 8,
  144118. 5,
  144119. 9,
  144120. 4,
  144121. 10,
  144122. 3,
  144123. 11,
  144124. 2,
  144125. 12,
  144126. 1,
  144127. 13,
  144128. 0,
  144129. 14,
  144130. };
  144131. static long _vq_lengthlist__16u2_p8_0[] = {
  144132. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144133. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144134. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144135. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144136. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144137. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144138. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144139. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144140. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144141. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144142. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144143. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144144. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144145. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144146. 14,
  144147. };
  144148. static float _vq_quantthresh__16u2_p8_0[] = {
  144149. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144150. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144151. };
  144152. static long _vq_quantmap__16u2_p8_0[] = {
  144153. 13, 11, 9, 7, 5, 3, 1, 0,
  144154. 2, 4, 6, 8, 10, 12, 14,
  144155. };
  144156. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144157. _vq_quantthresh__16u2_p8_0,
  144158. _vq_quantmap__16u2_p8_0,
  144159. 15,
  144160. 15
  144161. };
  144162. static static_codebook _16u2_p8_0 = {
  144163. 2, 225,
  144164. _vq_lengthlist__16u2_p8_0,
  144165. 1, -520986624, 1620377600, 4, 0,
  144166. _vq_quantlist__16u2_p8_0,
  144167. NULL,
  144168. &_vq_auxt__16u2_p8_0,
  144169. NULL,
  144170. 0
  144171. };
  144172. static long _vq_quantlist__16u2_p8_1[] = {
  144173. 10,
  144174. 9,
  144175. 11,
  144176. 8,
  144177. 12,
  144178. 7,
  144179. 13,
  144180. 6,
  144181. 14,
  144182. 5,
  144183. 15,
  144184. 4,
  144185. 16,
  144186. 3,
  144187. 17,
  144188. 2,
  144189. 18,
  144190. 1,
  144191. 19,
  144192. 0,
  144193. 20,
  144194. };
  144195. static long _vq_lengthlist__16u2_p8_1[] = {
  144196. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144197. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144198. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144199. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144200. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144201. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144202. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144203. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144204. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144205. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144206. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144207. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144208. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144209. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144210. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144211. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144212. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144213. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144214. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144215. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144216. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144217. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144218. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144219. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144221. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144222. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144223. 11,11,10,11,11,11,10,11,11,
  144224. };
  144225. static float _vq_quantthresh__16u2_p8_1[] = {
  144226. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144227. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144228. 6.5, 7.5, 8.5, 9.5,
  144229. };
  144230. static long _vq_quantmap__16u2_p8_1[] = {
  144231. 19, 17, 15, 13, 11, 9, 7, 5,
  144232. 3, 1, 0, 2, 4, 6, 8, 10,
  144233. 12, 14, 16, 18, 20,
  144234. };
  144235. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144236. _vq_quantthresh__16u2_p8_1,
  144237. _vq_quantmap__16u2_p8_1,
  144238. 21,
  144239. 21
  144240. };
  144241. static static_codebook _16u2_p8_1 = {
  144242. 2, 441,
  144243. _vq_lengthlist__16u2_p8_1,
  144244. 1, -529268736, 1611661312, 5, 0,
  144245. _vq_quantlist__16u2_p8_1,
  144246. NULL,
  144247. &_vq_auxt__16u2_p8_1,
  144248. NULL,
  144249. 0
  144250. };
  144251. static long _vq_quantlist__16u2_p9_0[] = {
  144252. 5586,
  144253. 4655,
  144254. 6517,
  144255. 3724,
  144256. 7448,
  144257. 2793,
  144258. 8379,
  144259. 1862,
  144260. 9310,
  144261. 931,
  144262. 10241,
  144263. 0,
  144264. 11172,
  144265. 5521,
  144266. 5651,
  144267. };
  144268. static long _vq_lengthlist__16u2_p9_0[] = {
  144269. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144270. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144272. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144275. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144276. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144277. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144281. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144282. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144283. 5,
  144284. };
  144285. static float _vq_quantthresh__16u2_p9_0[] = {
  144286. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144287. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144288. };
  144289. static long _vq_quantmap__16u2_p9_0[] = {
  144290. 11, 9, 7, 5, 3, 1, 13, 0,
  144291. 14, 2, 4, 6, 8, 10, 12,
  144292. };
  144293. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144294. _vq_quantthresh__16u2_p9_0,
  144295. _vq_quantmap__16u2_p9_0,
  144296. 15,
  144297. 15
  144298. };
  144299. static static_codebook _16u2_p9_0 = {
  144300. 2, 225,
  144301. _vq_lengthlist__16u2_p9_0,
  144302. 1, -510275072, 1611661312, 14, 0,
  144303. _vq_quantlist__16u2_p9_0,
  144304. NULL,
  144305. &_vq_auxt__16u2_p9_0,
  144306. NULL,
  144307. 0
  144308. };
  144309. static long _vq_quantlist__16u2_p9_1[] = {
  144310. 392,
  144311. 343,
  144312. 441,
  144313. 294,
  144314. 490,
  144315. 245,
  144316. 539,
  144317. 196,
  144318. 588,
  144319. 147,
  144320. 637,
  144321. 98,
  144322. 686,
  144323. 49,
  144324. 735,
  144325. 0,
  144326. 784,
  144327. 388,
  144328. 396,
  144329. };
  144330. static long _vq_lengthlist__16u2_p9_1[] = {
  144331. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144332. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144333. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144334. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144335. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144336. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144337. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144338. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144339. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144340. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144341. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144342. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144343. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144344. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144345. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144351. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144352. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144353. 11,11,11,11,11,11,11, 5, 4,
  144354. };
  144355. static float _vq_quantthresh__16u2_p9_1[] = {
  144356. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144357. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144358. 318.5, 367.5,
  144359. };
  144360. static long _vq_quantmap__16u2_p9_1[] = {
  144361. 15, 13, 11, 9, 7, 5, 3, 1,
  144362. 17, 0, 18, 2, 4, 6, 8, 10,
  144363. 12, 14, 16,
  144364. };
  144365. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144366. _vq_quantthresh__16u2_p9_1,
  144367. _vq_quantmap__16u2_p9_1,
  144368. 19,
  144369. 19
  144370. };
  144371. static static_codebook _16u2_p9_1 = {
  144372. 2, 361,
  144373. _vq_lengthlist__16u2_p9_1,
  144374. 1, -518488064, 1611661312, 10, 0,
  144375. _vq_quantlist__16u2_p9_1,
  144376. NULL,
  144377. &_vq_auxt__16u2_p9_1,
  144378. NULL,
  144379. 0
  144380. };
  144381. static long _vq_quantlist__16u2_p9_2[] = {
  144382. 24,
  144383. 23,
  144384. 25,
  144385. 22,
  144386. 26,
  144387. 21,
  144388. 27,
  144389. 20,
  144390. 28,
  144391. 19,
  144392. 29,
  144393. 18,
  144394. 30,
  144395. 17,
  144396. 31,
  144397. 16,
  144398. 32,
  144399. 15,
  144400. 33,
  144401. 14,
  144402. 34,
  144403. 13,
  144404. 35,
  144405. 12,
  144406. 36,
  144407. 11,
  144408. 37,
  144409. 10,
  144410. 38,
  144411. 9,
  144412. 39,
  144413. 8,
  144414. 40,
  144415. 7,
  144416. 41,
  144417. 6,
  144418. 42,
  144419. 5,
  144420. 43,
  144421. 4,
  144422. 44,
  144423. 3,
  144424. 45,
  144425. 2,
  144426. 46,
  144427. 1,
  144428. 47,
  144429. 0,
  144430. 48,
  144431. };
  144432. static long _vq_lengthlist__16u2_p9_2[] = {
  144433. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144434. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144435. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144436. 11,
  144437. };
  144438. static float _vq_quantthresh__16u2_p9_2[] = {
  144439. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144440. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144441. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144442. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144443. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144444. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144445. };
  144446. static long _vq_quantmap__16u2_p9_2[] = {
  144447. 47, 45, 43, 41, 39, 37, 35, 33,
  144448. 31, 29, 27, 25, 23, 21, 19, 17,
  144449. 15, 13, 11, 9, 7, 5, 3, 1,
  144450. 0, 2, 4, 6, 8, 10, 12, 14,
  144451. 16, 18, 20, 22, 24, 26, 28, 30,
  144452. 32, 34, 36, 38, 40, 42, 44, 46,
  144453. 48,
  144454. };
  144455. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144456. _vq_quantthresh__16u2_p9_2,
  144457. _vq_quantmap__16u2_p9_2,
  144458. 49,
  144459. 49
  144460. };
  144461. static static_codebook _16u2_p9_2 = {
  144462. 1, 49,
  144463. _vq_lengthlist__16u2_p9_2,
  144464. 1, -526909440, 1611661312, 6, 0,
  144465. _vq_quantlist__16u2_p9_2,
  144466. NULL,
  144467. &_vq_auxt__16u2_p9_2,
  144468. NULL,
  144469. 0
  144470. };
  144471. static long _vq_quantlist__8u0__p1_0[] = {
  144472. 1,
  144473. 0,
  144474. 2,
  144475. };
  144476. static long _vq_lengthlist__8u0__p1_0[] = {
  144477. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144478. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144479. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144480. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144481. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144482. 11,
  144483. };
  144484. static float _vq_quantthresh__8u0__p1_0[] = {
  144485. -0.5, 0.5,
  144486. };
  144487. static long _vq_quantmap__8u0__p1_0[] = {
  144488. 1, 0, 2,
  144489. };
  144490. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144491. _vq_quantthresh__8u0__p1_0,
  144492. _vq_quantmap__8u0__p1_0,
  144493. 3,
  144494. 3
  144495. };
  144496. static static_codebook _8u0__p1_0 = {
  144497. 4, 81,
  144498. _vq_lengthlist__8u0__p1_0,
  144499. 1, -535822336, 1611661312, 2, 0,
  144500. _vq_quantlist__8u0__p1_0,
  144501. NULL,
  144502. &_vq_auxt__8u0__p1_0,
  144503. NULL,
  144504. 0
  144505. };
  144506. static long _vq_quantlist__8u0__p2_0[] = {
  144507. 1,
  144508. 0,
  144509. 2,
  144510. };
  144511. static long _vq_lengthlist__8u0__p2_0[] = {
  144512. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144513. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144514. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144515. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144516. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144517. 8,
  144518. };
  144519. static float _vq_quantthresh__8u0__p2_0[] = {
  144520. -0.5, 0.5,
  144521. };
  144522. static long _vq_quantmap__8u0__p2_0[] = {
  144523. 1, 0, 2,
  144524. };
  144525. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144526. _vq_quantthresh__8u0__p2_0,
  144527. _vq_quantmap__8u0__p2_0,
  144528. 3,
  144529. 3
  144530. };
  144531. static static_codebook _8u0__p2_0 = {
  144532. 4, 81,
  144533. _vq_lengthlist__8u0__p2_0,
  144534. 1, -535822336, 1611661312, 2, 0,
  144535. _vq_quantlist__8u0__p2_0,
  144536. NULL,
  144537. &_vq_auxt__8u0__p2_0,
  144538. NULL,
  144539. 0
  144540. };
  144541. static long _vq_quantlist__8u0__p3_0[] = {
  144542. 2,
  144543. 1,
  144544. 3,
  144545. 0,
  144546. 4,
  144547. };
  144548. static long _vq_lengthlist__8u0__p3_0[] = {
  144549. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144550. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144551. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144552. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144553. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144554. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144555. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144556. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144557. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144558. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144559. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144560. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144561. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144562. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144563. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144564. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144565. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144566. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144567. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144568. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144569. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144570. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144571. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144572. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144573. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144574. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144575. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144576. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144577. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144578. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144579. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144580. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144581. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144582. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144583. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144584. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144585. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144586. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144587. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144588. 16,
  144589. };
  144590. static float _vq_quantthresh__8u0__p3_0[] = {
  144591. -1.5, -0.5, 0.5, 1.5,
  144592. };
  144593. static long _vq_quantmap__8u0__p3_0[] = {
  144594. 3, 1, 0, 2, 4,
  144595. };
  144596. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144597. _vq_quantthresh__8u0__p3_0,
  144598. _vq_quantmap__8u0__p3_0,
  144599. 5,
  144600. 5
  144601. };
  144602. static static_codebook _8u0__p3_0 = {
  144603. 4, 625,
  144604. _vq_lengthlist__8u0__p3_0,
  144605. 1, -533725184, 1611661312, 3, 0,
  144606. _vq_quantlist__8u0__p3_0,
  144607. NULL,
  144608. &_vq_auxt__8u0__p3_0,
  144609. NULL,
  144610. 0
  144611. };
  144612. static long _vq_quantlist__8u0__p4_0[] = {
  144613. 2,
  144614. 1,
  144615. 3,
  144616. 0,
  144617. 4,
  144618. };
  144619. static long _vq_lengthlist__8u0__p4_0[] = {
  144620. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144621. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144622. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144623. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144624. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144625. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144626. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144627. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144628. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144629. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144630. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144631. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144632. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144633. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144634. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144635. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144636. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144637. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144638. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144639. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144640. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144641. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144642. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144643. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144644. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144645. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144646. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144647. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144648. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144649. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144650. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144651. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144652. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144653. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144654. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144655. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144656. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144657. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144658. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144659. 12,
  144660. };
  144661. static float _vq_quantthresh__8u0__p4_0[] = {
  144662. -1.5, -0.5, 0.5, 1.5,
  144663. };
  144664. static long _vq_quantmap__8u0__p4_0[] = {
  144665. 3, 1, 0, 2, 4,
  144666. };
  144667. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144668. _vq_quantthresh__8u0__p4_0,
  144669. _vq_quantmap__8u0__p4_0,
  144670. 5,
  144671. 5
  144672. };
  144673. static static_codebook _8u0__p4_0 = {
  144674. 4, 625,
  144675. _vq_lengthlist__8u0__p4_0,
  144676. 1, -533725184, 1611661312, 3, 0,
  144677. _vq_quantlist__8u0__p4_0,
  144678. NULL,
  144679. &_vq_auxt__8u0__p4_0,
  144680. NULL,
  144681. 0
  144682. };
  144683. static long _vq_quantlist__8u0__p5_0[] = {
  144684. 4,
  144685. 3,
  144686. 5,
  144687. 2,
  144688. 6,
  144689. 1,
  144690. 7,
  144691. 0,
  144692. 8,
  144693. };
  144694. static long _vq_lengthlist__8u0__p5_0[] = {
  144695. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144696. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144697. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144698. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144699. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144700. 12,
  144701. };
  144702. static float _vq_quantthresh__8u0__p5_0[] = {
  144703. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144704. };
  144705. static long _vq_quantmap__8u0__p5_0[] = {
  144706. 7, 5, 3, 1, 0, 2, 4, 6,
  144707. 8,
  144708. };
  144709. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144710. _vq_quantthresh__8u0__p5_0,
  144711. _vq_quantmap__8u0__p5_0,
  144712. 9,
  144713. 9
  144714. };
  144715. static static_codebook _8u0__p5_0 = {
  144716. 2, 81,
  144717. _vq_lengthlist__8u0__p5_0,
  144718. 1, -531628032, 1611661312, 4, 0,
  144719. _vq_quantlist__8u0__p5_0,
  144720. NULL,
  144721. &_vq_auxt__8u0__p5_0,
  144722. NULL,
  144723. 0
  144724. };
  144725. static long _vq_quantlist__8u0__p6_0[] = {
  144726. 6,
  144727. 5,
  144728. 7,
  144729. 4,
  144730. 8,
  144731. 3,
  144732. 9,
  144733. 2,
  144734. 10,
  144735. 1,
  144736. 11,
  144737. 0,
  144738. 12,
  144739. };
  144740. static long _vq_lengthlist__8u0__p6_0[] = {
  144741. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144742. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144743. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144744. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144745. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144746. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144747. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144748. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144749. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144750. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144751. 16, 0,15, 0,17, 0, 0, 0, 0,
  144752. };
  144753. static float _vq_quantthresh__8u0__p6_0[] = {
  144754. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144755. 12.5, 17.5, 22.5, 27.5,
  144756. };
  144757. static long _vq_quantmap__8u0__p6_0[] = {
  144758. 11, 9, 7, 5, 3, 1, 0, 2,
  144759. 4, 6, 8, 10, 12,
  144760. };
  144761. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144762. _vq_quantthresh__8u0__p6_0,
  144763. _vq_quantmap__8u0__p6_0,
  144764. 13,
  144765. 13
  144766. };
  144767. static static_codebook _8u0__p6_0 = {
  144768. 2, 169,
  144769. _vq_lengthlist__8u0__p6_0,
  144770. 1, -526516224, 1616117760, 4, 0,
  144771. _vq_quantlist__8u0__p6_0,
  144772. NULL,
  144773. &_vq_auxt__8u0__p6_0,
  144774. NULL,
  144775. 0
  144776. };
  144777. static long _vq_quantlist__8u0__p6_1[] = {
  144778. 2,
  144779. 1,
  144780. 3,
  144781. 0,
  144782. 4,
  144783. };
  144784. static long _vq_lengthlist__8u0__p6_1[] = {
  144785. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144786. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144787. };
  144788. static float _vq_quantthresh__8u0__p6_1[] = {
  144789. -1.5, -0.5, 0.5, 1.5,
  144790. };
  144791. static long _vq_quantmap__8u0__p6_1[] = {
  144792. 3, 1, 0, 2, 4,
  144793. };
  144794. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144795. _vq_quantthresh__8u0__p6_1,
  144796. _vq_quantmap__8u0__p6_1,
  144797. 5,
  144798. 5
  144799. };
  144800. static static_codebook _8u0__p6_1 = {
  144801. 2, 25,
  144802. _vq_lengthlist__8u0__p6_1,
  144803. 1, -533725184, 1611661312, 3, 0,
  144804. _vq_quantlist__8u0__p6_1,
  144805. NULL,
  144806. &_vq_auxt__8u0__p6_1,
  144807. NULL,
  144808. 0
  144809. };
  144810. static long _vq_quantlist__8u0__p7_0[] = {
  144811. 1,
  144812. 0,
  144813. 2,
  144814. };
  144815. static long _vq_lengthlist__8u0__p7_0[] = {
  144816. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144817. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144818. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144819. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144820. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144821. 7,
  144822. };
  144823. static float _vq_quantthresh__8u0__p7_0[] = {
  144824. -157.5, 157.5,
  144825. };
  144826. static long _vq_quantmap__8u0__p7_0[] = {
  144827. 1, 0, 2,
  144828. };
  144829. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144830. _vq_quantthresh__8u0__p7_0,
  144831. _vq_quantmap__8u0__p7_0,
  144832. 3,
  144833. 3
  144834. };
  144835. static static_codebook _8u0__p7_0 = {
  144836. 4, 81,
  144837. _vq_lengthlist__8u0__p7_0,
  144838. 1, -518803456, 1628680192, 2, 0,
  144839. _vq_quantlist__8u0__p7_0,
  144840. NULL,
  144841. &_vq_auxt__8u0__p7_0,
  144842. NULL,
  144843. 0
  144844. };
  144845. static long _vq_quantlist__8u0__p7_1[] = {
  144846. 7,
  144847. 6,
  144848. 8,
  144849. 5,
  144850. 9,
  144851. 4,
  144852. 10,
  144853. 3,
  144854. 11,
  144855. 2,
  144856. 12,
  144857. 1,
  144858. 13,
  144859. 0,
  144860. 14,
  144861. };
  144862. static long _vq_lengthlist__8u0__p7_1[] = {
  144863. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144864. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144865. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144866. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144867. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144868. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144875. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144876. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144877. 10,
  144878. };
  144879. static float _vq_quantthresh__8u0__p7_1[] = {
  144880. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144881. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144882. };
  144883. static long _vq_quantmap__8u0__p7_1[] = {
  144884. 13, 11, 9, 7, 5, 3, 1, 0,
  144885. 2, 4, 6, 8, 10, 12, 14,
  144886. };
  144887. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144888. _vq_quantthresh__8u0__p7_1,
  144889. _vq_quantmap__8u0__p7_1,
  144890. 15,
  144891. 15
  144892. };
  144893. static static_codebook _8u0__p7_1 = {
  144894. 2, 225,
  144895. _vq_lengthlist__8u0__p7_1,
  144896. 1, -520986624, 1620377600, 4, 0,
  144897. _vq_quantlist__8u0__p7_1,
  144898. NULL,
  144899. &_vq_auxt__8u0__p7_1,
  144900. NULL,
  144901. 0
  144902. };
  144903. static long _vq_quantlist__8u0__p7_2[] = {
  144904. 10,
  144905. 9,
  144906. 11,
  144907. 8,
  144908. 12,
  144909. 7,
  144910. 13,
  144911. 6,
  144912. 14,
  144913. 5,
  144914. 15,
  144915. 4,
  144916. 16,
  144917. 3,
  144918. 17,
  144919. 2,
  144920. 18,
  144921. 1,
  144922. 19,
  144923. 0,
  144924. 20,
  144925. };
  144926. static long _vq_lengthlist__8u0__p7_2[] = {
  144927. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144928. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144929. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144930. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144931. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144932. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144933. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144934. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144935. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144936. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144937. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144938. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144939. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144940. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144941. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144942. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144943. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144944. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144945. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144946. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144947. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144948. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144949. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144950. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144951. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144952. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144953. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144954. 11,12,11,11,11,10,10,11,11,
  144955. };
  144956. static float _vq_quantthresh__8u0__p7_2[] = {
  144957. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144958. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144959. 6.5, 7.5, 8.5, 9.5,
  144960. };
  144961. static long _vq_quantmap__8u0__p7_2[] = {
  144962. 19, 17, 15, 13, 11, 9, 7, 5,
  144963. 3, 1, 0, 2, 4, 6, 8, 10,
  144964. 12, 14, 16, 18, 20,
  144965. };
  144966. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144967. _vq_quantthresh__8u0__p7_2,
  144968. _vq_quantmap__8u0__p7_2,
  144969. 21,
  144970. 21
  144971. };
  144972. static static_codebook _8u0__p7_2 = {
  144973. 2, 441,
  144974. _vq_lengthlist__8u0__p7_2,
  144975. 1, -529268736, 1611661312, 5, 0,
  144976. _vq_quantlist__8u0__p7_2,
  144977. NULL,
  144978. &_vq_auxt__8u0__p7_2,
  144979. NULL,
  144980. 0
  144981. };
  144982. static long _huff_lengthlist__8u0__single[] = {
  144983. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144984. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144985. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144986. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144987. };
  144988. static static_codebook _huff_book__8u0__single = {
  144989. 2, 64,
  144990. _huff_lengthlist__8u0__single,
  144991. 0, 0, 0, 0, 0,
  144992. NULL,
  144993. NULL,
  144994. NULL,
  144995. NULL,
  144996. 0
  144997. };
  144998. static long _vq_quantlist__8u1__p1_0[] = {
  144999. 1,
  145000. 0,
  145001. 2,
  145002. };
  145003. static long _vq_lengthlist__8u1__p1_0[] = {
  145004. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145005. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145006. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145007. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145008. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145009. 10,
  145010. };
  145011. static float _vq_quantthresh__8u1__p1_0[] = {
  145012. -0.5, 0.5,
  145013. };
  145014. static long _vq_quantmap__8u1__p1_0[] = {
  145015. 1, 0, 2,
  145016. };
  145017. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145018. _vq_quantthresh__8u1__p1_0,
  145019. _vq_quantmap__8u1__p1_0,
  145020. 3,
  145021. 3
  145022. };
  145023. static static_codebook _8u1__p1_0 = {
  145024. 4, 81,
  145025. _vq_lengthlist__8u1__p1_0,
  145026. 1, -535822336, 1611661312, 2, 0,
  145027. _vq_quantlist__8u1__p1_0,
  145028. NULL,
  145029. &_vq_auxt__8u1__p1_0,
  145030. NULL,
  145031. 0
  145032. };
  145033. static long _vq_quantlist__8u1__p2_0[] = {
  145034. 1,
  145035. 0,
  145036. 2,
  145037. };
  145038. static long _vq_lengthlist__8u1__p2_0[] = {
  145039. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145040. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145041. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145042. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145043. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145044. 7,
  145045. };
  145046. static float _vq_quantthresh__8u1__p2_0[] = {
  145047. -0.5, 0.5,
  145048. };
  145049. static long _vq_quantmap__8u1__p2_0[] = {
  145050. 1, 0, 2,
  145051. };
  145052. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145053. _vq_quantthresh__8u1__p2_0,
  145054. _vq_quantmap__8u1__p2_0,
  145055. 3,
  145056. 3
  145057. };
  145058. static static_codebook _8u1__p2_0 = {
  145059. 4, 81,
  145060. _vq_lengthlist__8u1__p2_0,
  145061. 1, -535822336, 1611661312, 2, 0,
  145062. _vq_quantlist__8u1__p2_0,
  145063. NULL,
  145064. &_vq_auxt__8u1__p2_0,
  145065. NULL,
  145066. 0
  145067. };
  145068. static long _vq_quantlist__8u1__p3_0[] = {
  145069. 2,
  145070. 1,
  145071. 3,
  145072. 0,
  145073. 4,
  145074. };
  145075. static long _vq_lengthlist__8u1__p3_0[] = {
  145076. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145077. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145078. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145079. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145080. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145081. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145082. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145083. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145084. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145085. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145086. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145087. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145088. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145089. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145090. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145091. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145092. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145093. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145094. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145095. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145096. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145097. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145098. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145099. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145100. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145101. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145102. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145103. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145104. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145105. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145106. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145107. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145108. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145109. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145110. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145111. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145112. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145113. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145114. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145115. 16,
  145116. };
  145117. static float _vq_quantthresh__8u1__p3_0[] = {
  145118. -1.5, -0.5, 0.5, 1.5,
  145119. };
  145120. static long _vq_quantmap__8u1__p3_0[] = {
  145121. 3, 1, 0, 2, 4,
  145122. };
  145123. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145124. _vq_quantthresh__8u1__p3_0,
  145125. _vq_quantmap__8u1__p3_0,
  145126. 5,
  145127. 5
  145128. };
  145129. static static_codebook _8u1__p3_0 = {
  145130. 4, 625,
  145131. _vq_lengthlist__8u1__p3_0,
  145132. 1, -533725184, 1611661312, 3, 0,
  145133. _vq_quantlist__8u1__p3_0,
  145134. NULL,
  145135. &_vq_auxt__8u1__p3_0,
  145136. NULL,
  145137. 0
  145138. };
  145139. static long _vq_quantlist__8u1__p4_0[] = {
  145140. 2,
  145141. 1,
  145142. 3,
  145143. 0,
  145144. 4,
  145145. };
  145146. static long _vq_lengthlist__8u1__p4_0[] = {
  145147. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145148. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145149. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145150. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145151. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145152. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145153. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145154. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145155. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145156. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145157. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145158. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145159. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145160. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145161. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145162. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145163. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145164. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145165. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145166. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145167. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145168. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145169. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145170. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145171. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145172. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145173. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145174. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145175. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145176. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145177. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145178. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145179. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145180. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145181. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145182. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145183. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145184. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145185. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145186. 10,
  145187. };
  145188. static float _vq_quantthresh__8u1__p4_0[] = {
  145189. -1.5, -0.5, 0.5, 1.5,
  145190. };
  145191. static long _vq_quantmap__8u1__p4_0[] = {
  145192. 3, 1, 0, 2, 4,
  145193. };
  145194. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145195. _vq_quantthresh__8u1__p4_0,
  145196. _vq_quantmap__8u1__p4_0,
  145197. 5,
  145198. 5
  145199. };
  145200. static static_codebook _8u1__p4_0 = {
  145201. 4, 625,
  145202. _vq_lengthlist__8u1__p4_0,
  145203. 1, -533725184, 1611661312, 3, 0,
  145204. _vq_quantlist__8u1__p4_0,
  145205. NULL,
  145206. &_vq_auxt__8u1__p4_0,
  145207. NULL,
  145208. 0
  145209. };
  145210. static long _vq_quantlist__8u1__p5_0[] = {
  145211. 4,
  145212. 3,
  145213. 5,
  145214. 2,
  145215. 6,
  145216. 1,
  145217. 7,
  145218. 0,
  145219. 8,
  145220. };
  145221. static long _vq_lengthlist__8u1__p5_0[] = {
  145222. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145223. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145224. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145225. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145226. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145227. 13,
  145228. };
  145229. static float _vq_quantthresh__8u1__p5_0[] = {
  145230. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145231. };
  145232. static long _vq_quantmap__8u1__p5_0[] = {
  145233. 7, 5, 3, 1, 0, 2, 4, 6,
  145234. 8,
  145235. };
  145236. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145237. _vq_quantthresh__8u1__p5_0,
  145238. _vq_quantmap__8u1__p5_0,
  145239. 9,
  145240. 9
  145241. };
  145242. static static_codebook _8u1__p5_0 = {
  145243. 2, 81,
  145244. _vq_lengthlist__8u1__p5_0,
  145245. 1, -531628032, 1611661312, 4, 0,
  145246. _vq_quantlist__8u1__p5_0,
  145247. NULL,
  145248. &_vq_auxt__8u1__p5_0,
  145249. NULL,
  145250. 0
  145251. };
  145252. static long _vq_quantlist__8u1__p6_0[] = {
  145253. 4,
  145254. 3,
  145255. 5,
  145256. 2,
  145257. 6,
  145258. 1,
  145259. 7,
  145260. 0,
  145261. 8,
  145262. };
  145263. static long _vq_lengthlist__8u1__p6_0[] = {
  145264. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145265. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145266. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145267. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145268. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145269. 10,
  145270. };
  145271. static float _vq_quantthresh__8u1__p6_0[] = {
  145272. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145273. };
  145274. static long _vq_quantmap__8u1__p6_0[] = {
  145275. 7, 5, 3, 1, 0, 2, 4, 6,
  145276. 8,
  145277. };
  145278. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145279. _vq_quantthresh__8u1__p6_0,
  145280. _vq_quantmap__8u1__p6_0,
  145281. 9,
  145282. 9
  145283. };
  145284. static static_codebook _8u1__p6_0 = {
  145285. 2, 81,
  145286. _vq_lengthlist__8u1__p6_0,
  145287. 1, -531628032, 1611661312, 4, 0,
  145288. _vq_quantlist__8u1__p6_0,
  145289. NULL,
  145290. &_vq_auxt__8u1__p6_0,
  145291. NULL,
  145292. 0
  145293. };
  145294. static long _vq_quantlist__8u1__p7_0[] = {
  145295. 1,
  145296. 0,
  145297. 2,
  145298. };
  145299. static long _vq_lengthlist__8u1__p7_0[] = {
  145300. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145301. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145302. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145303. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145304. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145305. 11,
  145306. };
  145307. static float _vq_quantthresh__8u1__p7_0[] = {
  145308. -5.5, 5.5,
  145309. };
  145310. static long _vq_quantmap__8u1__p7_0[] = {
  145311. 1, 0, 2,
  145312. };
  145313. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145314. _vq_quantthresh__8u1__p7_0,
  145315. _vq_quantmap__8u1__p7_0,
  145316. 3,
  145317. 3
  145318. };
  145319. static static_codebook _8u1__p7_0 = {
  145320. 4, 81,
  145321. _vq_lengthlist__8u1__p7_0,
  145322. 1, -529137664, 1618345984, 2, 0,
  145323. _vq_quantlist__8u1__p7_0,
  145324. NULL,
  145325. &_vq_auxt__8u1__p7_0,
  145326. NULL,
  145327. 0
  145328. };
  145329. static long _vq_quantlist__8u1__p7_1[] = {
  145330. 5,
  145331. 4,
  145332. 6,
  145333. 3,
  145334. 7,
  145335. 2,
  145336. 8,
  145337. 1,
  145338. 9,
  145339. 0,
  145340. 10,
  145341. };
  145342. static long _vq_lengthlist__8u1__p7_1[] = {
  145343. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145344. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145345. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145346. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145347. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145348. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145349. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145350. 9, 9, 9, 9, 9,10,10,10,10,
  145351. };
  145352. static float _vq_quantthresh__8u1__p7_1[] = {
  145353. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145354. 3.5, 4.5,
  145355. };
  145356. static long _vq_quantmap__8u1__p7_1[] = {
  145357. 9, 7, 5, 3, 1, 0, 2, 4,
  145358. 6, 8, 10,
  145359. };
  145360. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145361. _vq_quantthresh__8u1__p7_1,
  145362. _vq_quantmap__8u1__p7_1,
  145363. 11,
  145364. 11
  145365. };
  145366. static static_codebook _8u1__p7_1 = {
  145367. 2, 121,
  145368. _vq_lengthlist__8u1__p7_1,
  145369. 1, -531365888, 1611661312, 4, 0,
  145370. _vq_quantlist__8u1__p7_1,
  145371. NULL,
  145372. &_vq_auxt__8u1__p7_1,
  145373. NULL,
  145374. 0
  145375. };
  145376. static long _vq_quantlist__8u1__p8_0[] = {
  145377. 5,
  145378. 4,
  145379. 6,
  145380. 3,
  145381. 7,
  145382. 2,
  145383. 8,
  145384. 1,
  145385. 9,
  145386. 0,
  145387. 10,
  145388. };
  145389. static long _vq_lengthlist__8u1__p8_0[] = {
  145390. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145391. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145392. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145393. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145394. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145395. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145396. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145397. 12,13,13,14,14,15,15,15,15,
  145398. };
  145399. static float _vq_quantthresh__8u1__p8_0[] = {
  145400. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145401. 38.5, 49.5,
  145402. };
  145403. static long _vq_quantmap__8u1__p8_0[] = {
  145404. 9, 7, 5, 3, 1, 0, 2, 4,
  145405. 6, 8, 10,
  145406. };
  145407. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145408. _vq_quantthresh__8u1__p8_0,
  145409. _vq_quantmap__8u1__p8_0,
  145410. 11,
  145411. 11
  145412. };
  145413. static static_codebook _8u1__p8_0 = {
  145414. 2, 121,
  145415. _vq_lengthlist__8u1__p8_0,
  145416. 1, -524582912, 1618345984, 4, 0,
  145417. _vq_quantlist__8u1__p8_0,
  145418. NULL,
  145419. &_vq_auxt__8u1__p8_0,
  145420. NULL,
  145421. 0
  145422. };
  145423. static long _vq_quantlist__8u1__p8_1[] = {
  145424. 5,
  145425. 4,
  145426. 6,
  145427. 3,
  145428. 7,
  145429. 2,
  145430. 8,
  145431. 1,
  145432. 9,
  145433. 0,
  145434. 10,
  145435. };
  145436. static long _vq_lengthlist__8u1__p8_1[] = {
  145437. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145438. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145439. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145440. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145441. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145442. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145443. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145444. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145445. };
  145446. static float _vq_quantthresh__8u1__p8_1[] = {
  145447. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145448. 3.5, 4.5,
  145449. };
  145450. static long _vq_quantmap__8u1__p8_1[] = {
  145451. 9, 7, 5, 3, 1, 0, 2, 4,
  145452. 6, 8, 10,
  145453. };
  145454. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145455. _vq_quantthresh__8u1__p8_1,
  145456. _vq_quantmap__8u1__p8_1,
  145457. 11,
  145458. 11
  145459. };
  145460. static static_codebook _8u1__p8_1 = {
  145461. 2, 121,
  145462. _vq_lengthlist__8u1__p8_1,
  145463. 1, -531365888, 1611661312, 4, 0,
  145464. _vq_quantlist__8u1__p8_1,
  145465. NULL,
  145466. &_vq_auxt__8u1__p8_1,
  145467. NULL,
  145468. 0
  145469. };
  145470. static long _vq_quantlist__8u1__p9_0[] = {
  145471. 7,
  145472. 6,
  145473. 8,
  145474. 5,
  145475. 9,
  145476. 4,
  145477. 10,
  145478. 3,
  145479. 11,
  145480. 2,
  145481. 12,
  145482. 1,
  145483. 13,
  145484. 0,
  145485. 14,
  145486. };
  145487. static long _vq_lengthlist__8u1__p9_0[] = {
  145488. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145489. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145490. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145500. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145501. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145502. 10,
  145503. };
  145504. static float _vq_quantthresh__8u1__p9_0[] = {
  145505. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145506. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145507. };
  145508. static long _vq_quantmap__8u1__p9_0[] = {
  145509. 13, 11, 9, 7, 5, 3, 1, 0,
  145510. 2, 4, 6, 8, 10, 12, 14,
  145511. };
  145512. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145513. _vq_quantthresh__8u1__p9_0,
  145514. _vq_quantmap__8u1__p9_0,
  145515. 15,
  145516. 15
  145517. };
  145518. static static_codebook _8u1__p9_0 = {
  145519. 2, 225,
  145520. _vq_lengthlist__8u1__p9_0,
  145521. 1, -514071552, 1627381760, 4, 0,
  145522. _vq_quantlist__8u1__p9_0,
  145523. NULL,
  145524. &_vq_auxt__8u1__p9_0,
  145525. NULL,
  145526. 0
  145527. };
  145528. static long _vq_quantlist__8u1__p9_1[] = {
  145529. 7,
  145530. 6,
  145531. 8,
  145532. 5,
  145533. 9,
  145534. 4,
  145535. 10,
  145536. 3,
  145537. 11,
  145538. 2,
  145539. 12,
  145540. 1,
  145541. 13,
  145542. 0,
  145543. 14,
  145544. };
  145545. static long _vq_lengthlist__8u1__p9_1[] = {
  145546. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145547. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145548. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145549. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145550. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145551. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145552. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145553. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145554. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145555. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145556. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145557. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145558. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145559. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145560. 13,
  145561. };
  145562. static float _vq_quantthresh__8u1__p9_1[] = {
  145563. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145564. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145565. };
  145566. static long _vq_quantmap__8u1__p9_1[] = {
  145567. 13, 11, 9, 7, 5, 3, 1, 0,
  145568. 2, 4, 6, 8, 10, 12, 14,
  145569. };
  145570. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145571. _vq_quantthresh__8u1__p9_1,
  145572. _vq_quantmap__8u1__p9_1,
  145573. 15,
  145574. 15
  145575. };
  145576. static static_codebook _8u1__p9_1 = {
  145577. 2, 225,
  145578. _vq_lengthlist__8u1__p9_1,
  145579. 1, -522338304, 1620115456, 4, 0,
  145580. _vq_quantlist__8u1__p9_1,
  145581. NULL,
  145582. &_vq_auxt__8u1__p9_1,
  145583. NULL,
  145584. 0
  145585. };
  145586. static long _vq_quantlist__8u1__p9_2[] = {
  145587. 8,
  145588. 7,
  145589. 9,
  145590. 6,
  145591. 10,
  145592. 5,
  145593. 11,
  145594. 4,
  145595. 12,
  145596. 3,
  145597. 13,
  145598. 2,
  145599. 14,
  145600. 1,
  145601. 15,
  145602. 0,
  145603. 16,
  145604. };
  145605. static long _vq_lengthlist__8u1__p9_2[] = {
  145606. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145607. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145608. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145609. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145610. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145611. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145612. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145613. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145614. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145615. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145616. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145617. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145618. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145619. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145621. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145622. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145623. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145624. 10,
  145625. };
  145626. static float _vq_quantthresh__8u1__p9_2[] = {
  145627. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145628. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145629. };
  145630. static long _vq_quantmap__8u1__p9_2[] = {
  145631. 15, 13, 11, 9, 7, 5, 3, 1,
  145632. 0, 2, 4, 6, 8, 10, 12, 14,
  145633. 16,
  145634. };
  145635. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145636. _vq_quantthresh__8u1__p9_2,
  145637. _vq_quantmap__8u1__p9_2,
  145638. 17,
  145639. 17
  145640. };
  145641. static static_codebook _8u1__p9_2 = {
  145642. 2, 289,
  145643. _vq_lengthlist__8u1__p9_2,
  145644. 1, -529530880, 1611661312, 5, 0,
  145645. _vq_quantlist__8u1__p9_2,
  145646. NULL,
  145647. &_vq_auxt__8u1__p9_2,
  145648. NULL,
  145649. 0
  145650. };
  145651. static long _huff_lengthlist__8u1__single[] = {
  145652. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145653. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145654. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145655. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145656. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145657. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145658. 13, 8, 8,15,
  145659. };
  145660. static static_codebook _huff_book__8u1__single = {
  145661. 2, 100,
  145662. _huff_lengthlist__8u1__single,
  145663. 0, 0, 0, 0, 0,
  145664. NULL,
  145665. NULL,
  145666. NULL,
  145667. NULL,
  145668. 0
  145669. };
  145670. static long _huff_lengthlist__44u0__long[] = {
  145671. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145672. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145673. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145674. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145675. };
  145676. static static_codebook _huff_book__44u0__long = {
  145677. 2, 64,
  145678. _huff_lengthlist__44u0__long,
  145679. 0, 0, 0, 0, 0,
  145680. NULL,
  145681. NULL,
  145682. NULL,
  145683. NULL,
  145684. 0
  145685. };
  145686. static long _vq_quantlist__44u0__p1_0[] = {
  145687. 1,
  145688. 0,
  145689. 2,
  145690. };
  145691. static long _vq_lengthlist__44u0__p1_0[] = {
  145692. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145693. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145694. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145695. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145696. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145697. 13,
  145698. };
  145699. static float _vq_quantthresh__44u0__p1_0[] = {
  145700. -0.5, 0.5,
  145701. };
  145702. static long _vq_quantmap__44u0__p1_0[] = {
  145703. 1, 0, 2,
  145704. };
  145705. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145706. _vq_quantthresh__44u0__p1_0,
  145707. _vq_quantmap__44u0__p1_0,
  145708. 3,
  145709. 3
  145710. };
  145711. static static_codebook _44u0__p1_0 = {
  145712. 4, 81,
  145713. _vq_lengthlist__44u0__p1_0,
  145714. 1, -535822336, 1611661312, 2, 0,
  145715. _vq_quantlist__44u0__p1_0,
  145716. NULL,
  145717. &_vq_auxt__44u0__p1_0,
  145718. NULL,
  145719. 0
  145720. };
  145721. static long _vq_quantlist__44u0__p2_0[] = {
  145722. 1,
  145723. 0,
  145724. 2,
  145725. };
  145726. static long _vq_lengthlist__44u0__p2_0[] = {
  145727. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145728. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145729. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145730. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145731. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145732. 9,
  145733. };
  145734. static float _vq_quantthresh__44u0__p2_0[] = {
  145735. -0.5, 0.5,
  145736. };
  145737. static long _vq_quantmap__44u0__p2_0[] = {
  145738. 1, 0, 2,
  145739. };
  145740. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145741. _vq_quantthresh__44u0__p2_0,
  145742. _vq_quantmap__44u0__p2_0,
  145743. 3,
  145744. 3
  145745. };
  145746. static static_codebook _44u0__p2_0 = {
  145747. 4, 81,
  145748. _vq_lengthlist__44u0__p2_0,
  145749. 1, -535822336, 1611661312, 2, 0,
  145750. _vq_quantlist__44u0__p2_0,
  145751. NULL,
  145752. &_vq_auxt__44u0__p2_0,
  145753. NULL,
  145754. 0
  145755. };
  145756. static long _vq_quantlist__44u0__p3_0[] = {
  145757. 2,
  145758. 1,
  145759. 3,
  145760. 0,
  145761. 4,
  145762. };
  145763. static long _vq_lengthlist__44u0__p3_0[] = {
  145764. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145765. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145766. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145767. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145768. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145769. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145770. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145771. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145772. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145773. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145774. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145775. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145776. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145777. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145778. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145779. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145780. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145781. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145782. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145783. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145784. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145785. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145786. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145787. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145788. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145789. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145790. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145791. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145792. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145793. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145794. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145795. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145796. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145797. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145798. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145799. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145800. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145801. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145802. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145803. 19,
  145804. };
  145805. static float _vq_quantthresh__44u0__p3_0[] = {
  145806. -1.5, -0.5, 0.5, 1.5,
  145807. };
  145808. static long _vq_quantmap__44u0__p3_0[] = {
  145809. 3, 1, 0, 2, 4,
  145810. };
  145811. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145812. _vq_quantthresh__44u0__p3_0,
  145813. _vq_quantmap__44u0__p3_0,
  145814. 5,
  145815. 5
  145816. };
  145817. static static_codebook _44u0__p3_0 = {
  145818. 4, 625,
  145819. _vq_lengthlist__44u0__p3_0,
  145820. 1, -533725184, 1611661312, 3, 0,
  145821. _vq_quantlist__44u0__p3_0,
  145822. NULL,
  145823. &_vq_auxt__44u0__p3_0,
  145824. NULL,
  145825. 0
  145826. };
  145827. static long _vq_quantlist__44u0__p4_0[] = {
  145828. 2,
  145829. 1,
  145830. 3,
  145831. 0,
  145832. 4,
  145833. };
  145834. static long _vq_lengthlist__44u0__p4_0[] = {
  145835. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145836. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145837. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145838. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145839. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145840. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145841. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145842. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145843. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145844. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145845. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145846. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145847. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145848. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145849. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145850. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145851. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145852. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145853. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145854. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145855. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145856. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145857. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145858. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145859. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145860. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145861. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145862. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145863. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145864. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145865. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145866. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145867. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145868. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145869. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145870. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145871. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145872. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145873. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145874. 12,
  145875. };
  145876. static float _vq_quantthresh__44u0__p4_0[] = {
  145877. -1.5, -0.5, 0.5, 1.5,
  145878. };
  145879. static long _vq_quantmap__44u0__p4_0[] = {
  145880. 3, 1, 0, 2, 4,
  145881. };
  145882. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145883. _vq_quantthresh__44u0__p4_0,
  145884. _vq_quantmap__44u0__p4_0,
  145885. 5,
  145886. 5
  145887. };
  145888. static static_codebook _44u0__p4_0 = {
  145889. 4, 625,
  145890. _vq_lengthlist__44u0__p4_0,
  145891. 1, -533725184, 1611661312, 3, 0,
  145892. _vq_quantlist__44u0__p4_0,
  145893. NULL,
  145894. &_vq_auxt__44u0__p4_0,
  145895. NULL,
  145896. 0
  145897. };
  145898. static long _vq_quantlist__44u0__p5_0[] = {
  145899. 4,
  145900. 3,
  145901. 5,
  145902. 2,
  145903. 6,
  145904. 1,
  145905. 7,
  145906. 0,
  145907. 8,
  145908. };
  145909. static long _vq_lengthlist__44u0__p5_0[] = {
  145910. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145911. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145912. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145913. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145914. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145915. 12,
  145916. };
  145917. static float _vq_quantthresh__44u0__p5_0[] = {
  145918. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145919. };
  145920. static long _vq_quantmap__44u0__p5_0[] = {
  145921. 7, 5, 3, 1, 0, 2, 4, 6,
  145922. 8,
  145923. };
  145924. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145925. _vq_quantthresh__44u0__p5_0,
  145926. _vq_quantmap__44u0__p5_0,
  145927. 9,
  145928. 9
  145929. };
  145930. static static_codebook _44u0__p5_0 = {
  145931. 2, 81,
  145932. _vq_lengthlist__44u0__p5_0,
  145933. 1, -531628032, 1611661312, 4, 0,
  145934. _vq_quantlist__44u0__p5_0,
  145935. NULL,
  145936. &_vq_auxt__44u0__p5_0,
  145937. NULL,
  145938. 0
  145939. };
  145940. static long _vq_quantlist__44u0__p6_0[] = {
  145941. 6,
  145942. 5,
  145943. 7,
  145944. 4,
  145945. 8,
  145946. 3,
  145947. 9,
  145948. 2,
  145949. 10,
  145950. 1,
  145951. 11,
  145952. 0,
  145953. 12,
  145954. };
  145955. static long _vq_lengthlist__44u0__p6_0[] = {
  145956. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145957. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145958. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145959. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145960. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145961. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145962. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145963. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145964. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145965. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145966. 15,17,16,17,18,17,17,18, 0,
  145967. };
  145968. static float _vq_quantthresh__44u0__p6_0[] = {
  145969. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145970. 12.5, 17.5, 22.5, 27.5,
  145971. };
  145972. static long _vq_quantmap__44u0__p6_0[] = {
  145973. 11, 9, 7, 5, 3, 1, 0, 2,
  145974. 4, 6, 8, 10, 12,
  145975. };
  145976. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145977. _vq_quantthresh__44u0__p6_0,
  145978. _vq_quantmap__44u0__p6_0,
  145979. 13,
  145980. 13
  145981. };
  145982. static static_codebook _44u0__p6_0 = {
  145983. 2, 169,
  145984. _vq_lengthlist__44u0__p6_0,
  145985. 1, -526516224, 1616117760, 4, 0,
  145986. _vq_quantlist__44u0__p6_0,
  145987. NULL,
  145988. &_vq_auxt__44u0__p6_0,
  145989. NULL,
  145990. 0
  145991. };
  145992. static long _vq_quantlist__44u0__p6_1[] = {
  145993. 2,
  145994. 1,
  145995. 3,
  145996. 0,
  145997. 4,
  145998. };
  145999. static long _vq_lengthlist__44u0__p6_1[] = {
  146000. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146001. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146002. };
  146003. static float _vq_quantthresh__44u0__p6_1[] = {
  146004. -1.5, -0.5, 0.5, 1.5,
  146005. };
  146006. static long _vq_quantmap__44u0__p6_1[] = {
  146007. 3, 1, 0, 2, 4,
  146008. };
  146009. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146010. _vq_quantthresh__44u0__p6_1,
  146011. _vq_quantmap__44u0__p6_1,
  146012. 5,
  146013. 5
  146014. };
  146015. static static_codebook _44u0__p6_1 = {
  146016. 2, 25,
  146017. _vq_lengthlist__44u0__p6_1,
  146018. 1, -533725184, 1611661312, 3, 0,
  146019. _vq_quantlist__44u0__p6_1,
  146020. NULL,
  146021. &_vq_auxt__44u0__p6_1,
  146022. NULL,
  146023. 0
  146024. };
  146025. static long _vq_quantlist__44u0__p7_0[] = {
  146026. 2,
  146027. 1,
  146028. 3,
  146029. 0,
  146030. 4,
  146031. };
  146032. static long _vq_lengthlist__44u0__p7_0[] = {
  146033. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146036. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146040. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146058. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146063. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146064. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146065. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146066. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146067. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146068. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146069. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146070. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146071. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146072. 10,
  146073. };
  146074. static float _vq_quantthresh__44u0__p7_0[] = {
  146075. -253.5, -84.5, 84.5, 253.5,
  146076. };
  146077. static long _vq_quantmap__44u0__p7_0[] = {
  146078. 3, 1, 0, 2, 4,
  146079. };
  146080. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146081. _vq_quantthresh__44u0__p7_0,
  146082. _vq_quantmap__44u0__p7_0,
  146083. 5,
  146084. 5
  146085. };
  146086. static static_codebook _44u0__p7_0 = {
  146087. 4, 625,
  146088. _vq_lengthlist__44u0__p7_0,
  146089. 1, -518709248, 1626677248, 3, 0,
  146090. _vq_quantlist__44u0__p7_0,
  146091. NULL,
  146092. &_vq_auxt__44u0__p7_0,
  146093. NULL,
  146094. 0
  146095. };
  146096. static long _vq_quantlist__44u0__p7_1[] = {
  146097. 6,
  146098. 5,
  146099. 7,
  146100. 4,
  146101. 8,
  146102. 3,
  146103. 9,
  146104. 2,
  146105. 10,
  146106. 1,
  146107. 11,
  146108. 0,
  146109. 12,
  146110. };
  146111. static long _vq_lengthlist__44u0__p7_1[] = {
  146112. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146113. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146114. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146115. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146116. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146117. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146118. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146119. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146120. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146121. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146122. 15,15,15,15,15,15,15,15,15,
  146123. };
  146124. static float _vq_quantthresh__44u0__p7_1[] = {
  146125. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146126. 32.5, 45.5, 58.5, 71.5,
  146127. };
  146128. static long _vq_quantmap__44u0__p7_1[] = {
  146129. 11, 9, 7, 5, 3, 1, 0, 2,
  146130. 4, 6, 8, 10, 12,
  146131. };
  146132. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146133. _vq_quantthresh__44u0__p7_1,
  146134. _vq_quantmap__44u0__p7_1,
  146135. 13,
  146136. 13
  146137. };
  146138. static static_codebook _44u0__p7_1 = {
  146139. 2, 169,
  146140. _vq_lengthlist__44u0__p7_1,
  146141. 1, -523010048, 1618608128, 4, 0,
  146142. _vq_quantlist__44u0__p7_1,
  146143. NULL,
  146144. &_vq_auxt__44u0__p7_1,
  146145. NULL,
  146146. 0
  146147. };
  146148. static long _vq_quantlist__44u0__p7_2[] = {
  146149. 6,
  146150. 5,
  146151. 7,
  146152. 4,
  146153. 8,
  146154. 3,
  146155. 9,
  146156. 2,
  146157. 10,
  146158. 1,
  146159. 11,
  146160. 0,
  146161. 12,
  146162. };
  146163. static long _vq_lengthlist__44u0__p7_2[] = {
  146164. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146165. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146166. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146167. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146168. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146169. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146170. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146171. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146172. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146173. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146174. 9, 9, 9,10, 9, 9,10,10, 9,
  146175. };
  146176. static float _vq_quantthresh__44u0__p7_2[] = {
  146177. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146178. 2.5, 3.5, 4.5, 5.5,
  146179. };
  146180. static long _vq_quantmap__44u0__p7_2[] = {
  146181. 11, 9, 7, 5, 3, 1, 0, 2,
  146182. 4, 6, 8, 10, 12,
  146183. };
  146184. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146185. _vq_quantthresh__44u0__p7_2,
  146186. _vq_quantmap__44u0__p7_2,
  146187. 13,
  146188. 13
  146189. };
  146190. static static_codebook _44u0__p7_2 = {
  146191. 2, 169,
  146192. _vq_lengthlist__44u0__p7_2,
  146193. 1, -531103744, 1611661312, 4, 0,
  146194. _vq_quantlist__44u0__p7_2,
  146195. NULL,
  146196. &_vq_auxt__44u0__p7_2,
  146197. NULL,
  146198. 0
  146199. };
  146200. static long _huff_lengthlist__44u0__short[] = {
  146201. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146202. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146203. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146204. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146205. };
  146206. static static_codebook _huff_book__44u0__short = {
  146207. 2, 64,
  146208. _huff_lengthlist__44u0__short,
  146209. 0, 0, 0, 0, 0,
  146210. NULL,
  146211. NULL,
  146212. NULL,
  146213. NULL,
  146214. 0
  146215. };
  146216. static long _huff_lengthlist__44u1__long[] = {
  146217. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146218. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146219. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146220. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146221. };
  146222. static static_codebook _huff_book__44u1__long = {
  146223. 2, 64,
  146224. _huff_lengthlist__44u1__long,
  146225. 0, 0, 0, 0, 0,
  146226. NULL,
  146227. NULL,
  146228. NULL,
  146229. NULL,
  146230. 0
  146231. };
  146232. static long _vq_quantlist__44u1__p1_0[] = {
  146233. 1,
  146234. 0,
  146235. 2,
  146236. };
  146237. static long _vq_lengthlist__44u1__p1_0[] = {
  146238. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146239. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146240. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146241. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146242. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146243. 13,
  146244. };
  146245. static float _vq_quantthresh__44u1__p1_0[] = {
  146246. -0.5, 0.5,
  146247. };
  146248. static long _vq_quantmap__44u1__p1_0[] = {
  146249. 1, 0, 2,
  146250. };
  146251. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146252. _vq_quantthresh__44u1__p1_0,
  146253. _vq_quantmap__44u1__p1_0,
  146254. 3,
  146255. 3
  146256. };
  146257. static static_codebook _44u1__p1_0 = {
  146258. 4, 81,
  146259. _vq_lengthlist__44u1__p1_0,
  146260. 1, -535822336, 1611661312, 2, 0,
  146261. _vq_quantlist__44u1__p1_0,
  146262. NULL,
  146263. &_vq_auxt__44u1__p1_0,
  146264. NULL,
  146265. 0
  146266. };
  146267. static long _vq_quantlist__44u1__p2_0[] = {
  146268. 1,
  146269. 0,
  146270. 2,
  146271. };
  146272. static long _vq_lengthlist__44u1__p2_0[] = {
  146273. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146274. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146275. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146276. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146277. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146278. 9,
  146279. };
  146280. static float _vq_quantthresh__44u1__p2_0[] = {
  146281. -0.5, 0.5,
  146282. };
  146283. static long _vq_quantmap__44u1__p2_0[] = {
  146284. 1, 0, 2,
  146285. };
  146286. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146287. _vq_quantthresh__44u1__p2_0,
  146288. _vq_quantmap__44u1__p2_0,
  146289. 3,
  146290. 3
  146291. };
  146292. static static_codebook _44u1__p2_0 = {
  146293. 4, 81,
  146294. _vq_lengthlist__44u1__p2_0,
  146295. 1, -535822336, 1611661312, 2, 0,
  146296. _vq_quantlist__44u1__p2_0,
  146297. NULL,
  146298. &_vq_auxt__44u1__p2_0,
  146299. NULL,
  146300. 0
  146301. };
  146302. static long _vq_quantlist__44u1__p3_0[] = {
  146303. 2,
  146304. 1,
  146305. 3,
  146306. 0,
  146307. 4,
  146308. };
  146309. static long _vq_lengthlist__44u1__p3_0[] = {
  146310. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146311. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146312. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146313. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146314. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146315. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146316. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146317. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146318. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146319. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146320. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146321. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146322. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146323. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146324. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146325. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146326. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146327. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146328. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146329. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146330. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146331. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146332. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146333. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146334. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146335. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146336. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146337. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146338. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146339. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146340. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146341. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146342. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146343. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146344. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146345. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146346. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146347. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146348. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146349. 19,
  146350. };
  146351. static float _vq_quantthresh__44u1__p3_0[] = {
  146352. -1.5, -0.5, 0.5, 1.5,
  146353. };
  146354. static long _vq_quantmap__44u1__p3_0[] = {
  146355. 3, 1, 0, 2, 4,
  146356. };
  146357. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146358. _vq_quantthresh__44u1__p3_0,
  146359. _vq_quantmap__44u1__p3_0,
  146360. 5,
  146361. 5
  146362. };
  146363. static static_codebook _44u1__p3_0 = {
  146364. 4, 625,
  146365. _vq_lengthlist__44u1__p3_0,
  146366. 1, -533725184, 1611661312, 3, 0,
  146367. _vq_quantlist__44u1__p3_0,
  146368. NULL,
  146369. &_vq_auxt__44u1__p3_0,
  146370. NULL,
  146371. 0
  146372. };
  146373. static long _vq_quantlist__44u1__p4_0[] = {
  146374. 2,
  146375. 1,
  146376. 3,
  146377. 0,
  146378. 4,
  146379. };
  146380. static long _vq_lengthlist__44u1__p4_0[] = {
  146381. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146382. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146383. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146384. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146385. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146386. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146387. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146388. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146389. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146390. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146391. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146392. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146393. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146394. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146395. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146396. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146397. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146398. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146399. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146400. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146401. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146402. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146403. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146404. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146405. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146406. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146407. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146408. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146409. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146410. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146411. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146412. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146413. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146414. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146415. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146416. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146417. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146418. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146419. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146420. 12,
  146421. };
  146422. static float _vq_quantthresh__44u1__p4_0[] = {
  146423. -1.5, -0.5, 0.5, 1.5,
  146424. };
  146425. static long _vq_quantmap__44u1__p4_0[] = {
  146426. 3, 1, 0, 2, 4,
  146427. };
  146428. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146429. _vq_quantthresh__44u1__p4_0,
  146430. _vq_quantmap__44u1__p4_0,
  146431. 5,
  146432. 5
  146433. };
  146434. static static_codebook _44u1__p4_0 = {
  146435. 4, 625,
  146436. _vq_lengthlist__44u1__p4_0,
  146437. 1, -533725184, 1611661312, 3, 0,
  146438. _vq_quantlist__44u1__p4_0,
  146439. NULL,
  146440. &_vq_auxt__44u1__p4_0,
  146441. NULL,
  146442. 0
  146443. };
  146444. static long _vq_quantlist__44u1__p5_0[] = {
  146445. 4,
  146446. 3,
  146447. 5,
  146448. 2,
  146449. 6,
  146450. 1,
  146451. 7,
  146452. 0,
  146453. 8,
  146454. };
  146455. static long _vq_lengthlist__44u1__p5_0[] = {
  146456. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146457. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146458. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146459. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146460. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146461. 12,
  146462. };
  146463. static float _vq_quantthresh__44u1__p5_0[] = {
  146464. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146465. };
  146466. static long _vq_quantmap__44u1__p5_0[] = {
  146467. 7, 5, 3, 1, 0, 2, 4, 6,
  146468. 8,
  146469. };
  146470. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146471. _vq_quantthresh__44u1__p5_0,
  146472. _vq_quantmap__44u1__p5_0,
  146473. 9,
  146474. 9
  146475. };
  146476. static static_codebook _44u1__p5_0 = {
  146477. 2, 81,
  146478. _vq_lengthlist__44u1__p5_0,
  146479. 1, -531628032, 1611661312, 4, 0,
  146480. _vq_quantlist__44u1__p5_0,
  146481. NULL,
  146482. &_vq_auxt__44u1__p5_0,
  146483. NULL,
  146484. 0
  146485. };
  146486. static long _vq_quantlist__44u1__p6_0[] = {
  146487. 6,
  146488. 5,
  146489. 7,
  146490. 4,
  146491. 8,
  146492. 3,
  146493. 9,
  146494. 2,
  146495. 10,
  146496. 1,
  146497. 11,
  146498. 0,
  146499. 12,
  146500. };
  146501. static long _vq_lengthlist__44u1__p6_0[] = {
  146502. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146503. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146504. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146505. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146506. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146507. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146508. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146509. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146510. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146511. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146512. 15,17,16,17,18,17,17,18, 0,
  146513. };
  146514. static float _vq_quantthresh__44u1__p6_0[] = {
  146515. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146516. 12.5, 17.5, 22.5, 27.5,
  146517. };
  146518. static long _vq_quantmap__44u1__p6_0[] = {
  146519. 11, 9, 7, 5, 3, 1, 0, 2,
  146520. 4, 6, 8, 10, 12,
  146521. };
  146522. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146523. _vq_quantthresh__44u1__p6_0,
  146524. _vq_quantmap__44u1__p6_0,
  146525. 13,
  146526. 13
  146527. };
  146528. static static_codebook _44u1__p6_0 = {
  146529. 2, 169,
  146530. _vq_lengthlist__44u1__p6_0,
  146531. 1, -526516224, 1616117760, 4, 0,
  146532. _vq_quantlist__44u1__p6_0,
  146533. NULL,
  146534. &_vq_auxt__44u1__p6_0,
  146535. NULL,
  146536. 0
  146537. };
  146538. static long _vq_quantlist__44u1__p6_1[] = {
  146539. 2,
  146540. 1,
  146541. 3,
  146542. 0,
  146543. 4,
  146544. };
  146545. static long _vq_lengthlist__44u1__p6_1[] = {
  146546. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146547. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146548. };
  146549. static float _vq_quantthresh__44u1__p6_1[] = {
  146550. -1.5, -0.5, 0.5, 1.5,
  146551. };
  146552. static long _vq_quantmap__44u1__p6_1[] = {
  146553. 3, 1, 0, 2, 4,
  146554. };
  146555. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146556. _vq_quantthresh__44u1__p6_1,
  146557. _vq_quantmap__44u1__p6_1,
  146558. 5,
  146559. 5
  146560. };
  146561. static static_codebook _44u1__p6_1 = {
  146562. 2, 25,
  146563. _vq_lengthlist__44u1__p6_1,
  146564. 1, -533725184, 1611661312, 3, 0,
  146565. _vq_quantlist__44u1__p6_1,
  146566. NULL,
  146567. &_vq_auxt__44u1__p6_1,
  146568. NULL,
  146569. 0
  146570. };
  146571. static long _vq_quantlist__44u1__p7_0[] = {
  146572. 3,
  146573. 2,
  146574. 4,
  146575. 1,
  146576. 5,
  146577. 0,
  146578. 6,
  146579. };
  146580. static long _vq_lengthlist__44u1__p7_0[] = {
  146581. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146582. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146583. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146584. 8,
  146585. };
  146586. static float _vq_quantthresh__44u1__p7_0[] = {
  146587. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146588. };
  146589. static long _vq_quantmap__44u1__p7_0[] = {
  146590. 5, 3, 1, 0, 2, 4, 6,
  146591. };
  146592. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146593. _vq_quantthresh__44u1__p7_0,
  146594. _vq_quantmap__44u1__p7_0,
  146595. 7,
  146596. 7
  146597. };
  146598. static static_codebook _44u1__p7_0 = {
  146599. 2, 49,
  146600. _vq_lengthlist__44u1__p7_0,
  146601. 1, -518017024, 1626677248, 3, 0,
  146602. _vq_quantlist__44u1__p7_0,
  146603. NULL,
  146604. &_vq_auxt__44u1__p7_0,
  146605. NULL,
  146606. 0
  146607. };
  146608. static long _vq_quantlist__44u1__p7_1[] = {
  146609. 6,
  146610. 5,
  146611. 7,
  146612. 4,
  146613. 8,
  146614. 3,
  146615. 9,
  146616. 2,
  146617. 10,
  146618. 1,
  146619. 11,
  146620. 0,
  146621. 12,
  146622. };
  146623. static long _vq_lengthlist__44u1__p7_1[] = {
  146624. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146625. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146626. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146627. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146628. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146629. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146630. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146631. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146632. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146633. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146634. 15,15,15,15,15,15,15,15,15,
  146635. };
  146636. static float _vq_quantthresh__44u1__p7_1[] = {
  146637. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146638. 32.5, 45.5, 58.5, 71.5,
  146639. };
  146640. static long _vq_quantmap__44u1__p7_1[] = {
  146641. 11, 9, 7, 5, 3, 1, 0, 2,
  146642. 4, 6, 8, 10, 12,
  146643. };
  146644. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146645. _vq_quantthresh__44u1__p7_1,
  146646. _vq_quantmap__44u1__p7_1,
  146647. 13,
  146648. 13
  146649. };
  146650. static static_codebook _44u1__p7_1 = {
  146651. 2, 169,
  146652. _vq_lengthlist__44u1__p7_1,
  146653. 1, -523010048, 1618608128, 4, 0,
  146654. _vq_quantlist__44u1__p7_1,
  146655. NULL,
  146656. &_vq_auxt__44u1__p7_1,
  146657. NULL,
  146658. 0
  146659. };
  146660. static long _vq_quantlist__44u1__p7_2[] = {
  146661. 6,
  146662. 5,
  146663. 7,
  146664. 4,
  146665. 8,
  146666. 3,
  146667. 9,
  146668. 2,
  146669. 10,
  146670. 1,
  146671. 11,
  146672. 0,
  146673. 12,
  146674. };
  146675. static long _vq_lengthlist__44u1__p7_2[] = {
  146676. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146677. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146678. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146679. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146680. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146681. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146682. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146683. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146684. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146685. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146686. 9, 9, 9,10, 9, 9,10,10, 9,
  146687. };
  146688. static float _vq_quantthresh__44u1__p7_2[] = {
  146689. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146690. 2.5, 3.5, 4.5, 5.5,
  146691. };
  146692. static long _vq_quantmap__44u1__p7_2[] = {
  146693. 11, 9, 7, 5, 3, 1, 0, 2,
  146694. 4, 6, 8, 10, 12,
  146695. };
  146696. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146697. _vq_quantthresh__44u1__p7_2,
  146698. _vq_quantmap__44u1__p7_2,
  146699. 13,
  146700. 13
  146701. };
  146702. static static_codebook _44u1__p7_2 = {
  146703. 2, 169,
  146704. _vq_lengthlist__44u1__p7_2,
  146705. 1, -531103744, 1611661312, 4, 0,
  146706. _vq_quantlist__44u1__p7_2,
  146707. NULL,
  146708. &_vq_auxt__44u1__p7_2,
  146709. NULL,
  146710. 0
  146711. };
  146712. static long _huff_lengthlist__44u1__short[] = {
  146713. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146714. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146715. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146716. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146717. };
  146718. static static_codebook _huff_book__44u1__short = {
  146719. 2, 64,
  146720. _huff_lengthlist__44u1__short,
  146721. 0, 0, 0, 0, 0,
  146722. NULL,
  146723. NULL,
  146724. NULL,
  146725. NULL,
  146726. 0
  146727. };
  146728. static long _huff_lengthlist__44u2__long[] = {
  146729. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146730. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146731. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146732. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146733. };
  146734. static static_codebook _huff_book__44u2__long = {
  146735. 2, 64,
  146736. _huff_lengthlist__44u2__long,
  146737. 0, 0, 0, 0, 0,
  146738. NULL,
  146739. NULL,
  146740. NULL,
  146741. NULL,
  146742. 0
  146743. };
  146744. static long _vq_quantlist__44u2__p1_0[] = {
  146745. 1,
  146746. 0,
  146747. 2,
  146748. };
  146749. static long _vq_lengthlist__44u2__p1_0[] = {
  146750. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146751. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146752. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146753. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146754. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146755. 13,
  146756. };
  146757. static float _vq_quantthresh__44u2__p1_0[] = {
  146758. -0.5, 0.5,
  146759. };
  146760. static long _vq_quantmap__44u2__p1_0[] = {
  146761. 1, 0, 2,
  146762. };
  146763. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146764. _vq_quantthresh__44u2__p1_0,
  146765. _vq_quantmap__44u2__p1_0,
  146766. 3,
  146767. 3
  146768. };
  146769. static static_codebook _44u2__p1_0 = {
  146770. 4, 81,
  146771. _vq_lengthlist__44u2__p1_0,
  146772. 1, -535822336, 1611661312, 2, 0,
  146773. _vq_quantlist__44u2__p1_0,
  146774. NULL,
  146775. &_vq_auxt__44u2__p1_0,
  146776. NULL,
  146777. 0
  146778. };
  146779. static long _vq_quantlist__44u2__p2_0[] = {
  146780. 1,
  146781. 0,
  146782. 2,
  146783. };
  146784. static long _vq_lengthlist__44u2__p2_0[] = {
  146785. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146786. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146787. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146788. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146789. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146790. 9,
  146791. };
  146792. static float _vq_quantthresh__44u2__p2_0[] = {
  146793. -0.5, 0.5,
  146794. };
  146795. static long _vq_quantmap__44u2__p2_0[] = {
  146796. 1, 0, 2,
  146797. };
  146798. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146799. _vq_quantthresh__44u2__p2_0,
  146800. _vq_quantmap__44u2__p2_0,
  146801. 3,
  146802. 3
  146803. };
  146804. static static_codebook _44u2__p2_0 = {
  146805. 4, 81,
  146806. _vq_lengthlist__44u2__p2_0,
  146807. 1, -535822336, 1611661312, 2, 0,
  146808. _vq_quantlist__44u2__p2_0,
  146809. NULL,
  146810. &_vq_auxt__44u2__p2_0,
  146811. NULL,
  146812. 0
  146813. };
  146814. static long _vq_quantlist__44u2__p3_0[] = {
  146815. 2,
  146816. 1,
  146817. 3,
  146818. 0,
  146819. 4,
  146820. };
  146821. static long _vq_lengthlist__44u2__p3_0[] = {
  146822. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146823. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146824. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146825. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146826. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146827. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146828. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146829. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146830. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146831. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146832. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146833. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146834. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146835. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146836. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146837. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146838. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146839. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146840. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146841. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146842. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146843. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146844. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146845. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146846. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146847. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146848. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146849. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146850. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146851. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146852. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146853. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146854. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146855. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146856. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146857. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146858. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146859. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146860. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146861. 0,
  146862. };
  146863. static float _vq_quantthresh__44u2__p3_0[] = {
  146864. -1.5, -0.5, 0.5, 1.5,
  146865. };
  146866. static long _vq_quantmap__44u2__p3_0[] = {
  146867. 3, 1, 0, 2, 4,
  146868. };
  146869. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146870. _vq_quantthresh__44u2__p3_0,
  146871. _vq_quantmap__44u2__p3_0,
  146872. 5,
  146873. 5
  146874. };
  146875. static static_codebook _44u2__p3_0 = {
  146876. 4, 625,
  146877. _vq_lengthlist__44u2__p3_0,
  146878. 1, -533725184, 1611661312, 3, 0,
  146879. _vq_quantlist__44u2__p3_0,
  146880. NULL,
  146881. &_vq_auxt__44u2__p3_0,
  146882. NULL,
  146883. 0
  146884. };
  146885. static long _vq_quantlist__44u2__p4_0[] = {
  146886. 2,
  146887. 1,
  146888. 3,
  146889. 0,
  146890. 4,
  146891. };
  146892. static long _vq_lengthlist__44u2__p4_0[] = {
  146893. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146894. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146895. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146896. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146897. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146898. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146899. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146900. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146901. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146902. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146903. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146904. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146905. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146906. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146907. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146908. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146909. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146910. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146911. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146912. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146913. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146914. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146915. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146916. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146917. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146918. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146919. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146920. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146921. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146922. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146923. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146924. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146925. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146926. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146927. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146928. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146929. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146930. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146931. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146932. 13,
  146933. };
  146934. static float _vq_quantthresh__44u2__p4_0[] = {
  146935. -1.5, -0.5, 0.5, 1.5,
  146936. };
  146937. static long _vq_quantmap__44u2__p4_0[] = {
  146938. 3, 1, 0, 2, 4,
  146939. };
  146940. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146941. _vq_quantthresh__44u2__p4_0,
  146942. _vq_quantmap__44u2__p4_0,
  146943. 5,
  146944. 5
  146945. };
  146946. static static_codebook _44u2__p4_0 = {
  146947. 4, 625,
  146948. _vq_lengthlist__44u2__p4_0,
  146949. 1, -533725184, 1611661312, 3, 0,
  146950. _vq_quantlist__44u2__p4_0,
  146951. NULL,
  146952. &_vq_auxt__44u2__p4_0,
  146953. NULL,
  146954. 0
  146955. };
  146956. static long _vq_quantlist__44u2__p5_0[] = {
  146957. 4,
  146958. 3,
  146959. 5,
  146960. 2,
  146961. 6,
  146962. 1,
  146963. 7,
  146964. 0,
  146965. 8,
  146966. };
  146967. static long _vq_lengthlist__44u2__p5_0[] = {
  146968. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146969. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146970. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146971. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146972. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146973. 13,
  146974. };
  146975. static float _vq_quantthresh__44u2__p5_0[] = {
  146976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146977. };
  146978. static long _vq_quantmap__44u2__p5_0[] = {
  146979. 7, 5, 3, 1, 0, 2, 4, 6,
  146980. 8,
  146981. };
  146982. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146983. _vq_quantthresh__44u2__p5_0,
  146984. _vq_quantmap__44u2__p5_0,
  146985. 9,
  146986. 9
  146987. };
  146988. static static_codebook _44u2__p5_0 = {
  146989. 2, 81,
  146990. _vq_lengthlist__44u2__p5_0,
  146991. 1, -531628032, 1611661312, 4, 0,
  146992. _vq_quantlist__44u2__p5_0,
  146993. NULL,
  146994. &_vq_auxt__44u2__p5_0,
  146995. NULL,
  146996. 0
  146997. };
  146998. static long _vq_quantlist__44u2__p6_0[] = {
  146999. 6,
  147000. 5,
  147001. 7,
  147002. 4,
  147003. 8,
  147004. 3,
  147005. 9,
  147006. 2,
  147007. 10,
  147008. 1,
  147009. 11,
  147010. 0,
  147011. 12,
  147012. };
  147013. static long _vq_lengthlist__44u2__p6_0[] = {
  147014. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147015. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147016. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147017. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147018. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147019. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147020. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147021. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147022. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147023. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147024. 15,17,17,16,18,17,18, 0, 0,
  147025. };
  147026. static float _vq_quantthresh__44u2__p6_0[] = {
  147027. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147028. 12.5, 17.5, 22.5, 27.5,
  147029. };
  147030. static long _vq_quantmap__44u2__p6_0[] = {
  147031. 11, 9, 7, 5, 3, 1, 0, 2,
  147032. 4, 6, 8, 10, 12,
  147033. };
  147034. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147035. _vq_quantthresh__44u2__p6_0,
  147036. _vq_quantmap__44u2__p6_0,
  147037. 13,
  147038. 13
  147039. };
  147040. static static_codebook _44u2__p6_0 = {
  147041. 2, 169,
  147042. _vq_lengthlist__44u2__p6_0,
  147043. 1, -526516224, 1616117760, 4, 0,
  147044. _vq_quantlist__44u2__p6_0,
  147045. NULL,
  147046. &_vq_auxt__44u2__p6_0,
  147047. NULL,
  147048. 0
  147049. };
  147050. static long _vq_quantlist__44u2__p6_1[] = {
  147051. 2,
  147052. 1,
  147053. 3,
  147054. 0,
  147055. 4,
  147056. };
  147057. static long _vq_lengthlist__44u2__p6_1[] = {
  147058. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147059. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147060. };
  147061. static float _vq_quantthresh__44u2__p6_1[] = {
  147062. -1.5, -0.5, 0.5, 1.5,
  147063. };
  147064. static long _vq_quantmap__44u2__p6_1[] = {
  147065. 3, 1, 0, 2, 4,
  147066. };
  147067. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147068. _vq_quantthresh__44u2__p6_1,
  147069. _vq_quantmap__44u2__p6_1,
  147070. 5,
  147071. 5
  147072. };
  147073. static static_codebook _44u2__p6_1 = {
  147074. 2, 25,
  147075. _vq_lengthlist__44u2__p6_1,
  147076. 1, -533725184, 1611661312, 3, 0,
  147077. _vq_quantlist__44u2__p6_1,
  147078. NULL,
  147079. &_vq_auxt__44u2__p6_1,
  147080. NULL,
  147081. 0
  147082. };
  147083. static long _vq_quantlist__44u2__p7_0[] = {
  147084. 4,
  147085. 3,
  147086. 5,
  147087. 2,
  147088. 6,
  147089. 1,
  147090. 7,
  147091. 0,
  147092. 8,
  147093. };
  147094. static long _vq_lengthlist__44u2__p7_0[] = {
  147095. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147096. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147100. 11,
  147101. };
  147102. static float _vq_quantthresh__44u2__p7_0[] = {
  147103. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147104. };
  147105. static long _vq_quantmap__44u2__p7_0[] = {
  147106. 7, 5, 3, 1, 0, 2, 4, 6,
  147107. 8,
  147108. };
  147109. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147110. _vq_quantthresh__44u2__p7_0,
  147111. _vq_quantmap__44u2__p7_0,
  147112. 9,
  147113. 9
  147114. };
  147115. static static_codebook _44u2__p7_0 = {
  147116. 2, 81,
  147117. _vq_lengthlist__44u2__p7_0,
  147118. 1, -516612096, 1626677248, 4, 0,
  147119. _vq_quantlist__44u2__p7_0,
  147120. NULL,
  147121. &_vq_auxt__44u2__p7_0,
  147122. NULL,
  147123. 0
  147124. };
  147125. static long _vq_quantlist__44u2__p7_1[] = {
  147126. 6,
  147127. 5,
  147128. 7,
  147129. 4,
  147130. 8,
  147131. 3,
  147132. 9,
  147133. 2,
  147134. 10,
  147135. 1,
  147136. 11,
  147137. 0,
  147138. 12,
  147139. };
  147140. static long _vq_lengthlist__44u2__p7_1[] = {
  147141. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147142. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147143. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147144. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147145. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147146. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147147. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147148. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147149. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147150. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147151. 14,14,14,17,15,17,17,17,17,
  147152. };
  147153. static float _vq_quantthresh__44u2__p7_1[] = {
  147154. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147155. 32.5, 45.5, 58.5, 71.5,
  147156. };
  147157. static long _vq_quantmap__44u2__p7_1[] = {
  147158. 11, 9, 7, 5, 3, 1, 0, 2,
  147159. 4, 6, 8, 10, 12,
  147160. };
  147161. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147162. _vq_quantthresh__44u2__p7_1,
  147163. _vq_quantmap__44u2__p7_1,
  147164. 13,
  147165. 13
  147166. };
  147167. static static_codebook _44u2__p7_1 = {
  147168. 2, 169,
  147169. _vq_lengthlist__44u2__p7_1,
  147170. 1, -523010048, 1618608128, 4, 0,
  147171. _vq_quantlist__44u2__p7_1,
  147172. NULL,
  147173. &_vq_auxt__44u2__p7_1,
  147174. NULL,
  147175. 0
  147176. };
  147177. static long _vq_quantlist__44u2__p7_2[] = {
  147178. 6,
  147179. 5,
  147180. 7,
  147181. 4,
  147182. 8,
  147183. 3,
  147184. 9,
  147185. 2,
  147186. 10,
  147187. 1,
  147188. 11,
  147189. 0,
  147190. 12,
  147191. };
  147192. static long _vq_lengthlist__44u2__p7_2[] = {
  147193. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147194. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147195. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147196. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147197. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147198. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147199. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147200. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147201. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147202. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147203. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147204. };
  147205. static float _vq_quantthresh__44u2__p7_2[] = {
  147206. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147207. 2.5, 3.5, 4.5, 5.5,
  147208. };
  147209. static long _vq_quantmap__44u2__p7_2[] = {
  147210. 11, 9, 7, 5, 3, 1, 0, 2,
  147211. 4, 6, 8, 10, 12,
  147212. };
  147213. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147214. _vq_quantthresh__44u2__p7_2,
  147215. _vq_quantmap__44u2__p7_2,
  147216. 13,
  147217. 13
  147218. };
  147219. static static_codebook _44u2__p7_2 = {
  147220. 2, 169,
  147221. _vq_lengthlist__44u2__p7_2,
  147222. 1, -531103744, 1611661312, 4, 0,
  147223. _vq_quantlist__44u2__p7_2,
  147224. NULL,
  147225. &_vq_auxt__44u2__p7_2,
  147226. NULL,
  147227. 0
  147228. };
  147229. static long _huff_lengthlist__44u2__short[] = {
  147230. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147231. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147232. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147233. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147234. };
  147235. static static_codebook _huff_book__44u2__short = {
  147236. 2, 64,
  147237. _huff_lengthlist__44u2__short,
  147238. 0, 0, 0, 0, 0,
  147239. NULL,
  147240. NULL,
  147241. NULL,
  147242. NULL,
  147243. 0
  147244. };
  147245. static long _huff_lengthlist__44u3__long[] = {
  147246. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147247. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147248. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147249. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147250. };
  147251. static static_codebook _huff_book__44u3__long = {
  147252. 2, 64,
  147253. _huff_lengthlist__44u3__long,
  147254. 0, 0, 0, 0, 0,
  147255. NULL,
  147256. NULL,
  147257. NULL,
  147258. NULL,
  147259. 0
  147260. };
  147261. static long _vq_quantlist__44u3__p1_0[] = {
  147262. 1,
  147263. 0,
  147264. 2,
  147265. };
  147266. static long _vq_lengthlist__44u3__p1_0[] = {
  147267. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147268. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147269. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147270. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147271. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147272. 13,
  147273. };
  147274. static float _vq_quantthresh__44u3__p1_0[] = {
  147275. -0.5, 0.5,
  147276. };
  147277. static long _vq_quantmap__44u3__p1_0[] = {
  147278. 1, 0, 2,
  147279. };
  147280. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147281. _vq_quantthresh__44u3__p1_0,
  147282. _vq_quantmap__44u3__p1_0,
  147283. 3,
  147284. 3
  147285. };
  147286. static static_codebook _44u3__p1_0 = {
  147287. 4, 81,
  147288. _vq_lengthlist__44u3__p1_0,
  147289. 1, -535822336, 1611661312, 2, 0,
  147290. _vq_quantlist__44u3__p1_0,
  147291. NULL,
  147292. &_vq_auxt__44u3__p1_0,
  147293. NULL,
  147294. 0
  147295. };
  147296. static long _vq_quantlist__44u3__p2_0[] = {
  147297. 1,
  147298. 0,
  147299. 2,
  147300. };
  147301. static long _vq_lengthlist__44u3__p2_0[] = {
  147302. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147303. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147304. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147305. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147306. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147307. 9,
  147308. };
  147309. static float _vq_quantthresh__44u3__p2_0[] = {
  147310. -0.5, 0.5,
  147311. };
  147312. static long _vq_quantmap__44u3__p2_0[] = {
  147313. 1, 0, 2,
  147314. };
  147315. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147316. _vq_quantthresh__44u3__p2_0,
  147317. _vq_quantmap__44u3__p2_0,
  147318. 3,
  147319. 3
  147320. };
  147321. static static_codebook _44u3__p2_0 = {
  147322. 4, 81,
  147323. _vq_lengthlist__44u3__p2_0,
  147324. 1, -535822336, 1611661312, 2, 0,
  147325. _vq_quantlist__44u3__p2_0,
  147326. NULL,
  147327. &_vq_auxt__44u3__p2_0,
  147328. NULL,
  147329. 0
  147330. };
  147331. static long _vq_quantlist__44u3__p3_0[] = {
  147332. 2,
  147333. 1,
  147334. 3,
  147335. 0,
  147336. 4,
  147337. };
  147338. static long _vq_lengthlist__44u3__p3_0[] = {
  147339. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147340. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147341. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147342. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147343. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147344. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147345. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147346. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147347. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147348. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147349. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147350. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147351. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147352. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147353. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147354. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147355. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147356. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147357. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147358. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147359. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147360. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147361. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147362. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147363. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147364. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147365. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147366. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147367. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147368. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147369. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147370. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147371. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147372. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147373. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147374. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147375. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147376. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147377. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147378. 0,
  147379. };
  147380. static float _vq_quantthresh__44u3__p3_0[] = {
  147381. -1.5, -0.5, 0.5, 1.5,
  147382. };
  147383. static long _vq_quantmap__44u3__p3_0[] = {
  147384. 3, 1, 0, 2, 4,
  147385. };
  147386. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147387. _vq_quantthresh__44u3__p3_0,
  147388. _vq_quantmap__44u3__p3_0,
  147389. 5,
  147390. 5
  147391. };
  147392. static static_codebook _44u3__p3_0 = {
  147393. 4, 625,
  147394. _vq_lengthlist__44u3__p3_0,
  147395. 1, -533725184, 1611661312, 3, 0,
  147396. _vq_quantlist__44u3__p3_0,
  147397. NULL,
  147398. &_vq_auxt__44u3__p3_0,
  147399. NULL,
  147400. 0
  147401. };
  147402. static long _vq_quantlist__44u3__p4_0[] = {
  147403. 2,
  147404. 1,
  147405. 3,
  147406. 0,
  147407. 4,
  147408. };
  147409. static long _vq_lengthlist__44u3__p4_0[] = {
  147410. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147411. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147412. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147413. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147414. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147415. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147416. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147417. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147418. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147419. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147420. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147421. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147422. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147423. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147424. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147425. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147426. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147427. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147428. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147429. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147430. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147431. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147432. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147433. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147434. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147435. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147436. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147437. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147438. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147439. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147440. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147441. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147442. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147443. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147444. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147445. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147446. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147447. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147448. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147449. 13,
  147450. };
  147451. static float _vq_quantthresh__44u3__p4_0[] = {
  147452. -1.5, -0.5, 0.5, 1.5,
  147453. };
  147454. static long _vq_quantmap__44u3__p4_0[] = {
  147455. 3, 1, 0, 2, 4,
  147456. };
  147457. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147458. _vq_quantthresh__44u3__p4_0,
  147459. _vq_quantmap__44u3__p4_0,
  147460. 5,
  147461. 5
  147462. };
  147463. static static_codebook _44u3__p4_0 = {
  147464. 4, 625,
  147465. _vq_lengthlist__44u3__p4_0,
  147466. 1, -533725184, 1611661312, 3, 0,
  147467. _vq_quantlist__44u3__p4_0,
  147468. NULL,
  147469. &_vq_auxt__44u3__p4_0,
  147470. NULL,
  147471. 0
  147472. };
  147473. static long _vq_quantlist__44u3__p5_0[] = {
  147474. 4,
  147475. 3,
  147476. 5,
  147477. 2,
  147478. 6,
  147479. 1,
  147480. 7,
  147481. 0,
  147482. 8,
  147483. };
  147484. static long _vq_lengthlist__44u3__p5_0[] = {
  147485. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147486. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147487. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147488. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147489. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147490. 12,
  147491. };
  147492. static float _vq_quantthresh__44u3__p5_0[] = {
  147493. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147494. };
  147495. static long _vq_quantmap__44u3__p5_0[] = {
  147496. 7, 5, 3, 1, 0, 2, 4, 6,
  147497. 8,
  147498. };
  147499. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147500. _vq_quantthresh__44u3__p5_0,
  147501. _vq_quantmap__44u3__p5_0,
  147502. 9,
  147503. 9
  147504. };
  147505. static static_codebook _44u3__p5_0 = {
  147506. 2, 81,
  147507. _vq_lengthlist__44u3__p5_0,
  147508. 1, -531628032, 1611661312, 4, 0,
  147509. _vq_quantlist__44u3__p5_0,
  147510. NULL,
  147511. &_vq_auxt__44u3__p5_0,
  147512. NULL,
  147513. 0
  147514. };
  147515. static long _vq_quantlist__44u3__p6_0[] = {
  147516. 6,
  147517. 5,
  147518. 7,
  147519. 4,
  147520. 8,
  147521. 3,
  147522. 9,
  147523. 2,
  147524. 10,
  147525. 1,
  147526. 11,
  147527. 0,
  147528. 12,
  147529. };
  147530. static long _vq_lengthlist__44u3__p6_0[] = {
  147531. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147532. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147533. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147534. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147535. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147536. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147537. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147538. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147539. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147540. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147541. 15,16,16,16,17,18,16,20,18,
  147542. };
  147543. static float _vq_quantthresh__44u3__p6_0[] = {
  147544. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147545. 12.5, 17.5, 22.5, 27.5,
  147546. };
  147547. static long _vq_quantmap__44u3__p6_0[] = {
  147548. 11, 9, 7, 5, 3, 1, 0, 2,
  147549. 4, 6, 8, 10, 12,
  147550. };
  147551. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147552. _vq_quantthresh__44u3__p6_0,
  147553. _vq_quantmap__44u3__p6_0,
  147554. 13,
  147555. 13
  147556. };
  147557. static static_codebook _44u3__p6_0 = {
  147558. 2, 169,
  147559. _vq_lengthlist__44u3__p6_0,
  147560. 1, -526516224, 1616117760, 4, 0,
  147561. _vq_quantlist__44u3__p6_0,
  147562. NULL,
  147563. &_vq_auxt__44u3__p6_0,
  147564. NULL,
  147565. 0
  147566. };
  147567. static long _vq_quantlist__44u3__p6_1[] = {
  147568. 2,
  147569. 1,
  147570. 3,
  147571. 0,
  147572. 4,
  147573. };
  147574. static long _vq_lengthlist__44u3__p6_1[] = {
  147575. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147576. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147577. };
  147578. static float _vq_quantthresh__44u3__p6_1[] = {
  147579. -1.5, -0.5, 0.5, 1.5,
  147580. };
  147581. static long _vq_quantmap__44u3__p6_1[] = {
  147582. 3, 1, 0, 2, 4,
  147583. };
  147584. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147585. _vq_quantthresh__44u3__p6_1,
  147586. _vq_quantmap__44u3__p6_1,
  147587. 5,
  147588. 5
  147589. };
  147590. static static_codebook _44u3__p6_1 = {
  147591. 2, 25,
  147592. _vq_lengthlist__44u3__p6_1,
  147593. 1, -533725184, 1611661312, 3, 0,
  147594. _vq_quantlist__44u3__p6_1,
  147595. NULL,
  147596. &_vq_auxt__44u3__p6_1,
  147597. NULL,
  147598. 0
  147599. };
  147600. static long _vq_quantlist__44u3__p7_0[] = {
  147601. 4,
  147602. 3,
  147603. 5,
  147604. 2,
  147605. 6,
  147606. 1,
  147607. 7,
  147608. 0,
  147609. 8,
  147610. };
  147611. static long _vq_lengthlist__44u3__p7_0[] = {
  147612. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147613. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147614. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147616. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147617. 9,
  147618. };
  147619. static float _vq_quantthresh__44u3__p7_0[] = {
  147620. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147621. };
  147622. static long _vq_quantmap__44u3__p7_0[] = {
  147623. 7, 5, 3, 1, 0, 2, 4, 6,
  147624. 8,
  147625. };
  147626. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147627. _vq_quantthresh__44u3__p7_0,
  147628. _vq_quantmap__44u3__p7_0,
  147629. 9,
  147630. 9
  147631. };
  147632. static static_codebook _44u3__p7_0 = {
  147633. 2, 81,
  147634. _vq_lengthlist__44u3__p7_0,
  147635. 1, -515907584, 1627381760, 4, 0,
  147636. _vq_quantlist__44u3__p7_0,
  147637. NULL,
  147638. &_vq_auxt__44u3__p7_0,
  147639. NULL,
  147640. 0
  147641. };
  147642. static long _vq_quantlist__44u3__p7_1[] = {
  147643. 7,
  147644. 6,
  147645. 8,
  147646. 5,
  147647. 9,
  147648. 4,
  147649. 10,
  147650. 3,
  147651. 11,
  147652. 2,
  147653. 12,
  147654. 1,
  147655. 13,
  147656. 0,
  147657. 14,
  147658. };
  147659. static long _vq_lengthlist__44u3__p7_1[] = {
  147660. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147661. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147662. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147663. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147664. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147665. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147666. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147667. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147668. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147669. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147670. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147671. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147672. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147673. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147674. 17,
  147675. };
  147676. static float _vq_quantthresh__44u3__p7_1[] = {
  147677. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147678. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147679. };
  147680. static long _vq_quantmap__44u3__p7_1[] = {
  147681. 13, 11, 9, 7, 5, 3, 1, 0,
  147682. 2, 4, 6, 8, 10, 12, 14,
  147683. };
  147684. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147685. _vq_quantthresh__44u3__p7_1,
  147686. _vq_quantmap__44u3__p7_1,
  147687. 15,
  147688. 15
  147689. };
  147690. static static_codebook _44u3__p7_1 = {
  147691. 2, 225,
  147692. _vq_lengthlist__44u3__p7_1,
  147693. 1, -522338304, 1620115456, 4, 0,
  147694. _vq_quantlist__44u3__p7_1,
  147695. NULL,
  147696. &_vq_auxt__44u3__p7_1,
  147697. NULL,
  147698. 0
  147699. };
  147700. static long _vq_quantlist__44u3__p7_2[] = {
  147701. 8,
  147702. 7,
  147703. 9,
  147704. 6,
  147705. 10,
  147706. 5,
  147707. 11,
  147708. 4,
  147709. 12,
  147710. 3,
  147711. 13,
  147712. 2,
  147713. 14,
  147714. 1,
  147715. 15,
  147716. 0,
  147717. 16,
  147718. };
  147719. static long _vq_lengthlist__44u3__p7_2[] = {
  147720. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147721. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147722. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147723. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147724. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147725. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147726. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147727. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147728. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147729. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147730. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147731. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147732. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147733. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147734. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147735. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147736. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147737. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147738. 11,
  147739. };
  147740. static float _vq_quantthresh__44u3__p7_2[] = {
  147741. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147742. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147743. };
  147744. static long _vq_quantmap__44u3__p7_2[] = {
  147745. 15, 13, 11, 9, 7, 5, 3, 1,
  147746. 0, 2, 4, 6, 8, 10, 12, 14,
  147747. 16,
  147748. };
  147749. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147750. _vq_quantthresh__44u3__p7_2,
  147751. _vq_quantmap__44u3__p7_2,
  147752. 17,
  147753. 17
  147754. };
  147755. static static_codebook _44u3__p7_2 = {
  147756. 2, 289,
  147757. _vq_lengthlist__44u3__p7_2,
  147758. 1, -529530880, 1611661312, 5, 0,
  147759. _vq_quantlist__44u3__p7_2,
  147760. NULL,
  147761. &_vq_auxt__44u3__p7_2,
  147762. NULL,
  147763. 0
  147764. };
  147765. static long _huff_lengthlist__44u3__short[] = {
  147766. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147767. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147768. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147769. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147770. };
  147771. static static_codebook _huff_book__44u3__short = {
  147772. 2, 64,
  147773. _huff_lengthlist__44u3__short,
  147774. 0, 0, 0, 0, 0,
  147775. NULL,
  147776. NULL,
  147777. NULL,
  147778. NULL,
  147779. 0
  147780. };
  147781. static long _huff_lengthlist__44u4__long[] = {
  147782. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147783. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147784. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147785. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147786. };
  147787. static static_codebook _huff_book__44u4__long = {
  147788. 2, 64,
  147789. _huff_lengthlist__44u4__long,
  147790. 0, 0, 0, 0, 0,
  147791. NULL,
  147792. NULL,
  147793. NULL,
  147794. NULL,
  147795. 0
  147796. };
  147797. static long _vq_quantlist__44u4__p1_0[] = {
  147798. 1,
  147799. 0,
  147800. 2,
  147801. };
  147802. static long _vq_lengthlist__44u4__p1_0[] = {
  147803. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147804. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147805. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147806. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147807. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147808. 13,
  147809. };
  147810. static float _vq_quantthresh__44u4__p1_0[] = {
  147811. -0.5, 0.5,
  147812. };
  147813. static long _vq_quantmap__44u4__p1_0[] = {
  147814. 1, 0, 2,
  147815. };
  147816. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147817. _vq_quantthresh__44u4__p1_0,
  147818. _vq_quantmap__44u4__p1_0,
  147819. 3,
  147820. 3
  147821. };
  147822. static static_codebook _44u4__p1_0 = {
  147823. 4, 81,
  147824. _vq_lengthlist__44u4__p1_0,
  147825. 1, -535822336, 1611661312, 2, 0,
  147826. _vq_quantlist__44u4__p1_0,
  147827. NULL,
  147828. &_vq_auxt__44u4__p1_0,
  147829. NULL,
  147830. 0
  147831. };
  147832. static long _vq_quantlist__44u4__p2_0[] = {
  147833. 1,
  147834. 0,
  147835. 2,
  147836. };
  147837. static long _vq_lengthlist__44u4__p2_0[] = {
  147838. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147839. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147840. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147841. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147842. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147843. 9,
  147844. };
  147845. static float _vq_quantthresh__44u4__p2_0[] = {
  147846. -0.5, 0.5,
  147847. };
  147848. static long _vq_quantmap__44u4__p2_0[] = {
  147849. 1, 0, 2,
  147850. };
  147851. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147852. _vq_quantthresh__44u4__p2_0,
  147853. _vq_quantmap__44u4__p2_0,
  147854. 3,
  147855. 3
  147856. };
  147857. static static_codebook _44u4__p2_0 = {
  147858. 4, 81,
  147859. _vq_lengthlist__44u4__p2_0,
  147860. 1, -535822336, 1611661312, 2, 0,
  147861. _vq_quantlist__44u4__p2_0,
  147862. NULL,
  147863. &_vq_auxt__44u4__p2_0,
  147864. NULL,
  147865. 0
  147866. };
  147867. static long _vq_quantlist__44u4__p3_0[] = {
  147868. 2,
  147869. 1,
  147870. 3,
  147871. 0,
  147872. 4,
  147873. };
  147874. static long _vq_lengthlist__44u4__p3_0[] = {
  147875. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147876. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147877. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147878. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147879. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147880. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147881. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147882. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147883. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147884. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147885. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147886. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147887. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147888. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147889. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147890. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147891. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147892. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147893. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147894. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147895. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147896. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147897. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147898. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147899. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147900. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147901. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147902. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147903. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147904. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147905. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147906. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147907. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147908. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147909. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147910. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147911. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147912. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147913. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147914. 0,
  147915. };
  147916. static float _vq_quantthresh__44u4__p3_0[] = {
  147917. -1.5, -0.5, 0.5, 1.5,
  147918. };
  147919. static long _vq_quantmap__44u4__p3_0[] = {
  147920. 3, 1, 0, 2, 4,
  147921. };
  147922. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147923. _vq_quantthresh__44u4__p3_0,
  147924. _vq_quantmap__44u4__p3_0,
  147925. 5,
  147926. 5
  147927. };
  147928. static static_codebook _44u4__p3_0 = {
  147929. 4, 625,
  147930. _vq_lengthlist__44u4__p3_0,
  147931. 1, -533725184, 1611661312, 3, 0,
  147932. _vq_quantlist__44u4__p3_0,
  147933. NULL,
  147934. &_vq_auxt__44u4__p3_0,
  147935. NULL,
  147936. 0
  147937. };
  147938. static long _vq_quantlist__44u4__p4_0[] = {
  147939. 2,
  147940. 1,
  147941. 3,
  147942. 0,
  147943. 4,
  147944. };
  147945. static long _vq_lengthlist__44u4__p4_0[] = {
  147946. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147947. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147948. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147949. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147950. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147951. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147952. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147953. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147954. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147955. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147956. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147957. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147958. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147959. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147960. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147961. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147962. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147963. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147964. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147965. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147966. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147967. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147968. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147969. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147970. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147971. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147972. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147973. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147974. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147975. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147976. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147977. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147978. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147979. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147980. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147981. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147982. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147983. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147984. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147985. 13,
  147986. };
  147987. static float _vq_quantthresh__44u4__p4_0[] = {
  147988. -1.5, -0.5, 0.5, 1.5,
  147989. };
  147990. static long _vq_quantmap__44u4__p4_0[] = {
  147991. 3, 1, 0, 2, 4,
  147992. };
  147993. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147994. _vq_quantthresh__44u4__p4_0,
  147995. _vq_quantmap__44u4__p4_0,
  147996. 5,
  147997. 5
  147998. };
  147999. static static_codebook _44u4__p4_0 = {
  148000. 4, 625,
  148001. _vq_lengthlist__44u4__p4_0,
  148002. 1, -533725184, 1611661312, 3, 0,
  148003. _vq_quantlist__44u4__p4_0,
  148004. NULL,
  148005. &_vq_auxt__44u4__p4_0,
  148006. NULL,
  148007. 0
  148008. };
  148009. static long _vq_quantlist__44u4__p5_0[] = {
  148010. 4,
  148011. 3,
  148012. 5,
  148013. 2,
  148014. 6,
  148015. 1,
  148016. 7,
  148017. 0,
  148018. 8,
  148019. };
  148020. static long _vq_lengthlist__44u4__p5_0[] = {
  148021. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148022. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148023. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148024. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148025. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148026. 12,
  148027. };
  148028. static float _vq_quantthresh__44u4__p5_0[] = {
  148029. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148030. };
  148031. static long _vq_quantmap__44u4__p5_0[] = {
  148032. 7, 5, 3, 1, 0, 2, 4, 6,
  148033. 8,
  148034. };
  148035. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148036. _vq_quantthresh__44u4__p5_0,
  148037. _vq_quantmap__44u4__p5_0,
  148038. 9,
  148039. 9
  148040. };
  148041. static static_codebook _44u4__p5_0 = {
  148042. 2, 81,
  148043. _vq_lengthlist__44u4__p5_0,
  148044. 1, -531628032, 1611661312, 4, 0,
  148045. _vq_quantlist__44u4__p5_0,
  148046. NULL,
  148047. &_vq_auxt__44u4__p5_0,
  148048. NULL,
  148049. 0
  148050. };
  148051. static long _vq_quantlist__44u4__p6_0[] = {
  148052. 6,
  148053. 5,
  148054. 7,
  148055. 4,
  148056. 8,
  148057. 3,
  148058. 9,
  148059. 2,
  148060. 10,
  148061. 1,
  148062. 11,
  148063. 0,
  148064. 12,
  148065. };
  148066. static long _vq_lengthlist__44u4__p6_0[] = {
  148067. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148068. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148069. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148070. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148071. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148072. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148073. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148074. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148075. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148076. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148077. 16,16,16,17,17,18,17,20,21,
  148078. };
  148079. static float _vq_quantthresh__44u4__p6_0[] = {
  148080. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148081. 12.5, 17.5, 22.5, 27.5,
  148082. };
  148083. static long _vq_quantmap__44u4__p6_0[] = {
  148084. 11, 9, 7, 5, 3, 1, 0, 2,
  148085. 4, 6, 8, 10, 12,
  148086. };
  148087. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148088. _vq_quantthresh__44u4__p6_0,
  148089. _vq_quantmap__44u4__p6_0,
  148090. 13,
  148091. 13
  148092. };
  148093. static static_codebook _44u4__p6_0 = {
  148094. 2, 169,
  148095. _vq_lengthlist__44u4__p6_0,
  148096. 1, -526516224, 1616117760, 4, 0,
  148097. _vq_quantlist__44u4__p6_0,
  148098. NULL,
  148099. &_vq_auxt__44u4__p6_0,
  148100. NULL,
  148101. 0
  148102. };
  148103. static long _vq_quantlist__44u4__p6_1[] = {
  148104. 2,
  148105. 1,
  148106. 3,
  148107. 0,
  148108. 4,
  148109. };
  148110. static long _vq_lengthlist__44u4__p6_1[] = {
  148111. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148112. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148113. };
  148114. static float _vq_quantthresh__44u4__p6_1[] = {
  148115. -1.5, -0.5, 0.5, 1.5,
  148116. };
  148117. static long _vq_quantmap__44u4__p6_1[] = {
  148118. 3, 1, 0, 2, 4,
  148119. };
  148120. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148121. _vq_quantthresh__44u4__p6_1,
  148122. _vq_quantmap__44u4__p6_1,
  148123. 5,
  148124. 5
  148125. };
  148126. static static_codebook _44u4__p6_1 = {
  148127. 2, 25,
  148128. _vq_lengthlist__44u4__p6_1,
  148129. 1, -533725184, 1611661312, 3, 0,
  148130. _vq_quantlist__44u4__p6_1,
  148131. NULL,
  148132. &_vq_auxt__44u4__p6_1,
  148133. NULL,
  148134. 0
  148135. };
  148136. static long _vq_quantlist__44u4__p7_0[] = {
  148137. 6,
  148138. 5,
  148139. 7,
  148140. 4,
  148141. 8,
  148142. 3,
  148143. 9,
  148144. 2,
  148145. 10,
  148146. 1,
  148147. 11,
  148148. 0,
  148149. 12,
  148150. };
  148151. static long _vq_lengthlist__44u4__p7_0[] = {
  148152. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148153. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148154. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148155. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148156. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148157. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148162. 11,11,11,11,11,11,11,11,11,
  148163. };
  148164. static float _vq_quantthresh__44u4__p7_0[] = {
  148165. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148166. 637.5, 892.5, 1147.5, 1402.5,
  148167. };
  148168. static long _vq_quantmap__44u4__p7_0[] = {
  148169. 11, 9, 7, 5, 3, 1, 0, 2,
  148170. 4, 6, 8, 10, 12,
  148171. };
  148172. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148173. _vq_quantthresh__44u4__p7_0,
  148174. _vq_quantmap__44u4__p7_0,
  148175. 13,
  148176. 13
  148177. };
  148178. static static_codebook _44u4__p7_0 = {
  148179. 2, 169,
  148180. _vq_lengthlist__44u4__p7_0,
  148181. 1, -514332672, 1627381760, 4, 0,
  148182. _vq_quantlist__44u4__p7_0,
  148183. NULL,
  148184. &_vq_auxt__44u4__p7_0,
  148185. NULL,
  148186. 0
  148187. };
  148188. static long _vq_quantlist__44u4__p7_1[] = {
  148189. 7,
  148190. 6,
  148191. 8,
  148192. 5,
  148193. 9,
  148194. 4,
  148195. 10,
  148196. 3,
  148197. 11,
  148198. 2,
  148199. 12,
  148200. 1,
  148201. 13,
  148202. 0,
  148203. 14,
  148204. };
  148205. static long _vq_lengthlist__44u4__p7_1[] = {
  148206. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148207. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148208. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148209. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148210. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148211. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148212. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148213. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148214. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148215. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148216. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148217. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148218. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148219. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148220. 16,
  148221. };
  148222. static float _vq_quantthresh__44u4__p7_1[] = {
  148223. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148224. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148225. };
  148226. static long _vq_quantmap__44u4__p7_1[] = {
  148227. 13, 11, 9, 7, 5, 3, 1, 0,
  148228. 2, 4, 6, 8, 10, 12, 14,
  148229. };
  148230. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148231. _vq_quantthresh__44u4__p7_1,
  148232. _vq_quantmap__44u4__p7_1,
  148233. 15,
  148234. 15
  148235. };
  148236. static static_codebook _44u4__p7_1 = {
  148237. 2, 225,
  148238. _vq_lengthlist__44u4__p7_1,
  148239. 1, -522338304, 1620115456, 4, 0,
  148240. _vq_quantlist__44u4__p7_1,
  148241. NULL,
  148242. &_vq_auxt__44u4__p7_1,
  148243. NULL,
  148244. 0
  148245. };
  148246. static long _vq_quantlist__44u4__p7_2[] = {
  148247. 8,
  148248. 7,
  148249. 9,
  148250. 6,
  148251. 10,
  148252. 5,
  148253. 11,
  148254. 4,
  148255. 12,
  148256. 3,
  148257. 13,
  148258. 2,
  148259. 14,
  148260. 1,
  148261. 15,
  148262. 0,
  148263. 16,
  148264. };
  148265. static long _vq_lengthlist__44u4__p7_2[] = {
  148266. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148267. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148268. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148269. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148270. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148271. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148272. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148273. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148274. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148275. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148276. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148277. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148278. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148279. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148281. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148282. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148283. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148284. 10,
  148285. };
  148286. static float _vq_quantthresh__44u4__p7_2[] = {
  148287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148289. };
  148290. static long _vq_quantmap__44u4__p7_2[] = {
  148291. 15, 13, 11, 9, 7, 5, 3, 1,
  148292. 0, 2, 4, 6, 8, 10, 12, 14,
  148293. 16,
  148294. };
  148295. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148296. _vq_quantthresh__44u4__p7_2,
  148297. _vq_quantmap__44u4__p7_2,
  148298. 17,
  148299. 17
  148300. };
  148301. static static_codebook _44u4__p7_2 = {
  148302. 2, 289,
  148303. _vq_lengthlist__44u4__p7_2,
  148304. 1, -529530880, 1611661312, 5, 0,
  148305. _vq_quantlist__44u4__p7_2,
  148306. NULL,
  148307. &_vq_auxt__44u4__p7_2,
  148308. NULL,
  148309. 0
  148310. };
  148311. static long _huff_lengthlist__44u4__short[] = {
  148312. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148313. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148314. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148315. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148316. };
  148317. static static_codebook _huff_book__44u4__short = {
  148318. 2, 64,
  148319. _huff_lengthlist__44u4__short,
  148320. 0, 0, 0, 0, 0,
  148321. NULL,
  148322. NULL,
  148323. NULL,
  148324. NULL,
  148325. 0
  148326. };
  148327. static long _huff_lengthlist__44u5__long[] = {
  148328. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148329. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148330. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148331. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148332. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148333. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148334. 14, 8, 7, 8,
  148335. };
  148336. static static_codebook _huff_book__44u5__long = {
  148337. 2, 100,
  148338. _huff_lengthlist__44u5__long,
  148339. 0, 0, 0, 0, 0,
  148340. NULL,
  148341. NULL,
  148342. NULL,
  148343. NULL,
  148344. 0
  148345. };
  148346. static long _vq_quantlist__44u5__p1_0[] = {
  148347. 1,
  148348. 0,
  148349. 2,
  148350. };
  148351. static long _vq_lengthlist__44u5__p1_0[] = {
  148352. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148353. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148354. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148355. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148356. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148357. 12,
  148358. };
  148359. static float _vq_quantthresh__44u5__p1_0[] = {
  148360. -0.5, 0.5,
  148361. };
  148362. static long _vq_quantmap__44u5__p1_0[] = {
  148363. 1, 0, 2,
  148364. };
  148365. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148366. _vq_quantthresh__44u5__p1_0,
  148367. _vq_quantmap__44u5__p1_0,
  148368. 3,
  148369. 3
  148370. };
  148371. static static_codebook _44u5__p1_0 = {
  148372. 4, 81,
  148373. _vq_lengthlist__44u5__p1_0,
  148374. 1, -535822336, 1611661312, 2, 0,
  148375. _vq_quantlist__44u5__p1_0,
  148376. NULL,
  148377. &_vq_auxt__44u5__p1_0,
  148378. NULL,
  148379. 0
  148380. };
  148381. static long _vq_quantlist__44u5__p2_0[] = {
  148382. 1,
  148383. 0,
  148384. 2,
  148385. };
  148386. static long _vq_lengthlist__44u5__p2_0[] = {
  148387. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148388. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148389. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148390. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148391. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148392. 9,
  148393. };
  148394. static float _vq_quantthresh__44u5__p2_0[] = {
  148395. -0.5, 0.5,
  148396. };
  148397. static long _vq_quantmap__44u5__p2_0[] = {
  148398. 1, 0, 2,
  148399. };
  148400. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148401. _vq_quantthresh__44u5__p2_0,
  148402. _vq_quantmap__44u5__p2_0,
  148403. 3,
  148404. 3
  148405. };
  148406. static static_codebook _44u5__p2_0 = {
  148407. 4, 81,
  148408. _vq_lengthlist__44u5__p2_0,
  148409. 1, -535822336, 1611661312, 2, 0,
  148410. _vq_quantlist__44u5__p2_0,
  148411. NULL,
  148412. &_vq_auxt__44u5__p2_0,
  148413. NULL,
  148414. 0
  148415. };
  148416. static long _vq_quantlist__44u5__p3_0[] = {
  148417. 2,
  148418. 1,
  148419. 3,
  148420. 0,
  148421. 4,
  148422. };
  148423. static long _vq_lengthlist__44u5__p3_0[] = {
  148424. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148425. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148426. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148427. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148428. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148429. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148430. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148431. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148432. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148433. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148434. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148435. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148436. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148437. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148438. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148439. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148440. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148441. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148442. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148443. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148444. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148445. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148446. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148447. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148448. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148449. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148450. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148451. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148452. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148453. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148454. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148455. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148456. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148457. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148458. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148459. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148460. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148461. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148462. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148463. 0,
  148464. };
  148465. static float _vq_quantthresh__44u5__p3_0[] = {
  148466. -1.5, -0.5, 0.5, 1.5,
  148467. };
  148468. static long _vq_quantmap__44u5__p3_0[] = {
  148469. 3, 1, 0, 2, 4,
  148470. };
  148471. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148472. _vq_quantthresh__44u5__p3_0,
  148473. _vq_quantmap__44u5__p3_0,
  148474. 5,
  148475. 5
  148476. };
  148477. static static_codebook _44u5__p3_0 = {
  148478. 4, 625,
  148479. _vq_lengthlist__44u5__p3_0,
  148480. 1, -533725184, 1611661312, 3, 0,
  148481. _vq_quantlist__44u5__p3_0,
  148482. NULL,
  148483. &_vq_auxt__44u5__p3_0,
  148484. NULL,
  148485. 0
  148486. };
  148487. static long _vq_quantlist__44u5__p4_0[] = {
  148488. 2,
  148489. 1,
  148490. 3,
  148491. 0,
  148492. 4,
  148493. };
  148494. static long _vq_lengthlist__44u5__p4_0[] = {
  148495. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148496. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148497. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148498. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148499. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148500. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148501. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148502. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148503. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148504. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148505. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148506. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148507. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148508. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148509. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148510. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148511. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148512. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148513. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148514. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148515. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148516. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148517. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148518. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148519. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148520. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148521. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148522. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148523. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148524. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148525. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148526. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148527. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148528. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148529. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148530. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148531. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148532. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148533. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148534. 12,
  148535. };
  148536. static float _vq_quantthresh__44u5__p4_0[] = {
  148537. -1.5, -0.5, 0.5, 1.5,
  148538. };
  148539. static long _vq_quantmap__44u5__p4_0[] = {
  148540. 3, 1, 0, 2, 4,
  148541. };
  148542. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148543. _vq_quantthresh__44u5__p4_0,
  148544. _vq_quantmap__44u5__p4_0,
  148545. 5,
  148546. 5
  148547. };
  148548. static static_codebook _44u5__p4_0 = {
  148549. 4, 625,
  148550. _vq_lengthlist__44u5__p4_0,
  148551. 1, -533725184, 1611661312, 3, 0,
  148552. _vq_quantlist__44u5__p4_0,
  148553. NULL,
  148554. &_vq_auxt__44u5__p4_0,
  148555. NULL,
  148556. 0
  148557. };
  148558. static long _vq_quantlist__44u5__p5_0[] = {
  148559. 4,
  148560. 3,
  148561. 5,
  148562. 2,
  148563. 6,
  148564. 1,
  148565. 7,
  148566. 0,
  148567. 8,
  148568. };
  148569. static long _vq_lengthlist__44u5__p5_0[] = {
  148570. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148571. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148572. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148573. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148574. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148575. 14,
  148576. };
  148577. static float _vq_quantthresh__44u5__p5_0[] = {
  148578. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148579. };
  148580. static long _vq_quantmap__44u5__p5_0[] = {
  148581. 7, 5, 3, 1, 0, 2, 4, 6,
  148582. 8,
  148583. };
  148584. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148585. _vq_quantthresh__44u5__p5_0,
  148586. _vq_quantmap__44u5__p5_0,
  148587. 9,
  148588. 9
  148589. };
  148590. static static_codebook _44u5__p5_0 = {
  148591. 2, 81,
  148592. _vq_lengthlist__44u5__p5_0,
  148593. 1, -531628032, 1611661312, 4, 0,
  148594. _vq_quantlist__44u5__p5_0,
  148595. NULL,
  148596. &_vq_auxt__44u5__p5_0,
  148597. NULL,
  148598. 0
  148599. };
  148600. static long _vq_quantlist__44u5__p6_0[] = {
  148601. 4,
  148602. 3,
  148603. 5,
  148604. 2,
  148605. 6,
  148606. 1,
  148607. 7,
  148608. 0,
  148609. 8,
  148610. };
  148611. static long _vq_lengthlist__44u5__p6_0[] = {
  148612. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148613. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148614. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148615. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148616. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148617. 11,
  148618. };
  148619. static float _vq_quantthresh__44u5__p6_0[] = {
  148620. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148621. };
  148622. static long _vq_quantmap__44u5__p6_0[] = {
  148623. 7, 5, 3, 1, 0, 2, 4, 6,
  148624. 8,
  148625. };
  148626. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148627. _vq_quantthresh__44u5__p6_0,
  148628. _vq_quantmap__44u5__p6_0,
  148629. 9,
  148630. 9
  148631. };
  148632. static static_codebook _44u5__p6_0 = {
  148633. 2, 81,
  148634. _vq_lengthlist__44u5__p6_0,
  148635. 1, -531628032, 1611661312, 4, 0,
  148636. _vq_quantlist__44u5__p6_0,
  148637. NULL,
  148638. &_vq_auxt__44u5__p6_0,
  148639. NULL,
  148640. 0
  148641. };
  148642. static long _vq_quantlist__44u5__p7_0[] = {
  148643. 1,
  148644. 0,
  148645. 2,
  148646. };
  148647. static long _vq_lengthlist__44u5__p7_0[] = {
  148648. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148649. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148650. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148651. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148652. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148653. 12,
  148654. };
  148655. static float _vq_quantthresh__44u5__p7_0[] = {
  148656. -5.5, 5.5,
  148657. };
  148658. static long _vq_quantmap__44u5__p7_0[] = {
  148659. 1, 0, 2,
  148660. };
  148661. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148662. _vq_quantthresh__44u5__p7_0,
  148663. _vq_quantmap__44u5__p7_0,
  148664. 3,
  148665. 3
  148666. };
  148667. static static_codebook _44u5__p7_0 = {
  148668. 4, 81,
  148669. _vq_lengthlist__44u5__p7_0,
  148670. 1, -529137664, 1618345984, 2, 0,
  148671. _vq_quantlist__44u5__p7_0,
  148672. NULL,
  148673. &_vq_auxt__44u5__p7_0,
  148674. NULL,
  148675. 0
  148676. };
  148677. static long _vq_quantlist__44u5__p7_1[] = {
  148678. 5,
  148679. 4,
  148680. 6,
  148681. 3,
  148682. 7,
  148683. 2,
  148684. 8,
  148685. 1,
  148686. 9,
  148687. 0,
  148688. 10,
  148689. };
  148690. static long _vq_lengthlist__44u5__p7_1[] = {
  148691. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148692. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148693. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148694. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148695. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148696. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148697. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148698. 9, 9, 9, 9, 9,10,10,10,10,
  148699. };
  148700. static float _vq_quantthresh__44u5__p7_1[] = {
  148701. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148702. 3.5, 4.5,
  148703. };
  148704. static long _vq_quantmap__44u5__p7_1[] = {
  148705. 9, 7, 5, 3, 1, 0, 2, 4,
  148706. 6, 8, 10,
  148707. };
  148708. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148709. _vq_quantthresh__44u5__p7_1,
  148710. _vq_quantmap__44u5__p7_1,
  148711. 11,
  148712. 11
  148713. };
  148714. static static_codebook _44u5__p7_1 = {
  148715. 2, 121,
  148716. _vq_lengthlist__44u5__p7_1,
  148717. 1, -531365888, 1611661312, 4, 0,
  148718. _vq_quantlist__44u5__p7_1,
  148719. NULL,
  148720. &_vq_auxt__44u5__p7_1,
  148721. NULL,
  148722. 0
  148723. };
  148724. static long _vq_quantlist__44u5__p8_0[] = {
  148725. 5,
  148726. 4,
  148727. 6,
  148728. 3,
  148729. 7,
  148730. 2,
  148731. 8,
  148732. 1,
  148733. 9,
  148734. 0,
  148735. 10,
  148736. };
  148737. static long _vq_lengthlist__44u5__p8_0[] = {
  148738. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148739. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148740. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148741. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148742. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148743. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148744. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148745. 12,13,13,14,14,14,14,15,15,
  148746. };
  148747. static float _vq_quantthresh__44u5__p8_0[] = {
  148748. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148749. 38.5, 49.5,
  148750. };
  148751. static long _vq_quantmap__44u5__p8_0[] = {
  148752. 9, 7, 5, 3, 1, 0, 2, 4,
  148753. 6, 8, 10,
  148754. };
  148755. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148756. _vq_quantthresh__44u5__p8_0,
  148757. _vq_quantmap__44u5__p8_0,
  148758. 11,
  148759. 11
  148760. };
  148761. static static_codebook _44u5__p8_0 = {
  148762. 2, 121,
  148763. _vq_lengthlist__44u5__p8_0,
  148764. 1, -524582912, 1618345984, 4, 0,
  148765. _vq_quantlist__44u5__p8_0,
  148766. NULL,
  148767. &_vq_auxt__44u5__p8_0,
  148768. NULL,
  148769. 0
  148770. };
  148771. static long _vq_quantlist__44u5__p8_1[] = {
  148772. 5,
  148773. 4,
  148774. 6,
  148775. 3,
  148776. 7,
  148777. 2,
  148778. 8,
  148779. 1,
  148780. 9,
  148781. 0,
  148782. 10,
  148783. };
  148784. static long _vq_lengthlist__44u5__p8_1[] = {
  148785. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148786. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148787. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148788. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148789. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148790. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148791. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148792. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148793. };
  148794. static float _vq_quantthresh__44u5__p8_1[] = {
  148795. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148796. 3.5, 4.5,
  148797. };
  148798. static long _vq_quantmap__44u5__p8_1[] = {
  148799. 9, 7, 5, 3, 1, 0, 2, 4,
  148800. 6, 8, 10,
  148801. };
  148802. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148803. _vq_quantthresh__44u5__p8_1,
  148804. _vq_quantmap__44u5__p8_1,
  148805. 11,
  148806. 11
  148807. };
  148808. static static_codebook _44u5__p8_1 = {
  148809. 2, 121,
  148810. _vq_lengthlist__44u5__p8_1,
  148811. 1, -531365888, 1611661312, 4, 0,
  148812. _vq_quantlist__44u5__p8_1,
  148813. NULL,
  148814. &_vq_auxt__44u5__p8_1,
  148815. NULL,
  148816. 0
  148817. };
  148818. static long _vq_quantlist__44u5__p9_0[] = {
  148819. 6,
  148820. 5,
  148821. 7,
  148822. 4,
  148823. 8,
  148824. 3,
  148825. 9,
  148826. 2,
  148827. 10,
  148828. 1,
  148829. 11,
  148830. 0,
  148831. 12,
  148832. };
  148833. static long _vq_lengthlist__44u5__p9_0[] = {
  148834. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148835. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148836. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148837. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148838. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148839. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148840. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148841. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148842. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148843. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148844. 12,12,12,12,12,12,12,12,12,
  148845. };
  148846. static float _vq_quantthresh__44u5__p9_0[] = {
  148847. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148848. 637.5, 892.5, 1147.5, 1402.5,
  148849. };
  148850. static long _vq_quantmap__44u5__p9_0[] = {
  148851. 11, 9, 7, 5, 3, 1, 0, 2,
  148852. 4, 6, 8, 10, 12,
  148853. };
  148854. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148855. _vq_quantthresh__44u5__p9_0,
  148856. _vq_quantmap__44u5__p9_0,
  148857. 13,
  148858. 13
  148859. };
  148860. static static_codebook _44u5__p9_0 = {
  148861. 2, 169,
  148862. _vq_lengthlist__44u5__p9_0,
  148863. 1, -514332672, 1627381760, 4, 0,
  148864. _vq_quantlist__44u5__p9_0,
  148865. NULL,
  148866. &_vq_auxt__44u5__p9_0,
  148867. NULL,
  148868. 0
  148869. };
  148870. static long _vq_quantlist__44u5__p9_1[] = {
  148871. 7,
  148872. 6,
  148873. 8,
  148874. 5,
  148875. 9,
  148876. 4,
  148877. 10,
  148878. 3,
  148879. 11,
  148880. 2,
  148881. 12,
  148882. 1,
  148883. 13,
  148884. 0,
  148885. 14,
  148886. };
  148887. static long _vq_lengthlist__44u5__p9_1[] = {
  148888. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148889. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148890. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148891. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148892. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148893. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148894. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148895. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148896. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148897. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148898. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148899. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148900. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148901. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148902. 14,
  148903. };
  148904. static float _vq_quantthresh__44u5__p9_1[] = {
  148905. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148906. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148907. };
  148908. static long _vq_quantmap__44u5__p9_1[] = {
  148909. 13, 11, 9, 7, 5, 3, 1, 0,
  148910. 2, 4, 6, 8, 10, 12, 14,
  148911. };
  148912. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148913. _vq_quantthresh__44u5__p9_1,
  148914. _vq_quantmap__44u5__p9_1,
  148915. 15,
  148916. 15
  148917. };
  148918. static static_codebook _44u5__p9_1 = {
  148919. 2, 225,
  148920. _vq_lengthlist__44u5__p9_1,
  148921. 1, -522338304, 1620115456, 4, 0,
  148922. _vq_quantlist__44u5__p9_1,
  148923. NULL,
  148924. &_vq_auxt__44u5__p9_1,
  148925. NULL,
  148926. 0
  148927. };
  148928. static long _vq_quantlist__44u5__p9_2[] = {
  148929. 8,
  148930. 7,
  148931. 9,
  148932. 6,
  148933. 10,
  148934. 5,
  148935. 11,
  148936. 4,
  148937. 12,
  148938. 3,
  148939. 13,
  148940. 2,
  148941. 14,
  148942. 1,
  148943. 15,
  148944. 0,
  148945. 16,
  148946. };
  148947. static long _vq_lengthlist__44u5__p9_2[] = {
  148948. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148949. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148950. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148951. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148952. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148953. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148954. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148955. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148956. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148957. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148958. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148959. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148960. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148961. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148962. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148963. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148964. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148965. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148966. 10,
  148967. };
  148968. static float _vq_quantthresh__44u5__p9_2[] = {
  148969. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148970. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148971. };
  148972. static long _vq_quantmap__44u5__p9_2[] = {
  148973. 15, 13, 11, 9, 7, 5, 3, 1,
  148974. 0, 2, 4, 6, 8, 10, 12, 14,
  148975. 16,
  148976. };
  148977. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148978. _vq_quantthresh__44u5__p9_2,
  148979. _vq_quantmap__44u5__p9_2,
  148980. 17,
  148981. 17
  148982. };
  148983. static static_codebook _44u5__p9_2 = {
  148984. 2, 289,
  148985. _vq_lengthlist__44u5__p9_2,
  148986. 1, -529530880, 1611661312, 5, 0,
  148987. _vq_quantlist__44u5__p9_2,
  148988. NULL,
  148989. &_vq_auxt__44u5__p9_2,
  148990. NULL,
  148991. 0
  148992. };
  148993. static long _huff_lengthlist__44u5__short[] = {
  148994. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148995. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148996. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148997. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148998. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148999. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149000. 6, 8,15,17,
  149001. };
  149002. static static_codebook _huff_book__44u5__short = {
  149003. 2, 100,
  149004. _huff_lengthlist__44u5__short,
  149005. 0, 0, 0, 0, 0,
  149006. NULL,
  149007. NULL,
  149008. NULL,
  149009. NULL,
  149010. 0
  149011. };
  149012. static long _huff_lengthlist__44u6__long[] = {
  149013. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149014. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149015. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149016. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149017. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149018. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149019. 13, 8, 7, 7,
  149020. };
  149021. static static_codebook _huff_book__44u6__long = {
  149022. 2, 100,
  149023. _huff_lengthlist__44u6__long,
  149024. 0, 0, 0, 0, 0,
  149025. NULL,
  149026. NULL,
  149027. NULL,
  149028. NULL,
  149029. 0
  149030. };
  149031. static long _vq_quantlist__44u6__p1_0[] = {
  149032. 1,
  149033. 0,
  149034. 2,
  149035. };
  149036. static long _vq_lengthlist__44u6__p1_0[] = {
  149037. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149038. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149039. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149040. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149041. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149042. 12,
  149043. };
  149044. static float _vq_quantthresh__44u6__p1_0[] = {
  149045. -0.5, 0.5,
  149046. };
  149047. static long _vq_quantmap__44u6__p1_0[] = {
  149048. 1, 0, 2,
  149049. };
  149050. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149051. _vq_quantthresh__44u6__p1_0,
  149052. _vq_quantmap__44u6__p1_0,
  149053. 3,
  149054. 3
  149055. };
  149056. static static_codebook _44u6__p1_0 = {
  149057. 4, 81,
  149058. _vq_lengthlist__44u6__p1_0,
  149059. 1, -535822336, 1611661312, 2, 0,
  149060. _vq_quantlist__44u6__p1_0,
  149061. NULL,
  149062. &_vq_auxt__44u6__p1_0,
  149063. NULL,
  149064. 0
  149065. };
  149066. static long _vq_quantlist__44u6__p2_0[] = {
  149067. 1,
  149068. 0,
  149069. 2,
  149070. };
  149071. static long _vq_lengthlist__44u6__p2_0[] = {
  149072. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149073. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149074. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149075. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149076. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149077. 9,
  149078. };
  149079. static float _vq_quantthresh__44u6__p2_0[] = {
  149080. -0.5, 0.5,
  149081. };
  149082. static long _vq_quantmap__44u6__p2_0[] = {
  149083. 1, 0, 2,
  149084. };
  149085. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149086. _vq_quantthresh__44u6__p2_0,
  149087. _vq_quantmap__44u6__p2_0,
  149088. 3,
  149089. 3
  149090. };
  149091. static static_codebook _44u6__p2_0 = {
  149092. 4, 81,
  149093. _vq_lengthlist__44u6__p2_0,
  149094. 1, -535822336, 1611661312, 2, 0,
  149095. _vq_quantlist__44u6__p2_0,
  149096. NULL,
  149097. &_vq_auxt__44u6__p2_0,
  149098. NULL,
  149099. 0
  149100. };
  149101. static long _vq_quantlist__44u6__p3_0[] = {
  149102. 2,
  149103. 1,
  149104. 3,
  149105. 0,
  149106. 4,
  149107. };
  149108. static long _vq_lengthlist__44u6__p3_0[] = {
  149109. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149110. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149111. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149112. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149113. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149114. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149115. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149116. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149117. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149118. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149119. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149120. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149121. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149122. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149123. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149124. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149125. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149126. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149127. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149128. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149129. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149130. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149131. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149132. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149133. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149134. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149135. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149136. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149137. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149138. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149139. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149140. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149141. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149142. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149143. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149144. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149145. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149146. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149147. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149148. 19,
  149149. };
  149150. static float _vq_quantthresh__44u6__p3_0[] = {
  149151. -1.5, -0.5, 0.5, 1.5,
  149152. };
  149153. static long _vq_quantmap__44u6__p3_0[] = {
  149154. 3, 1, 0, 2, 4,
  149155. };
  149156. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149157. _vq_quantthresh__44u6__p3_0,
  149158. _vq_quantmap__44u6__p3_0,
  149159. 5,
  149160. 5
  149161. };
  149162. static static_codebook _44u6__p3_0 = {
  149163. 4, 625,
  149164. _vq_lengthlist__44u6__p3_0,
  149165. 1, -533725184, 1611661312, 3, 0,
  149166. _vq_quantlist__44u6__p3_0,
  149167. NULL,
  149168. &_vq_auxt__44u6__p3_0,
  149169. NULL,
  149170. 0
  149171. };
  149172. static long _vq_quantlist__44u6__p4_0[] = {
  149173. 2,
  149174. 1,
  149175. 3,
  149176. 0,
  149177. 4,
  149178. };
  149179. static long _vq_lengthlist__44u6__p4_0[] = {
  149180. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149181. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149182. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149183. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149184. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149185. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149186. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149187. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149188. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149189. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149190. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149191. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149192. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149193. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149194. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149195. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149196. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149197. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149198. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149199. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149200. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149201. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149202. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149203. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149204. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149205. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149206. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149207. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149208. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149209. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149210. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149211. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149212. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149213. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149214. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149215. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149216. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149217. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149218. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149219. 13,
  149220. };
  149221. static float _vq_quantthresh__44u6__p4_0[] = {
  149222. -1.5, -0.5, 0.5, 1.5,
  149223. };
  149224. static long _vq_quantmap__44u6__p4_0[] = {
  149225. 3, 1, 0, 2, 4,
  149226. };
  149227. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149228. _vq_quantthresh__44u6__p4_0,
  149229. _vq_quantmap__44u6__p4_0,
  149230. 5,
  149231. 5
  149232. };
  149233. static static_codebook _44u6__p4_0 = {
  149234. 4, 625,
  149235. _vq_lengthlist__44u6__p4_0,
  149236. 1, -533725184, 1611661312, 3, 0,
  149237. _vq_quantlist__44u6__p4_0,
  149238. NULL,
  149239. &_vq_auxt__44u6__p4_0,
  149240. NULL,
  149241. 0
  149242. };
  149243. static long _vq_quantlist__44u6__p5_0[] = {
  149244. 4,
  149245. 3,
  149246. 5,
  149247. 2,
  149248. 6,
  149249. 1,
  149250. 7,
  149251. 0,
  149252. 8,
  149253. };
  149254. static long _vq_lengthlist__44u6__p5_0[] = {
  149255. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149256. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149257. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149258. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149259. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149260. 14,
  149261. };
  149262. static float _vq_quantthresh__44u6__p5_0[] = {
  149263. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149264. };
  149265. static long _vq_quantmap__44u6__p5_0[] = {
  149266. 7, 5, 3, 1, 0, 2, 4, 6,
  149267. 8,
  149268. };
  149269. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149270. _vq_quantthresh__44u6__p5_0,
  149271. _vq_quantmap__44u6__p5_0,
  149272. 9,
  149273. 9
  149274. };
  149275. static static_codebook _44u6__p5_0 = {
  149276. 2, 81,
  149277. _vq_lengthlist__44u6__p5_0,
  149278. 1, -531628032, 1611661312, 4, 0,
  149279. _vq_quantlist__44u6__p5_0,
  149280. NULL,
  149281. &_vq_auxt__44u6__p5_0,
  149282. NULL,
  149283. 0
  149284. };
  149285. static long _vq_quantlist__44u6__p6_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__44u6__p6_0[] = {
  149297. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149298. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149299. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149300. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149301. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149302. 12,
  149303. };
  149304. static float _vq_quantthresh__44u6__p6_0[] = {
  149305. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149306. };
  149307. static long _vq_quantmap__44u6__p6_0[] = {
  149308. 7, 5, 3, 1, 0, 2, 4, 6,
  149309. 8,
  149310. };
  149311. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149312. _vq_quantthresh__44u6__p6_0,
  149313. _vq_quantmap__44u6__p6_0,
  149314. 9,
  149315. 9
  149316. };
  149317. static static_codebook _44u6__p6_0 = {
  149318. 2, 81,
  149319. _vq_lengthlist__44u6__p6_0,
  149320. 1, -531628032, 1611661312, 4, 0,
  149321. _vq_quantlist__44u6__p6_0,
  149322. NULL,
  149323. &_vq_auxt__44u6__p6_0,
  149324. NULL,
  149325. 0
  149326. };
  149327. static long _vq_quantlist__44u6__p7_0[] = {
  149328. 1,
  149329. 0,
  149330. 2,
  149331. };
  149332. static long _vq_lengthlist__44u6__p7_0[] = {
  149333. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149334. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149335. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149336. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149337. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149338. 10,
  149339. };
  149340. static float _vq_quantthresh__44u6__p7_0[] = {
  149341. -5.5, 5.5,
  149342. };
  149343. static long _vq_quantmap__44u6__p7_0[] = {
  149344. 1, 0, 2,
  149345. };
  149346. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149347. _vq_quantthresh__44u6__p7_0,
  149348. _vq_quantmap__44u6__p7_0,
  149349. 3,
  149350. 3
  149351. };
  149352. static static_codebook _44u6__p7_0 = {
  149353. 4, 81,
  149354. _vq_lengthlist__44u6__p7_0,
  149355. 1, -529137664, 1618345984, 2, 0,
  149356. _vq_quantlist__44u6__p7_0,
  149357. NULL,
  149358. &_vq_auxt__44u6__p7_0,
  149359. NULL,
  149360. 0
  149361. };
  149362. static long _vq_quantlist__44u6__p7_1[] = {
  149363. 5,
  149364. 4,
  149365. 6,
  149366. 3,
  149367. 7,
  149368. 2,
  149369. 8,
  149370. 1,
  149371. 9,
  149372. 0,
  149373. 10,
  149374. };
  149375. static long _vq_lengthlist__44u6__p7_1[] = {
  149376. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149377. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149378. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149379. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149380. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149381. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149382. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149383. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149384. };
  149385. static float _vq_quantthresh__44u6__p7_1[] = {
  149386. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149387. 3.5, 4.5,
  149388. };
  149389. static long _vq_quantmap__44u6__p7_1[] = {
  149390. 9, 7, 5, 3, 1, 0, 2, 4,
  149391. 6, 8, 10,
  149392. };
  149393. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149394. _vq_quantthresh__44u6__p7_1,
  149395. _vq_quantmap__44u6__p7_1,
  149396. 11,
  149397. 11
  149398. };
  149399. static static_codebook _44u6__p7_1 = {
  149400. 2, 121,
  149401. _vq_lengthlist__44u6__p7_1,
  149402. 1, -531365888, 1611661312, 4, 0,
  149403. _vq_quantlist__44u6__p7_1,
  149404. NULL,
  149405. &_vq_auxt__44u6__p7_1,
  149406. NULL,
  149407. 0
  149408. };
  149409. static long _vq_quantlist__44u6__p8_0[] = {
  149410. 5,
  149411. 4,
  149412. 6,
  149413. 3,
  149414. 7,
  149415. 2,
  149416. 8,
  149417. 1,
  149418. 9,
  149419. 0,
  149420. 10,
  149421. };
  149422. static long _vq_lengthlist__44u6__p8_0[] = {
  149423. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149424. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149425. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149426. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149427. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149428. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149429. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149430. 12,13,13,14,14,14,15,15,15,
  149431. };
  149432. static float _vq_quantthresh__44u6__p8_0[] = {
  149433. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149434. 38.5, 49.5,
  149435. };
  149436. static long _vq_quantmap__44u6__p8_0[] = {
  149437. 9, 7, 5, 3, 1, 0, 2, 4,
  149438. 6, 8, 10,
  149439. };
  149440. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149441. _vq_quantthresh__44u6__p8_0,
  149442. _vq_quantmap__44u6__p8_0,
  149443. 11,
  149444. 11
  149445. };
  149446. static static_codebook _44u6__p8_0 = {
  149447. 2, 121,
  149448. _vq_lengthlist__44u6__p8_0,
  149449. 1, -524582912, 1618345984, 4, 0,
  149450. _vq_quantlist__44u6__p8_0,
  149451. NULL,
  149452. &_vq_auxt__44u6__p8_0,
  149453. NULL,
  149454. 0
  149455. };
  149456. static long _vq_quantlist__44u6__p8_1[] = {
  149457. 5,
  149458. 4,
  149459. 6,
  149460. 3,
  149461. 7,
  149462. 2,
  149463. 8,
  149464. 1,
  149465. 9,
  149466. 0,
  149467. 10,
  149468. };
  149469. static long _vq_lengthlist__44u6__p8_1[] = {
  149470. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149471. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149472. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149473. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149474. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149475. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149476. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149477. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149478. };
  149479. static float _vq_quantthresh__44u6__p8_1[] = {
  149480. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149481. 3.5, 4.5,
  149482. };
  149483. static long _vq_quantmap__44u6__p8_1[] = {
  149484. 9, 7, 5, 3, 1, 0, 2, 4,
  149485. 6, 8, 10,
  149486. };
  149487. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149488. _vq_quantthresh__44u6__p8_1,
  149489. _vq_quantmap__44u6__p8_1,
  149490. 11,
  149491. 11
  149492. };
  149493. static static_codebook _44u6__p8_1 = {
  149494. 2, 121,
  149495. _vq_lengthlist__44u6__p8_1,
  149496. 1, -531365888, 1611661312, 4, 0,
  149497. _vq_quantlist__44u6__p8_1,
  149498. NULL,
  149499. &_vq_auxt__44u6__p8_1,
  149500. NULL,
  149501. 0
  149502. };
  149503. static long _vq_quantlist__44u6__p9_0[] = {
  149504. 7,
  149505. 6,
  149506. 8,
  149507. 5,
  149508. 9,
  149509. 4,
  149510. 10,
  149511. 3,
  149512. 11,
  149513. 2,
  149514. 12,
  149515. 1,
  149516. 13,
  149517. 0,
  149518. 14,
  149519. };
  149520. static long _vq_lengthlist__44u6__p9_0[] = {
  149521. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149522. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149523. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149524. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149525. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149526. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149527. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149528. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149529. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149530. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149531. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149532. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149533. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149534. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149535. 14,
  149536. };
  149537. static float _vq_quantthresh__44u6__p9_0[] = {
  149538. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149539. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149540. };
  149541. static long _vq_quantmap__44u6__p9_0[] = {
  149542. 13, 11, 9, 7, 5, 3, 1, 0,
  149543. 2, 4, 6, 8, 10, 12, 14,
  149544. };
  149545. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149546. _vq_quantthresh__44u6__p9_0,
  149547. _vq_quantmap__44u6__p9_0,
  149548. 15,
  149549. 15
  149550. };
  149551. static static_codebook _44u6__p9_0 = {
  149552. 2, 225,
  149553. _vq_lengthlist__44u6__p9_0,
  149554. 1, -514071552, 1627381760, 4, 0,
  149555. _vq_quantlist__44u6__p9_0,
  149556. NULL,
  149557. &_vq_auxt__44u6__p9_0,
  149558. NULL,
  149559. 0
  149560. };
  149561. static long _vq_quantlist__44u6__p9_1[] = {
  149562. 7,
  149563. 6,
  149564. 8,
  149565. 5,
  149566. 9,
  149567. 4,
  149568. 10,
  149569. 3,
  149570. 11,
  149571. 2,
  149572. 12,
  149573. 1,
  149574. 13,
  149575. 0,
  149576. 14,
  149577. };
  149578. static long _vq_lengthlist__44u6__p9_1[] = {
  149579. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149580. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149581. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149582. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149583. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149584. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149585. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149586. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149587. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149588. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149589. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149590. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149591. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149592. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149593. 13,
  149594. };
  149595. static float _vq_quantthresh__44u6__p9_1[] = {
  149596. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149597. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149598. };
  149599. static long _vq_quantmap__44u6__p9_1[] = {
  149600. 13, 11, 9, 7, 5, 3, 1, 0,
  149601. 2, 4, 6, 8, 10, 12, 14,
  149602. };
  149603. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149604. _vq_quantthresh__44u6__p9_1,
  149605. _vq_quantmap__44u6__p9_1,
  149606. 15,
  149607. 15
  149608. };
  149609. static static_codebook _44u6__p9_1 = {
  149610. 2, 225,
  149611. _vq_lengthlist__44u6__p9_1,
  149612. 1, -522338304, 1620115456, 4, 0,
  149613. _vq_quantlist__44u6__p9_1,
  149614. NULL,
  149615. &_vq_auxt__44u6__p9_1,
  149616. NULL,
  149617. 0
  149618. };
  149619. static long _vq_quantlist__44u6__p9_2[] = {
  149620. 8,
  149621. 7,
  149622. 9,
  149623. 6,
  149624. 10,
  149625. 5,
  149626. 11,
  149627. 4,
  149628. 12,
  149629. 3,
  149630. 13,
  149631. 2,
  149632. 14,
  149633. 1,
  149634. 15,
  149635. 0,
  149636. 16,
  149637. };
  149638. static long _vq_lengthlist__44u6__p9_2[] = {
  149639. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149640. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149641. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149642. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149643. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149644. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149645. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149646. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149647. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149648. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149649. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149651. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149652. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149653. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149654. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149655. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149656. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149657. 10,
  149658. };
  149659. static float _vq_quantthresh__44u6__p9_2[] = {
  149660. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149661. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149662. };
  149663. static long _vq_quantmap__44u6__p9_2[] = {
  149664. 15, 13, 11, 9, 7, 5, 3, 1,
  149665. 0, 2, 4, 6, 8, 10, 12, 14,
  149666. 16,
  149667. };
  149668. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149669. _vq_quantthresh__44u6__p9_2,
  149670. _vq_quantmap__44u6__p9_2,
  149671. 17,
  149672. 17
  149673. };
  149674. static static_codebook _44u6__p9_2 = {
  149675. 2, 289,
  149676. _vq_lengthlist__44u6__p9_2,
  149677. 1, -529530880, 1611661312, 5, 0,
  149678. _vq_quantlist__44u6__p9_2,
  149679. NULL,
  149680. &_vq_auxt__44u6__p9_2,
  149681. NULL,
  149682. 0
  149683. };
  149684. static long _huff_lengthlist__44u6__short[] = {
  149685. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149686. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149687. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149688. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149689. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149690. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149691. 7, 6, 9,16,
  149692. };
  149693. static static_codebook _huff_book__44u6__short = {
  149694. 2, 100,
  149695. _huff_lengthlist__44u6__short,
  149696. 0, 0, 0, 0, 0,
  149697. NULL,
  149698. NULL,
  149699. NULL,
  149700. NULL,
  149701. 0
  149702. };
  149703. static long _huff_lengthlist__44u7__long[] = {
  149704. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149705. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149706. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149707. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149708. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149709. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149710. 12, 8, 6, 7,
  149711. };
  149712. static static_codebook _huff_book__44u7__long = {
  149713. 2, 100,
  149714. _huff_lengthlist__44u7__long,
  149715. 0, 0, 0, 0, 0,
  149716. NULL,
  149717. NULL,
  149718. NULL,
  149719. NULL,
  149720. 0
  149721. };
  149722. static long _vq_quantlist__44u7__p1_0[] = {
  149723. 1,
  149724. 0,
  149725. 2,
  149726. };
  149727. static long _vq_lengthlist__44u7__p1_0[] = {
  149728. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149729. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149730. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149731. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149732. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149733. 12,
  149734. };
  149735. static float _vq_quantthresh__44u7__p1_0[] = {
  149736. -0.5, 0.5,
  149737. };
  149738. static long _vq_quantmap__44u7__p1_0[] = {
  149739. 1, 0, 2,
  149740. };
  149741. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149742. _vq_quantthresh__44u7__p1_0,
  149743. _vq_quantmap__44u7__p1_0,
  149744. 3,
  149745. 3
  149746. };
  149747. static static_codebook _44u7__p1_0 = {
  149748. 4, 81,
  149749. _vq_lengthlist__44u7__p1_0,
  149750. 1, -535822336, 1611661312, 2, 0,
  149751. _vq_quantlist__44u7__p1_0,
  149752. NULL,
  149753. &_vq_auxt__44u7__p1_0,
  149754. NULL,
  149755. 0
  149756. };
  149757. static long _vq_quantlist__44u7__p2_0[] = {
  149758. 1,
  149759. 0,
  149760. 2,
  149761. };
  149762. static long _vq_lengthlist__44u7__p2_0[] = {
  149763. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149764. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149765. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149766. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149767. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149768. 9,
  149769. };
  149770. static float _vq_quantthresh__44u7__p2_0[] = {
  149771. -0.5, 0.5,
  149772. };
  149773. static long _vq_quantmap__44u7__p2_0[] = {
  149774. 1, 0, 2,
  149775. };
  149776. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149777. _vq_quantthresh__44u7__p2_0,
  149778. _vq_quantmap__44u7__p2_0,
  149779. 3,
  149780. 3
  149781. };
  149782. static static_codebook _44u7__p2_0 = {
  149783. 4, 81,
  149784. _vq_lengthlist__44u7__p2_0,
  149785. 1, -535822336, 1611661312, 2, 0,
  149786. _vq_quantlist__44u7__p2_0,
  149787. NULL,
  149788. &_vq_auxt__44u7__p2_0,
  149789. NULL,
  149790. 0
  149791. };
  149792. static long _vq_quantlist__44u7__p3_0[] = {
  149793. 2,
  149794. 1,
  149795. 3,
  149796. 0,
  149797. 4,
  149798. };
  149799. static long _vq_lengthlist__44u7__p3_0[] = {
  149800. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149801. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149802. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149803. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149804. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149805. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149806. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149807. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149808. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149809. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149810. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149811. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149812. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149813. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149814. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149815. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149816. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149817. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149818. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149819. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149820. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149821. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149822. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149823. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149824. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149825. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149826. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149827. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149828. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149829. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149830. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149831. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149832. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149833. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149834. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149835. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149836. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149837. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149838. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149839. 0,
  149840. };
  149841. static float _vq_quantthresh__44u7__p3_0[] = {
  149842. -1.5, -0.5, 0.5, 1.5,
  149843. };
  149844. static long _vq_quantmap__44u7__p3_0[] = {
  149845. 3, 1, 0, 2, 4,
  149846. };
  149847. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149848. _vq_quantthresh__44u7__p3_0,
  149849. _vq_quantmap__44u7__p3_0,
  149850. 5,
  149851. 5
  149852. };
  149853. static static_codebook _44u7__p3_0 = {
  149854. 4, 625,
  149855. _vq_lengthlist__44u7__p3_0,
  149856. 1, -533725184, 1611661312, 3, 0,
  149857. _vq_quantlist__44u7__p3_0,
  149858. NULL,
  149859. &_vq_auxt__44u7__p3_0,
  149860. NULL,
  149861. 0
  149862. };
  149863. static long _vq_quantlist__44u7__p4_0[] = {
  149864. 2,
  149865. 1,
  149866. 3,
  149867. 0,
  149868. 4,
  149869. };
  149870. static long _vq_lengthlist__44u7__p4_0[] = {
  149871. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149872. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149873. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149874. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149875. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149876. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149877. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149878. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149879. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149880. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149881. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149882. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149883. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149884. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149885. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149886. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149887. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149888. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149889. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149890. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149891. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149892. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149893. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149894. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149895. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149896. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149897. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149898. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149899. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149900. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149901. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149902. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149903. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149904. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149905. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149906. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149907. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149908. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149909. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149910. 14,
  149911. };
  149912. static float _vq_quantthresh__44u7__p4_0[] = {
  149913. -1.5, -0.5, 0.5, 1.5,
  149914. };
  149915. static long _vq_quantmap__44u7__p4_0[] = {
  149916. 3, 1, 0, 2, 4,
  149917. };
  149918. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149919. _vq_quantthresh__44u7__p4_0,
  149920. _vq_quantmap__44u7__p4_0,
  149921. 5,
  149922. 5
  149923. };
  149924. static static_codebook _44u7__p4_0 = {
  149925. 4, 625,
  149926. _vq_lengthlist__44u7__p4_0,
  149927. 1, -533725184, 1611661312, 3, 0,
  149928. _vq_quantlist__44u7__p4_0,
  149929. NULL,
  149930. &_vq_auxt__44u7__p4_0,
  149931. NULL,
  149932. 0
  149933. };
  149934. static long _vq_quantlist__44u7__p5_0[] = {
  149935. 4,
  149936. 3,
  149937. 5,
  149938. 2,
  149939. 6,
  149940. 1,
  149941. 7,
  149942. 0,
  149943. 8,
  149944. };
  149945. static long _vq_lengthlist__44u7__p5_0[] = {
  149946. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149947. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149948. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149949. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149950. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149951. 14,
  149952. };
  149953. static float _vq_quantthresh__44u7__p5_0[] = {
  149954. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149955. };
  149956. static long _vq_quantmap__44u7__p5_0[] = {
  149957. 7, 5, 3, 1, 0, 2, 4, 6,
  149958. 8,
  149959. };
  149960. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149961. _vq_quantthresh__44u7__p5_0,
  149962. _vq_quantmap__44u7__p5_0,
  149963. 9,
  149964. 9
  149965. };
  149966. static static_codebook _44u7__p5_0 = {
  149967. 2, 81,
  149968. _vq_lengthlist__44u7__p5_0,
  149969. 1, -531628032, 1611661312, 4, 0,
  149970. _vq_quantlist__44u7__p5_0,
  149971. NULL,
  149972. &_vq_auxt__44u7__p5_0,
  149973. NULL,
  149974. 0
  149975. };
  149976. static long _vq_quantlist__44u7__p6_0[] = {
  149977. 4,
  149978. 3,
  149979. 5,
  149980. 2,
  149981. 6,
  149982. 1,
  149983. 7,
  149984. 0,
  149985. 8,
  149986. };
  149987. static long _vq_lengthlist__44u7__p6_0[] = {
  149988. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149989. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149990. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149991. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149992. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149993. 12,
  149994. };
  149995. static float _vq_quantthresh__44u7__p6_0[] = {
  149996. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149997. };
  149998. static long _vq_quantmap__44u7__p6_0[] = {
  149999. 7, 5, 3, 1, 0, 2, 4, 6,
  150000. 8,
  150001. };
  150002. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150003. _vq_quantthresh__44u7__p6_0,
  150004. _vq_quantmap__44u7__p6_0,
  150005. 9,
  150006. 9
  150007. };
  150008. static static_codebook _44u7__p6_0 = {
  150009. 2, 81,
  150010. _vq_lengthlist__44u7__p6_0,
  150011. 1, -531628032, 1611661312, 4, 0,
  150012. _vq_quantlist__44u7__p6_0,
  150013. NULL,
  150014. &_vq_auxt__44u7__p6_0,
  150015. NULL,
  150016. 0
  150017. };
  150018. static long _vq_quantlist__44u7__p7_0[] = {
  150019. 1,
  150020. 0,
  150021. 2,
  150022. };
  150023. static long _vq_lengthlist__44u7__p7_0[] = {
  150024. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150025. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150026. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150027. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150028. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150029. 10,
  150030. };
  150031. static float _vq_quantthresh__44u7__p7_0[] = {
  150032. -5.5, 5.5,
  150033. };
  150034. static long _vq_quantmap__44u7__p7_0[] = {
  150035. 1, 0, 2,
  150036. };
  150037. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150038. _vq_quantthresh__44u7__p7_0,
  150039. _vq_quantmap__44u7__p7_0,
  150040. 3,
  150041. 3
  150042. };
  150043. static static_codebook _44u7__p7_0 = {
  150044. 4, 81,
  150045. _vq_lengthlist__44u7__p7_0,
  150046. 1, -529137664, 1618345984, 2, 0,
  150047. _vq_quantlist__44u7__p7_0,
  150048. NULL,
  150049. &_vq_auxt__44u7__p7_0,
  150050. NULL,
  150051. 0
  150052. };
  150053. static long _vq_quantlist__44u7__p7_1[] = {
  150054. 5,
  150055. 4,
  150056. 6,
  150057. 3,
  150058. 7,
  150059. 2,
  150060. 8,
  150061. 1,
  150062. 9,
  150063. 0,
  150064. 10,
  150065. };
  150066. static long _vq_lengthlist__44u7__p7_1[] = {
  150067. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150068. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150069. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150070. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150071. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150072. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150073. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150074. 8, 9, 9, 9, 9, 9,10,10,10,
  150075. };
  150076. static float _vq_quantthresh__44u7__p7_1[] = {
  150077. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150078. 3.5, 4.5,
  150079. };
  150080. static long _vq_quantmap__44u7__p7_1[] = {
  150081. 9, 7, 5, 3, 1, 0, 2, 4,
  150082. 6, 8, 10,
  150083. };
  150084. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150085. _vq_quantthresh__44u7__p7_1,
  150086. _vq_quantmap__44u7__p7_1,
  150087. 11,
  150088. 11
  150089. };
  150090. static static_codebook _44u7__p7_1 = {
  150091. 2, 121,
  150092. _vq_lengthlist__44u7__p7_1,
  150093. 1, -531365888, 1611661312, 4, 0,
  150094. _vq_quantlist__44u7__p7_1,
  150095. NULL,
  150096. &_vq_auxt__44u7__p7_1,
  150097. NULL,
  150098. 0
  150099. };
  150100. static long _vq_quantlist__44u7__p8_0[] = {
  150101. 5,
  150102. 4,
  150103. 6,
  150104. 3,
  150105. 7,
  150106. 2,
  150107. 8,
  150108. 1,
  150109. 9,
  150110. 0,
  150111. 10,
  150112. };
  150113. static long _vq_lengthlist__44u7__p8_0[] = {
  150114. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150115. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150116. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150117. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150118. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150119. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150120. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150121. 12,13,13,14,14,15,15,15,16,
  150122. };
  150123. static float _vq_quantthresh__44u7__p8_0[] = {
  150124. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150125. 38.5, 49.5,
  150126. };
  150127. static long _vq_quantmap__44u7__p8_0[] = {
  150128. 9, 7, 5, 3, 1, 0, 2, 4,
  150129. 6, 8, 10,
  150130. };
  150131. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150132. _vq_quantthresh__44u7__p8_0,
  150133. _vq_quantmap__44u7__p8_0,
  150134. 11,
  150135. 11
  150136. };
  150137. static static_codebook _44u7__p8_0 = {
  150138. 2, 121,
  150139. _vq_lengthlist__44u7__p8_0,
  150140. 1, -524582912, 1618345984, 4, 0,
  150141. _vq_quantlist__44u7__p8_0,
  150142. NULL,
  150143. &_vq_auxt__44u7__p8_0,
  150144. NULL,
  150145. 0
  150146. };
  150147. static long _vq_quantlist__44u7__p8_1[] = {
  150148. 5,
  150149. 4,
  150150. 6,
  150151. 3,
  150152. 7,
  150153. 2,
  150154. 8,
  150155. 1,
  150156. 9,
  150157. 0,
  150158. 10,
  150159. };
  150160. static long _vq_lengthlist__44u7__p8_1[] = {
  150161. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150162. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150163. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150164. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150165. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150166. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150167. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150168. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150169. };
  150170. static float _vq_quantthresh__44u7__p8_1[] = {
  150171. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150172. 3.5, 4.5,
  150173. };
  150174. static long _vq_quantmap__44u7__p8_1[] = {
  150175. 9, 7, 5, 3, 1, 0, 2, 4,
  150176. 6, 8, 10,
  150177. };
  150178. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150179. _vq_quantthresh__44u7__p8_1,
  150180. _vq_quantmap__44u7__p8_1,
  150181. 11,
  150182. 11
  150183. };
  150184. static static_codebook _44u7__p8_1 = {
  150185. 2, 121,
  150186. _vq_lengthlist__44u7__p8_1,
  150187. 1, -531365888, 1611661312, 4, 0,
  150188. _vq_quantlist__44u7__p8_1,
  150189. NULL,
  150190. &_vq_auxt__44u7__p8_1,
  150191. NULL,
  150192. 0
  150193. };
  150194. static long _vq_quantlist__44u7__p9_0[] = {
  150195. 5,
  150196. 4,
  150197. 6,
  150198. 3,
  150199. 7,
  150200. 2,
  150201. 8,
  150202. 1,
  150203. 9,
  150204. 0,
  150205. 10,
  150206. };
  150207. static long _vq_lengthlist__44u7__p9_0[] = {
  150208. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150209. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150210. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150211. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150212. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150213. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150214. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150215. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150216. };
  150217. static float _vq_quantthresh__44u7__p9_0[] = {
  150218. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150219. 2229.5, 2866.5,
  150220. };
  150221. static long _vq_quantmap__44u7__p9_0[] = {
  150222. 9, 7, 5, 3, 1, 0, 2, 4,
  150223. 6, 8, 10,
  150224. };
  150225. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150226. _vq_quantthresh__44u7__p9_0,
  150227. _vq_quantmap__44u7__p9_0,
  150228. 11,
  150229. 11
  150230. };
  150231. static static_codebook _44u7__p9_0 = {
  150232. 2, 121,
  150233. _vq_lengthlist__44u7__p9_0,
  150234. 1, -512171520, 1630791680, 4, 0,
  150235. _vq_quantlist__44u7__p9_0,
  150236. NULL,
  150237. &_vq_auxt__44u7__p9_0,
  150238. NULL,
  150239. 0
  150240. };
  150241. static long _vq_quantlist__44u7__p9_1[] = {
  150242. 6,
  150243. 5,
  150244. 7,
  150245. 4,
  150246. 8,
  150247. 3,
  150248. 9,
  150249. 2,
  150250. 10,
  150251. 1,
  150252. 11,
  150253. 0,
  150254. 12,
  150255. };
  150256. static long _vq_lengthlist__44u7__p9_1[] = {
  150257. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150258. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150259. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150260. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150261. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150262. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150263. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150264. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150265. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150266. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150267. 15,15,15,15,17,17,16,17,16,
  150268. };
  150269. static float _vq_quantthresh__44u7__p9_1[] = {
  150270. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150271. 122.5, 171.5, 220.5, 269.5,
  150272. };
  150273. static long _vq_quantmap__44u7__p9_1[] = {
  150274. 11, 9, 7, 5, 3, 1, 0, 2,
  150275. 4, 6, 8, 10, 12,
  150276. };
  150277. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150278. _vq_quantthresh__44u7__p9_1,
  150279. _vq_quantmap__44u7__p9_1,
  150280. 13,
  150281. 13
  150282. };
  150283. static static_codebook _44u7__p9_1 = {
  150284. 2, 169,
  150285. _vq_lengthlist__44u7__p9_1,
  150286. 1, -518889472, 1622704128, 4, 0,
  150287. _vq_quantlist__44u7__p9_1,
  150288. NULL,
  150289. &_vq_auxt__44u7__p9_1,
  150290. NULL,
  150291. 0
  150292. };
  150293. static long _vq_quantlist__44u7__p9_2[] = {
  150294. 24,
  150295. 23,
  150296. 25,
  150297. 22,
  150298. 26,
  150299. 21,
  150300. 27,
  150301. 20,
  150302. 28,
  150303. 19,
  150304. 29,
  150305. 18,
  150306. 30,
  150307. 17,
  150308. 31,
  150309. 16,
  150310. 32,
  150311. 15,
  150312. 33,
  150313. 14,
  150314. 34,
  150315. 13,
  150316. 35,
  150317. 12,
  150318. 36,
  150319. 11,
  150320. 37,
  150321. 10,
  150322. 38,
  150323. 9,
  150324. 39,
  150325. 8,
  150326. 40,
  150327. 7,
  150328. 41,
  150329. 6,
  150330. 42,
  150331. 5,
  150332. 43,
  150333. 4,
  150334. 44,
  150335. 3,
  150336. 45,
  150337. 2,
  150338. 46,
  150339. 1,
  150340. 47,
  150341. 0,
  150342. 48,
  150343. };
  150344. static long _vq_lengthlist__44u7__p9_2[] = {
  150345. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150346. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150347. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150348. 8,
  150349. };
  150350. static float _vq_quantthresh__44u7__p9_2[] = {
  150351. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150352. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150353. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150354. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150355. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150356. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150357. };
  150358. static long _vq_quantmap__44u7__p9_2[] = {
  150359. 47, 45, 43, 41, 39, 37, 35, 33,
  150360. 31, 29, 27, 25, 23, 21, 19, 17,
  150361. 15, 13, 11, 9, 7, 5, 3, 1,
  150362. 0, 2, 4, 6, 8, 10, 12, 14,
  150363. 16, 18, 20, 22, 24, 26, 28, 30,
  150364. 32, 34, 36, 38, 40, 42, 44, 46,
  150365. 48,
  150366. };
  150367. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150368. _vq_quantthresh__44u7__p9_2,
  150369. _vq_quantmap__44u7__p9_2,
  150370. 49,
  150371. 49
  150372. };
  150373. static static_codebook _44u7__p9_2 = {
  150374. 1, 49,
  150375. _vq_lengthlist__44u7__p9_2,
  150376. 1, -526909440, 1611661312, 6, 0,
  150377. _vq_quantlist__44u7__p9_2,
  150378. NULL,
  150379. &_vq_auxt__44u7__p9_2,
  150380. NULL,
  150381. 0
  150382. };
  150383. static long _huff_lengthlist__44u7__short[] = {
  150384. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150385. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150386. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150387. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150388. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150389. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150390. 6, 8, 5, 9,
  150391. };
  150392. static static_codebook _huff_book__44u7__short = {
  150393. 2, 100,
  150394. _huff_lengthlist__44u7__short,
  150395. 0, 0, 0, 0, 0,
  150396. NULL,
  150397. NULL,
  150398. NULL,
  150399. NULL,
  150400. 0
  150401. };
  150402. static long _huff_lengthlist__44u8__long[] = {
  150403. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150404. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150405. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150406. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150407. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150408. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150409. 10, 8, 8, 9,
  150410. };
  150411. static static_codebook _huff_book__44u8__long = {
  150412. 2, 100,
  150413. _huff_lengthlist__44u8__long,
  150414. 0, 0, 0, 0, 0,
  150415. NULL,
  150416. NULL,
  150417. NULL,
  150418. NULL,
  150419. 0
  150420. };
  150421. static long _huff_lengthlist__44u8__short[] = {
  150422. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150423. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150424. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150425. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150426. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150427. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150428. 10,10,15,17,
  150429. };
  150430. static static_codebook _huff_book__44u8__short = {
  150431. 2, 100,
  150432. _huff_lengthlist__44u8__short,
  150433. 0, 0, 0, 0, 0,
  150434. NULL,
  150435. NULL,
  150436. NULL,
  150437. NULL,
  150438. 0
  150439. };
  150440. static long _vq_quantlist__44u8_p1_0[] = {
  150441. 1,
  150442. 0,
  150443. 2,
  150444. };
  150445. static long _vq_lengthlist__44u8_p1_0[] = {
  150446. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150447. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150448. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150449. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150450. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150451. 10,
  150452. };
  150453. static float _vq_quantthresh__44u8_p1_0[] = {
  150454. -0.5, 0.5,
  150455. };
  150456. static long _vq_quantmap__44u8_p1_0[] = {
  150457. 1, 0, 2,
  150458. };
  150459. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150460. _vq_quantthresh__44u8_p1_0,
  150461. _vq_quantmap__44u8_p1_0,
  150462. 3,
  150463. 3
  150464. };
  150465. static static_codebook _44u8_p1_0 = {
  150466. 4, 81,
  150467. _vq_lengthlist__44u8_p1_0,
  150468. 1, -535822336, 1611661312, 2, 0,
  150469. _vq_quantlist__44u8_p1_0,
  150470. NULL,
  150471. &_vq_auxt__44u8_p1_0,
  150472. NULL,
  150473. 0
  150474. };
  150475. static long _vq_quantlist__44u8_p2_0[] = {
  150476. 2,
  150477. 1,
  150478. 3,
  150479. 0,
  150480. 4,
  150481. };
  150482. static long _vq_lengthlist__44u8_p2_0[] = {
  150483. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150484. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150485. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150486. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150487. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150488. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150489. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150490. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150491. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150492. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150493. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150494. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150495. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150496. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150497. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150498. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150499. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150500. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150501. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150502. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150503. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150504. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150505. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150506. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150507. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150508. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150509. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150510. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150511. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150512. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150513. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150514. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150515. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150516. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150517. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150518. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150519. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150520. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150521. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150522. 14,
  150523. };
  150524. static float _vq_quantthresh__44u8_p2_0[] = {
  150525. -1.5, -0.5, 0.5, 1.5,
  150526. };
  150527. static long _vq_quantmap__44u8_p2_0[] = {
  150528. 3, 1, 0, 2, 4,
  150529. };
  150530. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150531. _vq_quantthresh__44u8_p2_0,
  150532. _vq_quantmap__44u8_p2_0,
  150533. 5,
  150534. 5
  150535. };
  150536. static static_codebook _44u8_p2_0 = {
  150537. 4, 625,
  150538. _vq_lengthlist__44u8_p2_0,
  150539. 1, -533725184, 1611661312, 3, 0,
  150540. _vq_quantlist__44u8_p2_0,
  150541. NULL,
  150542. &_vq_auxt__44u8_p2_0,
  150543. NULL,
  150544. 0
  150545. };
  150546. static long _vq_quantlist__44u8_p3_0[] = {
  150547. 4,
  150548. 3,
  150549. 5,
  150550. 2,
  150551. 6,
  150552. 1,
  150553. 7,
  150554. 0,
  150555. 8,
  150556. };
  150557. static long _vq_lengthlist__44u8_p3_0[] = {
  150558. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150559. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150560. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150561. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150562. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150563. 12,
  150564. };
  150565. static float _vq_quantthresh__44u8_p3_0[] = {
  150566. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150567. };
  150568. static long _vq_quantmap__44u8_p3_0[] = {
  150569. 7, 5, 3, 1, 0, 2, 4, 6,
  150570. 8,
  150571. };
  150572. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150573. _vq_quantthresh__44u8_p3_0,
  150574. _vq_quantmap__44u8_p3_0,
  150575. 9,
  150576. 9
  150577. };
  150578. static static_codebook _44u8_p3_0 = {
  150579. 2, 81,
  150580. _vq_lengthlist__44u8_p3_0,
  150581. 1, -531628032, 1611661312, 4, 0,
  150582. _vq_quantlist__44u8_p3_0,
  150583. NULL,
  150584. &_vq_auxt__44u8_p3_0,
  150585. NULL,
  150586. 0
  150587. };
  150588. static long _vq_quantlist__44u8_p4_0[] = {
  150589. 8,
  150590. 7,
  150591. 9,
  150592. 6,
  150593. 10,
  150594. 5,
  150595. 11,
  150596. 4,
  150597. 12,
  150598. 3,
  150599. 13,
  150600. 2,
  150601. 14,
  150602. 1,
  150603. 15,
  150604. 0,
  150605. 16,
  150606. };
  150607. static long _vq_lengthlist__44u8_p4_0[] = {
  150608. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150609. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150610. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150611. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150612. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150613. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150614. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150615. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150616. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150617. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150618. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150619. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150620. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150621. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150622. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150623. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150624. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150625. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150626. 14,
  150627. };
  150628. static float _vq_quantthresh__44u8_p4_0[] = {
  150629. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150630. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150631. };
  150632. static long _vq_quantmap__44u8_p4_0[] = {
  150633. 15, 13, 11, 9, 7, 5, 3, 1,
  150634. 0, 2, 4, 6, 8, 10, 12, 14,
  150635. 16,
  150636. };
  150637. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150638. _vq_quantthresh__44u8_p4_0,
  150639. _vq_quantmap__44u8_p4_0,
  150640. 17,
  150641. 17
  150642. };
  150643. static static_codebook _44u8_p4_0 = {
  150644. 2, 289,
  150645. _vq_lengthlist__44u8_p4_0,
  150646. 1, -529530880, 1611661312, 5, 0,
  150647. _vq_quantlist__44u8_p4_0,
  150648. NULL,
  150649. &_vq_auxt__44u8_p4_0,
  150650. NULL,
  150651. 0
  150652. };
  150653. static long _vq_quantlist__44u8_p5_0[] = {
  150654. 1,
  150655. 0,
  150656. 2,
  150657. };
  150658. static long _vq_lengthlist__44u8_p5_0[] = {
  150659. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150660. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150661. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150662. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150663. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150664. 10,
  150665. };
  150666. static float _vq_quantthresh__44u8_p5_0[] = {
  150667. -5.5, 5.5,
  150668. };
  150669. static long _vq_quantmap__44u8_p5_0[] = {
  150670. 1, 0, 2,
  150671. };
  150672. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150673. _vq_quantthresh__44u8_p5_0,
  150674. _vq_quantmap__44u8_p5_0,
  150675. 3,
  150676. 3
  150677. };
  150678. static static_codebook _44u8_p5_0 = {
  150679. 4, 81,
  150680. _vq_lengthlist__44u8_p5_0,
  150681. 1, -529137664, 1618345984, 2, 0,
  150682. _vq_quantlist__44u8_p5_0,
  150683. NULL,
  150684. &_vq_auxt__44u8_p5_0,
  150685. NULL,
  150686. 0
  150687. };
  150688. static long _vq_quantlist__44u8_p5_1[] = {
  150689. 5,
  150690. 4,
  150691. 6,
  150692. 3,
  150693. 7,
  150694. 2,
  150695. 8,
  150696. 1,
  150697. 9,
  150698. 0,
  150699. 10,
  150700. };
  150701. static long _vq_lengthlist__44u8_p5_1[] = {
  150702. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150703. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150704. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150705. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150706. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150707. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150708. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150709. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150710. };
  150711. static float _vq_quantthresh__44u8_p5_1[] = {
  150712. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150713. 3.5, 4.5,
  150714. };
  150715. static long _vq_quantmap__44u8_p5_1[] = {
  150716. 9, 7, 5, 3, 1, 0, 2, 4,
  150717. 6, 8, 10,
  150718. };
  150719. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150720. _vq_quantthresh__44u8_p5_1,
  150721. _vq_quantmap__44u8_p5_1,
  150722. 11,
  150723. 11
  150724. };
  150725. static static_codebook _44u8_p5_1 = {
  150726. 2, 121,
  150727. _vq_lengthlist__44u8_p5_1,
  150728. 1, -531365888, 1611661312, 4, 0,
  150729. _vq_quantlist__44u8_p5_1,
  150730. NULL,
  150731. &_vq_auxt__44u8_p5_1,
  150732. NULL,
  150733. 0
  150734. };
  150735. static long _vq_quantlist__44u8_p6_0[] = {
  150736. 6,
  150737. 5,
  150738. 7,
  150739. 4,
  150740. 8,
  150741. 3,
  150742. 9,
  150743. 2,
  150744. 10,
  150745. 1,
  150746. 11,
  150747. 0,
  150748. 12,
  150749. };
  150750. static long _vq_lengthlist__44u8_p6_0[] = {
  150751. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150752. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150753. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150754. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150755. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150756. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150757. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150758. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150759. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150760. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150761. 11,11,11,11,11,12,11,12,12,
  150762. };
  150763. static float _vq_quantthresh__44u8_p6_0[] = {
  150764. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150765. 12.5, 17.5, 22.5, 27.5,
  150766. };
  150767. static long _vq_quantmap__44u8_p6_0[] = {
  150768. 11, 9, 7, 5, 3, 1, 0, 2,
  150769. 4, 6, 8, 10, 12,
  150770. };
  150771. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150772. _vq_quantthresh__44u8_p6_0,
  150773. _vq_quantmap__44u8_p6_0,
  150774. 13,
  150775. 13
  150776. };
  150777. static static_codebook _44u8_p6_0 = {
  150778. 2, 169,
  150779. _vq_lengthlist__44u8_p6_0,
  150780. 1, -526516224, 1616117760, 4, 0,
  150781. _vq_quantlist__44u8_p6_0,
  150782. NULL,
  150783. &_vq_auxt__44u8_p6_0,
  150784. NULL,
  150785. 0
  150786. };
  150787. static long _vq_quantlist__44u8_p6_1[] = {
  150788. 2,
  150789. 1,
  150790. 3,
  150791. 0,
  150792. 4,
  150793. };
  150794. static long _vq_lengthlist__44u8_p6_1[] = {
  150795. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150796. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150797. };
  150798. static float _vq_quantthresh__44u8_p6_1[] = {
  150799. -1.5, -0.5, 0.5, 1.5,
  150800. };
  150801. static long _vq_quantmap__44u8_p6_1[] = {
  150802. 3, 1, 0, 2, 4,
  150803. };
  150804. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150805. _vq_quantthresh__44u8_p6_1,
  150806. _vq_quantmap__44u8_p6_1,
  150807. 5,
  150808. 5
  150809. };
  150810. static static_codebook _44u8_p6_1 = {
  150811. 2, 25,
  150812. _vq_lengthlist__44u8_p6_1,
  150813. 1, -533725184, 1611661312, 3, 0,
  150814. _vq_quantlist__44u8_p6_1,
  150815. NULL,
  150816. &_vq_auxt__44u8_p6_1,
  150817. NULL,
  150818. 0
  150819. };
  150820. static long _vq_quantlist__44u8_p7_0[] = {
  150821. 6,
  150822. 5,
  150823. 7,
  150824. 4,
  150825. 8,
  150826. 3,
  150827. 9,
  150828. 2,
  150829. 10,
  150830. 1,
  150831. 11,
  150832. 0,
  150833. 12,
  150834. };
  150835. static long _vq_lengthlist__44u8_p7_0[] = {
  150836. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150837. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150838. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150839. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150840. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150841. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150842. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150843. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150844. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150845. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150846. 13,13,14,14,14,15,15,15,16,
  150847. };
  150848. static float _vq_quantthresh__44u8_p7_0[] = {
  150849. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150850. 27.5, 38.5, 49.5, 60.5,
  150851. };
  150852. static long _vq_quantmap__44u8_p7_0[] = {
  150853. 11, 9, 7, 5, 3, 1, 0, 2,
  150854. 4, 6, 8, 10, 12,
  150855. };
  150856. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150857. _vq_quantthresh__44u8_p7_0,
  150858. _vq_quantmap__44u8_p7_0,
  150859. 13,
  150860. 13
  150861. };
  150862. static static_codebook _44u8_p7_0 = {
  150863. 2, 169,
  150864. _vq_lengthlist__44u8_p7_0,
  150865. 1, -523206656, 1618345984, 4, 0,
  150866. _vq_quantlist__44u8_p7_0,
  150867. NULL,
  150868. &_vq_auxt__44u8_p7_0,
  150869. NULL,
  150870. 0
  150871. };
  150872. static long _vq_quantlist__44u8_p7_1[] = {
  150873. 5,
  150874. 4,
  150875. 6,
  150876. 3,
  150877. 7,
  150878. 2,
  150879. 8,
  150880. 1,
  150881. 9,
  150882. 0,
  150883. 10,
  150884. };
  150885. static long _vq_lengthlist__44u8_p7_1[] = {
  150886. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150887. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150888. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150889. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150890. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150891. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150892. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150893. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150894. };
  150895. static float _vq_quantthresh__44u8_p7_1[] = {
  150896. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150897. 3.5, 4.5,
  150898. };
  150899. static long _vq_quantmap__44u8_p7_1[] = {
  150900. 9, 7, 5, 3, 1, 0, 2, 4,
  150901. 6, 8, 10,
  150902. };
  150903. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150904. _vq_quantthresh__44u8_p7_1,
  150905. _vq_quantmap__44u8_p7_1,
  150906. 11,
  150907. 11
  150908. };
  150909. static static_codebook _44u8_p7_1 = {
  150910. 2, 121,
  150911. _vq_lengthlist__44u8_p7_1,
  150912. 1, -531365888, 1611661312, 4, 0,
  150913. _vq_quantlist__44u8_p7_1,
  150914. NULL,
  150915. &_vq_auxt__44u8_p7_1,
  150916. NULL,
  150917. 0
  150918. };
  150919. static long _vq_quantlist__44u8_p8_0[] = {
  150920. 7,
  150921. 6,
  150922. 8,
  150923. 5,
  150924. 9,
  150925. 4,
  150926. 10,
  150927. 3,
  150928. 11,
  150929. 2,
  150930. 12,
  150931. 1,
  150932. 13,
  150933. 0,
  150934. 14,
  150935. };
  150936. static long _vq_lengthlist__44u8_p8_0[] = {
  150937. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150938. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150939. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150940. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150941. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150942. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150943. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150944. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150945. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150946. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150947. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150948. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150949. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150950. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150951. 17,
  150952. };
  150953. static float _vq_quantthresh__44u8_p8_0[] = {
  150954. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150955. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150956. };
  150957. static long _vq_quantmap__44u8_p8_0[] = {
  150958. 13, 11, 9, 7, 5, 3, 1, 0,
  150959. 2, 4, 6, 8, 10, 12, 14,
  150960. };
  150961. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150962. _vq_quantthresh__44u8_p8_0,
  150963. _vq_quantmap__44u8_p8_0,
  150964. 15,
  150965. 15
  150966. };
  150967. static static_codebook _44u8_p8_0 = {
  150968. 2, 225,
  150969. _vq_lengthlist__44u8_p8_0,
  150970. 1, -520986624, 1620377600, 4, 0,
  150971. _vq_quantlist__44u8_p8_0,
  150972. NULL,
  150973. &_vq_auxt__44u8_p8_0,
  150974. NULL,
  150975. 0
  150976. };
  150977. static long _vq_quantlist__44u8_p8_1[] = {
  150978. 10,
  150979. 9,
  150980. 11,
  150981. 8,
  150982. 12,
  150983. 7,
  150984. 13,
  150985. 6,
  150986. 14,
  150987. 5,
  150988. 15,
  150989. 4,
  150990. 16,
  150991. 3,
  150992. 17,
  150993. 2,
  150994. 18,
  150995. 1,
  150996. 19,
  150997. 0,
  150998. 20,
  150999. };
  151000. static long _vq_lengthlist__44u8_p8_1[] = {
  151001. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151002. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151003. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151004. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151005. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151006. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151007. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151008. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151009. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151010. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151011. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151012. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151013. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151014. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151015. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151016. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151017. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151018. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151019. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151020. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151021. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151022. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151023. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151024. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151025. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151026. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151027. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151028. 10,10,10,10,10,10,10,10,10,
  151029. };
  151030. static float _vq_quantthresh__44u8_p8_1[] = {
  151031. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151032. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151033. 6.5, 7.5, 8.5, 9.5,
  151034. };
  151035. static long _vq_quantmap__44u8_p8_1[] = {
  151036. 19, 17, 15, 13, 11, 9, 7, 5,
  151037. 3, 1, 0, 2, 4, 6, 8, 10,
  151038. 12, 14, 16, 18, 20,
  151039. };
  151040. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151041. _vq_quantthresh__44u8_p8_1,
  151042. _vq_quantmap__44u8_p8_1,
  151043. 21,
  151044. 21
  151045. };
  151046. static static_codebook _44u8_p8_1 = {
  151047. 2, 441,
  151048. _vq_lengthlist__44u8_p8_1,
  151049. 1, -529268736, 1611661312, 5, 0,
  151050. _vq_quantlist__44u8_p8_1,
  151051. NULL,
  151052. &_vq_auxt__44u8_p8_1,
  151053. NULL,
  151054. 0
  151055. };
  151056. static long _vq_quantlist__44u8_p9_0[] = {
  151057. 4,
  151058. 3,
  151059. 5,
  151060. 2,
  151061. 6,
  151062. 1,
  151063. 7,
  151064. 0,
  151065. 8,
  151066. };
  151067. static long _vq_lengthlist__44u8_p9_0[] = {
  151068. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151069. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151070. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151071. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151072. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151073. 8,
  151074. };
  151075. static float _vq_quantthresh__44u8_p9_0[] = {
  151076. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151077. };
  151078. static long _vq_quantmap__44u8_p9_0[] = {
  151079. 7, 5, 3, 1, 0, 2, 4, 6,
  151080. 8,
  151081. };
  151082. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151083. _vq_quantthresh__44u8_p9_0,
  151084. _vq_quantmap__44u8_p9_0,
  151085. 9,
  151086. 9
  151087. };
  151088. static static_codebook _44u8_p9_0 = {
  151089. 2, 81,
  151090. _vq_lengthlist__44u8_p9_0,
  151091. 1, -511895552, 1631393792, 4, 0,
  151092. _vq_quantlist__44u8_p9_0,
  151093. NULL,
  151094. &_vq_auxt__44u8_p9_0,
  151095. NULL,
  151096. 0
  151097. };
  151098. static long _vq_quantlist__44u8_p9_1[] = {
  151099. 9,
  151100. 8,
  151101. 10,
  151102. 7,
  151103. 11,
  151104. 6,
  151105. 12,
  151106. 5,
  151107. 13,
  151108. 4,
  151109. 14,
  151110. 3,
  151111. 15,
  151112. 2,
  151113. 16,
  151114. 1,
  151115. 17,
  151116. 0,
  151117. 18,
  151118. };
  151119. static long _vq_lengthlist__44u8_p9_1[] = {
  151120. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151121. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151122. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151123. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151124. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151125. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151126. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151127. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151128. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151129. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151130. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151131. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151132. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151133. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151134. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151135. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151136. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151137. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151138. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151139. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151140. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151141. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151142. 16,15,16,16,16,16,16,16,16,
  151143. };
  151144. static float _vq_quantthresh__44u8_p9_1[] = {
  151145. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151146. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151147. 367.5, 416.5,
  151148. };
  151149. static long _vq_quantmap__44u8_p9_1[] = {
  151150. 17, 15, 13, 11, 9, 7, 5, 3,
  151151. 1, 0, 2, 4, 6, 8, 10, 12,
  151152. 14, 16, 18,
  151153. };
  151154. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151155. _vq_quantthresh__44u8_p9_1,
  151156. _vq_quantmap__44u8_p9_1,
  151157. 19,
  151158. 19
  151159. };
  151160. static static_codebook _44u8_p9_1 = {
  151161. 2, 361,
  151162. _vq_lengthlist__44u8_p9_1,
  151163. 1, -518287360, 1622704128, 5, 0,
  151164. _vq_quantlist__44u8_p9_1,
  151165. NULL,
  151166. &_vq_auxt__44u8_p9_1,
  151167. NULL,
  151168. 0
  151169. };
  151170. static long _vq_quantlist__44u8_p9_2[] = {
  151171. 24,
  151172. 23,
  151173. 25,
  151174. 22,
  151175. 26,
  151176. 21,
  151177. 27,
  151178. 20,
  151179. 28,
  151180. 19,
  151181. 29,
  151182. 18,
  151183. 30,
  151184. 17,
  151185. 31,
  151186. 16,
  151187. 32,
  151188. 15,
  151189. 33,
  151190. 14,
  151191. 34,
  151192. 13,
  151193. 35,
  151194. 12,
  151195. 36,
  151196. 11,
  151197. 37,
  151198. 10,
  151199. 38,
  151200. 9,
  151201. 39,
  151202. 8,
  151203. 40,
  151204. 7,
  151205. 41,
  151206. 6,
  151207. 42,
  151208. 5,
  151209. 43,
  151210. 4,
  151211. 44,
  151212. 3,
  151213. 45,
  151214. 2,
  151215. 46,
  151216. 1,
  151217. 47,
  151218. 0,
  151219. 48,
  151220. };
  151221. static long _vq_lengthlist__44u8_p9_2[] = {
  151222. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151223. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151224. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151225. 7,
  151226. };
  151227. static float _vq_quantthresh__44u8_p9_2[] = {
  151228. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151229. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151230. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151231. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151232. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151233. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151234. };
  151235. static long _vq_quantmap__44u8_p9_2[] = {
  151236. 47, 45, 43, 41, 39, 37, 35, 33,
  151237. 31, 29, 27, 25, 23, 21, 19, 17,
  151238. 15, 13, 11, 9, 7, 5, 3, 1,
  151239. 0, 2, 4, 6, 8, 10, 12, 14,
  151240. 16, 18, 20, 22, 24, 26, 28, 30,
  151241. 32, 34, 36, 38, 40, 42, 44, 46,
  151242. 48,
  151243. };
  151244. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151245. _vq_quantthresh__44u8_p9_2,
  151246. _vq_quantmap__44u8_p9_2,
  151247. 49,
  151248. 49
  151249. };
  151250. static static_codebook _44u8_p9_2 = {
  151251. 1, 49,
  151252. _vq_lengthlist__44u8_p9_2,
  151253. 1, -526909440, 1611661312, 6, 0,
  151254. _vq_quantlist__44u8_p9_2,
  151255. NULL,
  151256. &_vq_auxt__44u8_p9_2,
  151257. NULL,
  151258. 0
  151259. };
  151260. static long _huff_lengthlist__44u9__long[] = {
  151261. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151262. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151263. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151264. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151265. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151266. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151267. 10, 8, 8, 9,
  151268. };
  151269. static static_codebook _huff_book__44u9__long = {
  151270. 2, 100,
  151271. _huff_lengthlist__44u9__long,
  151272. 0, 0, 0, 0, 0,
  151273. NULL,
  151274. NULL,
  151275. NULL,
  151276. NULL,
  151277. 0
  151278. };
  151279. static long _huff_lengthlist__44u9__short[] = {
  151280. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151281. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151282. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151283. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151284. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151285. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151286. 9, 9,12,15,
  151287. };
  151288. static static_codebook _huff_book__44u9__short = {
  151289. 2, 100,
  151290. _huff_lengthlist__44u9__short,
  151291. 0, 0, 0, 0, 0,
  151292. NULL,
  151293. NULL,
  151294. NULL,
  151295. NULL,
  151296. 0
  151297. };
  151298. static long _vq_quantlist__44u9_p1_0[] = {
  151299. 1,
  151300. 0,
  151301. 2,
  151302. };
  151303. static long _vq_lengthlist__44u9_p1_0[] = {
  151304. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151305. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151306. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151307. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151308. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151309. 10,
  151310. };
  151311. static float _vq_quantthresh__44u9_p1_0[] = {
  151312. -0.5, 0.5,
  151313. };
  151314. static long _vq_quantmap__44u9_p1_0[] = {
  151315. 1, 0, 2,
  151316. };
  151317. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151318. _vq_quantthresh__44u9_p1_0,
  151319. _vq_quantmap__44u9_p1_0,
  151320. 3,
  151321. 3
  151322. };
  151323. static static_codebook _44u9_p1_0 = {
  151324. 4, 81,
  151325. _vq_lengthlist__44u9_p1_0,
  151326. 1, -535822336, 1611661312, 2, 0,
  151327. _vq_quantlist__44u9_p1_0,
  151328. NULL,
  151329. &_vq_auxt__44u9_p1_0,
  151330. NULL,
  151331. 0
  151332. };
  151333. static long _vq_quantlist__44u9_p2_0[] = {
  151334. 2,
  151335. 1,
  151336. 3,
  151337. 0,
  151338. 4,
  151339. };
  151340. static long _vq_lengthlist__44u9_p2_0[] = {
  151341. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151342. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151343. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151344. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151345. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151346. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151347. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151348. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151349. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151350. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151351. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151352. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151353. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151354. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151355. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151356. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151357. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151358. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151359. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151360. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151361. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151362. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151363. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151364. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151365. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151366. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151367. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151368. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151369. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151370. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151371. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151372. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151373. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151374. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151375. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151376. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151377. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151378. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151379. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151380. 14,
  151381. };
  151382. static float _vq_quantthresh__44u9_p2_0[] = {
  151383. -1.5, -0.5, 0.5, 1.5,
  151384. };
  151385. static long _vq_quantmap__44u9_p2_0[] = {
  151386. 3, 1, 0, 2, 4,
  151387. };
  151388. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151389. _vq_quantthresh__44u9_p2_0,
  151390. _vq_quantmap__44u9_p2_0,
  151391. 5,
  151392. 5
  151393. };
  151394. static static_codebook _44u9_p2_0 = {
  151395. 4, 625,
  151396. _vq_lengthlist__44u9_p2_0,
  151397. 1, -533725184, 1611661312, 3, 0,
  151398. _vq_quantlist__44u9_p2_0,
  151399. NULL,
  151400. &_vq_auxt__44u9_p2_0,
  151401. NULL,
  151402. 0
  151403. };
  151404. static long _vq_quantlist__44u9_p3_0[] = {
  151405. 4,
  151406. 3,
  151407. 5,
  151408. 2,
  151409. 6,
  151410. 1,
  151411. 7,
  151412. 0,
  151413. 8,
  151414. };
  151415. static long _vq_lengthlist__44u9_p3_0[] = {
  151416. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151417. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151418. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151419. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151420. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151421. 11,
  151422. };
  151423. static float _vq_quantthresh__44u9_p3_0[] = {
  151424. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151425. };
  151426. static long _vq_quantmap__44u9_p3_0[] = {
  151427. 7, 5, 3, 1, 0, 2, 4, 6,
  151428. 8,
  151429. };
  151430. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151431. _vq_quantthresh__44u9_p3_0,
  151432. _vq_quantmap__44u9_p3_0,
  151433. 9,
  151434. 9
  151435. };
  151436. static static_codebook _44u9_p3_0 = {
  151437. 2, 81,
  151438. _vq_lengthlist__44u9_p3_0,
  151439. 1, -531628032, 1611661312, 4, 0,
  151440. _vq_quantlist__44u9_p3_0,
  151441. NULL,
  151442. &_vq_auxt__44u9_p3_0,
  151443. NULL,
  151444. 0
  151445. };
  151446. static long _vq_quantlist__44u9_p4_0[] = {
  151447. 8,
  151448. 7,
  151449. 9,
  151450. 6,
  151451. 10,
  151452. 5,
  151453. 11,
  151454. 4,
  151455. 12,
  151456. 3,
  151457. 13,
  151458. 2,
  151459. 14,
  151460. 1,
  151461. 15,
  151462. 0,
  151463. 16,
  151464. };
  151465. static long _vq_lengthlist__44u9_p4_0[] = {
  151466. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151467. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151468. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151469. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151470. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151471. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151472. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151473. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151474. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151475. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151476. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151477. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151478. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151479. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151480. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151481. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151482. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151483. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151484. 14,
  151485. };
  151486. static float _vq_quantthresh__44u9_p4_0[] = {
  151487. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151488. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151489. };
  151490. static long _vq_quantmap__44u9_p4_0[] = {
  151491. 15, 13, 11, 9, 7, 5, 3, 1,
  151492. 0, 2, 4, 6, 8, 10, 12, 14,
  151493. 16,
  151494. };
  151495. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151496. _vq_quantthresh__44u9_p4_0,
  151497. _vq_quantmap__44u9_p4_0,
  151498. 17,
  151499. 17
  151500. };
  151501. static static_codebook _44u9_p4_0 = {
  151502. 2, 289,
  151503. _vq_lengthlist__44u9_p4_0,
  151504. 1, -529530880, 1611661312, 5, 0,
  151505. _vq_quantlist__44u9_p4_0,
  151506. NULL,
  151507. &_vq_auxt__44u9_p4_0,
  151508. NULL,
  151509. 0
  151510. };
  151511. static long _vq_quantlist__44u9_p5_0[] = {
  151512. 1,
  151513. 0,
  151514. 2,
  151515. };
  151516. static long _vq_lengthlist__44u9_p5_0[] = {
  151517. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151518. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151519. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151520. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151521. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151522. 10,
  151523. };
  151524. static float _vq_quantthresh__44u9_p5_0[] = {
  151525. -5.5, 5.5,
  151526. };
  151527. static long _vq_quantmap__44u9_p5_0[] = {
  151528. 1, 0, 2,
  151529. };
  151530. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151531. _vq_quantthresh__44u9_p5_0,
  151532. _vq_quantmap__44u9_p5_0,
  151533. 3,
  151534. 3
  151535. };
  151536. static static_codebook _44u9_p5_0 = {
  151537. 4, 81,
  151538. _vq_lengthlist__44u9_p5_0,
  151539. 1, -529137664, 1618345984, 2, 0,
  151540. _vq_quantlist__44u9_p5_0,
  151541. NULL,
  151542. &_vq_auxt__44u9_p5_0,
  151543. NULL,
  151544. 0
  151545. };
  151546. static long _vq_quantlist__44u9_p5_1[] = {
  151547. 5,
  151548. 4,
  151549. 6,
  151550. 3,
  151551. 7,
  151552. 2,
  151553. 8,
  151554. 1,
  151555. 9,
  151556. 0,
  151557. 10,
  151558. };
  151559. static long _vq_lengthlist__44u9_p5_1[] = {
  151560. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151561. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151562. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151563. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151564. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151565. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151566. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151567. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151568. };
  151569. static float _vq_quantthresh__44u9_p5_1[] = {
  151570. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151571. 3.5, 4.5,
  151572. };
  151573. static long _vq_quantmap__44u9_p5_1[] = {
  151574. 9, 7, 5, 3, 1, 0, 2, 4,
  151575. 6, 8, 10,
  151576. };
  151577. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151578. _vq_quantthresh__44u9_p5_1,
  151579. _vq_quantmap__44u9_p5_1,
  151580. 11,
  151581. 11
  151582. };
  151583. static static_codebook _44u9_p5_1 = {
  151584. 2, 121,
  151585. _vq_lengthlist__44u9_p5_1,
  151586. 1, -531365888, 1611661312, 4, 0,
  151587. _vq_quantlist__44u9_p5_1,
  151588. NULL,
  151589. &_vq_auxt__44u9_p5_1,
  151590. NULL,
  151591. 0
  151592. };
  151593. static long _vq_quantlist__44u9_p6_0[] = {
  151594. 6,
  151595. 5,
  151596. 7,
  151597. 4,
  151598. 8,
  151599. 3,
  151600. 9,
  151601. 2,
  151602. 10,
  151603. 1,
  151604. 11,
  151605. 0,
  151606. 12,
  151607. };
  151608. static long _vq_lengthlist__44u9_p6_0[] = {
  151609. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151610. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151611. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151612. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151613. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151614. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151615. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151616. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151617. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151618. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151619. 10,11,11,11,11,12,11,12,12,
  151620. };
  151621. static float _vq_quantthresh__44u9_p6_0[] = {
  151622. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151623. 12.5, 17.5, 22.5, 27.5,
  151624. };
  151625. static long _vq_quantmap__44u9_p6_0[] = {
  151626. 11, 9, 7, 5, 3, 1, 0, 2,
  151627. 4, 6, 8, 10, 12,
  151628. };
  151629. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151630. _vq_quantthresh__44u9_p6_0,
  151631. _vq_quantmap__44u9_p6_0,
  151632. 13,
  151633. 13
  151634. };
  151635. static static_codebook _44u9_p6_0 = {
  151636. 2, 169,
  151637. _vq_lengthlist__44u9_p6_0,
  151638. 1, -526516224, 1616117760, 4, 0,
  151639. _vq_quantlist__44u9_p6_0,
  151640. NULL,
  151641. &_vq_auxt__44u9_p6_0,
  151642. NULL,
  151643. 0
  151644. };
  151645. static long _vq_quantlist__44u9_p6_1[] = {
  151646. 2,
  151647. 1,
  151648. 3,
  151649. 0,
  151650. 4,
  151651. };
  151652. static long _vq_lengthlist__44u9_p6_1[] = {
  151653. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151654. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151655. };
  151656. static float _vq_quantthresh__44u9_p6_1[] = {
  151657. -1.5, -0.5, 0.5, 1.5,
  151658. };
  151659. static long _vq_quantmap__44u9_p6_1[] = {
  151660. 3, 1, 0, 2, 4,
  151661. };
  151662. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151663. _vq_quantthresh__44u9_p6_1,
  151664. _vq_quantmap__44u9_p6_1,
  151665. 5,
  151666. 5
  151667. };
  151668. static static_codebook _44u9_p6_1 = {
  151669. 2, 25,
  151670. _vq_lengthlist__44u9_p6_1,
  151671. 1, -533725184, 1611661312, 3, 0,
  151672. _vq_quantlist__44u9_p6_1,
  151673. NULL,
  151674. &_vq_auxt__44u9_p6_1,
  151675. NULL,
  151676. 0
  151677. };
  151678. static long _vq_quantlist__44u9_p7_0[] = {
  151679. 6,
  151680. 5,
  151681. 7,
  151682. 4,
  151683. 8,
  151684. 3,
  151685. 9,
  151686. 2,
  151687. 10,
  151688. 1,
  151689. 11,
  151690. 0,
  151691. 12,
  151692. };
  151693. static long _vq_lengthlist__44u9_p7_0[] = {
  151694. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151695. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151696. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151697. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151698. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151699. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151700. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151701. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151702. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151703. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151704. 12,13,13,14,14,14,15,15,15,
  151705. };
  151706. static float _vq_quantthresh__44u9_p7_0[] = {
  151707. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151708. 27.5, 38.5, 49.5, 60.5,
  151709. };
  151710. static long _vq_quantmap__44u9_p7_0[] = {
  151711. 11, 9, 7, 5, 3, 1, 0, 2,
  151712. 4, 6, 8, 10, 12,
  151713. };
  151714. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151715. _vq_quantthresh__44u9_p7_0,
  151716. _vq_quantmap__44u9_p7_0,
  151717. 13,
  151718. 13
  151719. };
  151720. static static_codebook _44u9_p7_0 = {
  151721. 2, 169,
  151722. _vq_lengthlist__44u9_p7_0,
  151723. 1, -523206656, 1618345984, 4, 0,
  151724. _vq_quantlist__44u9_p7_0,
  151725. NULL,
  151726. &_vq_auxt__44u9_p7_0,
  151727. NULL,
  151728. 0
  151729. };
  151730. static long _vq_quantlist__44u9_p7_1[] = {
  151731. 5,
  151732. 4,
  151733. 6,
  151734. 3,
  151735. 7,
  151736. 2,
  151737. 8,
  151738. 1,
  151739. 9,
  151740. 0,
  151741. 10,
  151742. };
  151743. static long _vq_lengthlist__44u9_p7_1[] = {
  151744. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151745. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151746. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151747. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151748. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151749. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151750. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151751. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151752. };
  151753. static float _vq_quantthresh__44u9_p7_1[] = {
  151754. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151755. 3.5, 4.5,
  151756. };
  151757. static long _vq_quantmap__44u9_p7_1[] = {
  151758. 9, 7, 5, 3, 1, 0, 2, 4,
  151759. 6, 8, 10,
  151760. };
  151761. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151762. _vq_quantthresh__44u9_p7_1,
  151763. _vq_quantmap__44u9_p7_1,
  151764. 11,
  151765. 11
  151766. };
  151767. static static_codebook _44u9_p7_1 = {
  151768. 2, 121,
  151769. _vq_lengthlist__44u9_p7_1,
  151770. 1, -531365888, 1611661312, 4, 0,
  151771. _vq_quantlist__44u9_p7_1,
  151772. NULL,
  151773. &_vq_auxt__44u9_p7_1,
  151774. NULL,
  151775. 0
  151776. };
  151777. static long _vq_quantlist__44u9_p8_0[] = {
  151778. 7,
  151779. 6,
  151780. 8,
  151781. 5,
  151782. 9,
  151783. 4,
  151784. 10,
  151785. 3,
  151786. 11,
  151787. 2,
  151788. 12,
  151789. 1,
  151790. 13,
  151791. 0,
  151792. 14,
  151793. };
  151794. static long _vq_lengthlist__44u9_p8_0[] = {
  151795. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151796. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151797. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151798. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151799. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151800. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151801. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151802. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151803. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151804. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151805. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151806. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151807. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151808. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151809. 15,
  151810. };
  151811. static float _vq_quantthresh__44u9_p8_0[] = {
  151812. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151813. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151814. };
  151815. static long _vq_quantmap__44u9_p8_0[] = {
  151816. 13, 11, 9, 7, 5, 3, 1, 0,
  151817. 2, 4, 6, 8, 10, 12, 14,
  151818. };
  151819. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151820. _vq_quantthresh__44u9_p8_0,
  151821. _vq_quantmap__44u9_p8_0,
  151822. 15,
  151823. 15
  151824. };
  151825. static static_codebook _44u9_p8_0 = {
  151826. 2, 225,
  151827. _vq_lengthlist__44u9_p8_0,
  151828. 1, -520986624, 1620377600, 4, 0,
  151829. _vq_quantlist__44u9_p8_0,
  151830. NULL,
  151831. &_vq_auxt__44u9_p8_0,
  151832. NULL,
  151833. 0
  151834. };
  151835. static long _vq_quantlist__44u9_p8_1[] = {
  151836. 10,
  151837. 9,
  151838. 11,
  151839. 8,
  151840. 12,
  151841. 7,
  151842. 13,
  151843. 6,
  151844. 14,
  151845. 5,
  151846. 15,
  151847. 4,
  151848. 16,
  151849. 3,
  151850. 17,
  151851. 2,
  151852. 18,
  151853. 1,
  151854. 19,
  151855. 0,
  151856. 20,
  151857. };
  151858. static long _vq_lengthlist__44u9_p8_1[] = {
  151859. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151860. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151862. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151863. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151864. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151865. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151866. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151867. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151868. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151869. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151870. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151871. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151872. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151873. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151874. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151875. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151876. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151877. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151878. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151879. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151880. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151881. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151882. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151883. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151884. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151885. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151886. 10,10,10,10,10,10,10,10,10,
  151887. };
  151888. static float _vq_quantthresh__44u9_p8_1[] = {
  151889. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151890. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151891. 6.5, 7.5, 8.5, 9.5,
  151892. };
  151893. static long _vq_quantmap__44u9_p8_1[] = {
  151894. 19, 17, 15, 13, 11, 9, 7, 5,
  151895. 3, 1, 0, 2, 4, 6, 8, 10,
  151896. 12, 14, 16, 18, 20,
  151897. };
  151898. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151899. _vq_quantthresh__44u9_p8_1,
  151900. _vq_quantmap__44u9_p8_1,
  151901. 21,
  151902. 21
  151903. };
  151904. static static_codebook _44u9_p8_1 = {
  151905. 2, 441,
  151906. _vq_lengthlist__44u9_p8_1,
  151907. 1, -529268736, 1611661312, 5, 0,
  151908. _vq_quantlist__44u9_p8_1,
  151909. NULL,
  151910. &_vq_auxt__44u9_p8_1,
  151911. NULL,
  151912. 0
  151913. };
  151914. static long _vq_quantlist__44u9_p9_0[] = {
  151915. 7,
  151916. 6,
  151917. 8,
  151918. 5,
  151919. 9,
  151920. 4,
  151921. 10,
  151922. 3,
  151923. 11,
  151924. 2,
  151925. 12,
  151926. 1,
  151927. 13,
  151928. 0,
  151929. 14,
  151930. };
  151931. static long _vq_lengthlist__44u9_p9_0[] = {
  151932. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151933. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151934. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151945. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151946. 10,
  151947. };
  151948. static float _vq_quantthresh__44u9_p9_0[] = {
  151949. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151950. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151951. };
  151952. static long _vq_quantmap__44u9_p9_0[] = {
  151953. 13, 11, 9, 7, 5, 3, 1, 0,
  151954. 2, 4, 6, 8, 10, 12, 14,
  151955. };
  151956. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151957. _vq_quantthresh__44u9_p9_0,
  151958. _vq_quantmap__44u9_p9_0,
  151959. 15,
  151960. 15
  151961. };
  151962. static static_codebook _44u9_p9_0 = {
  151963. 2, 225,
  151964. _vq_lengthlist__44u9_p9_0,
  151965. 1, -510036736, 1631393792, 4, 0,
  151966. _vq_quantlist__44u9_p9_0,
  151967. NULL,
  151968. &_vq_auxt__44u9_p9_0,
  151969. NULL,
  151970. 0
  151971. };
  151972. static long _vq_quantlist__44u9_p9_1[] = {
  151973. 9,
  151974. 8,
  151975. 10,
  151976. 7,
  151977. 11,
  151978. 6,
  151979. 12,
  151980. 5,
  151981. 13,
  151982. 4,
  151983. 14,
  151984. 3,
  151985. 15,
  151986. 2,
  151987. 16,
  151988. 1,
  151989. 17,
  151990. 0,
  151991. 18,
  151992. };
  151993. static long _vq_lengthlist__44u9_p9_1[] = {
  151994. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151995. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151996. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151997. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151998. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151999. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152000. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152001. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152002. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152003. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152004. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152005. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152006. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152007. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152008. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152009. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152010. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152011. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152012. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152013. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152014. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152015. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152016. 17,17,15,17,15,17,16,16,17,
  152017. };
  152018. static float _vq_quantthresh__44u9_p9_1[] = {
  152019. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152020. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152021. 367.5, 416.5,
  152022. };
  152023. static long _vq_quantmap__44u9_p9_1[] = {
  152024. 17, 15, 13, 11, 9, 7, 5, 3,
  152025. 1, 0, 2, 4, 6, 8, 10, 12,
  152026. 14, 16, 18,
  152027. };
  152028. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152029. _vq_quantthresh__44u9_p9_1,
  152030. _vq_quantmap__44u9_p9_1,
  152031. 19,
  152032. 19
  152033. };
  152034. static static_codebook _44u9_p9_1 = {
  152035. 2, 361,
  152036. _vq_lengthlist__44u9_p9_1,
  152037. 1, -518287360, 1622704128, 5, 0,
  152038. _vq_quantlist__44u9_p9_1,
  152039. NULL,
  152040. &_vq_auxt__44u9_p9_1,
  152041. NULL,
  152042. 0
  152043. };
  152044. static long _vq_quantlist__44u9_p9_2[] = {
  152045. 24,
  152046. 23,
  152047. 25,
  152048. 22,
  152049. 26,
  152050. 21,
  152051. 27,
  152052. 20,
  152053. 28,
  152054. 19,
  152055. 29,
  152056. 18,
  152057. 30,
  152058. 17,
  152059. 31,
  152060. 16,
  152061. 32,
  152062. 15,
  152063. 33,
  152064. 14,
  152065. 34,
  152066. 13,
  152067. 35,
  152068. 12,
  152069. 36,
  152070. 11,
  152071. 37,
  152072. 10,
  152073. 38,
  152074. 9,
  152075. 39,
  152076. 8,
  152077. 40,
  152078. 7,
  152079. 41,
  152080. 6,
  152081. 42,
  152082. 5,
  152083. 43,
  152084. 4,
  152085. 44,
  152086. 3,
  152087. 45,
  152088. 2,
  152089. 46,
  152090. 1,
  152091. 47,
  152092. 0,
  152093. 48,
  152094. };
  152095. static long _vq_lengthlist__44u9_p9_2[] = {
  152096. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152097. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152098. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152099. 7,
  152100. };
  152101. static float _vq_quantthresh__44u9_p9_2[] = {
  152102. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152103. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152104. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152105. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152106. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152107. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152108. };
  152109. static long _vq_quantmap__44u9_p9_2[] = {
  152110. 47, 45, 43, 41, 39, 37, 35, 33,
  152111. 31, 29, 27, 25, 23, 21, 19, 17,
  152112. 15, 13, 11, 9, 7, 5, 3, 1,
  152113. 0, 2, 4, 6, 8, 10, 12, 14,
  152114. 16, 18, 20, 22, 24, 26, 28, 30,
  152115. 32, 34, 36, 38, 40, 42, 44, 46,
  152116. 48,
  152117. };
  152118. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152119. _vq_quantthresh__44u9_p9_2,
  152120. _vq_quantmap__44u9_p9_2,
  152121. 49,
  152122. 49
  152123. };
  152124. static static_codebook _44u9_p9_2 = {
  152125. 1, 49,
  152126. _vq_lengthlist__44u9_p9_2,
  152127. 1, -526909440, 1611661312, 6, 0,
  152128. _vq_quantlist__44u9_p9_2,
  152129. NULL,
  152130. &_vq_auxt__44u9_p9_2,
  152131. NULL,
  152132. 0
  152133. };
  152134. static long _huff_lengthlist__44un1__long[] = {
  152135. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152136. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152137. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152138. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152139. };
  152140. static static_codebook _huff_book__44un1__long = {
  152141. 2, 64,
  152142. _huff_lengthlist__44un1__long,
  152143. 0, 0, 0, 0, 0,
  152144. NULL,
  152145. NULL,
  152146. NULL,
  152147. NULL,
  152148. 0
  152149. };
  152150. static long _vq_quantlist__44un1__p1_0[] = {
  152151. 1,
  152152. 0,
  152153. 2,
  152154. };
  152155. static long _vq_lengthlist__44un1__p1_0[] = {
  152156. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152157. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152158. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152159. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152160. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152161. 12,
  152162. };
  152163. static float _vq_quantthresh__44un1__p1_0[] = {
  152164. -0.5, 0.5,
  152165. };
  152166. static long _vq_quantmap__44un1__p1_0[] = {
  152167. 1, 0, 2,
  152168. };
  152169. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152170. _vq_quantthresh__44un1__p1_0,
  152171. _vq_quantmap__44un1__p1_0,
  152172. 3,
  152173. 3
  152174. };
  152175. static static_codebook _44un1__p1_0 = {
  152176. 4, 81,
  152177. _vq_lengthlist__44un1__p1_0,
  152178. 1, -535822336, 1611661312, 2, 0,
  152179. _vq_quantlist__44un1__p1_0,
  152180. NULL,
  152181. &_vq_auxt__44un1__p1_0,
  152182. NULL,
  152183. 0
  152184. };
  152185. static long _vq_quantlist__44un1__p2_0[] = {
  152186. 1,
  152187. 0,
  152188. 2,
  152189. };
  152190. static long _vq_lengthlist__44un1__p2_0[] = {
  152191. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152192. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152193. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152194. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152195. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152196. 8,
  152197. };
  152198. static float _vq_quantthresh__44un1__p2_0[] = {
  152199. -0.5, 0.5,
  152200. };
  152201. static long _vq_quantmap__44un1__p2_0[] = {
  152202. 1, 0, 2,
  152203. };
  152204. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152205. _vq_quantthresh__44un1__p2_0,
  152206. _vq_quantmap__44un1__p2_0,
  152207. 3,
  152208. 3
  152209. };
  152210. static static_codebook _44un1__p2_0 = {
  152211. 4, 81,
  152212. _vq_lengthlist__44un1__p2_0,
  152213. 1, -535822336, 1611661312, 2, 0,
  152214. _vq_quantlist__44un1__p2_0,
  152215. NULL,
  152216. &_vq_auxt__44un1__p2_0,
  152217. NULL,
  152218. 0
  152219. };
  152220. static long _vq_quantlist__44un1__p3_0[] = {
  152221. 2,
  152222. 1,
  152223. 3,
  152224. 0,
  152225. 4,
  152226. };
  152227. static long _vq_lengthlist__44un1__p3_0[] = {
  152228. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152229. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152230. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152231. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152232. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152233. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152234. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152235. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152236. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152237. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152238. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152239. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152240. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152241. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152242. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152243. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152244. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152245. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152246. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152247. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152248. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152249. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152250. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152251. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152252. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152253. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152254. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152255. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152256. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152257. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152258. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152259. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152260. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152261. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152262. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152263. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152264. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152265. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152266. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152267. 17,
  152268. };
  152269. static float _vq_quantthresh__44un1__p3_0[] = {
  152270. -1.5, -0.5, 0.5, 1.5,
  152271. };
  152272. static long _vq_quantmap__44un1__p3_0[] = {
  152273. 3, 1, 0, 2, 4,
  152274. };
  152275. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152276. _vq_quantthresh__44un1__p3_0,
  152277. _vq_quantmap__44un1__p3_0,
  152278. 5,
  152279. 5
  152280. };
  152281. static static_codebook _44un1__p3_0 = {
  152282. 4, 625,
  152283. _vq_lengthlist__44un1__p3_0,
  152284. 1, -533725184, 1611661312, 3, 0,
  152285. _vq_quantlist__44un1__p3_0,
  152286. NULL,
  152287. &_vq_auxt__44un1__p3_0,
  152288. NULL,
  152289. 0
  152290. };
  152291. static long _vq_quantlist__44un1__p4_0[] = {
  152292. 2,
  152293. 1,
  152294. 3,
  152295. 0,
  152296. 4,
  152297. };
  152298. static long _vq_lengthlist__44un1__p4_0[] = {
  152299. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152300. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152301. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152302. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152303. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152304. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152305. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152306. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152307. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152308. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152309. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152310. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152311. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152312. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152313. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152314. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152315. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152316. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152317. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152318. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152319. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152320. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152321. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152322. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152323. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152324. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152325. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152326. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152327. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152328. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152329. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152330. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152331. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152332. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152333. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152334. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152335. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152336. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152337. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152338. 12,
  152339. };
  152340. static float _vq_quantthresh__44un1__p4_0[] = {
  152341. -1.5, -0.5, 0.5, 1.5,
  152342. };
  152343. static long _vq_quantmap__44un1__p4_0[] = {
  152344. 3, 1, 0, 2, 4,
  152345. };
  152346. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152347. _vq_quantthresh__44un1__p4_0,
  152348. _vq_quantmap__44un1__p4_0,
  152349. 5,
  152350. 5
  152351. };
  152352. static static_codebook _44un1__p4_0 = {
  152353. 4, 625,
  152354. _vq_lengthlist__44un1__p4_0,
  152355. 1, -533725184, 1611661312, 3, 0,
  152356. _vq_quantlist__44un1__p4_0,
  152357. NULL,
  152358. &_vq_auxt__44un1__p4_0,
  152359. NULL,
  152360. 0
  152361. };
  152362. static long _vq_quantlist__44un1__p5_0[] = {
  152363. 4,
  152364. 3,
  152365. 5,
  152366. 2,
  152367. 6,
  152368. 1,
  152369. 7,
  152370. 0,
  152371. 8,
  152372. };
  152373. static long _vq_lengthlist__44un1__p5_0[] = {
  152374. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152375. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152376. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152377. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152378. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152379. 12,
  152380. };
  152381. static float _vq_quantthresh__44un1__p5_0[] = {
  152382. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152383. };
  152384. static long _vq_quantmap__44un1__p5_0[] = {
  152385. 7, 5, 3, 1, 0, 2, 4, 6,
  152386. 8,
  152387. };
  152388. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152389. _vq_quantthresh__44un1__p5_0,
  152390. _vq_quantmap__44un1__p5_0,
  152391. 9,
  152392. 9
  152393. };
  152394. static static_codebook _44un1__p5_0 = {
  152395. 2, 81,
  152396. _vq_lengthlist__44un1__p5_0,
  152397. 1, -531628032, 1611661312, 4, 0,
  152398. _vq_quantlist__44un1__p5_0,
  152399. NULL,
  152400. &_vq_auxt__44un1__p5_0,
  152401. NULL,
  152402. 0
  152403. };
  152404. static long _vq_quantlist__44un1__p6_0[] = {
  152405. 6,
  152406. 5,
  152407. 7,
  152408. 4,
  152409. 8,
  152410. 3,
  152411. 9,
  152412. 2,
  152413. 10,
  152414. 1,
  152415. 11,
  152416. 0,
  152417. 12,
  152418. };
  152419. static long _vq_lengthlist__44un1__p6_0[] = {
  152420. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152421. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152422. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152423. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152424. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152425. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152426. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152427. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152428. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152429. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152430. 16, 0,15,18,18, 0,16, 0, 0,
  152431. };
  152432. static float _vq_quantthresh__44un1__p6_0[] = {
  152433. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152434. 12.5, 17.5, 22.5, 27.5,
  152435. };
  152436. static long _vq_quantmap__44un1__p6_0[] = {
  152437. 11, 9, 7, 5, 3, 1, 0, 2,
  152438. 4, 6, 8, 10, 12,
  152439. };
  152440. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152441. _vq_quantthresh__44un1__p6_0,
  152442. _vq_quantmap__44un1__p6_0,
  152443. 13,
  152444. 13
  152445. };
  152446. static static_codebook _44un1__p6_0 = {
  152447. 2, 169,
  152448. _vq_lengthlist__44un1__p6_0,
  152449. 1, -526516224, 1616117760, 4, 0,
  152450. _vq_quantlist__44un1__p6_0,
  152451. NULL,
  152452. &_vq_auxt__44un1__p6_0,
  152453. NULL,
  152454. 0
  152455. };
  152456. static long _vq_quantlist__44un1__p6_1[] = {
  152457. 2,
  152458. 1,
  152459. 3,
  152460. 0,
  152461. 4,
  152462. };
  152463. static long _vq_lengthlist__44un1__p6_1[] = {
  152464. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152465. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152466. };
  152467. static float _vq_quantthresh__44un1__p6_1[] = {
  152468. -1.5, -0.5, 0.5, 1.5,
  152469. };
  152470. static long _vq_quantmap__44un1__p6_1[] = {
  152471. 3, 1, 0, 2, 4,
  152472. };
  152473. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152474. _vq_quantthresh__44un1__p6_1,
  152475. _vq_quantmap__44un1__p6_1,
  152476. 5,
  152477. 5
  152478. };
  152479. static static_codebook _44un1__p6_1 = {
  152480. 2, 25,
  152481. _vq_lengthlist__44un1__p6_1,
  152482. 1, -533725184, 1611661312, 3, 0,
  152483. _vq_quantlist__44un1__p6_1,
  152484. NULL,
  152485. &_vq_auxt__44un1__p6_1,
  152486. NULL,
  152487. 0
  152488. };
  152489. static long _vq_quantlist__44un1__p7_0[] = {
  152490. 2,
  152491. 1,
  152492. 3,
  152493. 0,
  152494. 4,
  152495. };
  152496. static long _vq_lengthlist__44un1__p7_0[] = {
  152497. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152498. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152500. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152504. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152506. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152512. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152514. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152524. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152525. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152526. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152527. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152533. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152534. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152536. 10,
  152537. };
  152538. static float _vq_quantthresh__44un1__p7_0[] = {
  152539. -253.5, -84.5, 84.5, 253.5,
  152540. };
  152541. static long _vq_quantmap__44un1__p7_0[] = {
  152542. 3, 1, 0, 2, 4,
  152543. };
  152544. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152545. _vq_quantthresh__44un1__p7_0,
  152546. _vq_quantmap__44un1__p7_0,
  152547. 5,
  152548. 5
  152549. };
  152550. static static_codebook _44un1__p7_0 = {
  152551. 4, 625,
  152552. _vq_lengthlist__44un1__p7_0,
  152553. 1, -518709248, 1626677248, 3, 0,
  152554. _vq_quantlist__44un1__p7_0,
  152555. NULL,
  152556. &_vq_auxt__44un1__p7_0,
  152557. NULL,
  152558. 0
  152559. };
  152560. static long _vq_quantlist__44un1__p7_1[] = {
  152561. 6,
  152562. 5,
  152563. 7,
  152564. 4,
  152565. 8,
  152566. 3,
  152567. 9,
  152568. 2,
  152569. 10,
  152570. 1,
  152571. 11,
  152572. 0,
  152573. 12,
  152574. };
  152575. static long _vq_lengthlist__44un1__p7_1[] = {
  152576. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152577. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152578. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152579. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152580. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152581. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152582. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152583. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152584. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152585. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152586. 12,13,13,12,13,13,14,14,14,
  152587. };
  152588. static float _vq_quantthresh__44un1__p7_1[] = {
  152589. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152590. 32.5, 45.5, 58.5, 71.5,
  152591. };
  152592. static long _vq_quantmap__44un1__p7_1[] = {
  152593. 11, 9, 7, 5, 3, 1, 0, 2,
  152594. 4, 6, 8, 10, 12,
  152595. };
  152596. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152597. _vq_quantthresh__44un1__p7_1,
  152598. _vq_quantmap__44un1__p7_1,
  152599. 13,
  152600. 13
  152601. };
  152602. static static_codebook _44un1__p7_1 = {
  152603. 2, 169,
  152604. _vq_lengthlist__44un1__p7_1,
  152605. 1, -523010048, 1618608128, 4, 0,
  152606. _vq_quantlist__44un1__p7_1,
  152607. NULL,
  152608. &_vq_auxt__44un1__p7_1,
  152609. NULL,
  152610. 0
  152611. };
  152612. static long _vq_quantlist__44un1__p7_2[] = {
  152613. 6,
  152614. 5,
  152615. 7,
  152616. 4,
  152617. 8,
  152618. 3,
  152619. 9,
  152620. 2,
  152621. 10,
  152622. 1,
  152623. 11,
  152624. 0,
  152625. 12,
  152626. };
  152627. static long _vq_lengthlist__44un1__p7_2[] = {
  152628. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152629. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152630. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152631. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152632. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152633. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152634. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152635. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152636. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152637. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152638. 9, 9, 9,10,10,10,10,10,10,
  152639. };
  152640. static float _vq_quantthresh__44un1__p7_2[] = {
  152641. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152642. 2.5, 3.5, 4.5, 5.5,
  152643. };
  152644. static long _vq_quantmap__44un1__p7_2[] = {
  152645. 11, 9, 7, 5, 3, 1, 0, 2,
  152646. 4, 6, 8, 10, 12,
  152647. };
  152648. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152649. _vq_quantthresh__44un1__p7_2,
  152650. _vq_quantmap__44un1__p7_2,
  152651. 13,
  152652. 13
  152653. };
  152654. static static_codebook _44un1__p7_2 = {
  152655. 2, 169,
  152656. _vq_lengthlist__44un1__p7_2,
  152657. 1, -531103744, 1611661312, 4, 0,
  152658. _vq_quantlist__44un1__p7_2,
  152659. NULL,
  152660. &_vq_auxt__44un1__p7_2,
  152661. NULL,
  152662. 0
  152663. };
  152664. static long _huff_lengthlist__44un1__short[] = {
  152665. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152666. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152667. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152668. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152669. };
  152670. static static_codebook _huff_book__44un1__short = {
  152671. 2, 64,
  152672. _huff_lengthlist__44un1__short,
  152673. 0, 0, 0, 0, 0,
  152674. NULL,
  152675. NULL,
  152676. NULL,
  152677. NULL,
  152678. 0
  152679. };
  152680. /*** End of inlined file: res_books_uncoupled.h ***/
  152681. /***** residue backends *********************************************/
  152682. static vorbis_info_residue0 _residue_44_low_un={
  152683. 0,-1, -1, 8,-1,
  152684. {0},
  152685. {-1},
  152686. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152687. { -1, 25, -1, 45, -1, -1, -1}
  152688. };
  152689. static vorbis_info_residue0 _residue_44_mid_un={
  152690. 0,-1, -1, 10,-1,
  152691. /* 0 1 2 3 4 5 6 7 8 9 */
  152692. {0},
  152693. {-1},
  152694. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152695. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152696. };
  152697. static vorbis_info_residue0 _residue_44_hi_un={
  152698. 0,-1, -1, 10,-1,
  152699. /* 0 1 2 3 4 5 6 7 8 9 */
  152700. {0},
  152701. {-1},
  152702. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152703. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152704. };
  152705. /* mapping conventions:
  152706. only one submap (this would change for efficient 5.1 support for example)*/
  152707. /* Four psychoacoustic profiles are used, one for each blocktype */
  152708. static vorbis_info_mapping0 _map_nominal_u[2]={
  152709. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152710. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152711. };
  152712. static static_bookblock _resbook_44u_n1={
  152713. {
  152714. {0},
  152715. {0,0,&_44un1__p1_0},
  152716. {0,0,&_44un1__p2_0},
  152717. {0,0,&_44un1__p3_0},
  152718. {0,0,&_44un1__p4_0},
  152719. {0,0,&_44un1__p5_0},
  152720. {&_44un1__p6_0,&_44un1__p6_1},
  152721. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152722. }
  152723. };
  152724. static static_bookblock _resbook_44u_0={
  152725. {
  152726. {0},
  152727. {0,0,&_44u0__p1_0},
  152728. {0,0,&_44u0__p2_0},
  152729. {0,0,&_44u0__p3_0},
  152730. {0,0,&_44u0__p4_0},
  152731. {0,0,&_44u0__p5_0},
  152732. {&_44u0__p6_0,&_44u0__p6_1},
  152733. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152734. }
  152735. };
  152736. static static_bookblock _resbook_44u_1={
  152737. {
  152738. {0},
  152739. {0,0,&_44u1__p1_0},
  152740. {0,0,&_44u1__p2_0},
  152741. {0,0,&_44u1__p3_0},
  152742. {0,0,&_44u1__p4_0},
  152743. {0,0,&_44u1__p5_0},
  152744. {&_44u1__p6_0,&_44u1__p6_1},
  152745. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152746. }
  152747. };
  152748. static static_bookblock _resbook_44u_2={
  152749. {
  152750. {0},
  152751. {0,0,&_44u2__p1_0},
  152752. {0,0,&_44u2__p2_0},
  152753. {0,0,&_44u2__p3_0},
  152754. {0,0,&_44u2__p4_0},
  152755. {0,0,&_44u2__p5_0},
  152756. {&_44u2__p6_0,&_44u2__p6_1},
  152757. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152758. }
  152759. };
  152760. static static_bookblock _resbook_44u_3={
  152761. {
  152762. {0},
  152763. {0,0,&_44u3__p1_0},
  152764. {0,0,&_44u3__p2_0},
  152765. {0,0,&_44u3__p3_0},
  152766. {0,0,&_44u3__p4_0},
  152767. {0,0,&_44u3__p5_0},
  152768. {&_44u3__p6_0,&_44u3__p6_1},
  152769. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152770. }
  152771. };
  152772. static static_bookblock _resbook_44u_4={
  152773. {
  152774. {0},
  152775. {0,0,&_44u4__p1_0},
  152776. {0,0,&_44u4__p2_0},
  152777. {0,0,&_44u4__p3_0},
  152778. {0,0,&_44u4__p4_0},
  152779. {0,0,&_44u4__p5_0},
  152780. {&_44u4__p6_0,&_44u4__p6_1},
  152781. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152782. }
  152783. };
  152784. static static_bookblock _resbook_44u_5={
  152785. {
  152786. {0},
  152787. {0,0,&_44u5__p1_0},
  152788. {0,0,&_44u5__p2_0},
  152789. {0,0,&_44u5__p3_0},
  152790. {0,0,&_44u5__p4_0},
  152791. {0,0,&_44u5__p5_0},
  152792. {0,0,&_44u5__p6_0},
  152793. {&_44u5__p7_0,&_44u5__p7_1},
  152794. {&_44u5__p8_0,&_44u5__p8_1},
  152795. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152796. }
  152797. };
  152798. static static_bookblock _resbook_44u_6={
  152799. {
  152800. {0},
  152801. {0,0,&_44u6__p1_0},
  152802. {0,0,&_44u6__p2_0},
  152803. {0,0,&_44u6__p3_0},
  152804. {0,0,&_44u6__p4_0},
  152805. {0,0,&_44u6__p5_0},
  152806. {0,0,&_44u6__p6_0},
  152807. {&_44u6__p7_0,&_44u6__p7_1},
  152808. {&_44u6__p8_0,&_44u6__p8_1},
  152809. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152810. }
  152811. };
  152812. static static_bookblock _resbook_44u_7={
  152813. {
  152814. {0},
  152815. {0,0,&_44u7__p1_0},
  152816. {0,0,&_44u7__p2_0},
  152817. {0,0,&_44u7__p3_0},
  152818. {0,0,&_44u7__p4_0},
  152819. {0,0,&_44u7__p5_0},
  152820. {0,0,&_44u7__p6_0},
  152821. {&_44u7__p7_0,&_44u7__p7_1},
  152822. {&_44u7__p8_0,&_44u7__p8_1},
  152823. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152824. }
  152825. };
  152826. static static_bookblock _resbook_44u_8={
  152827. {
  152828. {0},
  152829. {0,0,&_44u8_p1_0},
  152830. {0,0,&_44u8_p2_0},
  152831. {0,0,&_44u8_p3_0},
  152832. {0,0,&_44u8_p4_0},
  152833. {&_44u8_p5_0,&_44u8_p5_1},
  152834. {&_44u8_p6_0,&_44u8_p6_1},
  152835. {&_44u8_p7_0,&_44u8_p7_1},
  152836. {&_44u8_p8_0,&_44u8_p8_1},
  152837. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152838. }
  152839. };
  152840. static static_bookblock _resbook_44u_9={
  152841. {
  152842. {0},
  152843. {0,0,&_44u9_p1_0},
  152844. {0,0,&_44u9_p2_0},
  152845. {0,0,&_44u9_p3_0},
  152846. {0,0,&_44u9_p4_0},
  152847. {&_44u9_p5_0,&_44u9_p5_1},
  152848. {&_44u9_p6_0,&_44u9_p6_1},
  152849. {&_44u9_p7_0,&_44u9_p7_1},
  152850. {&_44u9_p8_0,&_44u9_p8_1},
  152851. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152852. }
  152853. };
  152854. static vorbis_residue_template _res_44u_n1[]={
  152855. {1,0, &_residue_44_low_un,
  152856. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152857. &_resbook_44u_n1,&_resbook_44u_n1},
  152858. {1,0, &_residue_44_low_un,
  152859. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152860. &_resbook_44u_n1,&_resbook_44u_n1}
  152861. };
  152862. static vorbis_residue_template _res_44u_0[]={
  152863. {1,0, &_residue_44_low_un,
  152864. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152865. &_resbook_44u_0,&_resbook_44u_0},
  152866. {1,0, &_residue_44_low_un,
  152867. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152868. &_resbook_44u_0,&_resbook_44u_0}
  152869. };
  152870. static vorbis_residue_template _res_44u_1[]={
  152871. {1,0, &_residue_44_low_un,
  152872. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152873. &_resbook_44u_1,&_resbook_44u_1},
  152874. {1,0, &_residue_44_low_un,
  152875. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152876. &_resbook_44u_1,&_resbook_44u_1}
  152877. };
  152878. static vorbis_residue_template _res_44u_2[]={
  152879. {1,0, &_residue_44_low_un,
  152880. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152881. &_resbook_44u_2,&_resbook_44u_2},
  152882. {1,0, &_residue_44_low_un,
  152883. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152884. &_resbook_44u_2,&_resbook_44u_2}
  152885. };
  152886. static vorbis_residue_template _res_44u_3[]={
  152887. {1,0, &_residue_44_low_un,
  152888. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152889. &_resbook_44u_3,&_resbook_44u_3},
  152890. {1,0, &_residue_44_low_un,
  152891. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152892. &_resbook_44u_3,&_resbook_44u_3}
  152893. };
  152894. static vorbis_residue_template _res_44u_4[]={
  152895. {1,0, &_residue_44_low_un,
  152896. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152897. &_resbook_44u_4,&_resbook_44u_4},
  152898. {1,0, &_residue_44_low_un,
  152899. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152900. &_resbook_44u_4,&_resbook_44u_4}
  152901. };
  152902. static vorbis_residue_template _res_44u_5[]={
  152903. {1,0, &_residue_44_mid_un,
  152904. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152905. &_resbook_44u_5,&_resbook_44u_5},
  152906. {1,0, &_residue_44_mid_un,
  152907. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152908. &_resbook_44u_5,&_resbook_44u_5}
  152909. };
  152910. static vorbis_residue_template _res_44u_6[]={
  152911. {1,0, &_residue_44_mid_un,
  152912. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152913. &_resbook_44u_6,&_resbook_44u_6},
  152914. {1,0, &_residue_44_mid_un,
  152915. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152916. &_resbook_44u_6,&_resbook_44u_6}
  152917. };
  152918. static vorbis_residue_template _res_44u_7[]={
  152919. {1,0, &_residue_44_mid_un,
  152920. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152921. &_resbook_44u_7,&_resbook_44u_7},
  152922. {1,0, &_residue_44_mid_un,
  152923. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152924. &_resbook_44u_7,&_resbook_44u_7}
  152925. };
  152926. static vorbis_residue_template _res_44u_8[]={
  152927. {1,0, &_residue_44_hi_un,
  152928. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152929. &_resbook_44u_8,&_resbook_44u_8},
  152930. {1,0, &_residue_44_hi_un,
  152931. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152932. &_resbook_44u_8,&_resbook_44u_8}
  152933. };
  152934. static vorbis_residue_template _res_44u_9[]={
  152935. {1,0, &_residue_44_hi_un,
  152936. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152937. &_resbook_44u_9,&_resbook_44u_9},
  152938. {1,0, &_residue_44_hi_un,
  152939. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152940. &_resbook_44u_9,&_resbook_44u_9}
  152941. };
  152942. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152943. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152944. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152945. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152946. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152947. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152948. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152949. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152950. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152951. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152952. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152953. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152954. };
  152955. /*** End of inlined file: residue_44u.h ***/
  152956. static double rate_mapping_44_un[12]={
  152957. 32000.,48000.,60000.,70000.,80000.,86000.,
  152958. 96000.,110000.,120000.,140000.,160000.,240001.
  152959. };
  152960. ve_setup_data_template ve_setup_44_uncoupled={
  152961. 11,
  152962. rate_mapping_44_un,
  152963. quality_mapping_44,
  152964. -1,
  152965. 40000,
  152966. 50000,
  152967. blocksize_short_44,
  152968. blocksize_long_44,
  152969. _psy_tone_masteratt_44,
  152970. _psy_tone_0dB,
  152971. _psy_tone_suppress,
  152972. _vp_tonemask_adj_otherblock,
  152973. _vp_tonemask_adj_longblock,
  152974. _vp_tonemask_adj_otherblock,
  152975. _psy_noiseguards_44,
  152976. _psy_noisebias_impulse,
  152977. _psy_noisebias_padding,
  152978. _psy_noisebias_trans,
  152979. _psy_noisebias_long,
  152980. _psy_noise_suppress,
  152981. _psy_compand_44,
  152982. _psy_compand_short_mapping,
  152983. _psy_compand_long_mapping,
  152984. {_noise_start_short_44,_noise_start_long_44},
  152985. {_noise_part_short_44,_noise_part_long_44},
  152986. _noise_thresh_44,
  152987. _psy_ath_floater,
  152988. _psy_ath_abs,
  152989. _psy_lowpass_44,
  152990. _psy_global_44,
  152991. _global_mapping_44,
  152992. NULL,
  152993. _floor_books,
  152994. _floor,
  152995. _floor_short_mapping_44,
  152996. _floor_long_mapping_44,
  152997. _mapres_template_44_uncoupled
  152998. };
  152999. /*** End of inlined file: setup_44u.h ***/
  153000. /*** Start of inlined file: setup_32.h ***/
  153001. static double rate_mapping_32[12]={
  153002. 18000.,28000.,35000.,45000.,56000.,60000.,
  153003. 75000.,90000.,100000.,115000.,150000.,190000.,
  153004. };
  153005. static double rate_mapping_32_un[12]={
  153006. 30000.,42000.,52000.,64000.,72000.,78000.,
  153007. 86000.,92000.,110000.,120000.,140000.,190000.,
  153008. };
  153009. static double _psy_lowpass_32[12]={
  153010. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153011. };
  153012. ve_setup_data_template ve_setup_32_stereo={
  153013. 11,
  153014. rate_mapping_32,
  153015. quality_mapping_44,
  153016. 2,
  153017. 26000,
  153018. 40000,
  153019. blocksize_short_44,
  153020. blocksize_long_44,
  153021. _psy_tone_masteratt_44,
  153022. _psy_tone_0dB,
  153023. _psy_tone_suppress,
  153024. _vp_tonemask_adj_otherblock,
  153025. _vp_tonemask_adj_longblock,
  153026. _vp_tonemask_adj_otherblock,
  153027. _psy_noiseguards_44,
  153028. _psy_noisebias_impulse,
  153029. _psy_noisebias_padding,
  153030. _psy_noisebias_trans,
  153031. _psy_noisebias_long,
  153032. _psy_noise_suppress,
  153033. _psy_compand_44,
  153034. _psy_compand_short_mapping,
  153035. _psy_compand_long_mapping,
  153036. {_noise_start_short_44,_noise_start_long_44},
  153037. {_noise_part_short_44,_noise_part_long_44},
  153038. _noise_thresh_44,
  153039. _psy_ath_floater,
  153040. _psy_ath_abs,
  153041. _psy_lowpass_32,
  153042. _psy_global_44,
  153043. _global_mapping_44,
  153044. _psy_stereo_modes_44,
  153045. _floor_books,
  153046. _floor,
  153047. _floor_short_mapping_44,
  153048. _floor_long_mapping_44,
  153049. _mapres_template_44_stereo
  153050. };
  153051. ve_setup_data_template ve_setup_32_uncoupled={
  153052. 11,
  153053. rate_mapping_32_un,
  153054. quality_mapping_44,
  153055. -1,
  153056. 26000,
  153057. 40000,
  153058. blocksize_short_44,
  153059. blocksize_long_44,
  153060. _psy_tone_masteratt_44,
  153061. _psy_tone_0dB,
  153062. _psy_tone_suppress,
  153063. _vp_tonemask_adj_otherblock,
  153064. _vp_tonemask_adj_longblock,
  153065. _vp_tonemask_adj_otherblock,
  153066. _psy_noiseguards_44,
  153067. _psy_noisebias_impulse,
  153068. _psy_noisebias_padding,
  153069. _psy_noisebias_trans,
  153070. _psy_noisebias_long,
  153071. _psy_noise_suppress,
  153072. _psy_compand_44,
  153073. _psy_compand_short_mapping,
  153074. _psy_compand_long_mapping,
  153075. {_noise_start_short_44,_noise_start_long_44},
  153076. {_noise_part_short_44,_noise_part_long_44},
  153077. _noise_thresh_44,
  153078. _psy_ath_floater,
  153079. _psy_ath_abs,
  153080. _psy_lowpass_32,
  153081. _psy_global_44,
  153082. _global_mapping_44,
  153083. NULL,
  153084. _floor_books,
  153085. _floor,
  153086. _floor_short_mapping_44,
  153087. _floor_long_mapping_44,
  153088. _mapres_template_44_uncoupled
  153089. };
  153090. /*** End of inlined file: setup_32.h ***/
  153091. /*** Start of inlined file: setup_8.h ***/
  153092. /*** Start of inlined file: psych_8.h ***/
  153093. static att3 _psy_tone_masteratt_8[3]={
  153094. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153095. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153096. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153097. };
  153098. static vp_adjblock _vp_tonemask_adj_8[3]={
  153099. /* adjust for mode zero */
  153100. /* 63 125 250 500 1 2 4 8 16 */
  153101. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153102. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153103. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153104. };
  153105. static noise3 _psy_noisebias_8[3]={
  153106. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153107. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153108. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153109. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153110. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153111. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153112. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153113. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153114. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153115. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153116. };
  153117. /* stereo mode by base quality level */
  153118. static adj_stereo _psy_stereo_modes_8[3]={
  153119. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153120. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153121. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153122. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153123. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153124. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153125. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153126. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153127. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153128. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153129. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153130. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153131. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153132. };
  153133. static noiseguard _psy_noiseguards_8[2]={
  153134. {10,10,-1},
  153135. {10,10,-1},
  153136. };
  153137. static compandblock _psy_compand_8[2]={
  153138. {{
  153139. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153140. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153141. 12,12,13,13,14,14,15, 15, /* 23dB */
  153142. 16,16,17,17,17,18,18, 19, /* 31dB */
  153143. 19,19,20,21,22,23,24, 25, /* 39dB */
  153144. }},
  153145. {{
  153146. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153147. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153148. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153149. 9,10,11,12,13,14,15, 16, /* 31dB */
  153150. 17,18,19,20,21,22,23, 24, /* 39dB */
  153151. }},
  153152. };
  153153. static double _psy_lowpass_8[3]={3.,4.,4.};
  153154. static int _noise_start_8[2]={
  153155. 64,64,
  153156. };
  153157. static int _noise_part_8[2]={
  153158. 8,8,
  153159. };
  153160. static int _psy_ath_floater_8[3]={
  153161. -100,-100,-105,
  153162. };
  153163. static int _psy_ath_abs_8[3]={
  153164. -130,-130,-140,
  153165. };
  153166. /*** End of inlined file: psych_8.h ***/
  153167. /*** Start of inlined file: residue_8.h ***/
  153168. /***** residue backends *********************************************/
  153169. static static_bookblock _resbook_8s_0={
  153170. {
  153171. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153172. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153173. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153174. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153175. }
  153176. };
  153177. static static_bookblock _resbook_8s_1={
  153178. {
  153179. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153180. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153181. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153182. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153183. }
  153184. };
  153185. static vorbis_residue_template _res_8s_0[]={
  153186. {2,0, &_residue_44_mid,
  153187. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153188. &_resbook_8s_0,&_resbook_8s_0},
  153189. };
  153190. static vorbis_residue_template _res_8s_1[]={
  153191. {2,0, &_residue_44_mid,
  153192. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153193. &_resbook_8s_1,&_resbook_8s_1},
  153194. };
  153195. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153196. { _map_nominal, _res_8s_0 }, /* 0 */
  153197. { _map_nominal, _res_8s_1 }, /* 1 */
  153198. };
  153199. static static_bookblock _resbook_8u_0={
  153200. {
  153201. {0},
  153202. {0,0,&_8u0__p1_0},
  153203. {0,0,&_8u0__p2_0},
  153204. {0,0,&_8u0__p3_0},
  153205. {0,0,&_8u0__p4_0},
  153206. {0,0,&_8u0__p5_0},
  153207. {&_8u0__p6_0,&_8u0__p6_1},
  153208. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153209. }
  153210. };
  153211. static static_bookblock _resbook_8u_1={
  153212. {
  153213. {0},
  153214. {0,0,&_8u1__p1_0},
  153215. {0,0,&_8u1__p2_0},
  153216. {0,0,&_8u1__p3_0},
  153217. {0,0,&_8u1__p4_0},
  153218. {0,0,&_8u1__p5_0},
  153219. {0,0,&_8u1__p6_0},
  153220. {&_8u1__p7_0,&_8u1__p7_1},
  153221. {&_8u1__p8_0,&_8u1__p8_1},
  153222. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153223. }
  153224. };
  153225. static vorbis_residue_template _res_8u_0[]={
  153226. {1,0, &_residue_44_low_un,
  153227. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153228. &_resbook_8u_0,&_resbook_8u_0},
  153229. };
  153230. static vorbis_residue_template _res_8u_1[]={
  153231. {1,0, &_residue_44_mid_un,
  153232. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153233. &_resbook_8u_1,&_resbook_8u_1},
  153234. };
  153235. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153236. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153237. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153238. };
  153239. /*** End of inlined file: residue_8.h ***/
  153240. static int blocksize_8[2]={
  153241. 512,512
  153242. };
  153243. static int _floor_mapping_8[2]={
  153244. 6,6,
  153245. };
  153246. static double rate_mapping_8[3]={
  153247. 6000.,9000.,32000.,
  153248. };
  153249. static double rate_mapping_8_uncoupled[3]={
  153250. 8000.,14000.,42000.,
  153251. };
  153252. static double quality_mapping_8[3]={
  153253. -.1,.0,1.
  153254. };
  153255. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153256. static double _global_mapping_8[3]={ 1., 2., 3. };
  153257. ve_setup_data_template ve_setup_8_stereo={
  153258. 2,
  153259. rate_mapping_8,
  153260. quality_mapping_8,
  153261. 2,
  153262. 8000,
  153263. 9000,
  153264. blocksize_8,
  153265. blocksize_8,
  153266. _psy_tone_masteratt_8,
  153267. _psy_tone_0dB,
  153268. _psy_tone_suppress,
  153269. _vp_tonemask_adj_8,
  153270. NULL,
  153271. _vp_tonemask_adj_8,
  153272. _psy_noiseguards_8,
  153273. _psy_noisebias_8,
  153274. _psy_noisebias_8,
  153275. NULL,
  153276. NULL,
  153277. _psy_noise_suppress,
  153278. _psy_compand_8,
  153279. _psy_compand_8_mapping,
  153280. NULL,
  153281. {_noise_start_8,_noise_start_8},
  153282. {_noise_part_8,_noise_part_8},
  153283. _noise_thresh_5only,
  153284. _psy_ath_floater_8,
  153285. _psy_ath_abs_8,
  153286. _psy_lowpass_8,
  153287. _psy_global_44,
  153288. _global_mapping_8,
  153289. _psy_stereo_modes_8,
  153290. _floor_books,
  153291. _floor,
  153292. _floor_mapping_8,
  153293. NULL,
  153294. _mapres_template_8_stereo
  153295. };
  153296. ve_setup_data_template ve_setup_8_uncoupled={
  153297. 2,
  153298. rate_mapping_8_uncoupled,
  153299. quality_mapping_8,
  153300. -1,
  153301. 8000,
  153302. 9000,
  153303. blocksize_8,
  153304. blocksize_8,
  153305. _psy_tone_masteratt_8,
  153306. _psy_tone_0dB,
  153307. _psy_tone_suppress,
  153308. _vp_tonemask_adj_8,
  153309. NULL,
  153310. _vp_tonemask_adj_8,
  153311. _psy_noiseguards_8,
  153312. _psy_noisebias_8,
  153313. _psy_noisebias_8,
  153314. NULL,
  153315. NULL,
  153316. _psy_noise_suppress,
  153317. _psy_compand_8,
  153318. _psy_compand_8_mapping,
  153319. NULL,
  153320. {_noise_start_8,_noise_start_8},
  153321. {_noise_part_8,_noise_part_8},
  153322. _noise_thresh_5only,
  153323. _psy_ath_floater_8,
  153324. _psy_ath_abs_8,
  153325. _psy_lowpass_8,
  153326. _psy_global_44,
  153327. _global_mapping_8,
  153328. _psy_stereo_modes_8,
  153329. _floor_books,
  153330. _floor,
  153331. _floor_mapping_8,
  153332. NULL,
  153333. _mapres_template_8_uncoupled
  153334. };
  153335. /*** End of inlined file: setup_8.h ***/
  153336. /*** Start of inlined file: setup_11.h ***/
  153337. /*** Start of inlined file: psych_11.h ***/
  153338. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153339. static att3 _psy_tone_masteratt_11[3]={
  153340. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153341. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153342. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153343. };
  153344. static vp_adjblock _vp_tonemask_adj_11[3]={
  153345. /* adjust for mode zero */
  153346. /* 63 125 250 500 1 2 4 8 16 */
  153347. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153348. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153349. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153350. };
  153351. static noise3 _psy_noisebias_11[3]={
  153352. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153353. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153354. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153355. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153356. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153357. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153358. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153359. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153360. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153361. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153362. };
  153363. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153364. /*** End of inlined file: psych_11.h ***/
  153365. static int blocksize_11[2]={
  153366. 512,512
  153367. };
  153368. static int _floor_mapping_11[2]={
  153369. 6,6,
  153370. };
  153371. static double rate_mapping_11[3]={
  153372. 8000.,13000.,44000.,
  153373. };
  153374. static double rate_mapping_11_uncoupled[3]={
  153375. 12000.,20000.,50000.,
  153376. };
  153377. static double quality_mapping_11[3]={
  153378. -.1,.0,1.
  153379. };
  153380. ve_setup_data_template ve_setup_11_stereo={
  153381. 2,
  153382. rate_mapping_11,
  153383. quality_mapping_11,
  153384. 2,
  153385. 9000,
  153386. 15000,
  153387. blocksize_11,
  153388. blocksize_11,
  153389. _psy_tone_masteratt_11,
  153390. _psy_tone_0dB,
  153391. _psy_tone_suppress,
  153392. _vp_tonemask_adj_11,
  153393. NULL,
  153394. _vp_tonemask_adj_11,
  153395. _psy_noiseguards_8,
  153396. _psy_noisebias_11,
  153397. _psy_noisebias_11,
  153398. NULL,
  153399. NULL,
  153400. _psy_noise_suppress,
  153401. _psy_compand_8,
  153402. _psy_compand_8_mapping,
  153403. NULL,
  153404. {_noise_start_8,_noise_start_8},
  153405. {_noise_part_8,_noise_part_8},
  153406. _noise_thresh_11,
  153407. _psy_ath_floater_8,
  153408. _psy_ath_abs_8,
  153409. _psy_lowpass_11,
  153410. _psy_global_44,
  153411. _global_mapping_8,
  153412. _psy_stereo_modes_8,
  153413. _floor_books,
  153414. _floor,
  153415. _floor_mapping_11,
  153416. NULL,
  153417. _mapres_template_8_stereo
  153418. };
  153419. ve_setup_data_template ve_setup_11_uncoupled={
  153420. 2,
  153421. rate_mapping_11_uncoupled,
  153422. quality_mapping_11,
  153423. -1,
  153424. 9000,
  153425. 15000,
  153426. blocksize_11,
  153427. blocksize_11,
  153428. _psy_tone_masteratt_11,
  153429. _psy_tone_0dB,
  153430. _psy_tone_suppress,
  153431. _vp_tonemask_adj_11,
  153432. NULL,
  153433. _vp_tonemask_adj_11,
  153434. _psy_noiseguards_8,
  153435. _psy_noisebias_11,
  153436. _psy_noisebias_11,
  153437. NULL,
  153438. NULL,
  153439. _psy_noise_suppress,
  153440. _psy_compand_8,
  153441. _psy_compand_8_mapping,
  153442. NULL,
  153443. {_noise_start_8,_noise_start_8},
  153444. {_noise_part_8,_noise_part_8},
  153445. _noise_thresh_11,
  153446. _psy_ath_floater_8,
  153447. _psy_ath_abs_8,
  153448. _psy_lowpass_11,
  153449. _psy_global_44,
  153450. _global_mapping_8,
  153451. _psy_stereo_modes_8,
  153452. _floor_books,
  153453. _floor,
  153454. _floor_mapping_11,
  153455. NULL,
  153456. _mapres_template_8_uncoupled
  153457. };
  153458. /*** End of inlined file: setup_11.h ***/
  153459. /*** Start of inlined file: setup_16.h ***/
  153460. /*** Start of inlined file: psych_16.h ***/
  153461. /* stereo mode by base quality level */
  153462. static adj_stereo _psy_stereo_modes_16[4]={
  153463. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153464. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153465. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153466. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153467. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153468. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153469. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153470. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153471. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153472. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153473. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153474. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153475. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153476. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153477. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153478. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153479. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153480. };
  153481. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153482. static att3 _psy_tone_masteratt_16[4]={
  153483. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153484. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153485. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153486. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153487. };
  153488. static vp_adjblock _vp_tonemask_adj_16[4]={
  153489. /* adjust for mode zero */
  153490. /* 63 125 250 500 1 2 4 8 16 */
  153491. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153492. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153493. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153494. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153495. };
  153496. static noise3 _psy_noisebias_16_short[4]={
  153497. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153498. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153499. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153500. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153501. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153502. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153503. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153504. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153505. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153506. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153507. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153508. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153509. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153510. };
  153511. static noise3 _psy_noisebias_16_impulse[4]={
  153512. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153513. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153514. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153515. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153516. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153517. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153518. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153519. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153520. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153521. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153522. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153523. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153524. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153525. };
  153526. static noise3 _psy_noisebias_16[4]={
  153527. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153528. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153529. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153530. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153531. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153532. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153533. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153534. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153535. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153536. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153537. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153538. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153539. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153540. };
  153541. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153542. static int _noise_start_16[3]={ 256,256,9999 };
  153543. static int _noise_part_16[4]={ 8,8,8,8 };
  153544. static int _psy_ath_floater_16[4]={
  153545. -100,-100,-100,-105,
  153546. };
  153547. static int _psy_ath_abs_16[4]={
  153548. -130,-130,-130,-140,
  153549. };
  153550. /*** End of inlined file: psych_16.h ***/
  153551. /*** Start of inlined file: residue_16.h ***/
  153552. /***** residue backends *********************************************/
  153553. static static_bookblock _resbook_16s_0={
  153554. {
  153555. {0},
  153556. {0,0,&_16c0_s_p1_0},
  153557. {0,0,&_16c0_s_p2_0},
  153558. {0,0,&_16c0_s_p3_0},
  153559. {0,0,&_16c0_s_p4_0},
  153560. {0,0,&_16c0_s_p5_0},
  153561. {0,0,&_16c0_s_p6_0},
  153562. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153563. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153564. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153565. }
  153566. };
  153567. static static_bookblock _resbook_16s_1={
  153568. {
  153569. {0},
  153570. {0,0,&_16c1_s_p1_0},
  153571. {0,0,&_16c1_s_p2_0},
  153572. {0,0,&_16c1_s_p3_0},
  153573. {0,0,&_16c1_s_p4_0},
  153574. {0,0,&_16c1_s_p5_0},
  153575. {0,0,&_16c1_s_p6_0},
  153576. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153577. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153578. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153579. }
  153580. };
  153581. static static_bookblock _resbook_16s_2={
  153582. {
  153583. {0},
  153584. {0,0,&_16c2_s_p1_0},
  153585. {0,0,&_16c2_s_p2_0},
  153586. {0,0,&_16c2_s_p3_0},
  153587. {0,0,&_16c2_s_p4_0},
  153588. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153589. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153590. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153591. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153592. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153593. }
  153594. };
  153595. static vorbis_residue_template _res_16s_0[]={
  153596. {2,0, &_residue_44_mid,
  153597. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153598. &_resbook_16s_0,&_resbook_16s_0},
  153599. };
  153600. static vorbis_residue_template _res_16s_1[]={
  153601. {2,0, &_residue_44_mid,
  153602. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153603. &_resbook_16s_1,&_resbook_16s_1},
  153604. {2,0, &_residue_44_mid,
  153605. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153606. &_resbook_16s_1,&_resbook_16s_1}
  153607. };
  153608. static vorbis_residue_template _res_16s_2[]={
  153609. {2,0, &_residue_44_high,
  153610. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153611. &_resbook_16s_2,&_resbook_16s_2},
  153612. {2,0, &_residue_44_high,
  153613. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153614. &_resbook_16s_2,&_resbook_16s_2}
  153615. };
  153616. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153617. { _map_nominal, _res_16s_0 }, /* 0 */
  153618. { _map_nominal, _res_16s_1 }, /* 1 */
  153619. { _map_nominal, _res_16s_2 }, /* 2 */
  153620. };
  153621. static static_bookblock _resbook_16u_0={
  153622. {
  153623. {0},
  153624. {0,0,&_16u0__p1_0},
  153625. {0,0,&_16u0__p2_0},
  153626. {0,0,&_16u0__p3_0},
  153627. {0,0,&_16u0__p4_0},
  153628. {0,0,&_16u0__p5_0},
  153629. {&_16u0__p6_0,&_16u0__p6_1},
  153630. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153631. }
  153632. };
  153633. static static_bookblock _resbook_16u_1={
  153634. {
  153635. {0},
  153636. {0,0,&_16u1__p1_0},
  153637. {0,0,&_16u1__p2_0},
  153638. {0,0,&_16u1__p3_0},
  153639. {0,0,&_16u1__p4_0},
  153640. {0,0,&_16u1__p5_0},
  153641. {0,0,&_16u1__p6_0},
  153642. {&_16u1__p7_0,&_16u1__p7_1},
  153643. {&_16u1__p8_0,&_16u1__p8_1},
  153644. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153645. }
  153646. };
  153647. static static_bookblock _resbook_16u_2={
  153648. {
  153649. {0},
  153650. {0,0,&_16u2_p1_0},
  153651. {0,0,&_16u2_p2_0},
  153652. {0,0,&_16u2_p3_0},
  153653. {0,0,&_16u2_p4_0},
  153654. {&_16u2_p5_0,&_16u2_p5_1},
  153655. {&_16u2_p6_0,&_16u2_p6_1},
  153656. {&_16u2_p7_0,&_16u2_p7_1},
  153657. {&_16u2_p8_0,&_16u2_p8_1},
  153658. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153659. }
  153660. };
  153661. static vorbis_residue_template _res_16u_0[]={
  153662. {1,0, &_residue_44_low_un,
  153663. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153664. &_resbook_16u_0,&_resbook_16u_0},
  153665. };
  153666. static vorbis_residue_template _res_16u_1[]={
  153667. {1,0, &_residue_44_mid_un,
  153668. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153669. &_resbook_16u_1,&_resbook_16u_1},
  153670. {1,0, &_residue_44_mid_un,
  153671. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153672. &_resbook_16u_1,&_resbook_16u_1}
  153673. };
  153674. static vorbis_residue_template _res_16u_2[]={
  153675. {1,0, &_residue_44_hi_un,
  153676. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153677. &_resbook_16u_2,&_resbook_16u_2},
  153678. {1,0, &_residue_44_hi_un,
  153679. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153680. &_resbook_16u_2,&_resbook_16u_2}
  153681. };
  153682. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153683. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153684. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153685. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153686. };
  153687. /*** End of inlined file: residue_16.h ***/
  153688. static int blocksize_16_short[3]={
  153689. 1024,512,512
  153690. };
  153691. static int blocksize_16_long[3]={
  153692. 1024,1024,1024
  153693. };
  153694. static int _floor_mapping_16_short[3]={
  153695. 9,3,3
  153696. };
  153697. static int _floor_mapping_16[3]={
  153698. 9,9,9
  153699. };
  153700. static double rate_mapping_16[4]={
  153701. 12000.,20000.,44000.,86000.
  153702. };
  153703. static double rate_mapping_16_uncoupled[4]={
  153704. 16000.,28000.,64000.,100000.
  153705. };
  153706. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153707. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153708. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153709. ve_setup_data_template ve_setup_16_stereo={
  153710. 3,
  153711. rate_mapping_16,
  153712. quality_mapping_16,
  153713. 2,
  153714. 15000,
  153715. 19000,
  153716. blocksize_16_short,
  153717. blocksize_16_long,
  153718. _psy_tone_masteratt_16,
  153719. _psy_tone_0dB,
  153720. _psy_tone_suppress,
  153721. _vp_tonemask_adj_16,
  153722. _vp_tonemask_adj_16,
  153723. _vp_tonemask_adj_16,
  153724. _psy_noiseguards_8,
  153725. _psy_noisebias_16_impulse,
  153726. _psy_noisebias_16_short,
  153727. _psy_noisebias_16_short,
  153728. _psy_noisebias_16,
  153729. _psy_noise_suppress,
  153730. _psy_compand_8,
  153731. _psy_compand_16_mapping,
  153732. _psy_compand_16_mapping,
  153733. {_noise_start_16,_noise_start_16},
  153734. { _noise_part_16, _noise_part_16},
  153735. _noise_thresh_16,
  153736. _psy_ath_floater_16,
  153737. _psy_ath_abs_16,
  153738. _psy_lowpass_16,
  153739. _psy_global_44,
  153740. _global_mapping_16,
  153741. _psy_stereo_modes_16,
  153742. _floor_books,
  153743. _floor,
  153744. _floor_mapping_16_short,
  153745. _floor_mapping_16,
  153746. _mapres_template_16_stereo
  153747. };
  153748. ve_setup_data_template ve_setup_16_uncoupled={
  153749. 3,
  153750. rate_mapping_16_uncoupled,
  153751. quality_mapping_16,
  153752. -1,
  153753. 15000,
  153754. 19000,
  153755. blocksize_16_short,
  153756. blocksize_16_long,
  153757. _psy_tone_masteratt_16,
  153758. _psy_tone_0dB,
  153759. _psy_tone_suppress,
  153760. _vp_tonemask_adj_16,
  153761. _vp_tonemask_adj_16,
  153762. _vp_tonemask_adj_16,
  153763. _psy_noiseguards_8,
  153764. _psy_noisebias_16_impulse,
  153765. _psy_noisebias_16_short,
  153766. _psy_noisebias_16_short,
  153767. _psy_noisebias_16,
  153768. _psy_noise_suppress,
  153769. _psy_compand_8,
  153770. _psy_compand_16_mapping,
  153771. _psy_compand_16_mapping,
  153772. {_noise_start_16,_noise_start_16},
  153773. { _noise_part_16, _noise_part_16},
  153774. _noise_thresh_16,
  153775. _psy_ath_floater_16,
  153776. _psy_ath_abs_16,
  153777. _psy_lowpass_16,
  153778. _psy_global_44,
  153779. _global_mapping_16,
  153780. _psy_stereo_modes_16,
  153781. _floor_books,
  153782. _floor,
  153783. _floor_mapping_16_short,
  153784. _floor_mapping_16,
  153785. _mapres_template_16_uncoupled
  153786. };
  153787. /*** End of inlined file: setup_16.h ***/
  153788. /*** Start of inlined file: setup_22.h ***/
  153789. static double rate_mapping_22[4]={
  153790. 15000.,20000.,44000.,86000.
  153791. };
  153792. static double rate_mapping_22_uncoupled[4]={
  153793. 16000.,28000.,50000.,90000.
  153794. };
  153795. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153796. ve_setup_data_template ve_setup_22_stereo={
  153797. 3,
  153798. rate_mapping_22,
  153799. quality_mapping_16,
  153800. 2,
  153801. 19000,
  153802. 26000,
  153803. blocksize_16_short,
  153804. blocksize_16_long,
  153805. _psy_tone_masteratt_16,
  153806. _psy_tone_0dB,
  153807. _psy_tone_suppress,
  153808. _vp_tonemask_adj_16,
  153809. _vp_tonemask_adj_16,
  153810. _vp_tonemask_adj_16,
  153811. _psy_noiseguards_8,
  153812. _psy_noisebias_16_impulse,
  153813. _psy_noisebias_16_short,
  153814. _psy_noisebias_16_short,
  153815. _psy_noisebias_16,
  153816. _psy_noise_suppress,
  153817. _psy_compand_8,
  153818. _psy_compand_8_mapping,
  153819. _psy_compand_8_mapping,
  153820. {_noise_start_16,_noise_start_16},
  153821. { _noise_part_16, _noise_part_16},
  153822. _noise_thresh_16,
  153823. _psy_ath_floater_16,
  153824. _psy_ath_abs_16,
  153825. _psy_lowpass_22,
  153826. _psy_global_44,
  153827. _global_mapping_16,
  153828. _psy_stereo_modes_16,
  153829. _floor_books,
  153830. _floor,
  153831. _floor_mapping_16_short,
  153832. _floor_mapping_16,
  153833. _mapres_template_16_stereo
  153834. };
  153835. ve_setup_data_template ve_setup_22_uncoupled={
  153836. 3,
  153837. rate_mapping_22_uncoupled,
  153838. quality_mapping_16,
  153839. -1,
  153840. 19000,
  153841. 26000,
  153842. blocksize_16_short,
  153843. blocksize_16_long,
  153844. _psy_tone_masteratt_16,
  153845. _psy_tone_0dB,
  153846. _psy_tone_suppress,
  153847. _vp_tonemask_adj_16,
  153848. _vp_tonemask_adj_16,
  153849. _vp_tonemask_adj_16,
  153850. _psy_noiseguards_8,
  153851. _psy_noisebias_16_impulse,
  153852. _psy_noisebias_16_short,
  153853. _psy_noisebias_16_short,
  153854. _psy_noisebias_16,
  153855. _psy_noise_suppress,
  153856. _psy_compand_8,
  153857. _psy_compand_8_mapping,
  153858. _psy_compand_8_mapping,
  153859. {_noise_start_16,_noise_start_16},
  153860. { _noise_part_16, _noise_part_16},
  153861. _noise_thresh_16,
  153862. _psy_ath_floater_16,
  153863. _psy_ath_abs_16,
  153864. _psy_lowpass_22,
  153865. _psy_global_44,
  153866. _global_mapping_16,
  153867. _psy_stereo_modes_16,
  153868. _floor_books,
  153869. _floor,
  153870. _floor_mapping_16_short,
  153871. _floor_mapping_16,
  153872. _mapres_template_16_uncoupled
  153873. };
  153874. /*** End of inlined file: setup_22.h ***/
  153875. /*** Start of inlined file: setup_X.h ***/
  153876. static double rate_mapping_X[12]={
  153877. -1.,-1.,-1.,-1.,-1.,-1.,
  153878. -1.,-1.,-1.,-1.,-1.,-1.
  153879. };
  153880. ve_setup_data_template ve_setup_X_stereo={
  153881. 11,
  153882. rate_mapping_X,
  153883. quality_mapping_44,
  153884. 2,
  153885. 50000,
  153886. 200000,
  153887. blocksize_short_44,
  153888. blocksize_long_44,
  153889. _psy_tone_masteratt_44,
  153890. _psy_tone_0dB,
  153891. _psy_tone_suppress,
  153892. _vp_tonemask_adj_otherblock,
  153893. _vp_tonemask_adj_longblock,
  153894. _vp_tonemask_adj_otherblock,
  153895. _psy_noiseguards_44,
  153896. _psy_noisebias_impulse,
  153897. _psy_noisebias_padding,
  153898. _psy_noisebias_trans,
  153899. _psy_noisebias_long,
  153900. _psy_noise_suppress,
  153901. _psy_compand_44,
  153902. _psy_compand_short_mapping,
  153903. _psy_compand_long_mapping,
  153904. {_noise_start_short_44,_noise_start_long_44},
  153905. {_noise_part_short_44,_noise_part_long_44},
  153906. _noise_thresh_44,
  153907. _psy_ath_floater,
  153908. _psy_ath_abs,
  153909. _psy_lowpass_44,
  153910. _psy_global_44,
  153911. _global_mapping_44,
  153912. _psy_stereo_modes_44,
  153913. _floor_books,
  153914. _floor,
  153915. _floor_short_mapping_44,
  153916. _floor_long_mapping_44,
  153917. _mapres_template_44_stereo
  153918. };
  153919. ve_setup_data_template ve_setup_X_uncoupled={
  153920. 11,
  153921. rate_mapping_X,
  153922. quality_mapping_44,
  153923. -1,
  153924. 50000,
  153925. 200000,
  153926. blocksize_short_44,
  153927. blocksize_long_44,
  153928. _psy_tone_masteratt_44,
  153929. _psy_tone_0dB,
  153930. _psy_tone_suppress,
  153931. _vp_tonemask_adj_otherblock,
  153932. _vp_tonemask_adj_longblock,
  153933. _vp_tonemask_adj_otherblock,
  153934. _psy_noiseguards_44,
  153935. _psy_noisebias_impulse,
  153936. _psy_noisebias_padding,
  153937. _psy_noisebias_trans,
  153938. _psy_noisebias_long,
  153939. _psy_noise_suppress,
  153940. _psy_compand_44,
  153941. _psy_compand_short_mapping,
  153942. _psy_compand_long_mapping,
  153943. {_noise_start_short_44,_noise_start_long_44},
  153944. {_noise_part_short_44,_noise_part_long_44},
  153945. _noise_thresh_44,
  153946. _psy_ath_floater,
  153947. _psy_ath_abs,
  153948. _psy_lowpass_44,
  153949. _psy_global_44,
  153950. _global_mapping_44,
  153951. NULL,
  153952. _floor_books,
  153953. _floor,
  153954. _floor_short_mapping_44,
  153955. _floor_long_mapping_44,
  153956. _mapres_template_44_uncoupled
  153957. };
  153958. ve_setup_data_template ve_setup_XX_stereo={
  153959. 2,
  153960. rate_mapping_X,
  153961. quality_mapping_8,
  153962. 2,
  153963. 0,
  153964. 8000,
  153965. blocksize_8,
  153966. blocksize_8,
  153967. _psy_tone_masteratt_8,
  153968. _psy_tone_0dB,
  153969. _psy_tone_suppress,
  153970. _vp_tonemask_adj_8,
  153971. NULL,
  153972. _vp_tonemask_adj_8,
  153973. _psy_noiseguards_8,
  153974. _psy_noisebias_8,
  153975. _psy_noisebias_8,
  153976. NULL,
  153977. NULL,
  153978. _psy_noise_suppress,
  153979. _psy_compand_8,
  153980. _psy_compand_8_mapping,
  153981. NULL,
  153982. {_noise_start_8,_noise_start_8},
  153983. {_noise_part_8,_noise_part_8},
  153984. _noise_thresh_5only,
  153985. _psy_ath_floater_8,
  153986. _psy_ath_abs_8,
  153987. _psy_lowpass_8,
  153988. _psy_global_44,
  153989. _global_mapping_8,
  153990. _psy_stereo_modes_8,
  153991. _floor_books,
  153992. _floor,
  153993. _floor_mapping_8,
  153994. NULL,
  153995. _mapres_template_8_stereo
  153996. };
  153997. ve_setup_data_template ve_setup_XX_uncoupled={
  153998. 2,
  153999. rate_mapping_X,
  154000. quality_mapping_8,
  154001. -1,
  154002. 0,
  154003. 8000,
  154004. blocksize_8,
  154005. blocksize_8,
  154006. _psy_tone_masteratt_8,
  154007. _psy_tone_0dB,
  154008. _psy_tone_suppress,
  154009. _vp_tonemask_adj_8,
  154010. NULL,
  154011. _vp_tonemask_adj_8,
  154012. _psy_noiseguards_8,
  154013. _psy_noisebias_8,
  154014. _psy_noisebias_8,
  154015. NULL,
  154016. NULL,
  154017. _psy_noise_suppress,
  154018. _psy_compand_8,
  154019. _psy_compand_8_mapping,
  154020. NULL,
  154021. {_noise_start_8,_noise_start_8},
  154022. {_noise_part_8,_noise_part_8},
  154023. _noise_thresh_5only,
  154024. _psy_ath_floater_8,
  154025. _psy_ath_abs_8,
  154026. _psy_lowpass_8,
  154027. _psy_global_44,
  154028. _global_mapping_8,
  154029. _psy_stereo_modes_8,
  154030. _floor_books,
  154031. _floor,
  154032. _floor_mapping_8,
  154033. NULL,
  154034. _mapres_template_8_uncoupled
  154035. };
  154036. /*** End of inlined file: setup_X.h ***/
  154037. static ve_setup_data_template *setup_list[]={
  154038. &ve_setup_44_stereo,
  154039. &ve_setup_44_uncoupled,
  154040. &ve_setup_32_stereo,
  154041. &ve_setup_32_uncoupled,
  154042. &ve_setup_22_stereo,
  154043. &ve_setup_22_uncoupled,
  154044. &ve_setup_16_stereo,
  154045. &ve_setup_16_uncoupled,
  154046. &ve_setup_11_stereo,
  154047. &ve_setup_11_uncoupled,
  154048. &ve_setup_8_stereo,
  154049. &ve_setup_8_uncoupled,
  154050. &ve_setup_X_stereo,
  154051. &ve_setup_X_uncoupled,
  154052. &ve_setup_XX_stereo,
  154053. &ve_setup_XX_uncoupled,
  154054. 0
  154055. };
  154056. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154057. if(vi && vi->codec_setup){
  154058. vi->version=0;
  154059. vi->channels=ch;
  154060. vi->rate=rate;
  154061. return(0);
  154062. }
  154063. return(OV_EINVAL);
  154064. }
  154065. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154066. static_codebook ***books,
  154067. vorbis_info_floor1 *in,
  154068. int *x){
  154069. int i,k,is=s;
  154070. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154071. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154072. memcpy(f,in+x[is],sizeof(*f));
  154073. /* fill in the lowpass field, even if it's temporary */
  154074. f->n=ci->blocksizes[block]>>1;
  154075. /* books */
  154076. {
  154077. int partitions=f->partitions;
  154078. int maxclass=-1;
  154079. int maxbook=-1;
  154080. for(i=0;i<partitions;i++)
  154081. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154082. for(i=0;i<=maxclass;i++){
  154083. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154084. f->class_book[i]+=ci->books;
  154085. for(k=0;k<(1<<f->class_subs[i]);k++){
  154086. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154087. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154088. }
  154089. }
  154090. for(i=0;i<=maxbook;i++)
  154091. ci->book_param[ci->books++]=books[x[is]][i];
  154092. }
  154093. /* for now, we're only using floor 1 */
  154094. ci->floor_type[ci->floors]=1;
  154095. ci->floor_param[ci->floors]=f;
  154096. ci->floors++;
  154097. return;
  154098. }
  154099. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154100. vorbis_info_psy_global *in,
  154101. double *x){
  154102. int i,is=s;
  154103. double ds=s-is;
  154104. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154105. vorbis_info_psy_global *g=&ci->psy_g_param;
  154106. memcpy(g,in+(int)x[is],sizeof(*g));
  154107. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154108. is=(int)ds;
  154109. ds-=is;
  154110. if(ds==0 && is>0){
  154111. is--;
  154112. ds=1.;
  154113. }
  154114. /* interpolate the trigger threshholds */
  154115. for(i=0;i<4;i++){
  154116. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154117. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154118. }
  154119. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154120. return;
  154121. }
  154122. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154123. highlevel_encode_setup *hi,
  154124. adj_stereo *p){
  154125. float s=hi->stereo_point_setting;
  154126. int i,is=s;
  154127. double ds=s-is;
  154128. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154129. vorbis_info_psy_global *g=&ci->psy_g_param;
  154130. if(p){
  154131. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154132. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154133. if(hi->managed){
  154134. /* interpolate the kHz threshholds */
  154135. for(i=0;i<PACKETBLOBS;i++){
  154136. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154137. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154138. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154139. g->coupling_pkHz[i]=kHz;
  154140. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154141. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154142. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154143. }
  154144. }else{
  154145. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154146. for(i=0;i<PACKETBLOBS;i++){
  154147. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154148. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154149. g->coupling_pkHz[i]=kHz;
  154150. }
  154151. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154152. for(i=0;i<PACKETBLOBS;i++){
  154153. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154154. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154155. }
  154156. }
  154157. }else{
  154158. for(i=0;i<PACKETBLOBS;i++){
  154159. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154160. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154161. }
  154162. }
  154163. return;
  154164. }
  154165. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154166. int *nn_start,
  154167. int *nn_partition,
  154168. double *nn_thresh,
  154169. int block){
  154170. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154171. vorbis_info_psy *p=ci->psy_param[block];
  154172. highlevel_encode_setup *hi=&ci->hi;
  154173. int is=s;
  154174. if(block>=ci->psys)
  154175. ci->psys=block+1;
  154176. if(!p){
  154177. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154178. ci->psy_param[block]=p;
  154179. }
  154180. memcpy(p,&_psy_info_template,sizeof(*p));
  154181. p->blockflag=block>>1;
  154182. if(hi->noise_normalize_p){
  154183. p->normal_channel_p=1;
  154184. p->normal_point_p=1;
  154185. p->normal_start=nn_start[is];
  154186. p->normal_partition=nn_partition[is];
  154187. p->normal_thresh=nn_thresh[is];
  154188. }
  154189. return;
  154190. }
  154191. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154192. att3 *att,
  154193. int *max,
  154194. vp_adjblock *in){
  154195. int i,is=s;
  154196. double ds=s-is;
  154197. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154198. vorbis_info_psy *p=ci->psy_param[block];
  154199. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154200. filling the values in here */
  154201. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154202. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154203. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154204. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154205. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154206. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154207. for(i=0;i<P_BANDS;i++)
  154208. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154209. return;
  154210. }
  154211. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154212. compandblock *in, double *x){
  154213. int i,is=s;
  154214. double ds=s-is;
  154215. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154216. vorbis_info_psy *p=ci->psy_param[block];
  154217. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154218. is=(int)ds;
  154219. ds-=is;
  154220. if(ds==0 && is>0){
  154221. is--;
  154222. ds=1.;
  154223. }
  154224. /* interpolate the compander settings */
  154225. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154226. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154227. return;
  154228. }
  154229. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154230. int *suppress){
  154231. int is=s;
  154232. double ds=s-is;
  154233. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154234. vorbis_info_psy *p=ci->psy_param[block];
  154235. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154236. return;
  154237. }
  154238. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154239. int *suppress,
  154240. noise3 *in,
  154241. noiseguard *guard,
  154242. double userbias){
  154243. int i,is=s,j;
  154244. double ds=s-is;
  154245. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154246. vorbis_info_psy *p=ci->psy_param[block];
  154247. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154248. p->noisewindowlomin=guard[block].lo;
  154249. p->noisewindowhimin=guard[block].hi;
  154250. p->noisewindowfixed=guard[block].fixed;
  154251. for(j=0;j<P_NOISECURVES;j++)
  154252. for(i=0;i<P_BANDS;i++)
  154253. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154254. /* impulse blocks may take a user specified bias to boost the
  154255. nominal/high noise encoding depth */
  154256. for(j=0;j<P_NOISECURVES;j++){
  154257. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154258. for(i=0;i<P_BANDS;i++){
  154259. p->noiseoff[j][i]+=userbias;
  154260. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154261. }
  154262. }
  154263. return;
  154264. }
  154265. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154266. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154267. vorbis_info_psy *p=ci->psy_param[block];
  154268. p->ath_adjatt=ci->hi.ath_floating_dB;
  154269. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154270. return;
  154271. }
  154272. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154273. int i;
  154274. for(i=0;i<ci->books;i++)
  154275. if(ci->book_param[i]==book)return(i);
  154276. return(ci->books++);
  154277. }
  154278. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154279. int *shortb,int *longb){
  154280. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154281. int is=s;
  154282. int blockshort=shortb[is];
  154283. int blocklong=longb[is];
  154284. ci->blocksizes[0]=blockshort;
  154285. ci->blocksizes[1]=blocklong;
  154286. }
  154287. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154288. int number, int block,
  154289. vorbis_residue_template *res){
  154290. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154291. int i,n;
  154292. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154293. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154294. memcpy(r,res->res,sizeof(*r));
  154295. if(ci->residues<=number)ci->residues=number+1;
  154296. switch(ci->blocksizes[block]){
  154297. case 64:case 128:case 256:
  154298. r->grouping=16;
  154299. break;
  154300. default:
  154301. r->grouping=32;
  154302. break;
  154303. }
  154304. ci->residue_type[number]=res->res_type;
  154305. /* to be adjusted by lowpass/pointlimit later */
  154306. n=r->end=ci->blocksizes[block]>>1;
  154307. if(res->res_type==2)
  154308. n=r->end*=vi->channels;
  154309. /* fill in all the books */
  154310. {
  154311. int booklist=0,k;
  154312. if(ci->hi.managed){
  154313. for(i=0;i<r->partitions;i++)
  154314. for(k=0;k<3;k++)
  154315. if(res->books_base_managed->books[i][k])
  154316. r->secondstages[i]|=(1<<k);
  154317. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154318. ci->book_param[r->groupbook]=res->book_aux_managed;
  154319. for(i=0;i<r->partitions;i++){
  154320. for(k=0;k<3;k++){
  154321. if(res->books_base_managed->books[i][k]){
  154322. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154323. r->booklist[booklist++]=bookid;
  154324. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154325. }
  154326. }
  154327. }
  154328. }else{
  154329. for(i=0;i<r->partitions;i++)
  154330. for(k=0;k<3;k++)
  154331. if(res->books_base->books[i][k])
  154332. r->secondstages[i]|=(1<<k);
  154333. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154334. ci->book_param[r->groupbook]=res->book_aux;
  154335. for(i=0;i<r->partitions;i++){
  154336. for(k=0;k<3;k++){
  154337. if(res->books_base->books[i][k]){
  154338. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154339. r->booklist[booklist++]=bookid;
  154340. ci->book_param[bookid]=res->books_base->books[i][k];
  154341. }
  154342. }
  154343. }
  154344. }
  154345. }
  154346. /* lowpass setup/pointlimit */
  154347. {
  154348. double freq=ci->hi.lowpass_kHz*1000.;
  154349. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154350. double nyq=vi->rate/2.;
  154351. long blocksize=ci->blocksizes[block]>>1;
  154352. /* lowpass needs to be set in the floor and the residue. */
  154353. if(freq>nyq)freq=nyq;
  154354. /* in the floor, the granularity can be very fine; it doesn't alter
  154355. the encoding structure, only the samples used to fit the floor
  154356. approximation */
  154357. f->n=freq/nyq*blocksize;
  154358. /* this res may by limited by the maximum pointlimit of the mode,
  154359. not the lowpass. the floor is always lowpass limited. */
  154360. if(res->limit_type){
  154361. if(ci->hi.managed)
  154362. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154363. else
  154364. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154365. if(freq>nyq)freq=nyq;
  154366. }
  154367. /* in the residue, we're constrained, physically, by partition
  154368. boundaries. We still lowpass 'wherever', but we have to round up
  154369. here to next boundary, or the vorbis spec will round it *down* to
  154370. previous boundary in encode/decode */
  154371. if(ci->residue_type[block]==2)
  154372. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154373. r->grouping;
  154374. else
  154375. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154376. r->grouping;
  154377. }
  154378. }
  154379. /* we assume two maps in this encoder */
  154380. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154381. vorbis_mapping_template *maps){
  154382. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154383. int i,j,is=s,modes=2;
  154384. vorbis_info_mapping0 *map=maps[is].map;
  154385. vorbis_info_mode *mode=_mode_template;
  154386. vorbis_residue_template *res=maps[is].res;
  154387. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154388. for(i=0;i<modes;i++){
  154389. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154390. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154391. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154392. if(i>=ci->modes)ci->modes=i+1;
  154393. ci->map_type[i]=0;
  154394. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154395. if(i>=ci->maps)ci->maps=i+1;
  154396. for(j=0;j<map[i].submaps;j++)
  154397. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154398. ,res+map[i].residuesubmap[j]);
  154399. }
  154400. }
  154401. static double setting_to_approx_bitrate(vorbis_info *vi){
  154402. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154403. highlevel_encode_setup *hi=&ci->hi;
  154404. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154405. int is=hi->base_setting;
  154406. double ds=hi->base_setting-is;
  154407. int ch=vi->channels;
  154408. double *r=setup->rate_mapping;
  154409. if(r==NULL)
  154410. return(-1);
  154411. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154412. }
  154413. static void get_setup_template(vorbis_info *vi,
  154414. long ch,long srate,
  154415. double req,int q_or_bitrate){
  154416. int i=0,j;
  154417. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154418. highlevel_encode_setup *hi=&ci->hi;
  154419. if(q_or_bitrate)req/=ch;
  154420. while(setup_list[i]){
  154421. if(setup_list[i]->coupling_restriction==-1 ||
  154422. setup_list[i]->coupling_restriction==ch){
  154423. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154424. srate<=setup_list[i]->samplerate_max_restriction){
  154425. int mappings=setup_list[i]->mappings;
  154426. double *map=(q_or_bitrate?
  154427. setup_list[i]->rate_mapping:
  154428. setup_list[i]->quality_mapping);
  154429. /* the template matches. Does the requested quality mode
  154430. fall within this template's modes? */
  154431. if(req<map[0]){++i;continue;}
  154432. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154433. for(j=0;j<mappings;j++)
  154434. if(req>=map[j] && req<map[j+1])break;
  154435. /* an all-points match */
  154436. hi->setup=setup_list[i];
  154437. if(j==mappings)
  154438. hi->base_setting=j-.001;
  154439. else{
  154440. float low=map[j];
  154441. float high=map[j+1];
  154442. float del=(req-low)/(high-low);
  154443. hi->base_setting=j+del;
  154444. }
  154445. return;
  154446. }
  154447. }
  154448. i++;
  154449. }
  154450. hi->setup=NULL;
  154451. }
  154452. /* encoders will need to use vorbis_info_init beforehand and call
  154453. vorbis_info clear when all done */
  154454. /* two interfaces; this, more detailed one, and later a convenience
  154455. layer on top */
  154456. /* the final setup call */
  154457. int vorbis_encode_setup_init(vorbis_info *vi){
  154458. int i0=0,singleblock=0;
  154459. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154460. ve_setup_data_template *setup=NULL;
  154461. highlevel_encode_setup *hi=&ci->hi;
  154462. if(ci==NULL)return(OV_EINVAL);
  154463. if(!hi->impulse_block_p)i0=1;
  154464. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154465. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154466. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154467. /* again, bound this to avoid the app shooting itself int he foot
  154468. too badly */
  154469. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154470. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154471. /* get the appropriate setup template; matches the fetch in previous
  154472. stages */
  154473. setup=(ve_setup_data_template *)hi->setup;
  154474. if(setup==NULL)return(OV_EINVAL);
  154475. hi->set_in_stone=1;
  154476. /* choose block sizes from configured sizes as well as paying
  154477. attention to long_block_p and short_block_p. If the configured
  154478. short and long blocks are the same length, we set long_block_p
  154479. and unset short_block_p */
  154480. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154481. setup->blocksize_short,
  154482. setup->blocksize_long);
  154483. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154484. /* floor setup; choose proper floor params. Allocated on the floor
  154485. stack in order; if we alloc only long floor, it's 0 */
  154486. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154487. setup->floor_books,
  154488. setup->floor_params,
  154489. setup->floor_short_mapping);
  154490. if(!singleblock)
  154491. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154492. setup->floor_books,
  154493. setup->floor_params,
  154494. setup->floor_long_mapping);
  154495. /* setup of [mostly] short block detection and stereo*/
  154496. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154497. setup->global_params,
  154498. setup->global_mapping);
  154499. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154500. /* basic psych setup and noise normalization */
  154501. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154502. setup->psy_noise_normal_start[0],
  154503. setup->psy_noise_normal_partition[0],
  154504. setup->psy_noise_normal_thresh,
  154505. 0);
  154506. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154507. setup->psy_noise_normal_start[0],
  154508. setup->psy_noise_normal_partition[0],
  154509. setup->psy_noise_normal_thresh,
  154510. 1);
  154511. if(!singleblock){
  154512. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154513. setup->psy_noise_normal_start[1],
  154514. setup->psy_noise_normal_partition[1],
  154515. setup->psy_noise_normal_thresh,
  154516. 2);
  154517. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154518. setup->psy_noise_normal_start[1],
  154519. setup->psy_noise_normal_partition[1],
  154520. setup->psy_noise_normal_thresh,
  154521. 3);
  154522. }
  154523. /* tone masking setup */
  154524. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154525. setup->psy_tone_masteratt,
  154526. setup->psy_tone_0dB,
  154527. setup->psy_tone_adj_impulse);
  154528. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154529. setup->psy_tone_masteratt,
  154530. setup->psy_tone_0dB,
  154531. setup->psy_tone_adj_other);
  154532. if(!singleblock){
  154533. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154534. setup->psy_tone_masteratt,
  154535. setup->psy_tone_0dB,
  154536. setup->psy_tone_adj_other);
  154537. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154538. setup->psy_tone_masteratt,
  154539. setup->psy_tone_0dB,
  154540. setup->psy_tone_adj_long);
  154541. }
  154542. /* noise companding setup */
  154543. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154544. setup->psy_noise_compand,
  154545. setup->psy_noise_compand_short_mapping);
  154546. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154547. setup->psy_noise_compand,
  154548. setup->psy_noise_compand_short_mapping);
  154549. if(!singleblock){
  154550. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154551. setup->psy_noise_compand,
  154552. setup->psy_noise_compand_long_mapping);
  154553. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154554. setup->psy_noise_compand,
  154555. setup->psy_noise_compand_long_mapping);
  154556. }
  154557. /* peak guarding setup */
  154558. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154559. setup->psy_tone_dBsuppress);
  154560. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154561. setup->psy_tone_dBsuppress);
  154562. if(!singleblock){
  154563. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154564. setup->psy_tone_dBsuppress);
  154565. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154566. setup->psy_tone_dBsuppress);
  154567. }
  154568. /* noise bias setup */
  154569. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154570. setup->psy_noise_dBsuppress,
  154571. setup->psy_noise_bias_impulse,
  154572. setup->psy_noiseguards,
  154573. (i0==0?hi->impulse_noisetune:0.));
  154574. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154575. setup->psy_noise_dBsuppress,
  154576. setup->psy_noise_bias_padding,
  154577. setup->psy_noiseguards,0.);
  154578. if(!singleblock){
  154579. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154580. setup->psy_noise_dBsuppress,
  154581. setup->psy_noise_bias_trans,
  154582. setup->psy_noiseguards,0.);
  154583. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154584. setup->psy_noise_dBsuppress,
  154585. setup->psy_noise_bias_long,
  154586. setup->psy_noiseguards,0.);
  154587. }
  154588. vorbis_encode_ath_setup(vi,0);
  154589. vorbis_encode_ath_setup(vi,1);
  154590. if(!singleblock){
  154591. vorbis_encode_ath_setup(vi,2);
  154592. vorbis_encode_ath_setup(vi,3);
  154593. }
  154594. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154595. /* set bitrate readonlies and management */
  154596. if(hi->bitrate_av>0)
  154597. vi->bitrate_nominal=hi->bitrate_av;
  154598. else{
  154599. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154600. }
  154601. vi->bitrate_lower=hi->bitrate_min;
  154602. vi->bitrate_upper=hi->bitrate_max;
  154603. if(hi->bitrate_av)
  154604. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154605. else
  154606. vi->bitrate_window=0.;
  154607. if(hi->managed){
  154608. ci->bi.avg_rate=hi->bitrate_av;
  154609. ci->bi.min_rate=hi->bitrate_min;
  154610. ci->bi.max_rate=hi->bitrate_max;
  154611. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154612. ci->bi.reservoir_bias=
  154613. hi->bitrate_reservoir_bias;
  154614. ci->bi.slew_damp=hi->bitrate_av_damp;
  154615. }
  154616. return(0);
  154617. }
  154618. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154619. long channels,
  154620. long rate){
  154621. int ret=0,i,is;
  154622. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154623. highlevel_encode_setup *hi=&ci->hi;
  154624. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154625. double ds;
  154626. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154627. if(ret)return(ret);
  154628. is=hi->base_setting;
  154629. ds=hi->base_setting-is;
  154630. hi->short_setting=hi->base_setting;
  154631. hi->long_setting=hi->base_setting;
  154632. hi->managed=0;
  154633. hi->impulse_block_p=1;
  154634. hi->noise_normalize_p=1;
  154635. hi->stereo_point_setting=hi->base_setting;
  154636. hi->lowpass_kHz=
  154637. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154638. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154639. setup->psy_ath_float[is+1]*ds;
  154640. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154641. setup->psy_ath_abs[is+1]*ds;
  154642. hi->amplitude_track_dBpersec=-6.;
  154643. hi->trigger_setting=hi->base_setting;
  154644. for(i=0;i<4;i++){
  154645. hi->block[i].tone_mask_setting=hi->base_setting;
  154646. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154647. hi->block[i].noise_bias_setting=hi->base_setting;
  154648. hi->block[i].noise_compand_setting=hi->base_setting;
  154649. }
  154650. return(ret);
  154651. }
  154652. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154653. long channels,
  154654. long rate,
  154655. float quality){
  154656. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154657. highlevel_encode_setup *hi=&ci->hi;
  154658. quality+=.0000001;
  154659. if(quality>=1.)quality=.9999;
  154660. get_setup_template(vi,channels,rate,quality,0);
  154661. if(!hi->setup)return OV_EIMPL;
  154662. return vorbis_encode_setup_setting(vi,channels,rate);
  154663. }
  154664. int vorbis_encode_init_vbr(vorbis_info *vi,
  154665. long channels,
  154666. long rate,
  154667. float base_quality /* 0. to 1. */
  154668. ){
  154669. int ret=0;
  154670. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154671. if(ret){
  154672. vorbis_info_clear(vi);
  154673. return ret;
  154674. }
  154675. ret=vorbis_encode_setup_init(vi);
  154676. if(ret)
  154677. vorbis_info_clear(vi);
  154678. return(ret);
  154679. }
  154680. int vorbis_encode_setup_managed(vorbis_info *vi,
  154681. long channels,
  154682. long rate,
  154683. long max_bitrate,
  154684. long nominal_bitrate,
  154685. long min_bitrate){
  154686. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154687. highlevel_encode_setup *hi=&ci->hi;
  154688. double tnominal=nominal_bitrate;
  154689. int ret=0;
  154690. if(nominal_bitrate<=0.){
  154691. if(max_bitrate>0.){
  154692. if(min_bitrate>0.)
  154693. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154694. else
  154695. nominal_bitrate=max_bitrate*.875;
  154696. }else{
  154697. if(min_bitrate>0.){
  154698. nominal_bitrate=min_bitrate;
  154699. }else{
  154700. return(OV_EINVAL);
  154701. }
  154702. }
  154703. }
  154704. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154705. if(!hi->setup)return OV_EIMPL;
  154706. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154707. if(ret){
  154708. vorbis_info_clear(vi);
  154709. return ret;
  154710. }
  154711. /* initialize management with sane defaults */
  154712. hi->managed=1;
  154713. hi->bitrate_min=min_bitrate;
  154714. hi->bitrate_max=max_bitrate;
  154715. hi->bitrate_av=tnominal;
  154716. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154717. hi->bitrate_reservoir=nominal_bitrate*2;
  154718. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154719. return(ret);
  154720. }
  154721. int vorbis_encode_init(vorbis_info *vi,
  154722. long channels,
  154723. long rate,
  154724. long max_bitrate,
  154725. long nominal_bitrate,
  154726. long min_bitrate){
  154727. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154728. max_bitrate,
  154729. nominal_bitrate,
  154730. min_bitrate);
  154731. if(ret){
  154732. vorbis_info_clear(vi);
  154733. return(ret);
  154734. }
  154735. ret=vorbis_encode_setup_init(vi);
  154736. if(ret)
  154737. vorbis_info_clear(vi);
  154738. return(ret);
  154739. }
  154740. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154741. if(vi){
  154742. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154743. highlevel_encode_setup *hi=&ci->hi;
  154744. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154745. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154746. switch(number){
  154747. /* now deprecated *****************/
  154748. case OV_ECTL_RATEMANAGE_GET:
  154749. {
  154750. struct ovectl_ratemanage_arg *ai=
  154751. (struct ovectl_ratemanage_arg *)arg;
  154752. ai->management_active=hi->managed;
  154753. ai->bitrate_hard_window=ai->bitrate_av_window=
  154754. (double)hi->bitrate_reservoir/vi->rate;
  154755. ai->bitrate_av_window_center=1.;
  154756. ai->bitrate_hard_min=hi->bitrate_min;
  154757. ai->bitrate_hard_max=hi->bitrate_max;
  154758. ai->bitrate_av_lo=hi->bitrate_av;
  154759. ai->bitrate_av_hi=hi->bitrate_av;
  154760. }
  154761. return(0);
  154762. /* now deprecated *****************/
  154763. case OV_ECTL_RATEMANAGE_SET:
  154764. {
  154765. struct ovectl_ratemanage_arg *ai=
  154766. (struct ovectl_ratemanage_arg *)arg;
  154767. if(ai==NULL){
  154768. hi->managed=0;
  154769. }else{
  154770. hi->managed=ai->management_active;
  154771. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154772. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154773. }
  154774. }
  154775. return 0;
  154776. /* now deprecated *****************/
  154777. case OV_ECTL_RATEMANAGE_AVG:
  154778. {
  154779. struct ovectl_ratemanage_arg *ai=
  154780. (struct ovectl_ratemanage_arg *)arg;
  154781. if(ai==NULL){
  154782. hi->bitrate_av=0;
  154783. }else{
  154784. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154785. }
  154786. }
  154787. return(0);
  154788. /* now deprecated *****************/
  154789. case OV_ECTL_RATEMANAGE_HARD:
  154790. {
  154791. struct ovectl_ratemanage_arg *ai=
  154792. (struct ovectl_ratemanage_arg *)arg;
  154793. if(ai==NULL){
  154794. hi->bitrate_min=0;
  154795. hi->bitrate_max=0;
  154796. }else{
  154797. hi->bitrate_min=ai->bitrate_hard_min;
  154798. hi->bitrate_max=ai->bitrate_hard_max;
  154799. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154800. (hi->bitrate_max+hi->bitrate_min)*.5;
  154801. }
  154802. if(hi->bitrate_reservoir<128.)
  154803. hi->bitrate_reservoir=128.;
  154804. }
  154805. return(0);
  154806. /* replacement ratemanage interface */
  154807. case OV_ECTL_RATEMANAGE2_GET:
  154808. {
  154809. struct ovectl_ratemanage2_arg *ai=
  154810. (struct ovectl_ratemanage2_arg *)arg;
  154811. if(ai==NULL)return OV_EINVAL;
  154812. ai->management_active=hi->managed;
  154813. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154814. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154815. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154816. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154817. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154818. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154819. }
  154820. return (0);
  154821. case OV_ECTL_RATEMANAGE2_SET:
  154822. {
  154823. struct ovectl_ratemanage2_arg *ai=
  154824. (struct ovectl_ratemanage2_arg *)arg;
  154825. if(ai==NULL){
  154826. hi->managed=0;
  154827. }else{
  154828. /* sanity check; only catch invariant violations */
  154829. if(ai->bitrate_limit_min_kbps>0 &&
  154830. ai->bitrate_average_kbps>0 &&
  154831. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154832. return OV_EINVAL;
  154833. if(ai->bitrate_limit_max_kbps>0 &&
  154834. ai->bitrate_average_kbps>0 &&
  154835. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154836. return OV_EINVAL;
  154837. if(ai->bitrate_limit_min_kbps>0 &&
  154838. ai->bitrate_limit_max_kbps>0 &&
  154839. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154840. return OV_EINVAL;
  154841. if(ai->bitrate_average_damping <= 0.)
  154842. return OV_EINVAL;
  154843. if(ai->bitrate_limit_reservoir_bits < 0)
  154844. return OV_EINVAL;
  154845. if(ai->bitrate_limit_reservoir_bias < 0.)
  154846. return OV_EINVAL;
  154847. if(ai->bitrate_limit_reservoir_bias > 1.)
  154848. return OV_EINVAL;
  154849. hi->managed=ai->management_active;
  154850. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154851. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154852. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154853. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154854. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154855. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154856. }
  154857. }
  154858. return 0;
  154859. case OV_ECTL_LOWPASS_GET:
  154860. {
  154861. double *farg=(double *)arg;
  154862. *farg=hi->lowpass_kHz;
  154863. }
  154864. return(0);
  154865. case OV_ECTL_LOWPASS_SET:
  154866. {
  154867. double *farg=(double *)arg;
  154868. hi->lowpass_kHz=*farg;
  154869. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154870. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154871. }
  154872. return(0);
  154873. case OV_ECTL_IBLOCK_GET:
  154874. {
  154875. double *farg=(double *)arg;
  154876. *farg=hi->impulse_noisetune;
  154877. }
  154878. return(0);
  154879. case OV_ECTL_IBLOCK_SET:
  154880. {
  154881. double *farg=(double *)arg;
  154882. hi->impulse_noisetune=*farg;
  154883. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154884. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154885. }
  154886. return(0);
  154887. }
  154888. return(OV_EIMPL);
  154889. }
  154890. return(OV_EINVAL);
  154891. }
  154892. #endif
  154893. /*** End of inlined file: vorbisenc.c ***/
  154894. /*** Start of inlined file: vorbisfile.c ***/
  154895. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154896. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154897. // tasks..
  154898. #if JUCE_MSVC
  154899. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154900. #endif
  154901. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154902. #if JUCE_USE_OGGVORBIS
  154903. #include <stdlib.h>
  154904. #include <stdio.h>
  154905. #include <errno.h>
  154906. #include <string.h>
  154907. #include <math.h>
  154908. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154909. one logical bitstream arranged end to end (the only form of Ogg
  154910. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154911. multiplexing] is not allowed in Vorbis) */
  154912. /* A Vorbis file can be played beginning to end (streamed) without
  154913. worrying ahead of time about chaining (see decoder_example.c). If
  154914. we have the whole file, however, and want random access
  154915. (seeking/scrubbing) or desire to know the total length/time of a
  154916. file, we need to account for the possibility of chaining. */
  154917. /* We can handle things a number of ways; we can determine the entire
  154918. bitstream structure right off the bat, or find pieces on demand.
  154919. This example determines and caches structure for the entire
  154920. bitstream, but builds a virtual decoder on the fly when moving
  154921. between links in the chain. */
  154922. /* There are also different ways to implement seeking. Enough
  154923. information exists in an Ogg bitstream to seek to
  154924. sample-granularity positions in the output. Or, one can seek by
  154925. picking some portion of the stream roughly in the desired area if
  154926. we only want coarse navigation through the stream. */
  154927. /*************************************************************************
  154928. * Many, many internal helpers. The intention is not to be confusing;
  154929. * rampant duplication and monolithic function implementation would be
  154930. * harder to understand anyway. The high level functions are last. Begin
  154931. * grokking near the end of the file */
  154932. /* read a little more data from the file/pipe into the ogg_sync framer
  154933. */
  154934. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154935. over 8k gets what they deserve */
  154936. static long _get_data(OggVorbis_File *vf){
  154937. errno=0;
  154938. if(vf->datasource){
  154939. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154940. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154941. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154942. if(bytes==0 && errno)return(-1);
  154943. return(bytes);
  154944. }else
  154945. return(0);
  154946. }
  154947. /* save a tiny smidge of verbosity to make the code more readable */
  154948. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154949. if(vf->datasource){
  154950. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154951. vf->offset=offset;
  154952. ogg_sync_reset(&vf->oy);
  154953. }else{
  154954. /* shouldn't happen unless someone writes a broken callback */
  154955. return;
  154956. }
  154957. }
  154958. /* The read/seek functions track absolute position within the stream */
  154959. /* from the head of the stream, get the next page. boundary specifies
  154960. if the function is allowed to fetch more data from the stream (and
  154961. how much) or only use internally buffered data.
  154962. boundary: -1) unbounded search
  154963. 0) read no additional data; use cached only
  154964. n) search for a new page beginning for n bytes
  154965. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154966. n) found a page at absolute offset n */
  154967. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154968. ogg_int64_t boundary){
  154969. if(boundary>0)boundary+=vf->offset;
  154970. while(1){
  154971. long more;
  154972. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154973. more=ogg_sync_pageseek(&vf->oy,og);
  154974. if(more<0){
  154975. /* skipped n bytes */
  154976. vf->offset-=more;
  154977. }else{
  154978. if(more==0){
  154979. /* send more paramedics */
  154980. if(!boundary)return(OV_FALSE);
  154981. {
  154982. long ret=_get_data(vf);
  154983. if(ret==0)return(OV_EOF);
  154984. if(ret<0)return(OV_EREAD);
  154985. }
  154986. }else{
  154987. /* got a page. Return the offset at the page beginning,
  154988. advance the internal offset past the page end */
  154989. ogg_int64_t ret=vf->offset;
  154990. vf->offset+=more;
  154991. return(ret);
  154992. }
  154993. }
  154994. }
  154995. }
  154996. /* find the latest page beginning before the current stream cursor
  154997. position. Much dirtier than the above as Ogg doesn't have any
  154998. backward search linkage. no 'readp' as it will certainly have to
  154999. read. */
  155000. /* returns offset or OV_EREAD, OV_FAULT */
  155001. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155002. ogg_int64_t begin=vf->offset;
  155003. ogg_int64_t end=begin;
  155004. ogg_int64_t ret;
  155005. ogg_int64_t offset=-1;
  155006. while(offset==-1){
  155007. begin-=CHUNKSIZE;
  155008. if(begin<0)
  155009. begin=0;
  155010. _seek_helper(vf,begin);
  155011. while(vf->offset<end){
  155012. ret=_get_next_page(vf,og,end-vf->offset);
  155013. if(ret==OV_EREAD)return(OV_EREAD);
  155014. if(ret<0){
  155015. break;
  155016. }else{
  155017. offset=ret;
  155018. }
  155019. }
  155020. }
  155021. /* we have the offset. Actually snork and hold the page now */
  155022. _seek_helper(vf,offset);
  155023. ret=_get_next_page(vf,og,CHUNKSIZE);
  155024. if(ret<0)
  155025. /* this shouldn't be possible */
  155026. return(OV_EFAULT);
  155027. return(offset);
  155028. }
  155029. /* finds each bitstream link one at a time using a bisection search
  155030. (has to begin by knowing the offset of the lb's initial page).
  155031. Recurses for each link so it can alloc the link storage after
  155032. finding them all, then unroll and fill the cache at the same time */
  155033. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155034. ogg_int64_t begin,
  155035. ogg_int64_t searched,
  155036. ogg_int64_t end,
  155037. long currentno,
  155038. long m){
  155039. ogg_int64_t endsearched=end;
  155040. ogg_int64_t next=end;
  155041. ogg_page og;
  155042. ogg_int64_t ret;
  155043. /* the below guards against garbage seperating the last and
  155044. first pages of two links. */
  155045. while(searched<endsearched){
  155046. ogg_int64_t bisect;
  155047. if(endsearched-searched<CHUNKSIZE){
  155048. bisect=searched;
  155049. }else{
  155050. bisect=(searched+endsearched)/2;
  155051. }
  155052. _seek_helper(vf,bisect);
  155053. ret=_get_next_page(vf,&og,-1);
  155054. if(ret==OV_EREAD)return(OV_EREAD);
  155055. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155056. endsearched=bisect;
  155057. if(ret>=0)next=ret;
  155058. }else{
  155059. searched=ret+og.header_len+og.body_len;
  155060. }
  155061. }
  155062. _seek_helper(vf,next);
  155063. ret=_get_next_page(vf,&og,-1);
  155064. if(ret==OV_EREAD)return(OV_EREAD);
  155065. if(searched>=end || ret<0){
  155066. vf->links=m+1;
  155067. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155068. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155069. vf->offsets[m+1]=searched;
  155070. }else{
  155071. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155072. end,ogg_page_serialno(&og),m+1);
  155073. if(ret==OV_EREAD)return(OV_EREAD);
  155074. }
  155075. vf->offsets[m]=begin;
  155076. vf->serialnos[m]=currentno;
  155077. return(0);
  155078. }
  155079. /* uses the local ogg_stream storage in vf; this is important for
  155080. non-streaming input sources */
  155081. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155082. long *serialno,ogg_page *og_ptr){
  155083. ogg_page og;
  155084. ogg_packet op;
  155085. int i,ret;
  155086. if(!og_ptr){
  155087. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155088. if(llret==OV_EREAD)return(OV_EREAD);
  155089. if(llret<0)return OV_ENOTVORBIS;
  155090. og_ptr=&og;
  155091. }
  155092. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155093. if(serialno)*serialno=vf->os.serialno;
  155094. vf->ready_state=STREAMSET;
  155095. /* extract the initial header from the first page and verify that the
  155096. Ogg bitstream is in fact Vorbis data */
  155097. vorbis_info_init(vi);
  155098. vorbis_comment_init(vc);
  155099. i=0;
  155100. while(i<3){
  155101. ogg_stream_pagein(&vf->os,og_ptr);
  155102. while(i<3){
  155103. int result=ogg_stream_packetout(&vf->os,&op);
  155104. if(result==0)break;
  155105. if(result==-1){
  155106. ret=OV_EBADHEADER;
  155107. goto bail_header;
  155108. }
  155109. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155110. goto bail_header;
  155111. }
  155112. i++;
  155113. }
  155114. if(i<3)
  155115. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155116. ret=OV_EBADHEADER;
  155117. goto bail_header;
  155118. }
  155119. }
  155120. return 0;
  155121. bail_header:
  155122. vorbis_info_clear(vi);
  155123. vorbis_comment_clear(vc);
  155124. vf->ready_state=OPENED;
  155125. return ret;
  155126. }
  155127. /* last step of the OggVorbis_File initialization; get all the
  155128. vorbis_info structs and PCM positions. Only called by the seekable
  155129. initialization (local stream storage is hacked slightly; pay
  155130. attention to how that's done) */
  155131. /* this is void and does not propogate errors up because we want to be
  155132. able to open and use damaged bitstreams as well as we can. Just
  155133. watch out for missing information for links in the OggVorbis_File
  155134. struct */
  155135. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155136. ogg_page og;
  155137. int i;
  155138. ogg_int64_t ret;
  155139. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155140. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155141. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155142. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155143. for(i=0;i<vf->links;i++){
  155144. if(i==0){
  155145. /* we already grabbed the initial header earlier. Just set the offset */
  155146. vf->dataoffsets[i]=dataoffset;
  155147. _seek_helper(vf,dataoffset);
  155148. }else{
  155149. /* seek to the location of the initial header */
  155150. _seek_helper(vf,vf->offsets[i]);
  155151. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155152. vf->dataoffsets[i]=-1;
  155153. }else{
  155154. vf->dataoffsets[i]=vf->offset;
  155155. }
  155156. }
  155157. /* fetch beginning PCM offset */
  155158. if(vf->dataoffsets[i]!=-1){
  155159. ogg_int64_t accumulated=0;
  155160. long lastblock=-1;
  155161. int result;
  155162. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155163. while(1){
  155164. ogg_packet op;
  155165. ret=_get_next_page(vf,&og,-1);
  155166. if(ret<0)
  155167. /* this should not be possible unless the file is
  155168. truncated/mangled */
  155169. break;
  155170. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155171. break;
  155172. /* count blocksizes of all frames in the page */
  155173. ogg_stream_pagein(&vf->os,&og);
  155174. while((result=ogg_stream_packetout(&vf->os,&op))){
  155175. if(result>0){ /* ignore holes */
  155176. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155177. if(lastblock!=-1)
  155178. accumulated+=(lastblock+thisblock)>>2;
  155179. lastblock=thisblock;
  155180. }
  155181. }
  155182. if(ogg_page_granulepos(&og)!=-1){
  155183. /* pcm offset of last packet on the first audio page */
  155184. accumulated= ogg_page_granulepos(&og)-accumulated;
  155185. break;
  155186. }
  155187. }
  155188. /* less than zero? This is a stream with samples trimmed off
  155189. the beginning, a normal occurrence; set the offset to zero */
  155190. if(accumulated<0)accumulated=0;
  155191. vf->pcmlengths[i*2]=accumulated;
  155192. }
  155193. /* get the PCM length of this link. To do this,
  155194. get the last page of the stream */
  155195. {
  155196. ogg_int64_t end=vf->offsets[i+1];
  155197. _seek_helper(vf,end);
  155198. while(1){
  155199. ret=_get_prev_page(vf,&og);
  155200. if(ret<0){
  155201. /* this should not be possible */
  155202. vorbis_info_clear(vf->vi+i);
  155203. vorbis_comment_clear(vf->vc+i);
  155204. break;
  155205. }
  155206. if(ogg_page_granulepos(&og)!=-1){
  155207. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155208. break;
  155209. }
  155210. vf->offset=ret;
  155211. }
  155212. }
  155213. }
  155214. }
  155215. static int _make_decode_ready(OggVorbis_File *vf){
  155216. if(vf->ready_state>STREAMSET)return 0;
  155217. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155218. if(vf->seekable){
  155219. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155220. return OV_EBADLINK;
  155221. }else{
  155222. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155223. return OV_EBADLINK;
  155224. }
  155225. vorbis_block_init(&vf->vd,&vf->vb);
  155226. vf->ready_state=INITSET;
  155227. vf->bittrack=0.f;
  155228. vf->samptrack=0.f;
  155229. return 0;
  155230. }
  155231. static int _open_seekable2(OggVorbis_File *vf){
  155232. long serialno=vf->current_serialno;
  155233. ogg_int64_t dataoffset=vf->offset, end;
  155234. ogg_page og;
  155235. /* we're partially open and have a first link header state in
  155236. storage in vf */
  155237. /* we can seek, so set out learning all about this file */
  155238. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155239. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155240. /* We get the offset for the last page of the physical bitstream.
  155241. Most OggVorbis files will contain a single logical bitstream */
  155242. end=_get_prev_page(vf,&og);
  155243. if(end<0)return(end);
  155244. /* more than one logical bitstream? */
  155245. if(ogg_page_serialno(&og)!=serialno){
  155246. /* Chained bitstream. Bisect-search each logical bitstream
  155247. section. Do so based on serial number only */
  155248. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155249. }else{
  155250. /* Only one logical bitstream */
  155251. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155252. }
  155253. /* the initial header memory is referenced by vf after; don't free it */
  155254. _prefetch_all_headers(vf,dataoffset);
  155255. return(ov_raw_seek(vf,0));
  155256. }
  155257. /* clear out the current logical bitstream decoder */
  155258. static void _decode_clear(OggVorbis_File *vf){
  155259. vorbis_dsp_clear(&vf->vd);
  155260. vorbis_block_clear(&vf->vb);
  155261. vf->ready_state=OPENED;
  155262. }
  155263. /* fetch and process a packet. Handles the case where we're at a
  155264. bitstream boundary and dumps the decoding machine. If the decoding
  155265. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155266. date (seek and read both use this. seek uses a special hack with
  155267. readp).
  155268. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155269. 0) need more data (only if readp==0)
  155270. 1) got a packet
  155271. */
  155272. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155273. ogg_packet *op_in,
  155274. int readp,
  155275. int spanp){
  155276. ogg_page og;
  155277. /* handle one packet. Try to fetch it from current stream state */
  155278. /* extract packets from page */
  155279. while(1){
  155280. /* process a packet if we can. If the machine isn't loaded,
  155281. neither is a page */
  155282. if(vf->ready_state==INITSET){
  155283. while(1) {
  155284. ogg_packet op;
  155285. ogg_packet *op_ptr=(op_in?op_in:&op);
  155286. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155287. ogg_int64_t granulepos;
  155288. op_in=NULL;
  155289. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155290. if(result>0){
  155291. /* got a packet. process it */
  155292. granulepos=op_ptr->granulepos;
  155293. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155294. header handling. The
  155295. header packets aren't
  155296. audio, so if/when we
  155297. submit them,
  155298. vorbis_synthesis will
  155299. reject them */
  155300. /* suck in the synthesis data and track bitrate */
  155301. {
  155302. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155303. /* for proper use of libvorbis within libvorbisfile,
  155304. oldsamples will always be zero. */
  155305. if(oldsamples)return(OV_EFAULT);
  155306. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155307. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155308. vf->bittrack+=op_ptr->bytes*8;
  155309. }
  155310. /* update the pcm offset. */
  155311. if(granulepos!=-1 && !op_ptr->e_o_s){
  155312. int link=(vf->seekable?vf->current_link:0);
  155313. int i,samples;
  155314. /* this packet has a pcm_offset on it (the last packet
  155315. completed on a page carries the offset) After processing
  155316. (above), we know the pcm position of the *last* sample
  155317. ready to be returned. Find the offset of the *first*
  155318. As an aside, this trick is inaccurate if we begin
  155319. reading anew right at the last page; the end-of-stream
  155320. granulepos declares the last frame in the stream, and the
  155321. last packet of the last page may be a partial frame.
  155322. So, we need a previous granulepos from an in-sequence page
  155323. to have a reference point. Thus the !op_ptr->e_o_s clause
  155324. above */
  155325. if(vf->seekable && link>0)
  155326. granulepos-=vf->pcmlengths[link*2];
  155327. if(granulepos<0)granulepos=0; /* actually, this
  155328. shouldn't be possible
  155329. here unless the stream
  155330. is very broken */
  155331. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155332. granulepos-=samples;
  155333. for(i=0;i<link;i++)
  155334. granulepos+=vf->pcmlengths[i*2+1];
  155335. vf->pcm_offset=granulepos;
  155336. }
  155337. return(1);
  155338. }
  155339. }
  155340. else
  155341. break;
  155342. }
  155343. }
  155344. if(vf->ready_state>=OPENED){
  155345. ogg_int64_t ret;
  155346. if(!readp)return(0);
  155347. if((ret=_get_next_page(vf,&og,-1))<0){
  155348. return(OV_EOF); /* eof.
  155349. leave unitialized */
  155350. }
  155351. /* bitrate tracking; add the header's bytes here, the body bytes
  155352. are done by packet above */
  155353. vf->bittrack+=og.header_len*8;
  155354. /* has our decoding just traversed a bitstream boundary? */
  155355. if(vf->ready_state==INITSET){
  155356. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155357. if(!spanp)
  155358. return(OV_EOF);
  155359. _decode_clear(vf);
  155360. if(!vf->seekable){
  155361. vorbis_info_clear(vf->vi);
  155362. vorbis_comment_clear(vf->vc);
  155363. }
  155364. }
  155365. }
  155366. }
  155367. /* Do we need to load a new machine before submitting the page? */
  155368. /* This is different in the seekable and non-seekable cases.
  155369. In the seekable case, we already have all the header
  155370. information loaded and cached; we just initialize the machine
  155371. with it and continue on our merry way.
  155372. In the non-seekable (streaming) case, we'll only be at a
  155373. boundary if we just left the previous logical bitstream and
  155374. we're now nominally at the header of the next bitstream
  155375. */
  155376. if(vf->ready_state!=INITSET){
  155377. int link;
  155378. if(vf->ready_state<STREAMSET){
  155379. if(vf->seekable){
  155380. vf->current_serialno=ogg_page_serialno(&og);
  155381. /* match the serialno to bitstream section. We use this rather than
  155382. offset positions to avoid problems near logical bitstream
  155383. boundaries */
  155384. for(link=0;link<vf->links;link++)
  155385. if(vf->serialnos[link]==vf->current_serialno)break;
  155386. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155387. stream. error out,
  155388. leave machine
  155389. uninitialized */
  155390. vf->current_link=link;
  155391. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155392. vf->ready_state=STREAMSET;
  155393. }else{
  155394. /* we're streaming */
  155395. /* fetch the three header packets, build the info struct */
  155396. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155397. if(ret)return(ret);
  155398. vf->current_link++;
  155399. link=0;
  155400. }
  155401. }
  155402. {
  155403. int ret=_make_decode_ready(vf);
  155404. if(ret<0)return ret;
  155405. }
  155406. }
  155407. ogg_stream_pagein(&vf->os,&og);
  155408. }
  155409. }
  155410. /* if, eg, 64 bit stdio is configured by default, this will build with
  155411. fseek64 */
  155412. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155413. if(f==NULL)return(-1);
  155414. return fseek(f,off,whence);
  155415. }
  155416. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155417. long ibytes, ov_callbacks callbacks){
  155418. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155419. int ret;
  155420. memset(vf,0,sizeof(*vf));
  155421. vf->datasource=f;
  155422. vf->callbacks = callbacks;
  155423. /* init the framing state */
  155424. ogg_sync_init(&vf->oy);
  155425. /* perhaps some data was previously read into a buffer for testing
  155426. against other stream types. Allow initialization from this
  155427. previously read data (as we may be reading from a non-seekable
  155428. stream) */
  155429. if(initial){
  155430. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155431. memcpy(buffer,initial,ibytes);
  155432. ogg_sync_wrote(&vf->oy,ibytes);
  155433. }
  155434. /* can we seek? Stevens suggests the seek test was portable */
  155435. if(offsettest!=-1)vf->seekable=1;
  155436. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155437. entry for partial open */
  155438. vf->links=1;
  155439. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155440. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155441. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155442. /* Try to fetch the headers, maintaining all the storage */
  155443. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155444. vf->datasource=NULL;
  155445. ov_clear(vf);
  155446. }else
  155447. vf->ready_state=PARTOPEN;
  155448. return(ret);
  155449. }
  155450. static int _ov_open2(OggVorbis_File *vf){
  155451. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155452. vf->ready_state=OPENED;
  155453. if(vf->seekable){
  155454. int ret=_open_seekable2(vf);
  155455. if(ret){
  155456. vf->datasource=NULL;
  155457. ov_clear(vf);
  155458. }
  155459. return(ret);
  155460. }else
  155461. vf->ready_state=STREAMSET;
  155462. return 0;
  155463. }
  155464. /* clear out the OggVorbis_File struct */
  155465. int ov_clear(OggVorbis_File *vf){
  155466. if(vf){
  155467. vorbis_block_clear(&vf->vb);
  155468. vorbis_dsp_clear(&vf->vd);
  155469. ogg_stream_clear(&vf->os);
  155470. if(vf->vi && vf->links){
  155471. int i;
  155472. for(i=0;i<vf->links;i++){
  155473. vorbis_info_clear(vf->vi+i);
  155474. vorbis_comment_clear(vf->vc+i);
  155475. }
  155476. _ogg_free(vf->vi);
  155477. _ogg_free(vf->vc);
  155478. }
  155479. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155480. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155481. if(vf->serialnos)_ogg_free(vf->serialnos);
  155482. if(vf->offsets)_ogg_free(vf->offsets);
  155483. ogg_sync_clear(&vf->oy);
  155484. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155485. memset(vf,0,sizeof(*vf));
  155486. }
  155487. #ifdef DEBUG_LEAKS
  155488. _VDBG_dump();
  155489. #endif
  155490. return(0);
  155491. }
  155492. /* inspects the OggVorbis file and finds/documents all the logical
  155493. bitstreams contained in it. Tries to be tolerant of logical
  155494. bitstream sections that are truncated/woogie.
  155495. return: -1) error
  155496. 0) OK
  155497. */
  155498. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155499. ov_callbacks callbacks){
  155500. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155501. if(ret)return ret;
  155502. return _ov_open2(vf);
  155503. }
  155504. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155505. ov_callbacks callbacks = {
  155506. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155507. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155508. (int (*)(void *)) fclose,
  155509. (long (*)(void *)) ftell
  155510. };
  155511. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155512. }
  155513. /* cheap hack for game usage where downsampling is desirable; there's
  155514. no need for SRC as we can just do it cheaply in libvorbis. */
  155515. int ov_halfrate(OggVorbis_File *vf,int flag){
  155516. int i;
  155517. if(vf->vi==NULL)return OV_EINVAL;
  155518. if(!vf->seekable)return OV_EINVAL;
  155519. if(vf->ready_state>=STREAMSET)
  155520. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155521. will be able to swap this on the fly, but
  155522. for now dumping the decode machine is needed
  155523. to reinit the MDCT lookups. 1.1 libvorbis
  155524. is planned to be able to switch on the fly */
  155525. for(i=0;i<vf->links;i++){
  155526. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155527. ov_halfrate(vf,0);
  155528. return OV_EINVAL;
  155529. }
  155530. }
  155531. return 0;
  155532. }
  155533. int ov_halfrate_p(OggVorbis_File *vf){
  155534. if(vf->vi==NULL)return OV_EINVAL;
  155535. return vorbis_synthesis_halfrate_p(vf->vi);
  155536. }
  155537. /* Only partially open the vorbis file; test for Vorbisness, and load
  155538. the headers for the first chain. Do not seek (although test for
  155539. seekability). Use ov_test_open to finish opening the file, else
  155540. ov_clear to close/free it. Same return codes as open. */
  155541. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155542. ov_callbacks callbacks)
  155543. {
  155544. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155545. }
  155546. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155547. ov_callbacks callbacks = {
  155548. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155549. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155550. (int (*)(void *)) fclose,
  155551. (long (*)(void *)) ftell
  155552. };
  155553. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155554. }
  155555. int ov_test_open(OggVorbis_File *vf){
  155556. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155557. return _ov_open2(vf);
  155558. }
  155559. /* How many logical bitstreams in this physical bitstream? */
  155560. long ov_streams(OggVorbis_File *vf){
  155561. return vf->links;
  155562. }
  155563. /* Is the FILE * associated with vf seekable? */
  155564. long ov_seekable(OggVorbis_File *vf){
  155565. return vf->seekable;
  155566. }
  155567. /* returns the bitrate for a given logical bitstream or the entire
  155568. physical bitstream. If the file is open for random access, it will
  155569. find the *actual* average bitrate. If the file is streaming, it
  155570. returns the nominal bitrate (if set) else the average of the
  155571. upper/lower bounds (if set) else -1 (unset).
  155572. If you want the actual bitrate field settings, get them from the
  155573. vorbis_info structs */
  155574. long ov_bitrate(OggVorbis_File *vf,int i){
  155575. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155576. if(i>=vf->links)return(OV_EINVAL);
  155577. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155578. if(i<0){
  155579. ogg_int64_t bits=0;
  155580. int i;
  155581. float br;
  155582. for(i=0;i<vf->links;i++)
  155583. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155584. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155585. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155586. * so this is slightly transformed to make it work.
  155587. */
  155588. br = bits/ov_time_total(vf,-1);
  155589. return(rint(br));
  155590. }else{
  155591. if(vf->seekable){
  155592. /* return the actual bitrate */
  155593. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155594. }else{
  155595. /* return nominal if set */
  155596. if(vf->vi[i].bitrate_nominal>0){
  155597. return vf->vi[i].bitrate_nominal;
  155598. }else{
  155599. if(vf->vi[i].bitrate_upper>0){
  155600. if(vf->vi[i].bitrate_lower>0){
  155601. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155602. }else{
  155603. return vf->vi[i].bitrate_upper;
  155604. }
  155605. }
  155606. return(OV_FALSE);
  155607. }
  155608. }
  155609. }
  155610. }
  155611. /* returns the actual bitrate since last call. returns -1 if no
  155612. additional data to offer since last call (or at beginning of stream),
  155613. EINVAL if stream is only partially open
  155614. */
  155615. long ov_bitrate_instant(OggVorbis_File *vf){
  155616. int link=(vf->seekable?vf->current_link:0);
  155617. long ret;
  155618. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155619. if(vf->samptrack==0)return(OV_FALSE);
  155620. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155621. vf->bittrack=0.f;
  155622. vf->samptrack=0.f;
  155623. return(ret);
  155624. }
  155625. /* Guess */
  155626. long ov_serialnumber(OggVorbis_File *vf,int i){
  155627. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155628. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155629. if(i<0){
  155630. return(vf->current_serialno);
  155631. }else{
  155632. return(vf->serialnos[i]);
  155633. }
  155634. }
  155635. /* returns: total raw (compressed) length of content if i==-1
  155636. raw (compressed) length of that logical bitstream for i==0 to n
  155637. OV_EINVAL if the stream is not seekable (we can't know the length)
  155638. or if stream is only partially open
  155639. */
  155640. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155641. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155642. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155643. if(i<0){
  155644. ogg_int64_t acc=0;
  155645. int i;
  155646. for(i=0;i<vf->links;i++)
  155647. acc+=ov_raw_total(vf,i);
  155648. return(acc);
  155649. }else{
  155650. return(vf->offsets[i+1]-vf->offsets[i]);
  155651. }
  155652. }
  155653. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155654. (samples) of that logical bitstream for i==0 to n
  155655. OV_EINVAL if the stream is not seekable (we can't know the
  155656. length) or only partially open
  155657. */
  155658. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155659. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155660. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155661. if(i<0){
  155662. ogg_int64_t acc=0;
  155663. int i;
  155664. for(i=0;i<vf->links;i++)
  155665. acc+=ov_pcm_total(vf,i);
  155666. return(acc);
  155667. }else{
  155668. return(vf->pcmlengths[i*2+1]);
  155669. }
  155670. }
  155671. /* returns: total seconds of content if i==-1
  155672. seconds in that logical bitstream for i==0 to n
  155673. OV_EINVAL if the stream is not seekable (we can't know the
  155674. length) or only partially open
  155675. */
  155676. double ov_time_total(OggVorbis_File *vf,int i){
  155677. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155678. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155679. if(i<0){
  155680. double acc=0;
  155681. int i;
  155682. for(i=0;i<vf->links;i++)
  155683. acc+=ov_time_total(vf,i);
  155684. return(acc);
  155685. }else{
  155686. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155687. }
  155688. }
  155689. /* seek to an offset relative to the *compressed* data. This also
  155690. scans packets to update the PCM cursor. It will cross a logical
  155691. bitstream boundary, but only if it can't get any packets out of the
  155692. tail of the bitstream we seek to (so no surprises).
  155693. returns zero on success, nonzero on failure */
  155694. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155695. ogg_stream_state work_os;
  155696. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155697. if(!vf->seekable)
  155698. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155699. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155700. /* don't yet clear out decoding machine (if it's initialized), in
  155701. the case we're in the same link. Restart the decode lapping, and
  155702. let _fetch_and_process_packet deal with a potential bitstream
  155703. boundary */
  155704. vf->pcm_offset=-1;
  155705. ogg_stream_reset_serialno(&vf->os,
  155706. vf->current_serialno); /* must set serialno */
  155707. vorbis_synthesis_restart(&vf->vd);
  155708. _seek_helper(vf,pos);
  155709. /* we need to make sure the pcm_offset is set, but we don't want to
  155710. advance the raw cursor past good packets just to get to the first
  155711. with a granulepos. That's not equivalent behavior to beginning
  155712. decoding as immediately after the seek position as possible.
  155713. So, a hack. We use two stream states; a local scratch state and
  155714. the shared vf->os stream state. We use the local state to
  155715. scan, and the shared state as a buffer for later decode.
  155716. Unfortuantely, on the last page we still advance to last packet
  155717. because the granulepos on the last page is not necessarily on a
  155718. packet boundary, and we need to make sure the granpos is
  155719. correct.
  155720. */
  155721. {
  155722. ogg_page og;
  155723. ogg_packet op;
  155724. int lastblock=0;
  155725. int accblock=0;
  155726. int thisblock;
  155727. int eosflag;
  155728. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155729. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155730. return from not necessarily
  155731. starting from the beginning */
  155732. while(1){
  155733. if(vf->ready_state>=STREAMSET){
  155734. /* snarf/scan a packet if we can */
  155735. int result=ogg_stream_packetout(&work_os,&op);
  155736. if(result>0){
  155737. if(vf->vi[vf->current_link].codec_setup){
  155738. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155739. if(thisblock<0){
  155740. ogg_stream_packetout(&vf->os,NULL);
  155741. thisblock=0;
  155742. }else{
  155743. if(eosflag)
  155744. ogg_stream_packetout(&vf->os,NULL);
  155745. else
  155746. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155747. }
  155748. if(op.granulepos!=-1){
  155749. int i,link=vf->current_link;
  155750. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155751. if(granulepos<0)granulepos=0;
  155752. for(i=0;i<link;i++)
  155753. granulepos+=vf->pcmlengths[i*2+1];
  155754. vf->pcm_offset=granulepos-accblock;
  155755. break;
  155756. }
  155757. lastblock=thisblock;
  155758. continue;
  155759. }else
  155760. ogg_stream_packetout(&vf->os,NULL);
  155761. }
  155762. }
  155763. if(!lastblock){
  155764. if(_get_next_page(vf,&og,-1)<0){
  155765. vf->pcm_offset=ov_pcm_total(vf,-1);
  155766. break;
  155767. }
  155768. }else{
  155769. /* huh? Bogus stream with packets but no granulepos */
  155770. vf->pcm_offset=-1;
  155771. break;
  155772. }
  155773. /* has our decoding just traversed a bitstream boundary? */
  155774. if(vf->ready_state>=STREAMSET)
  155775. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155776. _decode_clear(vf); /* clear out stream state */
  155777. ogg_stream_clear(&work_os);
  155778. }
  155779. if(vf->ready_state<STREAMSET){
  155780. int link;
  155781. vf->current_serialno=ogg_page_serialno(&og);
  155782. for(link=0;link<vf->links;link++)
  155783. if(vf->serialnos[link]==vf->current_serialno)break;
  155784. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155785. error out, leave
  155786. machine uninitialized */
  155787. vf->current_link=link;
  155788. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155789. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155790. vf->ready_state=STREAMSET;
  155791. }
  155792. ogg_stream_pagein(&vf->os,&og);
  155793. ogg_stream_pagein(&work_os,&og);
  155794. eosflag=ogg_page_eos(&og);
  155795. }
  155796. }
  155797. ogg_stream_clear(&work_os);
  155798. vf->bittrack=0.f;
  155799. vf->samptrack=0.f;
  155800. return(0);
  155801. seek_error:
  155802. /* dump the machine so we're in a known state */
  155803. vf->pcm_offset=-1;
  155804. ogg_stream_clear(&work_os);
  155805. _decode_clear(vf);
  155806. return OV_EBADLINK;
  155807. }
  155808. /* Page granularity seek (faster than sample granularity because we
  155809. don't do the last bit of decode to find a specific sample).
  155810. Seek to the last [granule marked] page preceeding the specified pos
  155811. location, such that decoding past the returned point will quickly
  155812. arrive at the requested position. */
  155813. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155814. int link=-1;
  155815. ogg_int64_t result=0;
  155816. ogg_int64_t total=ov_pcm_total(vf,-1);
  155817. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155818. if(!vf->seekable)return(OV_ENOSEEK);
  155819. if(pos<0 || pos>total)return(OV_EINVAL);
  155820. /* which bitstream section does this pcm offset occur in? */
  155821. for(link=vf->links-1;link>=0;link--){
  155822. total-=vf->pcmlengths[link*2+1];
  155823. if(pos>=total)break;
  155824. }
  155825. /* search within the logical bitstream for the page with the highest
  155826. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155827. missing pages or incorrect frame number information in the
  155828. bitstream could make our task impossible. Account for that (it
  155829. would be an error condition) */
  155830. /* new search algorithm by HB (Nicholas Vinen) */
  155831. {
  155832. ogg_int64_t end=vf->offsets[link+1];
  155833. ogg_int64_t begin=vf->offsets[link];
  155834. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155835. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155836. ogg_int64_t target=pos-total+begintime;
  155837. ogg_int64_t best=begin;
  155838. ogg_page og;
  155839. while(begin<end){
  155840. ogg_int64_t bisect;
  155841. if(end-begin<CHUNKSIZE){
  155842. bisect=begin;
  155843. }else{
  155844. /* take a (pretty decent) guess. */
  155845. bisect=begin +
  155846. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155847. if(bisect<=begin)
  155848. bisect=begin+1;
  155849. }
  155850. _seek_helper(vf,bisect);
  155851. while(begin<end){
  155852. result=_get_next_page(vf,&og,end-vf->offset);
  155853. if(result==OV_EREAD) goto seek_error;
  155854. if(result<0){
  155855. if(bisect<=begin+1)
  155856. end=begin; /* found it */
  155857. else{
  155858. if(bisect==0) goto seek_error;
  155859. bisect-=CHUNKSIZE;
  155860. if(bisect<=begin)bisect=begin+1;
  155861. _seek_helper(vf,bisect);
  155862. }
  155863. }else{
  155864. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155865. if(granulepos==-1)continue;
  155866. if(granulepos<target){
  155867. best=result; /* raw offset of packet with granulepos */
  155868. begin=vf->offset; /* raw offset of next page */
  155869. begintime=granulepos;
  155870. if(target-begintime>44100)break;
  155871. bisect=begin; /* *not* begin + 1 */
  155872. }else{
  155873. if(bisect<=begin+1)
  155874. end=begin; /* found it */
  155875. else{
  155876. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155877. end=result;
  155878. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155879. if(bisect<=begin)bisect=begin+1;
  155880. _seek_helper(vf,bisect);
  155881. }else{
  155882. end=result;
  155883. endtime=granulepos;
  155884. break;
  155885. }
  155886. }
  155887. }
  155888. }
  155889. }
  155890. }
  155891. /* found our page. seek to it, update pcm offset. Easier case than
  155892. raw_seek, don't keep packets preceeding granulepos. */
  155893. {
  155894. ogg_page og;
  155895. ogg_packet op;
  155896. /* seek */
  155897. _seek_helper(vf,best);
  155898. vf->pcm_offset=-1;
  155899. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155900. if(link!=vf->current_link){
  155901. /* Different link; dump entire decode machine */
  155902. _decode_clear(vf);
  155903. vf->current_link=link;
  155904. vf->current_serialno=ogg_page_serialno(&og);
  155905. vf->ready_state=STREAMSET;
  155906. }else{
  155907. vorbis_synthesis_restart(&vf->vd);
  155908. }
  155909. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155910. ogg_stream_pagein(&vf->os,&og);
  155911. /* pull out all but last packet; the one with granulepos */
  155912. while(1){
  155913. result=ogg_stream_packetpeek(&vf->os,&op);
  155914. if(result==0){
  155915. /* !!! the packet finishing this page originated on a
  155916. preceeding page. Keep fetching previous pages until we
  155917. get one with a granulepos or without the 'continued' flag
  155918. set. Then just use raw_seek for simplicity. */
  155919. _seek_helper(vf,best);
  155920. while(1){
  155921. result=_get_prev_page(vf,&og);
  155922. if(result<0) goto seek_error;
  155923. if(ogg_page_granulepos(&og)>-1 ||
  155924. !ogg_page_continued(&og)){
  155925. return ov_raw_seek(vf,result);
  155926. }
  155927. vf->offset=result;
  155928. }
  155929. }
  155930. if(result<0){
  155931. result = OV_EBADPACKET;
  155932. goto seek_error;
  155933. }
  155934. if(op.granulepos!=-1){
  155935. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155936. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155937. vf->pcm_offset+=total;
  155938. break;
  155939. }else
  155940. result=ogg_stream_packetout(&vf->os,NULL);
  155941. }
  155942. }
  155943. }
  155944. /* verify result */
  155945. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155946. result=OV_EFAULT;
  155947. goto seek_error;
  155948. }
  155949. vf->bittrack=0.f;
  155950. vf->samptrack=0.f;
  155951. return(0);
  155952. seek_error:
  155953. /* dump machine so we're in a known state */
  155954. vf->pcm_offset=-1;
  155955. _decode_clear(vf);
  155956. return (int)result;
  155957. }
  155958. /* seek to a sample offset relative to the decompressed pcm stream
  155959. returns zero on success, nonzero on failure */
  155960. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155961. int thisblock,lastblock=0;
  155962. int ret=ov_pcm_seek_page(vf,pos);
  155963. if(ret<0)return(ret);
  155964. if((ret=_make_decode_ready(vf)))return ret;
  155965. /* discard leading packets we don't need for the lapping of the
  155966. position we want; don't decode them */
  155967. while(1){
  155968. ogg_packet op;
  155969. ogg_page og;
  155970. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155971. if(ret>0){
  155972. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155973. if(thisblock<0){
  155974. ogg_stream_packetout(&vf->os,NULL);
  155975. continue; /* non audio packet */
  155976. }
  155977. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155978. if(vf->pcm_offset+((thisblock+
  155979. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155980. /* remove the packet from packet queue and track its granulepos */
  155981. ogg_stream_packetout(&vf->os,NULL);
  155982. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155983. only tracking, no
  155984. pcm_decode */
  155985. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155986. /* end of logical stream case is hard, especially with exact
  155987. length positioning. */
  155988. if(op.granulepos>-1){
  155989. int i;
  155990. /* always believe the stream markers */
  155991. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155992. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155993. for(i=0;i<vf->current_link;i++)
  155994. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155995. }
  155996. lastblock=thisblock;
  155997. }else{
  155998. if(ret<0 && ret!=OV_HOLE)break;
  155999. /* suck in a new page */
  156000. if(_get_next_page(vf,&og,-1)<0)break;
  156001. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156002. if(vf->ready_state<STREAMSET){
  156003. int link;
  156004. vf->current_serialno=ogg_page_serialno(&og);
  156005. for(link=0;link<vf->links;link++)
  156006. if(vf->serialnos[link]==vf->current_serialno)break;
  156007. if(link==vf->links)return(OV_EBADLINK);
  156008. vf->current_link=link;
  156009. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156010. vf->ready_state=STREAMSET;
  156011. ret=_make_decode_ready(vf);
  156012. if(ret)return ret;
  156013. lastblock=0;
  156014. }
  156015. ogg_stream_pagein(&vf->os,&og);
  156016. }
  156017. }
  156018. vf->bittrack=0.f;
  156019. vf->samptrack=0.f;
  156020. /* discard samples until we reach the desired position. Crossing a
  156021. logical bitstream boundary with abandon is OK. */
  156022. while(vf->pcm_offset<pos){
  156023. ogg_int64_t target=pos-vf->pcm_offset;
  156024. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156025. if(samples>target)samples=target;
  156026. vorbis_synthesis_read(&vf->vd,samples);
  156027. vf->pcm_offset+=samples;
  156028. if(samples<target)
  156029. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156030. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156031. }
  156032. return 0;
  156033. }
  156034. /* seek to a playback time relative to the decompressed pcm stream
  156035. returns zero on success, nonzero on failure */
  156036. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156037. /* translate time to PCM position and call ov_pcm_seek */
  156038. int link=-1;
  156039. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156040. double time_total=ov_time_total(vf,-1);
  156041. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156042. if(!vf->seekable)return(OV_ENOSEEK);
  156043. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156044. /* which bitstream section does this time offset occur in? */
  156045. for(link=vf->links-1;link>=0;link--){
  156046. pcm_total-=vf->pcmlengths[link*2+1];
  156047. time_total-=ov_time_total(vf,link);
  156048. if(seconds>=time_total)break;
  156049. }
  156050. /* enough information to convert time offset to pcm offset */
  156051. {
  156052. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156053. return(ov_pcm_seek(vf,target));
  156054. }
  156055. }
  156056. /* page-granularity version of ov_time_seek
  156057. returns zero on success, nonzero on failure */
  156058. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156059. /* translate time to PCM position and call ov_pcm_seek */
  156060. int link=-1;
  156061. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156062. double time_total=ov_time_total(vf,-1);
  156063. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156064. if(!vf->seekable)return(OV_ENOSEEK);
  156065. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156066. /* which bitstream section does this time offset occur in? */
  156067. for(link=vf->links-1;link>=0;link--){
  156068. pcm_total-=vf->pcmlengths[link*2+1];
  156069. time_total-=ov_time_total(vf,link);
  156070. if(seconds>=time_total)break;
  156071. }
  156072. /* enough information to convert time offset to pcm offset */
  156073. {
  156074. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156075. return(ov_pcm_seek_page(vf,target));
  156076. }
  156077. }
  156078. /* tell the current stream offset cursor. Note that seek followed by
  156079. tell will likely not give the set offset due to caching */
  156080. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156081. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156082. return(vf->offset);
  156083. }
  156084. /* return PCM offset (sample) of next PCM sample to be read */
  156085. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156086. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156087. return(vf->pcm_offset);
  156088. }
  156089. /* return time offset (seconds) of next PCM sample to be read */
  156090. double ov_time_tell(OggVorbis_File *vf){
  156091. int link=0;
  156092. ogg_int64_t pcm_total=0;
  156093. double time_total=0.f;
  156094. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156095. if(vf->seekable){
  156096. pcm_total=ov_pcm_total(vf,-1);
  156097. time_total=ov_time_total(vf,-1);
  156098. /* which bitstream section does this time offset occur in? */
  156099. for(link=vf->links-1;link>=0;link--){
  156100. pcm_total-=vf->pcmlengths[link*2+1];
  156101. time_total-=ov_time_total(vf,link);
  156102. if(vf->pcm_offset>=pcm_total)break;
  156103. }
  156104. }
  156105. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156106. }
  156107. /* link: -1) return the vorbis_info struct for the bitstream section
  156108. currently being decoded
  156109. 0-n) to request information for a specific bitstream section
  156110. In the case of a non-seekable bitstream, any call returns the
  156111. current bitstream. NULL in the case that the machine is not
  156112. initialized */
  156113. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156114. if(vf->seekable){
  156115. if(link<0)
  156116. if(vf->ready_state>=STREAMSET)
  156117. return vf->vi+vf->current_link;
  156118. else
  156119. return vf->vi;
  156120. else
  156121. if(link>=vf->links)
  156122. return NULL;
  156123. else
  156124. return vf->vi+link;
  156125. }else{
  156126. return vf->vi;
  156127. }
  156128. }
  156129. /* grr, strong typing, grr, no templates/inheritence, grr */
  156130. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156131. if(vf->seekable){
  156132. if(link<0)
  156133. if(vf->ready_state>=STREAMSET)
  156134. return vf->vc+vf->current_link;
  156135. else
  156136. return vf->vc;
  156137. else
  156138. if(link>=vf->links)
  156139. return NULL;
  156140. else
  156141. return vf->vc+link;
  156142. }else{
  156143. return vf->vc;
  156144. }
  156145. }
  156146. static int host_is_big_endian() {
  156147. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156148. unsigned char *bytewise = (unsigned char *)&pattern;
  156149. if (bytewise[0] == 0xfe) return 1;
  156150. return 0;
  156151. }
  156152. /* up to this point, everything could more or less hide the multiple
  156153. logical bitstream nature of chaining from the toplevel application
  156154. if the toplevel application didn't particularly care. However, at
  156155. the point that we actually read audio back, the multiple-section
  156156. nature must surface: Multiple bitstream sections do not necessarily
  156157. have to have the same number of channels or sampling rate.
  156158. ov_read returns the sequential logical bitstream number currently
  156159. being decoded along with the PCM data in order that the toplevel
  156160. application can take action on channel/sample rate changes. This
  156161. number will be incremented even for streamed (non-seekable) streams
  156162. (for seekable streams, it represents the actual logical bitstream
  156163. index within the physical bitstream. Note that the accessor
  156164. functions above are aware of this dichotomy).
  156165. input values: buffer) a buffer to hold packed PCM data for return
  156166. length) the byte length requested to be placed into buffer
  156167. bigendianp) should the data be packed LSB first (0) or
  156168. MSB first (1)
  156169. word) word size for output. currently 1 (byte) or
  156170. 2 (16 bit short)
  156171. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156172. 0) EOF
  156173. n) number of bytes of PCM actually returned. The
  156174. below works on a packet-by-packet basis, so the
  156175. return length is not related to the 'length' passed
  156176. in, just guaranteed to fit.
  156177. *section) set to the logical bitstream number */
  156178. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156179. int bigendianp,int word,int sgned,int *bitstream){
  156180. int i,j;
  156181. int host_endian = host_is_big_endian();
  156182. float **pcm;
  156183. long samples;
  156184. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156185. while(1){
  156186. if(vf->ready_state==INITSET){
  156187. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156188. if(samples)break;
  156189. }
  156190. /* suck in another packet */
  156191. {
  156192. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156193. if(ret==OV_EOF)
  156194. return(0);
  156195. if(ret<=0)
  156196. return(ret);
  156197. }
  156198. }
  156199. if(samples>0){
  156200. /* yay! proceed to pack data into the byte buffer */
  156201. long channels=ov_info(vf,-1)->channels;
  156202. long bytespersample=word * channels;
  156203. vorbis_fpu_control fpu;
  156204. (void) fpu; // (to avoid a warning about it being unused)
  156205. if(samples>length/bytespersample)samples=length/bytespersample;
  156206. if(samples <= 0)
  156207. return OV_EINVAL;
  156208. /* a tight loop to pack each size */
  156209. {
  156210. int val;
  156211. if(word==1){
  156212. int off=(sgned?0:128);
  156213. vorbis_fpu_setround(&fpu);
  156214. for(j=0;j<samples;j++)
  156215. for(i=0;i<channels;i++){
  156216. val=vorbis_ftoi(pcm[i][j]*128.f);
  156217. if(val>127)val=127;
  156218. else if(val<-128)val=-128;
  156219. *buffer++=val+off;
  156220. }
  156221. vorbis_fpu_restore(fpu);
  156222. }else{
  156223. int off=(sgned?0:32768);
  156224. if(host_endian==bigendianp){
  156225. if(sgned){
  156226. vorbis_fpu_setround(&fpu);
  156227. for(i=0;i<channels;i++) { /* It's faster in this order */
  156228. float *src=pcm[i];
  156229. short *dest=((short *)buffer)+i;
  156230. for(j=0;j<samples;j++) {
  156231. val=vorbis_ftoi(src[j]*32768.f);
  156232. if(val>32767)val=32767;
  156233. else if(val<-32768)val=-32768;
  156234. *dest=val;
  156235. dest+=channels;
  156236. }
  156237. }
  156238. vorbis_fpu_restore(fpu);
  156239. }else{
  156240. vorbis_fpu_setround(&fpu);
  156241. for(i=0;i<channels;i++) {
  156242. float *src=pcm[i];
  156243. short *dest=((short *)buffer)+i;
  156244. for(j=0;j<samples;j++) {
  156245. val=vorbis_ftoi(src[j]*32768.f);
  156246. if(val>32767)val=32767;
  156247. else if(val<-32768)val=-32768;
  156248. *dest=val+off;
  156249. dest+=channels;
  156250. }
  156251. }
  156252. vorbis_fpu_restore(fpu);
  156253. }
  156254. }else if(bigendianp){
  156255. vorbis_fpu_setround(&fpu);
  156256. for(j=0;j<samples;j++)
  156257. for(i=0;i<channels;i++){
  156258. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156259. if(val>32767)val=32767;
  156260. else if(val<-32768)val=-32768;
  156261. val+=off;
  156262. *buffer++=(val>>8);
  156263. *buffer++=(val&0xff);
  156264. }
  156265. vorbis_fpu_restore(fpu);
  156266. }else{
  156267. int val;
  156268. vorbis_fpu_setround(&fpu);
  156269. for(j=0;j<samples;j++)
  156270. for(i=0;i<channels;i++){
  156271. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156272. if(val>32767)val=32767;
  156273. else if(val<-32768)val=-32768;
  156274. val+=off;
  156275. *buffer++=(val&0xff);
  156276. *buffer++=(val>>8);
  156277. }
  156278. vorbis_fpu_restore(fpu);
  156279. }
  156280. }
  156281. }
  156282. vorbis_synthesis_read(&vf->vd,samples);
  156283. vf->pcm_offset+=samples;
  156284. if(bitstream)*bitstream=vf->current_link;
  156285. return(samples*bytespersample);
  156286. }else{
  156287. return(samples);
  156288. }
  156289. }
  156290. /* input values: pcm_channels) a float vector per channel of output
  156291. length) the sample length being read by the app
  156292. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156293. 0) EOF
  156294. n) number of samples of PCM actually returned. The
  156295. below works on a packet-by-packet basis, so the
  156296. return length is not related to the 'length' passed
  156297. in, just guaranteed to fit.
  156298. *section) set to the logical bitstream number */
  156299. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156300. int *bitstream){
  156301. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156302. while(1){
  156303. if(vf->ready_state==INITSET){
  156304. float **pcm;
  156305. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156306. if(samples){
  156307. if(pcm_channels)*pcm_channels=pcm;
  156308. if(samples>length)samples=length;
  156309. vorbis_synthesis_read(&vf->vd,samples);
  156310. vf->pcm_offset+=samples;
  156311. if(bitstream)*bitstream=vf->current_link;
  156312. return samples;
  156313. }
  156314. }
  156315. /* suck in another packet */
  156316. {
  156317. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156318. if(ret==OV_EOF)return(0);
  156319. if(ret<=0)return(ret);
  156320. }
  156321. }
  156322. }
  156323. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156324. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156325. ogg_int64_t off);
  156326. static void _ov_splice(float **pcm,float **lappcm,
  156327. int n1, int n2,
  156328. int ch1, int ch2,
  156329. float *w1, float *w2){
  156330. int i,j;
  156331. float *w=w1;
  156332. int n=n1;
  156333. if(n1>n2){
  156334. n=n2;
  156335. w=w2;
  156336. }
  156337. /* splice */
  156338. for(j=0;j<ch1 && j<ch2;j++){
  156339. float *s=lappcm[j];
  156340. float *d=pcm[j];
  156341. for(i=0;i<n;i++){
  156342. float wd=w[i]*w[i];
  156343. float ws=1.-wd;
  156344. d[i]=d[i]*wd + s[i]*ws;
  156345. }
  156346. }
  156347. /* window from zero */
  156348. for(;j<ch2;j++){
  156349. float *d=pcm[j];
  156350. for(i=0;i<n;i++){
  156351. float wd=w[i]*w[i];
  156352. d[i]=d[i]*wd;
  156353. }
  156354. }
  156355. }
  156356. /* make sure vf is INITSET */
  156357. static int _ov_initset(OggVorbis_File *vf){
  156358. while(1){
  156359. if(vf->ready_state==INITSET)break;
  156360. /* suck in another packet */
  156361. {
  156362. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156363. if(ret<0 && ret!=OV_HOLE)return(ret);
  156364. }
  156365. }
  156366. return 0;
  156367. }
  156368. /* make sure vf is INITSET and that we have a primed buffer; if
  156369. we're crosslapping at a stream section boundary, this also makes
  156370. sure we're sanity checking against the right stream information */
  156371. static int _ov_initprime(OggVorbis_File *vf){
  156372. vorbis_dsp_state *vd=&vf->vd;
  156373. while(1){
  156374. if(vf->ready_state==INITSET)
  156375. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156376. /* suck in another packet */
  156377. {
  156378. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156379. if(ret<0 && ret!=OV_HOLE)return(ret);
  156380. }
  156381. }
  156382. return 0;
  156383. }
  156384. /* grab enough data for lapping from vf; this may be in the form of
  156385. unreturned, already-decoded pcm, remaining PCM we will need to
  156386. decode, or synthetic postextrapolation from last packets. */
  156387. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156388. float **lappcm,int lapsize){
  156389. int lapcount=0,i;
  156390. float **pcm;
  156391. /* try first to decode the lapping data */
  156392. while(lapcount<lapsize){
  156393. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156394. if(samples){
  156395. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156396. for(i=0;i<vi->channels;i++)
  156397. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156398. lapcount+=samples;
  156399. vorbis_synthesis_read(vd,samples);
  156400. }else{
  156401. /* suck in another packet */
  156402. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156403. if(ret==OV_EOF)break;
  156404. }
  156405. }
  156406. if(lapcount<lapsize){
  156407. /* failed to get lapping data from normal decode; pry it from the
  156408. postextrapolation buffering, or the second half of the MDCT
  156409. from the last packet */
  156410. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156411. if(samples==0){
  156412. for(i=0;i<vi->channels;i++)
  156413. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156414. lapcount=lapsize;
  156415. }else{
  156416. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156417. for(i=0;i<vi->channels;i++)
  156418. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156419. lapcount+=samples;
  156420. }
  156421. }
  156422. }
  156423. /* this sets up crosslapping of a sample by using trailing data from
  156424. sample 1 and lapping it into the windowing buffer of sample 2 */
  156425. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156426. vorbis_info *vi1,*vi2;
  156427. float **lappcm;
  156428. float **pcm;
  156429. float *w1,*w2;
  156430. int n1,n2,i,ret,hs1,hs2;
  156431. if(vf1==vf2)return(0); /* degenerate case */
  156432. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156433. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156434. /* the relevant overlap buffers must be pre-checked and pre-primed
  156435. before looking at settings in the event that priming would cross
  156436. a bitstream boundary. So, do it now */
  156437. ret=_ov_initset(vf1);
  156438. if(ret)return(ret);
  156439. ret=_ov_initprime(vf2);
  156440. if(ret)return(ret);
  156441. vi1=ov_info(vf1,-1);
  156442. vi2=ov_info(vf2,-1);
  156443. hs1=ov_halfrate_p(vf1);
  156444. hs2=ov_halfrate_p(vf2);
  156445. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156446. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156447. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156448. w1=vorbis_window(&vf1->vd,0);
  156449. w2=vorbis_window(&vf2->vd,0);
  156450. for(i=0;i<vi1->channels;i++)
  156451. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156452. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156453. /* have a lapping buffer from vf1; now to splice it into the lapping
  156454. buffer of vf2 */
  156455. /* consolidate and expose the buffer. */
  156456. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156457. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156458. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156459. /* splice */
  156460. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156461. /* done */
  156462. return(0);
  156463. }
  156464. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156465. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156466. vorbis_info *vi;
  156467. float **lappcm;
  156468. float **pcm;
  156469. float *w1,*w2;
  156470. int n1,n2,ch1,ch2,hs;
  156471. int i,ret;
  156472. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156473. ret=_ov_initset(vf);
  156474. if(ret)return(ret);
  156475. vi=ov_info(vf,-1);
  156476. hs=ov_halfrate_p(vf);
  156477. ch1=vi->channels;
  156478. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156479. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156480. persistent; even if the decode state
  156481. from this link gets dumped, this
  156482. window array continues to exist */
  156483. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156484. for(i=0;i<ch1;i++)
  156485. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156486. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156487. /* have lapping data; seek and prime the buffer */
  156488. ret=localseek(vf,pos);
  156489. if(ret)return ret;
  156490. ret=_ov_initprime(vf);
  156491. if(ret)return(ret);
  156492. /* Guard against cross-link changes; they're perfectly legal */
  156493. vi=ov_info(vf,-1);
  156494. ch2=vi->channels;
  156495. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156496. w2=vorbis_window(&vf->vd,0);
  156497. /* consolidate and expose the buffer. */
  156498. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156499. /* splice */
  156500. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156501. /* done */
  156502. return(0);
  156503. }
  156504. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156505. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156506. }
  156507. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156508. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156509. }
  156510. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156511. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156512. }
  156513. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156514. int (*localseek)(OggVorbis_File *,double)){
  156515. vorbis_info *vi;
  156516. float **lappcm;
  156517. float **pcm;
  156518. float *w1,*w2;
  156519. int n1,n2,ch1,ch2,hs;
  156520. int i,ret;
  156521. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156522. ret=_ov_initset(vf);
  156523. if(ret)return(ret);
  156524. vi=ov_info(vf,-1);
  156525. hs=ov_halfrate_p(vf);
  156526. ch1=vi->channels;
  156527. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156528. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156529. persistent; even if the decode state
  156530. from this link gets dumped, this
  156531. window array continues to exist */
  156532. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156533. for(i=0;i<ch1;i++)
  156534. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156535. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156536. /* have lapping data; seek and prime the buffer */
  156537. ret=localseek(vf,pos);
  156538. if(ret)return ret;
  156539. ret=_ov_initprime(vf);
  156540. if(ret)return(ret);
  156541. /* Guard against cross-link changes; they're perfectly legal */
  156542. vi=ov_info(vf,-1);
  156543. ch2=vi->channels;
  156544. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156545. w2=vorbis_window(&vf->vd,0);
  156546. /* consolidate and expose the buffer. */
  156547. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156548. /* splice */
  156549. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156550. /* done */
  156551. return(0);
  156552. }
  156553. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156554. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156555. }
  156556. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156557. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156558. }
  156559. #endif
  156560. /*** End of inlined file: vorbisfile.c ***/
  156561. /*** Start of inlined file: window.c ***/
  156562. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156563. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156564. // tasks..
  156565. #if JUCE_MSVC
  156566. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156567. #endif
  156568. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156569. #if JUCE_USE_OGGVORBIS
  156570. #include <stdlib.h>
  156571. #include <math.h>
  156572. static float vwin64[32] = {
  156573. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156574. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156575. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156576. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156577. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156578. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156579. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156580. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156581. };
  156582. static float vwin128[64] = {
  156583. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156584. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156585. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156586. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156587. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156588. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156589. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156590. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156591. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156592. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156593. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156594. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156595. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156596. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156597. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156598. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156599. };
  156600. static float vwin256[128] = {
  156601. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156602. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156603. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156604. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156605. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156606. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156607. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156608. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156609. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156610. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156611. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156612. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156613. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156614. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156615. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156616. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156617. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156618. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156619. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156620. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156621. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156622. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156623. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156624. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156625. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156626. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156627. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156628. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156629. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156630. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156631. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156632. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156633. };
  156634. static float vwin512[256] = {
  156635. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156636. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156637. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156638. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156639. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156640. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156641. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156642. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156643. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156644. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156645. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156646. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156647. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156648. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156649. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156650. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156651. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156652. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156653. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156654. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156655. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156656. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156657. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156658. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156659. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156660. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156661. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156662. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156663. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156664. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156665. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156666. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156667. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156668. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156669. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156670. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156671. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156672. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156673. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156674. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156675. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156676. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156677. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156678. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156679. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156680. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156681. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156682. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156683. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156684. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156685. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156686. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156687. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156688. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156689. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156690. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156691. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156692. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156693. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156694. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156695. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156696. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156697. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156698. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156699. };
  156700. static float vwin1024[512] = {
  156701. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156702. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156703. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156704. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156705. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156706. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156707. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156708. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156709. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156710. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156711. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156712. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156713. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156714. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156715. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156716. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156717. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156718. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156719. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156720. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156721. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156722. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156723. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156724. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156725. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156726. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156727. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156728. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156729. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156730. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156731. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156732. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156733. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156734. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156735. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156736. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156737. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156738. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156739. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156740. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156741. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156742. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156743. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156744. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156745. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156746. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156747. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156748. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156749. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156750. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156751. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156752. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156753. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156754. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156755. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156756. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156757. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156758. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156759. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156760. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156761. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156762. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156763. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156764. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156765. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156766. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156767. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156768. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156769. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156770. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156771. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156772. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156773. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156774. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156775. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156776. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156777. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156778. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156779. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156780. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156781. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156782. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156783. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156784. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156785. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156786. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156787. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156788. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156789. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156790. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156791. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156792. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156793. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156794. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156795. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156796. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156797. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156798. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156799. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156800. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156801. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156802. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156803. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156804. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156805. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156806. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156807. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156808. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156809. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156810. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156811. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156812. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156813. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156814. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156815. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156816. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156817. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156818. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156819. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156820. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156821. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156822. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156823. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156824. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156825. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156826. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156827. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156828. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156829. };
  156830. static float vwin2048[1024] = {
  156831. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156832. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156833. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156834. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156835. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156836. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156837. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156838. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156839. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156840. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156841. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156842. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156843. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156844. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156845. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156846. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156847. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156848. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156849. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156850. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156851. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156852. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156853. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156854. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156855. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156856. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156857. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156858. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156859. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156860. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156861. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156862. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156863. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156864. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156865. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156866. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156867. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156868. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156869. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156870. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156871. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156872. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156873. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156874. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156875. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156876. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156877. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156878. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156879. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156880. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156881. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156882. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156883. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156884. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156885. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156886. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156887. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156888. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156889. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156890. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156891. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156892. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156893. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156894. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156895. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156896. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156897. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156898. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156899. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156900. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156901. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156902. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156903. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156904. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156905. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156906. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156907. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156908. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156909. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156910. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156911. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156912. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156913. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156914. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156915. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156916. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156917. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156918. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156919. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156920. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156921. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156922. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156923. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156924. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156925. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156926. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156927. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156928. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156929. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156930. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156931. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156932. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156933. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156934. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156935. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156936. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156937. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156938. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156939. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156940. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156941. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156942. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156943. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156944. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156945. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156946. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156947. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156948. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156949. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156950. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156951. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156952. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156953. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156954. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156955. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156956. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156957. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156958. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156959. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156960. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156961. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156962. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156963. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156964. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156965. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156966. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156967. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156968. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156969. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156970. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156971. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156972. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156973. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156974. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156975. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156976. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156977. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156978. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156979. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156980. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156981. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156982. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156983. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156984. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156985. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156986. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156987. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156988. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156989. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156990. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156991. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156992. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156993. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156994. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156995. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156996. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156997. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156998. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156999. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157000. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157001. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157002. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157003. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157004. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157005. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157006. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157007. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157008. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157009. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157010. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157011. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157012. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157013. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157014. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157015. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157016. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157017. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157018. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157019. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157020. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157021. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157022. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157023. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157024. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157025. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157026. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157027. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157028. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157029. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157030. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157031. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157032. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157033. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157034. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157035. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157036. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157037. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157038. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157039. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157040. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157041. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157042. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157043. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157044. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157045. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157046. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157047. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157048. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157049. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157050. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157051. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157052. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157053. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157054. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157055. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157056. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157057. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157058. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157059. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157060. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157061. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157062. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157063. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157064. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157065. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157066. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157067. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157068. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157069. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157070. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157071. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157072. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157073. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157074. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157075. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157076. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157077. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157078. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157079. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157080. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157081. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157082. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157083. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157084. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157085. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157086. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157087. };
  157088. static float vwin4096[2048] = {
  157089. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157090. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157091. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157092. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157093. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157094. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157095. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157096. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157097. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157098. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157099. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157100. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157101. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157102. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157103. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157104. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157105. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157106. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157107. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157108. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157109. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157110. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157111. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157112. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157113. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157114. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157115. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157116. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157117. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157118. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157119. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157120. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157121. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157122. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157123. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157124. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157125. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157126. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157127. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157128. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157129. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157130. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157131. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157132. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157133. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157134. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157135. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157136. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157137. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157138. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157139. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157140. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157141. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157142. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157143. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157144. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157145. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157146. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157147. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157148. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157149. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157150. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157151. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157152. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157153. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157154. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157155. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157156. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157157. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157158. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157159. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157160. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157161. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157162. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157163. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157164. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157165. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157166. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157167. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157168. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157169. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157170. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157171. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157172. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157173. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157174. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157175. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157176. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157177. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157178. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157179. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157180. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157181. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157182. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157183. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157184. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157185. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157186. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157187. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157188. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157189. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157190. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157191. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157192. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157193. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157194. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157195. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157196. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157197. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157198. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157199. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157200. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157201. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157202. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157203. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157204. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157205. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157206. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157207. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157208. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157209. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157210. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157211. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157212. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157213. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157214. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157215. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157216. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157217. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157218. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157219. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157220. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157221. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157222. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157223. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157224. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157225. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157226. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157227. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157228. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157229. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157230. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157231. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157232. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157233. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157234. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157235. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157236. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157237. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157238. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157239. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157240. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157241. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157242. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157243. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157244. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157245. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157246. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157247. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157248. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157249. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157250. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157251. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157252. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157253. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157254. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157255. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157256. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157257. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157258. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157259. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157260. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157261. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157262. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157263. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157264. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157265. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157266. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157267. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157268. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157269. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157270. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157271. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157272. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157273. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157274. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157275. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157276. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157277. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157278. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157279. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157280. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157281. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157282. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157283. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157284. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157285. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157286. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157287. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157288. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157289. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157290. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157291. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157292. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157293. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157294. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157295. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157296. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157297. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157298. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157299. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157300. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157301. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157302. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157303. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157304. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157305. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157306. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157307. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157308. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157309. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157310. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157311. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157312. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157313. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157314. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157315. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157316. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157317. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157318. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157319. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157320. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157321. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157322. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157323. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157324. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157325. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157326. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157327. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157328. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157329. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157330. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157331. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157332. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157333. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157334. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157335. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157336. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157337. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157338. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157339. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157340. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157341. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157342. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157343. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157344. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157345. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157346. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157347. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157348. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157349. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157350. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157351. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157352. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157353. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157354. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157355. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157356. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157357. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157358. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157359. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157360. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157361. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157362. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157363. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157364. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157365. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157366. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157367. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157368. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157369. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157370. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157371. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157372. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157373. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157374. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157375. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157376. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157377. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157378. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157379. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157380. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157381. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157382. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157383. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157384. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157385. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157386. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157387. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157388. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157389. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157390. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157391. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157392. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157393. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157394. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157395. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157396. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157397. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157398. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157399. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157400. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157401. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157402. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157403. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157404. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157405. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157406. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157407. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157408. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157409. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157410. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157411. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157412. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157413. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157414. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157415. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157416. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157417. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157418. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157419. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157420. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157421. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157422. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157423. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157424. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157425. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157426. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157427. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157428. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157429. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157430. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157431. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157432. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157433. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157434. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157435. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157436. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157437. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157438. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157439. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157440. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157441. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157442. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157443. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157444. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157445. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157446. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157447. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157448. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157449. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157450. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157451. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157452. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157453. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157454. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157455. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157456. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157457. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157458. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157459. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157460. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157461. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157462. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157463. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157464. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157465. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157466. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157467. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157468. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157469. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157470. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157471. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157472. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157473. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157474. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157475. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157476. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157477. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157478. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157479. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157480. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157481. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157482. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157483. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157484. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157485. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157486. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157487. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157488. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157489. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157490. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157491. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157492. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157493. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157494. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157495. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157496. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157497. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157498. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157499. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157500. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157501. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157502. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157503. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157504. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157505. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157506. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157507. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157508. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157509. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157510. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157511. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157512. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157513. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157514. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157515. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157516. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157517. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157518. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157519. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157520. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157521. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157522. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157523. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157524. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157525. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157526. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157527. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157528. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157529. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157530. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157531. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157532. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157533. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157534. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157535. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157536. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157537. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157538. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157539. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157540. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157541. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157542. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157543. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157544. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157545. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157546. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157547. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157548. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157549. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157550. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157551. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157552. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157553. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157554. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157555. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157556. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157557. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157558. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157559. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157560. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157561. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157562. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157563. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157564. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157565. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157566. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157567. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157568. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157569. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157570. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157571. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157572. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157573. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157574. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157575. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157576. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157577. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157578. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157579. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157580. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157581. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157582. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157583. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157584. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157585. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157586. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157587. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157588. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157589. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157590. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157591. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157592. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157593. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157594. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157595. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157596. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157597. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157598. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157599. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157600. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157601. };
  157602. static float vwin8192[4096] = {
  157603. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157604. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157605. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157606. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157607. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157608. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157609. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157610. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157611. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157612. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157613. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157614. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157615. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157616. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157617. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157618. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157619. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157620. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157621. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157622. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157623. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157624. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157625. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157626. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157627. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157628. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157629. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157630. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157631. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157632. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157633. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157634. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157635. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157636. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157637. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157638. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157639. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157640. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157641. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157642. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157643. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157644. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157645. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157646. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157647. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157648. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157649. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157650. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157651. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157652. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157653. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157654. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157655. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157656. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157657. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157658. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157659. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157660. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157661. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157662. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157663. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157664. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157665. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157666. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157667. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157668. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157669. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157670. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157671. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157672. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157673. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157674. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157675. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157676. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157677. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157678. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157679. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157680. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157681. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157682. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157683. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157684. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157685. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157686. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157687. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157688. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157689. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157690. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157691. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157692. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157693. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157694. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157695. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157696. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157697. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157698. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157699. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157700. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157701. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157702. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157703. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157704. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157705. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157706. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157707. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157708. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157709. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157710. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157711. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157712. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157713. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157714. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157715. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157716. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157717. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157718. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157719. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157720. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157721. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157722. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157723. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157724. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157725. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157726. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157727. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157728. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157729. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157730. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157731. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157732. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157733. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157734. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157735. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157736. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157737. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157738. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157739. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157740. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157741. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157742. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157743. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157744. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157745. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157746. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157747. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157748. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157749. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157750. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157751. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157752. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157753. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157754. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157755. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157756. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157757. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157758. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157759. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157760. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157761. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157762. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157763. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157764. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157765. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157766. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157767. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157768. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157769. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157770. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157771. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157772. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157773. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157774. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157775. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157776. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157777. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157778. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157779. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157780. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157781. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157782. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157783. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157784. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157785. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157786. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157787. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157788. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157789. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157790. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157791. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157792. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157793. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157794. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157795. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157796. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157797. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157798. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157799. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157800. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157801. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157802. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157803. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157804. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157805. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157806. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157807. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157808. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157809. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157810. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157811. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157812. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157813. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157814. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157815. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157816. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157817. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157818. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157819. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157820. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157821. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157822. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157823. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157824. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157825. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157826. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157827. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157828. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157829. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157830. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157831. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157832. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157833. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157834. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157835. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157836. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157837. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157838. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157839. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157840. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157841. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157842. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157843. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157844. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157845. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157846. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157847. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157848. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157849. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157850. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157851. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157852. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157853. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157854. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157855. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157856. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157857. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157858. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157859. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157860. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157861. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157862. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157863. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157864. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157865. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157866. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157867. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157868. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157869. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157870. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157871. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157872. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157873. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157874. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157875. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157876. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157877. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157878. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157879. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157880. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157881. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157882. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157883. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157884. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157885. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157886. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157887. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157888. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157889. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157890. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157891. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157892. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157893. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157894. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157895. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157896. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157897. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157898. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157899. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157900. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157901. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157902. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157903. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157904. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157905. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157906. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157907. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157908. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157909. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157910. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157911. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157912. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157913. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157914. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157915. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157916. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157917. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157918. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157919. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157920. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157921. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157922. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157923. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157924. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157925. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157926. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157927. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157928. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157929. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157930. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157931. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157932. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157933. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157934. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157935. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157936. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157937. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157938. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157939. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157940. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157941. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157942. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157943. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157944. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157945. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157946. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157947. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157948. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157949. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157950. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157951. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157952. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157953. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157954. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157955. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157956. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157957. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157958. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157959. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157960. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157961. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157962. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157963. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157964. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157965. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157966. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157967. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157968. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157969. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157970. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157971. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157972. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157973. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157974. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157975. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157976. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157977. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157978. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157979. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157980. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157981. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157982. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157983. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157984. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157985. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157986. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157987. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157988. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157989. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157990. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157991. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157992. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157993. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157994. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157995. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157996. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157997. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157998. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157999. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158000. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158001. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158002. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158003. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158004. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158005. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158006. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158007. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158008. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158009. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158010. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158011. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158012. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158013. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158014. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158015. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158016. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158017. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158018. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158019. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158020. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158021. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158022. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158023. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158024. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158025. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158026. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158027. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158028. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158029. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158030. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158031. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158032. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158033. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158034. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158035. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158036. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158037. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158038. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158039. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158040. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158041. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158042. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158043. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158044. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158045. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158046. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158047. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158048. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158049. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158050. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158051. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158052. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158053. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158054. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158055. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158056. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158057. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158058. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158059. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158060. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158061. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158062. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158063. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158064. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158065. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158066. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158067. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158068. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158069. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158070. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158071. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158072. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158073. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158074. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158075. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158076. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158077. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158078. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158079. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158080. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158081. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158082. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158083. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158084. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158085. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158086. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158087. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158088. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158089. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158090. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158091. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158092. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158093. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158094. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158095. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158096. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158097. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158098. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158099. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158100. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158101. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158102. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158103. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158104. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158105. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158106. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158107. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158108. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158109. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158110. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158111. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158112. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158113. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158114. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158115. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158116. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158117. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158118. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158119. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158120. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158121. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158122. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158123. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158124. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158125. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158126. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158127. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158128. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158129. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158130. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158131. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158132. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158133. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158134. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158135. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158136. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158137. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158138. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158139. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158140. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158141. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158142. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158143. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158144. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158145. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158146. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158147. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158148. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158149. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158150. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158151. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158152. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158153. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158154. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158155. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158156. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158157. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158158. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158159. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158160. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158161. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158162. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158163. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158164. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158165. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158166. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158167. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158168. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158169. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158170. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158171. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158172. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158173. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158174. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158175. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158176. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158177. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158178. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158179. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158180. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158181. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158182. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158183. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158184. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158185. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158186. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158187. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158188. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158189. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158190. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158191. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158192. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158193. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158194. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158195. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158196. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158197. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158198. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158199. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158200. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158201. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158202. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158203. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158204. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158205. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158206. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158207. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158208. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158209. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158210. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158211. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158212. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158213. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158214. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158215. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158216. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158217. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158218. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158219. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158220. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158221. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158222. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158223. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158224. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158225. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158226. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158227. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158228. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158229. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158230. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158231. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158232. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158233. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158234. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158235. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158236. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158237. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158238. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158239. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158240. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158241. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158242. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158243. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158244. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158245. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158246. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158247. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158248. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158249. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158250. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158251. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158252. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158253. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158254. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158255. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158256. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158257. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158258. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158259. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158260. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158261. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158262. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158263. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158264. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158265. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158266. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158267. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158268. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158269. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158270. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158271. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158272. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158273. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158274. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158275. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158276. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158277. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158278. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158279. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158280. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158281. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158282. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158283. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158284. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158285. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158286. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158287. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158288. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158289. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158290. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158291. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158292. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158293. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158294. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158295. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158296. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158297. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158298. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158299. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158300. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158301. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158302. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158303. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158304. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158305. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158306. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158307. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158308. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158309. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158310. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158311. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158312. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158313. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158314. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158315. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158316. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158317. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158318. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158319. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158320. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158321. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158322. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158323. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158324. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158325. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158326. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158327. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158328. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158329. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158330. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158331. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158332. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158333. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158334. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158335. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158336. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158337. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158338. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158339. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158340. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158341. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158342. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158343. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158344. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158345. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158346. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158347. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158348. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158349. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158350. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158351. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158352. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158353. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158354. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158355. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158356. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158357. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158358. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158359. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158360. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158361. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158362. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158363. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158364. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158365. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158366. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158367. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158368. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158369. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158370. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158371. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158372. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158373. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158374. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158375. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158376. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158377. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158378. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158379. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158380. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158381. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158382. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158383. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158384. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158385. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158386. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158387. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158388. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158389. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158390. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158391. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158392. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158393. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158394. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158395. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158396. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158397. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158398. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158399. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158400. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158401. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158402. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158403. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158404. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158405. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158406. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158407. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158408. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158409. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158410. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158411. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158412. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158413. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158414. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158415. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158416. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158417. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158418. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158419. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158420. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158421. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158422. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158423. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158424. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158425. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158426. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158427. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158428. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158429. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158430. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158431. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158432. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158433. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158434. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158435. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158436. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158437. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158438. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158439. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158440. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158441. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158442. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158443. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158444. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158445. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158446. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158447. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158448. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158449. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158450. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158451. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158452. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158453. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158454. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158455. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158456. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158457. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158458. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158459. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158460. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158461. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158462. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158463. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158464. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158465. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158466. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158467. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158468. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158469. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158470. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158471. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158472. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158473. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158474. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158475. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158476. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158477. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158478. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158479. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158480. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158481. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158482. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158483. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158484. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158485. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158486. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158487. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158488. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158489. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158490. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158491. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158492. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158493. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158494. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158495. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158496. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158497. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158498. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158499. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158500. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158501. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158502. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158503. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158504. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158505. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158506. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158507. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158508. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158509. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158510. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158511. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158512. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158513. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158514. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158515. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158516. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158517. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158518. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158519. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158520. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158521. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158522. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158523. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158524. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158525. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158526. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158527. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158528. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158529. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158530. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158531. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158532. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158533. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158534. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158535. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158536. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158537. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158538. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158539. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158540. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158541. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158542. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158543. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158544. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158545. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158546. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158547. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158548. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158549. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158550. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158551. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158552. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158553. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158554. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158555. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158556. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158557. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158558. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158559. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158560. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158561. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158562. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158563. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158564. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158565. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158566. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158567. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158568. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158569. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158570. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158571. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158572. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158573. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158574. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158575. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158576. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158577. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158578. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158579. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158580. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158581. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158582. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158583. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158584. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158585. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158586. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158587. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158588. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158589. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158590. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158591. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158592. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158593. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158594. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158595. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158596. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158597. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158598. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158599. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158600. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158601. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158602. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158603. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158604. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158605. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158606. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158607. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158608. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158609. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158610. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158611. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158612. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158613. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158614. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158615. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158616. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158617. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158618. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158619. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158620. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158621. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158622. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158623. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158624. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158625. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158626. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158627. };
  158628. static float *vwin[8] = {
  158629. vwin64,
  158630. vwin128,
  158631. vwin256,
  158632. vwin512,
  158633. vwin1024,
  158634. vwin2048,
  158635. vwin4096,
  158636. vwin8192,
  158637. };
  158638. float *_vorbis_window_get(int n){
  158639. return vwin[n];
  158640. }
  158641. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158642. int lW,int W,int nW){
  158643. lW=(W?lW:0);
  158644. nW=(W?nW:0);
  158645. {
  158646. float *windowLW=vwin[winno[lW]];
  158647. float *windowNW=vwin[winno[nW]];
  158648. long n=blocksizes[W];
  158649. long ln=blocksizes[lW];
  158650. long rn=blocksizes[nW];
  158651. long leftbegin=n/4-ln/4;
  158652. long leftend=leftbegin+ln/2;
  158653. long rightbegin=n/2+n/4-rn/4;
  158654. long rightend=rightbegin+rn/2;
  158655. int i,p;
  158656. for(i=0;i<leftbegin;i++)
  158657. d[i]=0.f;
  158658. for(p=0;i<leftend;i++,p++)
  158659. d[i]*=windowLW[p];
  158660. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158661. d[i]*=windowNW[p];
  158662. for(;i<n;i++)
  158663. d[i]=0.f;
  158664. }
  158665. }
  158666. #endif
  158667. /*** End of inlined file: window.c ***/
  158668. #else
  158669. #include <vorbis/vorbisenc.h>
  158670. #include <vorbis/codec.h>
  158671. #include <vorbis/vorbisfile.h>
  158672. #endif
  158673. }
  158674. #undef max
  158675. #undef min
  158676. BEGIN_JUCE_NAMESPACE
  158677. static const char* const oggFormatName = "Ogg-Vorbis file";
  158678. static const char* const oggExtensions[] = { ".ogg", 0 };
  158679. class OggReader : public AudioFormatReader
  158680. {
  158681. OggVorbisNamespace::OggVorbis_File ovFile;
  158682. OggVorbisNamespace::ov_callbacks callbacks;
  158683. AudioSampleBuffer reservoir;
  158684. int reservoirStart, samplesInReservoir;
  158685. public:
  158686. OggReader (InputStream* const inp)
  158687. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158688. reservoir (2, 4096),
  158689. reservoirStart (0),
  158690. samplesInReservoir (0)
  158691. {
  158692. using namespace OggVorbisNamespace;
  158693. sampleRate = 0;
  158694. usesFloatingPointData = true;
  158695. callbacks.read_func = &oggReadCallback;
  158696. callbacks.seek_func = &oggSeekCallback;
  158697. callbacks.close_func = &oggCloseCallback;
  158698. callbacks.tell_func = &oggTellCallback;
  158699. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158700. if (err == 0)
  158701. {
  158702. vorbis_info* info = ov_info (&ovFile, -1);
  158703. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158704. numChannels = info->channels;
  158705. bitsPerSample = 16;
  158706. sampleRate = info->rate;
  158707. reservoir.setSize (numChannels,
  158708. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158709. }
  158710. }
  158711. ~OggReader()
  158712. {
  158713. OggVorbisNamespace::ov_clear (&ovFile);
  158714. }
  158715. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158716. int64 startSampleInFile, int numSamples)
  158717. {
  158718. while (numSamples > 0)
  158719. {
  158720. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158721. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158722. {
  158723. // got a few samples overlapping, so use them before seeking..
  158724. const int numToUse = jmin (numSamples, numAvailable);
  158725. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158726. if (destSamples[i] != 0)
  158727. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158728. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158729. sizeof (float) * numToUse);
  158730. startSampleInFile += numToUse;
  158731. numSamples -= numToUse;
  158732. startOffsetInDestBuffer += numToUse;
  158733. if (numSamples == 0)
  158734. break;
  158735. }
  158736. if (startSampleInFile < reservoirStart
  158737. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158738. {
  158739. // buffer miss, so refill the reservoir
  158740. int bitStream = 0;
  158741. reservoirStart = jmax (0, (int) startSampleInFile);
  158742. samplesInReservoir = reservoir.getNumSamples();
  158743. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158744. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158745. int offset = 0;
  158746. int numToRead = samplesInReservoir;
  158747. while (numToRead > 0)
  158748. {
  158749. float** dataIn = 0;
  158750. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158751. if (samps <= 0)
  158752. break;
  158753. jassert (samps <= numToRead);
  158754. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158755. {
  158756. memcpy (reservoir.getSampleData (i, offset),
  158757. dataIn[i],
  158758. sizeof (float) * samps);
  158759. }
  158760. numToRead -= samps;
  158761. offset += samps;
  158762. }
  158763. if (numToRead > 0)
  158764. reservoir.clear (offset, numToRead);
  158765. }
  158766. }
  158767. if (numSamples > 0)
  158768. {
  158769. for (int i = numDestChannels; --i >= 0;)
  158770. if (destSamples[i] != 0)
  158771. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158772. sizeof (int) * numSamples);
  158773. }
  158774. return true;
  158775. }
  158776. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158777. {
  158778. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158779. }
  158780. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158781. {
  158782. InputStream* const in = static_cast <InputStream*> (datasource);
  158783. if (whence == SEEK_CUR)
  158784. offset += in->getPosition();
  158785. else if (whence == SEEK_END)
  158786. offset += in->getTotalLength();
  158787. in->setPosition (offset);
  158788. return 0;
  158789. }
  158790. static int oggCloseCallback (void*)
  158791. {
  158792. return 0;
  158793. }
  158794. static long oggTellCallback (void* datasource)
  158795. {
  158796. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158797. }
  158798. juce_UseDebuggingNewOperator
  158799. };
  158800. class OggWriter : public AudioFormatWriter
  158801. {
  158802. OggVorbisNamespace::ogg_stream_state os;
  158803. OggVorbisNamespace::ogg_page og;
  158804. OggVorbisNamespace::ogg_packet op;
  158805. OggVorbisNamespace::vorbis_info vi;
  158806. OggVorbisNamespace::vorbis_comment vc;
  158807. OggVorbisNamespace::vorbis_dsp_state vd;
  158808. OggVorbisNamespace::vorbis_block vb;
  158809. public:
  158810. bool ok;
  158811. OggWriter (OutputStream* const out,
  158812. const double sampleRate,
  158813. const int numChannels,
  158814. const int bitsPerSample,
  158815. const int qualityIndex)
  158816. : AudioFormatWriter (out, TRANS (oggFormatName),
  158817. sampleRate,
  158818. numChannels,
  158819. bitsPerSample)
  158820. {
  158821. using namespace OggVorbisNamespace;
  158822. ok = false;
  158823. vorbis_info_init (&vi);
  158824. if (vorbis_encode_init_vbr (&vi,
  158825. numChannels,
  158826. (int) sampleRate,
  158827. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158828. {
  158829. vorbis_comment_init (&vc);
  158830. if (JUCEApplication::getInstance() != 0)
  158831. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158832. vorbis_analysis_init (&vd, &vi);
  158833. vorbis_block_init (&vd, &vb);
  158834. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158835. ogg_packet header;
  158836. ogg_packet header_comm;
  158837. ogg_packet header_code;
  158838. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158839. ogg_stream_packetin (&os, &header);
  158840. ogg_stream_packetin (&os, &header_comm);
  158841. ogg_stream_packetin (&os, &header_code);
  158842. for (;;)
  158843. {
  158844. if (ogg_stream_flush (&os, &og) == 0)
  158845. break;
  158846. output->write (og.header, og.header_len);
  158847. output->write (og.body, og.body_len);
  158848. }
  158849. ok = true;
  158850. }
  158851. }
  158852. ~OggWriter()
  158853. {
  158854. using namespace OggVorbisNamespace;
  158855. if (ok)
  158856. {
  158857. // write a zero-length packet to show ogg that we're finished..
  158858. write (0, 0);
  158859. ogg_stream_clear (&os);
  158860. vorbis_block_clear (&vb);
  158861. vorbis_dsp_clear (&vd);
  158862. vorbis_comment_clear (&vc);
  158863. vorbis_info_clear (&vi);
  158864. output->flush();
  158865. }
  158866. else
  158867. {
  158868. vorbis_info_clear (&vi);
  158869. output = 0; // to stop the base class deleting this, as it needs to be returned
  158870. // to the caller of createWriter()
  158871. }
  158872. }
  158873. bool write (const int** samplesToWrite, int numSamples)
  158874. {
  158875. using namespace OggVorbisNamespace;
  158876. if (! ok)
  158877. return false;
  158878. if (numSamples > 0)
  158879. {
  158880. const double gain = 1.0 / 0x80000000u;
  158881. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158882. for (int i = numChannels; --i >= 0;)
  158883. {
  158884. float* const dst = vorbisBuffer[i];
  158885. const int* const src = samplesToWrite [i];
  158886. if (src != 0 && dst != 0)
  158887. {
  158888. for (int j = 0; j < numSamples; ++j)
  158889. dst[j] = (float) (src[j] * gain);
  158890. }
  158891. }
  158892. }
  158893. vorbis_analysis_wrote (&vd, numSamples);
  158894. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158895. {
  158896. vorbis_analysis (&vb, 0);
  158897. vorbis_bitrate_addblock (&vb);
  158898. while (vorbis_bitrate_flushpacket (&vd, &op))
  158899. {
  158900. ogg_stream_packetin (&os, &op);
  158901. for (;;)
  158902. {
  158903. if (ogg_stream_pageout (&os, &og) == 0)
  158904. break;
  158905. output->write (og.header, og.header_len);
  158906. output->write (og.body, og.body_len);
  158907. if (ogg_page_eos (&og))
  158908. break;
  158909. }
  158910. }
  158911. }
  158912. return true;
  158913. }
  158914. juce_UseDebuggingNewOperator
  158915. };
  158916. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158917. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158918. {
  158919. }
  158920. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158921. {
  158922. }
  158923. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158924. {
  158925. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158926. return Array <int> (rates);
  158927. }
  158928. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158929. {
  158930. Array <int> depths;
  158931. depths.add (32);
  158932. return depths;
  158933. }
  158934. bool OggVorbisAudioFormat::canDoStereo()
  158935. {
  158936. return true;
  158937. }
  158938. bool OggVorbisAudioFormat::canDoMono()
  158939. {
  158940. return true;
  158941. }
  158942. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158943. const bool deleteStreamIfOpeningFails)
  158944. {
  158945. ScopedPointer <OggReader> r (new OggReader (in));
  158946. if (r->sampleRate != 0)
  158947. return r.release();
  158948. if (! deleteStreamIfOpeningFails)
  158949. r->input = 0;
  158950. return 0;
  158951. }
  158952. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158953. double sampleRate,
  158954. unsigned int numChannels,
  158955. int bitsPerSample,
  158956. const StringPairArray& /*metadataValues*/,
  158957. int qualityOptionIndex)
  158958. {
  158959. ScopedPointer <OggWriter> w (new OggWriter (out,
  158960. sampleRate,
  158961. numChannels,
  158962. bitsPerSample,
  158963. qualityOptionIndex));
  158964. return w->ok ? w.release() : 0;
  158965. }
  158966. bool OggVorbisAudioFormat::isCompressed()
  158967. {
  158968. return true;
  158969. }
  158970. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158971. {
  158972. StringArray s;
  158973. s.add ("Low Quality");
  158974. s.add ("Medium Quality");
  158975. s.add ("High Quality");
  158976. return s;
  158977. }
  158978. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158979. {
  158980. FileInputStream* const in = source.createInputStream();
  158981. if (in != 0)
  158982. {
  158983. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158984. if (r != 0)
  158985. {
  158986. const int64 numSamps = r->lengthInSamples;
  158987. r = 0;
  158988. const int64 fileNumSamps = source.getSize() / 4;
  158989. const double ratio = numSamps / (double) fileNumSamps;
  158990. if (ratio > 12.0)
  158991. return 0;
  158992. else if (ratio > 6.0)
  158993. return 1;
  158994. else
  158995. return 2;
  158996. }
  158997. }
  158998. return 1;
  158999. }
  159000. END_JUCE_NAMESPACE
  159001. #endif
  159002. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159003. #endif
  159004. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159005. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159006. #if JUCE_MSVC
  159007. #pragma warning (push)
  159008. #endif
  159009. namespace jpeglibNamespace
  159010. {
  159011. #if JUCE_INCLUDE_JPEGLIB_CODE
  159012. #if JUCE_MINGW
  159013. typedef unsigned char boolean;
  159014. #endif
  159015. extern "C"
  159016. {
  159017. #define JPEG_INTERNALS
  159018. #undef FAR
  159019. /*** Start of inlined file: jpeglib.h ***/
  159020. #ifndef JPEGLIB_H
  159021. #define JPEGLIB_H
  159022. /*
  159023. * First we include the configuration files that record how this
  159024. * installation of the JPEG library is set up. jconfig.h can be
  159025. * generated automatically for many systems. jmorecfg.h contains
  159026. * manual configuration options that most people need not worry about.
  159027. */
  159028. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159029. /*** Start of inlined file: jconfig.h ***/
  159030. /* see jconfig.doc for explanations */
  159031. // disable all the warnings under MSVC
  159032. #ifdef _MSC_VER
  159033. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159034. #endif
  159035. #ifdef __BORLANDC__
  159036. #pragma warn -8057
  159037. #pragma warn -8019
  159038. #pragma warn -8004
  159039. #pragma warn -8008
  159040. #endif
  159041. #define HAVE_PROTOTYPES
  159042. #define HAVE_UNSIGNED_CHAR
  159043. #define HAVE_UNSIGNED_SHORT
  159044. /* #define void char */
  159045. /* #define const */
  159046. #undef CHAR_IS_UNSIGNED
  159047. #define HAVE_STDDEF_H
  159048. #define HAVE_STDLIB_H
  159049. #undef NEED_BSD_STRINGS
  159050. #undef NEED_SYS_TYPES_H
  159051. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159052. #undef NEED_SHORT_EXTERNAL_NAMES
  159053. #undef INCOMPLETE_TYPES_BROKEN
  159054. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159055. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159056. typedef unsigned char boolean;
  159057. #endif
  159058. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159059. #ifdef JPEG_INTERNALS
  159060. #undef RIGHT_SHIFT_IS_UNSIGNED
  159061. #endif /* JPEG_INTERNALS */
  159062. #ifdef JPEG_CJPEG_DJPEG
  159063. #define BMP_SUPPORTED /* BMP image file format */
  159064. #define GIF_SUPPORTED /* GIF image file format */
  159065. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159066. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159067. #define TARGA_SUPPORTED /* Targa image file format */
  159068. #define TWO_FILE_COMMANDLINE /* optional */
  159069. #define USE_SETMODE /* Microsoft has setmode() */
  159070. #undef NEED_SIGNAL_CATCHER
  159071. #undef DONT_USE_B_MODE
  159072. #undef PROGRESS_REPORT /* optional */
  159073. #endif /* JPEG_CJPEG_DJPEG */
  159074. /*** End of inlined file: jconfig.h ***/
  159075. /* widely used configuration options */
  159076. #endif
  159077. /*** Start of inlined file: jmorecfg.h ***/
  159078. /*
  159079. * Define BITS_IN_JSAMPLE as either
  159080. * 8 for 8-bit sample values (the usual setting)
  159081. * 12 for 12-bit sample values
  159082. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159083. * JPEG standard, and the IJG code does not support anything else!
  159084. * We do not support run-time selection of data precision, sorry.
  159085. */
  159086. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159087. /*
  159088. * Maximum number of components (color channels) allowed in JPEG image.
  159089. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159090. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159091. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159092. * really short on memory. (Each allowed component costs a hundred or so
  159093. * bytes of storage, whether actually used in an image or not.)
  159094. */
  159095. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159096. /*
  159097. * Basic data types.
  159098. * You may need to change these if you have a machine with unusual data
  159099. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159100. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159101. * but it had better be at least 16.
  159102. */
  159103. /* Representation of a single sample (pixel element value).
  159104. * We frequently allocate large arrays of these, so it's important to keep
  159105. * them small. But if you have memory to burn and access to char or short
  159106. * arrays is very slow on your hardware, you might want to change these.
  159107. */
  159108. #if BITS_IN_JSAMPLE == 8
  159109. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159110. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159111. */
  159112. #ifdef HAVE_UNSIGNED_CHAR
  159113. typedef unsigned char JSAMPLE;
  159114. #define GETJSAMPLE(value) ((int) (value))
  159115. #else /* not HAVE_UNSIGNED_CHAR */
  159116. typedef char JSAMPLE;
  159117. #ifdef CHAR_IS_UNSIGNED
  159118. #define GETJSAMPLE(value) ((int) (value))
  159119. #else
  159120. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159121. #endif /* CHAR_IS_UNSIGNED */
  159122. #endif /* HAVE_UNSIGNED_CHAR */
  159123. #define MAXJSAMPLE 255
  159124. #define CENTERJSAMPLE 128
  159125. #endif /* BITS_IN_JSAMPLE == 8 */
  159126. #if BITS_IN_JSAMPLE == 12
  159127. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159128. * On nearly all machines "short" will do nicely.
  159129. */
  159130. typedef short JSAMPLE;
  159131. #define GETJSAMPLE(value) ((int) (value))
  159132. #define MAXJSAMPLE 4095
  159133. #define CENTERJSAMPLE 2048
  159134. #endif /* BITS_IN_JSAMPLE == 12 */
  159135. /* Representation of a DCT frequency coefficient.
  159136. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159137. * Again, we allocate large arrays of these, but you can change to int
  159138. * if you have memory to burn and "short" is really slow.
  159139. */
  159140. typedef short JCOEF;
  159141. /* Compressed datastreams are represented as arrays of JOCTET.
  159142. * These must be EXACTLY 8 bits wide, at least once they are written to
  159143. * external storage. Note that when using the stdio data source/destination
  159144. * managers, this is also the data type passed to fread/fwrite.
  159145. */
  159146. #ifdef HAVE_UNSIGNED_CHAR
  159147. typedef unsigned char JOCTET;
  159148. #define GETJOCTET(value) (value)
  159149. #else /* not HAVE_UNSIGNED_CHAR */
  159150. typedef char JOCTET;
  159151. #ifdef CHAR_IS_UNSIGNED
  159152. #define GETJOCTET(value) (value)
  159153. #else
  159154. #define GETJOCTET(value) ((value) & 0xFF)
  159155. #endif /* CHAR_IS_UNSIGNED */
  159156. #endif /* HAVE_UNSIGNED_CHAR */
  159157. /* These typedefs are used for various table entries and so forth.
  159158. * They must be at least as wide as specified; but making them too big
  159159. * won't cost a huge amount of memory, so we don't provide special
  159160. * extraction code like we did for JSAMPLE. (In other words, these
  159161. * typedefs live at a different point on the speed/space tradeoff curve.)
  159162. */
  159163. /* UINT8 must hold at least the values 0..255. */
  159164. #ifdef HAVE_UNSIGNED_CHAR
  159165. typedef unsigned char UINT8;
  159166. #else /* not HAVE_UNSIGNED_CHAR */
  159167. #ifdef CHAR_IS_UNSIGNED
  159168. typedef char UINT8;
  159169. #else /* not CHAR_IS_UNSIGNED */
  159170. typedef short UINT8;
  159171. #endif /* CHAR_IS_UNSIGNED */
  159172. #endif /* HAVE_UNSIGNED_CHAR */
  159173. /* UINT16 must hold at least the values 0..65535. */
  159174. #ifdef HAVE_UNSIGNED_SHORT
  159175. typedef unsigned short UINT16;
  159176. #else /* not HAVE_UNSIGNED_SHORT */
  159177. typedef unsigned int UINT16;
  159178. #endif /* HAVE_UNSIGNED_SHORT */
  159179. /* INT16 must hold at least the values -32768..32767. */
  159180. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159181. typedef short INT16;
  159182. #endif
  159183. /* INT32 must hold at least signed 32-bit values. */
  159184. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159185. typedef long INT32;
  159186. #endif
  159187. /* Datatype used for image dimensions. The JPEG standard only supports
  159188. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159189. * "unsigned int" is sufficient on all machines. However, if you need to
  159190. * handle larger images and you don't mind deviating from the spec, you
  159191. * can change this datatype.
  159192. */
  159193. typedef unsigned int JDIMENSION;
  159194. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159195. /* These macros are used in all function definitions and extern declarations.
  159196. * You could modify them if you need to change function linkage conventions;
  159197. * in particular, you'll need to do that to make the library a Windows DLL.
  159198. * Another application is to make all functions global for use with debuggers
  159199. * or code profilers that require it.
  159200. */
  159201. /* a function called through method pointers: */
  159202. #define METHODDEF(type) static type
  159203. /* a function used only in its module: */
  159204. #define LOCAL(type) static type
  159205. /* a function referenced thru EXTERNs: */
  159206. #define GLOBAL(type) type
  159207. /* a reference to a GLOBAL function: */
  159208. #define EXTERN(type) extern type
  159209. /* This macro is used to declare a "method", that is, a function pointer.
  159210. * We want to supply prototype parameters if the compiler can cope.
  159211. * Note that the arglist parameter must be parenthesized!
  159212. * Again, you can customize this if you need special linkage keywords.
  159213. */
  159214. #ifdef HAVE_PROTOTYPES
  159215. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159216. #else
  159217. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159218. #endif
  159219. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159220. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159221. * by just saying "FAR *" where such a pointer is needed. In a few places
  159222. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159223. */
  159224. #ifdef NEED_FAR_POINTERS
  159225. #define FAR far
  159226. #else
  159227. #define FAR
  159228. #endif
  159229. /*
  159230. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159231. * in standard header files. Or you may have conflicts with application-
  159232. * specific header files that you want to include together with these files.
  159233. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159234. */
  159235. #ifndef HAVE_BOOLEAN
  159236. typedef int boolean;
  159237. #endif
  159238. #ifndef FALSE /* in case these macros already exist */
  159239. #define FALSE 0 /* values of boolean */
  159240. #endif
  159241. #ifndef TRUE
  159242. #define TRUE 1
  159243. #endif
  159244. /*
  159245. * The remaining options affect code selection within the JPEG library,
  159246. * but they don't need to be visible to most applications using the library.
  159247. * To minimize application namespace pollution, the symbols won't be
  159248. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159249. */
  159250. #ifdef JPEG_INTERNALS
  159251. #define JPEG_INTERNAL_OPTIONS
  159252. #endif
  159253. #ifdef JPEG_INTERNAL_OPTIONS
  159254. /*
  159255. * These defines indicate whether to include various optional functions.
  159256. * Undefining some of these symbols will produce a smaller but less capable
  159257. * library. Note that you can leave certain source files out of the
  159258. * compilation/linking process if you've #undef'd the corresponding symbols.
  159259. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159260. */
  159261. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159262. /* Capability options common to encoder and decoder: */
  159263. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159264. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159265. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159266. /* Encoder capability options: */
  159267. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159268. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159269. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159270. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159271. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159272. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159273. * precision, so jchuff.c normally uses entropy optimization to compute
  159274. * usable tables for higher precision. If you don't want to do optimization,
  159275. * you'll have to supply different default Huffman tables.
  159276. * The exact same statements apply for progressive JPEG: the default tables
  159277. * don't work for progressive mode. (This may get fixed, however.)
  159278. */
  159279. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159280. /* Decoder capability options: */
  159281. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159282. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159283. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159284. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159285. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159286. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159287. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159288. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159289. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159290. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159291. /* more capability options later, no doubt */
  159292. /*
  159293. * Ordering of RGB data in scanlines passed to or from the application.
  159294. * If your application wants to deal with data in the order B,G,R, just
  159295. * change these macros. You can also deal with formats such as R,G,B,X
  159296. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159297. * the offsets will also change the order in which colormap data is organized.
  159298. * RESTRICTIONS:
  159299. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159300. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159301. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159302. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159303. * is not 3 (they don't understand about dummy color components!). So you
  159304. * can't use color quantization if you change that value.
  159305. */
  159306. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159307. #define RGB_GREEN 1 /* Offset of Green */
  159308. #define RGB_BLUE 2 /* Offset of Blue */
  159309. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159310. /* Definitions for speed-related optimizations. */
  159311. /* If your compiler supports inline functions, define INLINE
  159312. * as the inline keyword; otherwise define it as empty.
  159313. */
  159314. #ifndef INLINE
  159315. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159316. #define INLINE __inline__
  159317. #endif
  159318. #ifndef INLINE
  159319. #define INLINE /* default is to define it as empty */
  159320. #endif
  159321. #endif
  159322. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159323. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159324. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159325. */
  159326. #ifndef MULTIPLIER
  159327. #define MULTIPLIER int /* type for fastest integer multiply */
  159328. #endif
  159329. /* FAST_FLOAT should be either float or double, whichever is done faster
  159330. * by your compiler. (Note that this type is only used in the floating point
  159331. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159332. * Typically, float is faster in ANSI C compilers, while double is faster in
  159333. * pre-ANSI compilers (because they insist on converting to double anyway).
  159334. * The code below therefore chooses float if we have ANSI-style prototypes.
  159335. */
  159336. #ifndef FAST_FLOAT
  159337. #ifdef HAVE_PROTOTYPES
  159338. #define FAST_FLOAT float
  159339. #else
  159340. #define FAST_FLOAT double
  159341. #endif
  159342. #endif
  159343. #endif /* JPEG_INTERNAL_OPTIONS */
  159344. /*** End of inlined file: jmorecfg.h ***/
  159345. /* seldom changed options */
  159346. /* Version ID for the JPEG library.
  159347. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159348. */
  159349. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159350. /* Various constants determining the sizes of things.
  159351. * All of these are specified by the JPEG standard, so don't change them
  159352. * if you want to be compatible.
  159353. */
  159354. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159355. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159356. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159357. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159358. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159359. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159360. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159361. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159362. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159363. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159364. * to handle it. We even let you do this from the jconfig.h file. However,
  159365. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159366. * sometimes emits noncompliant files doesn't mean you should too.
  159367. */
  159368. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159369. #ifndef D_MAX_BLOCKS_IN_MCU
  159370. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159371. #endif
  159372. /* Data structures for images (arrays of samples and of DCT coefficients).
  159373. * On 80x86 machines, the image arrays are too big for near pointers,
  159374. * but the pointer arrays can fit in near memory.
  159375. */
  159376. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159377. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159378. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159379. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159380. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159381. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159382. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159383. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159384. /* Types for JPEG compression parameters and working tables. */
  159385. /* DCT coefficient quantization tables. */
  159386. typedef struct {
  159387. /* This array gives the coefficient quantizers in natural array order
  159388. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159389. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159390. */
  159391. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159392. /* This field is used only during compression. It's initialized FALSE when
  159393. * the table is created, and set TRUE when it's been output to the file.
  159394. * You could suppress output of a table by setting this to TRUE.
  159395. * (See jpeg_suppress_tables for an example.)
  159396. */
  159397. boolean sent_table; /* TRUE when table has been output */
  159398. } JQUANT_TBL;
  159399. /* Huffman coding tables. */
  159400. typedef struct {
  159401. /* These two fields directly represent the contents of a JPEG DHT marker */
  159402. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159403. /* length k bits; bits[0] is unused */
  159404. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159405. /* This field is used only during compression. It's initialized FALSE when
  159406. * the table is created, and set TRUE when it's been output to the file.
  159407. * You could suppress output of a table by setting this to TRUE.
  159408. * (See jpeg_suppress_tables for an example.)
  159409. */
  159410. boolean sent_table; /* TRUE when table has been output */
  159411. } JHUFF_TBL;
  159412. /* Basic info about one component (color channel). */
  159413. typedef struct {
  159414. /* These values are fixed over the whole image. */
  159415. /* For compression, they must be supplied by parameter setup; */
  159416. /* for decompression, they are read from the SOF marker. */
  159417. int component_id; /* identifier for this component (0..255) */
  159418. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159419. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159420. int v_samp_factor; /* vertical sampling factor (1..4) */
  159421. int quant_tbl_no; /* quantization table selector (0..3) */
  159422. /* These values may vary between scans. */
  159423. /* For compression, they must be supplied by parameter setup; */
  159424. /* for decompression, they are read from the SOS marker. */
  159425. /* The decompressor output side may not use these variables. */
  159426. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159427. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159428. /* Remaining fields should be treated as private by applications. */
  159429. /* These values are computed during compression or decompression startup: */
  159430. /* Component's size in DCT blocks.
  159431. * Any dummy blocks added to complete an MCU are not counted; therefore
  159432. * these values do not depend on whether a scan is interleaved or not.
  159433. */
  159434. JDIMENSION width_in_blocks;
  159435. JDIMENSION height_in_blocks;
  159436. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159437. * For decompression this is the size of the output from one DCT block,
  159438. * reflecting any scaling we choose to apply during the IDCT step.
  159439. * Values of 1,2,4,8 are likely to be supported. Note that different
  159440. * components may receive different IDCT scalings.
  159441. */
  159442. int DCT_scaled_size;
  159443. /* The downsampled dimensions are the component's actual, unpadded number
  159444. * of samples at the main buffer (preprocessing/compression interface), thus
  159445. * downsampled_width = ceil(image_width * Hi/Hmax)
  159446. * and similarly for height. For decompression, IDCT scaling is included, so
  159447. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159448. */
  159449. JDIMENSION downsampled_width; /* actual width in samples */
  159450. JDIMENSION downsampled_height; /* actual height in samples */
  159451. /* This flag is used only for decompression. In cases where some of the
  159452. * components will be ignored (eg grayscale output from YCbCr image),
  159453. * we can skip most computations for the unused components.
  159454. */
  159455. boolean component_needed; /* do we need the value of this component? */
  159456. /* These values are computed before starting a scan of the component. */
  159457. /* The decompressor output side may not use these variables. */
  159458. int MCU_width; /* number of blocks per MCU, horizontally */
  159459. int MCU_height; /* number of blocks per MCU, vertically */
  159460. int MCU_blocks; /* MCU_width * MCU_height */
  159461. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159462. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159463. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159464. /* Saved quantization table for component; NULL if none yet saved.
  159465. * See jdinput.c comments about the need for this information.
  159466. * This field is currently used only for decompression.
  159467. */
  159468. JQUANT_TBL * quant_table;
  159469. /* Private per-component storage for DCT or IDCT subsystem. */
  159470. void * dct_table;
  159471. } jpeg_component_info;
  159472. /* The script for encoding a multiple-scan file is an array of these: */
  159473. typedef struct {
  159474. int comps_in_scan; /* number of components encoded in this scan */
  159475. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159476. int Ss, Se; /* progressive JPEG spectral selection parms */
  159477. int Ah, Al; /* progressive JPEG successive approx. parms */
  159478. } jpeg_scan_info;
  159479. /* The decompressor can save APPn and COM markers in a list of these: */
  159480. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159481. struct jpeg_marker_struct {
  159482. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159483. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159484. unsigned int original_length; /* # bytes of data in the file */
  159485. unsigned int data_length; /* # bytes of data saved at data[] */
  159486. JOCTET FAR * data; /* the data contained in the marker */
  159487. /* the marker length word is not counted in data_length or original_length */
  159488. };
  159489. /* Known color spaces. */
  159490. typedef enum {
  159491. JCS_UNKNOWN, /* error/unspecified */
  159492. JCS_GRAYSCALE, /* monochrome */
  159493. JCS_RGB, /* red/green/blue */
  159494. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159495. JCS_CMYK, /* C/M/Y/K */
  159496. JCS_YCCK /* Y/Cb/Cr/K */
  159497. } J_COLOR_SPACE;
  159498. /* DCT/IDCT algorithm options. */
  159499. typedef enum {
  159500. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159501. JDCT_IFAST, /* faster, less accurate integer method */
  159502. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159503. } J_DCT_METHOD;
  159504. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159505. #define JDCT_DEFAULT JDCT_ISLOW
  159506. #endif
  159507. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159508. #define JDCT_FASTEST JDCT_IFAST
  159509. #endif
  159510. /* Dithering options for decompression. */
  159511. typedef enum {
  159512. JDITHER_NONE, /* no dithering */
  159513. JDITHER_ORDERED, /* simple ordered dither */
  159514. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159515. } J_DITHER_MODE;
  159516. /* Common fields between JPEG compression and decompression master structs. */
  159517. #define jpeg_common_fields \
  159518. struct jpeg_error_mgr * err; /* Error handler module */\
  159519. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159520. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159521. void * client_data; /* Available for use by application */\
  159522. boolean is_decompressor; /* So common code can tell which is which */\
  159523. int global_state /* For checking call sequence validity */
  159524. /* Routines that are to be used by both halves of the library are declared
  159525. * to receive a pointer to this structure. There are no actual instances of
  159526. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159527. */
  159528. struct jpeg_common_struct {
  159529. jpeg_common_fields; /* Fields common to both master struct types */
  159530. /* Additional fields follow in an actual jpeg_compress_struct or
  159531. * jpeg_decompress_struct. All three structs must agree on these
  159532. * initial fields! (This would be a lot cleaner in C++.)
  159533. */
  159534. };
  159535. typedef struct jpeg_common_struct * j_common_ptr;
  159536. typedef struct jpeg_compress_struct * j_compress_ptr;
  159537. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159538. /* Master record for a compression instance */
  159539. struct jpeg_compress_struct {
  159540. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159541. /* Destination for compressed data */
  159542. struct jpeg_destination_mgr * dest;
  159543. /* Description of source image --- these fields must be filled in by
  159544. * outer application before starting compression. in_color_space must
  159545. * be correct before you can even call jpeg_set_defaults().
  159546. */
  159547. JDIMENSION image_width; /* input image width */
  159548. JDIMENSION image_height; /* input image height */
  159549. int input_components; /* # of color components in input image */
  159550. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159551. double input_gamma; /* image gamma of input image */
  159552. /* Compression parameters --- these fields must be set before calling
  159553. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159554. * initialize everything to reasonable defaults, then changing anything
  159555. * the application specifically wants to change. That way you won't get
  159556. * burnt when new parameters are added. Also note that there are several
  159557. * helper routines to simplify changing parameters.
  159558. */
  159559. int data_precision; /* bits of precision in image data */
  159560. int num_components; /* # of color components in JPEG image */
  159561. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159562. jpeg_component_info * comp_info;
  159563. /* comp_info[i] describes component that appears i'th in SOF */
  159564. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159565. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159566. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159567. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159568. /* ptrs to Huffman coding tables, or NULL if not defined */
  159569. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159570. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159571. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159572. int num_scans; /* # of entries in scan_info array */
  159573. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159574. /* The default value of scan_info is NULL, which causes a single-scan
  159575. * sequential JPEG file to be emitted. To create a multi-scan file,
  159576. * set num_scans and scan_info to point to an array of scan definitions.
  159577. */
  159578. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159579. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159580. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159581. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159582. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159583. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159584. /* The restart interval can be specified in absolute MCUs by setting
  159585. * restart_interval, or in MCU rows by setting restart_in_rows
  159586. * (in which case the correct restart_interval will be figured
  159587. * for each scan).
  159588. */
  159589. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159590. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159591. /* Parameters controlling emission of special markers. */
  159592. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159593. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159594. UINT8 JFIF_minor_version;
  159595. /* These three values are not used by the JPEG code, merely copied */
  159596. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159597. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159598. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159599. UINT8 density_unit; /* JFIF code for pixel size units */
  159600. UINT16 X_density; /* Horizontal pixel density */
  159601. UINT16 Y_density; /* Vertical pixel density */
  159602. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159603. /* State variable: index of next scanline to be written to
  159604. * jpeg_write_scanlines(). Application may use this to control its
  159605. * processing loop, e.g., "while (next_scanline < image_height)".
  159606. */
  159607. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159608. /* Remaining fields are known throughout compressor, but generally
  159609. * should not be touched by a surrounding application.
  159610. */
  159611. /*
  159612. * These fields are computed during compression startup
  159613. */
  159614. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159615. int max_h_samp_factor; /* largest h_samp_factor */
  159616. int max_v_samp_factor; /* largest v_samp_factor */
  159617. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159618. /* The coefficient controller receives data in units of MCU rows as defined
  159619. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159620. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159621. * "iMCU" (interleaved MCU) row.
  159622. */
  159623. /*
  159624. * These fields are valid during any one scan.
  159625. * They describe the components and MCUs actually appearing in the scan.
  159626. */
  159627. int comps_in_scan; /* # of JPEG components in this scan */
  159628. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159629. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159630. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159631. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159632. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159633. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159634. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159635. /* i'th block in an MCU */
  159636. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159637. /*
  159638. * Links to compression subobjects (methods and private variables of modules)
  159639. */
  159640. struct jpeg_comp_master * master;
  159641. struct jpeg_c_main_controller * main;
  159642. struct jpeg_c_prep_controller * prep;
  159643. struct jpeg_c_coef_controller * coef;
  159644. struct jpeg_marker_writer * marker;
  159645. struct jpeg_color_converter * cconvert;
  159646. struct jpeg_downsampler * downsample;
  159647. struct jpeg_forward_dct * fdct;
  159648. struct jpeg_entropy_encoder * entropy;
  159649. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159650. int script_space_size;
  159651. };
  159652. /* Master record for a decompression instance */
  159653. struct jpeg_decompress_struct {
  159654. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159655. /* Source of compressed data */
  159656. struct jpeg_source_mgr * src;
  159657. /* Basic description of image --- filled in by jpeg_read_header(). */
  159658. /* Application may inspect these values to decide how to process image. */
  159659. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159660. JDIMENSION image_height; /* nominal image height */
  159661. int num_components; /* # of color components in JPEG image */
  159662. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159663. /* Decompression processing parameters --- these fields must be set before
  159664. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159665. * them to default values.
  159666. */
  159667. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159668. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159669. double output_gamma; /* image gamma wanted in output */
  159670. boolean buffered_image; /* TRUE=multiple output passes */
  159671. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159672. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159673. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159674. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159675. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159676. /* the following are ignored if not quantize_colors: */
  159677. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159678. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159679. int desired_number_of_colors; /* max # colors to use in created colormap */
  159680. /* these are significant only in buffered-image mode: */
  159681. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159682. boolean enable_external_quant;/* enable future use of external colormap */
  159683. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159684. /* Description of actual output image that will be returned to application.
  159685. * These fields are computed by jpeg_start_decompress().
  159686. * You can also use jpeg_calc_output_dimensions() to determine these values
  159687. * in advance of calling jpeg_start_decompress().
  159688. */
  159689. JDIMENSION output_width; /* scaled image width */
  159690. JDIMENSION output_height; /* scaled image height */
  159691. int out_color_components; /* # of color components in out_color_space */
  159692. int output_components; /* # of color components returned */
  159693. /* output_components is 1 (a colormap index) when quantizing colors;
  159694. * otherwise it equals out_color_components.
  159695. */
  159696. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159697. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159698. * high, space and time will be wasted due to unnecessary data copying.
  159699. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159700. */
  159701. /* When quantizing colors, the output colormap is described by these fields.
  159702. * The application can supply a colormap by setting colormap non-NULL before
  159703. * calling jpeg_start_decompress; otherwise a colormap is created during
  159704. * jpeg_start_decompress or jpeg_start_output.
  159705. * The map has out_color_components rows and actual_number_of_colors columns.
  159706. */
  159707. int actual_number_of_colors; /* number of entries in use */
  159708. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159709. /* State variables: these variables indicate the progress of decompression.
  159710. * The application may examine these but must not modify them.
  159711. */
  159712. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159713. * Application may use this to control its processing loop, e.g.,
  159714. * "while (output_scanline < output_height)".
  159715. */
  159716. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159717. /* Current input scan number and number of iMCU rows completed in scan.
  159718. * These indicate the progress of the decompressor input side.
  159719. */
  159720. int input_scan_number; /* Number of SOS markers seen so far */
  159721. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159722. /* The "output scan number" is the notional scan being displayed by the
  159723. * output side. The decompressor will not allow output scan/row number
  159724. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159725. */
  159726. int output_scan_number; /* Nominal scan number being displayed */
  159727. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159728. /* Current progression status. coef_bits[c][i] indicates the precision
  159729. * with which component c's DCT coefficient i (in zigzag order) is known.
  159730. * It is -1 when no data has yet been received, otherwise it is the point
  159731. * transform (shift) value for the most recent scan of the coefficient
  159732. * (thus, 0 at completion of the progression).
  159733. * This pointer is NULL when reading a non-progressive file.
  159734. */
  159735. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159736. /* Internal JPEG parameters --- the application usually need not look at
  159737. * these fields. Note that the decompressor output side may not use
  159738. * any parameters that can change between scans.
  159739. */
  159740. /* Quantization and Huffman tables are carried forward across input
  159741. * datastreams when processing abbreviated JPEG datastreams.
  159742. */
  159743. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159744. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159745. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159746. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159747. /* ptrs to Huffman coding tables, or NULL if not defined */
  159748. /* These parameters are never carried across datastreams, since they
  159749. * are given in SOF/SOS markers or defined to be reset by SOI.
  159750. */
  159751. int data_precision; /* bits of precision in image data */
  159752. jpeg_component_info * comp_info;
  159753. /* comp_info[i] describes component that appears i'th in SOF */
  159754. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159755. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159756. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159757. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159758. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159759. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159760. /* These fields record data obtained from optional markers recognized by
  159761. * the JPEG library.
  159762. */
  159763. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159764. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159765. UINT8 JFIF_major_version; /* JFIF version number */
  159766. UINT8 JFIF_minor_version;
  159767. UINT8 density_unit; /* JFIF code for pixel size units */
  159768. UINT16 X_density; /* Horizontal pixel density */
  159769. UINT16 Y_density; /* Vertical pixel density */
  159770. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159771. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159772. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159773. /* Aside from the specific data retained from APPn markers known to the
  159774. * library, the uninterpreted contents of any or all APPn and COM markers
  159775. * can be saved in a list for examination by the application.
  159776. */
  159777. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159778. /* Remaining fields are known throughout decompressor, but generally
  159779. * should not be touched by a surrounding application.
  159780. */
  159781. /*
  159782. * These fields are computed during decompression startup
  159783. */
  159784. int max_h_samp_factor; /* largest h_samp_factor */
  159785. int max_v_samp_factor; /* largest v_samp_factor */
  159786. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159787. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159788. /* The coefficient controller's input and output progress is measured in
  159789. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159790. * in fully interleaved JPEG scans, but are used whether the scan is
  159791. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159792. * rows of each component. Therefore, the IDCT output contains
  159793. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159794. */
  159795. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159796. /*
  159797. * These fields are valid during any one scan.
  159798. * They describe the components and MCUs actually appearing in the scan.
  159799. * Note that the decompressor output side must not use these fields.
  159800. */
  159801. int comps_in_scan; /* # of JPEG components in this scan */
  159802. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159803. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159804. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159805. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159806. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159807. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159808. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159809. /* i'th block in an MCU */
  159810. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159811. /* This field is shared between entropy decoder and marker parser.
  159812. * It is either zero or the code of a JPEG marker that has been
  159813. * read from the data source, but has not yet been processed.
  159814. */
  159815. int unread_marker;
  159816. /*
  159817. * Links to decompression subobjects (methods, private variables of modules)
  159818. */
  159819. struct jpeg_decomp_master * master;
  159820. struct jpeg_d_main_controller * main;
  159821. struct jpeg_d_coef_controller * coef;
  159822. struct jpeg_d_post_controller * post;
  159823. struct jpeg_input_controller * inputctl;
  159824. struct jpeg_marker_reader * marker;
  159825. struct jpeg_entropy_decoder * entropy;
  159826. struct jpeg_inverse_dct * idct;
  159827. struct jpeg_upsampler * upsample;
  159828. struct jpeg_color_deconverter * cconvert;
  159829. struct jpeg_color_quantizer * cquantize;
  159830. };
  159831. /* "Object" declarations for JPEG modules that may be supplied or called
  159832. * directly by the surrounding application.
  159833. * As with all objects in the JPEG library, these structs only define the
  159834. * publicly visible methods and state variables of a module. Additional
  159835. * private fields may exist after the public ones.
  159836. */
  159837. /* Error handler object */
  159838. struct jpeg_error_mgr {
  159839. /* Error exit handler: does not return to caller */
  159840. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159841. /* Conditionally emit a trace or warning message */
  159842. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159843. /* Routine that actually outputs a trace or error message */
  159844. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159845. /* Format a message string for the most recent JPEG error or message */
  159846. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159847. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159848. /* Reset error state variables at start of a new image */
  159849. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159850. /* The message ID code and any parameters are saved here.
  159851. * A message can have one string parameter or up to 8 int parameters.
  159852. */
  159853. int msg_code;
  159854. #define JMSG_STR_PARM_MAX 80
  159855. union {
  159856. int i[8];
  159857. char s[JMSG_STR_PARM_MAX];
  159858. } msg_parm;
  159859. /* Standard state variables for error facility */
  159860. int trace_level; /* max msg_level that will be displayed */
  159861. /* For recoverable corrupt-data errors, we emit a warning message,
  159862. * but keep going unless emit_message chooses to abort. emit_message
  159863. * should count warnings in num_warnings. The surrounding application
  159864. * can check for bad data by seeing if num_warnings is nonzero at the
  159865. * end of processing.
  159866. */
  159867. long num_warnings; /* number of corrupt-data warnings */
  159868. /* These fields point to the table(s) of error message strings.
  159869. * An application can change the table pointer to switch to a different
  159870. * message list (typically, to change the language in which errors are
  159871. * reported). Some applications may wish to add additional error codes
  159872. * that will be handled by the JPEG library error mechanism; the second
  159873. * table pointer is used for this purpose.
  159874. *
  159875. * First table includes all errors generated by JPEG library itself.
  159876. * Error code 0 is reserved for a "no such error string" message.
  159877. */
  159878. const char * const * jpeg_message_table; /* Library errors */
  159879. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159880. /* Second table can be added by application (see cjpeg/djpeg for example).
  159881. * It contains strings numbered first_addon_message..last_addon_message.
  159882. */
  159883. const char * const * addon_message_table; /* Non-library errors */
  159884. int first_addon_message; /* code for first string in addon table */
  159885. int last_addon_message; /* code for last string in addon table */
  159886. };
  159887. /* Progress monitor object */
  159888. struct jpeg_progress_mgr {
  159889. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159890. long pass_counter; /* work units completed in this pass */
  159891. long pass_limit; /* total number of work units in this pass */
  159892. int completed_passes; /* passes completed so far */
  159893. int total_passes; /* total number of passes expected */
  159894. };
  159895. /* Data destination object for compression */
  159896. struct jpeg_destination_mgr {
  159897. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159898. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159899. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159900. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159901. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159902. };
  159903. /* Data source object for decompression */
  159904. struct jpeg_source_mgr {
  159905. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159906. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159907. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159908. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159909. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159910. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159911. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159912. };
  159913. /* Memory manager object.
  159914. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159915. * and "really big" objects (virtual arrays with backing store if needed).
  159916. * The memory manager does not allow individual objects to be freed; rather,
  159917. * each created object is assigned to a pool, and whole pools can be freed
  159918. * at once. This is faster and more convenient than remembering exactly what
  159919. * to free, especially where malloc()/free() are not too speedy.
  159920. * NB: alloc routines never return NULL. They exit to error_exit if not
  159921. * successful.
  159922. */
  159923. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159924. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159925. #define JPOOL_NUMPOOLS 2
  159926. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159927. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159928. struct jpeg_memory_mgr {
  159929. /* Method pointers */
  159930. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159931. size_t sizeofobject));
  159932. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159933. size_t sizeofobject));
  159934. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159935. JDIMENSION samplesperrow,
  159936. JDIMENSION numrows));
  159937. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159938. JDIMENSION blocksperrow,
  159939. JDIMENSION numrows));
  159940. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159941. int pool_id,
  159942. boolean pre_zero,
  159943. JDIMENSION samplesperrow,
  159944. JDIMENSION numrows,
  159945. JDIMENSION maxaccess));
  159946. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159947. int pool_id,
  159948. boolean pre_zero,
  159949. JDIMENSION blocksperrow,
  159950. JDIMENSION numrows,
  159951. JDIMENSION maxaccess));
  159952. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159953. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159954. jvirt_sarray_ptr ptr,
  159955. JDIMENSION start_row,
  159956. JDIMENSION num_rows,
  159957. boolean writable));
  159958. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159959. jvirt_barray_ptr ptr,
  159960. JDIMENSION start_row,
  159961. JDIMENSION num_rows,
  159962. boolean writable));
  159963. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159964. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159965. /* Limit on memory allocation for this JPEG object. (Note that this is
  159966. * merely advisory, not a guaranteed maximum; it only affects the space
  159967. * used for virtual-array buffers.) May be changed by outer application
  159968. * after creating the JPEG object.
  159969. */
  159970. long max_memory_to_use;
  159971. /* Maximum allocation request accepted by alloc_large. */
  159972. long max_alloc_chunk;
  159973. };
  159974. /* Routine signature for application-supplied marker processing methods.
  159975. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159976. */
  159977. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159978. /* Declarations for routines called by application.
  159979. * The JPP macro hides prototype parameters from compilers that can't cope.
  159980. * Note JPP requires double parentheses.
  159981. */
  159982. #ifdef HAVE_PROTOTYPES
  159983. #define JPP(arglist) arglist
  159984. #else
  159985. #define JPP(arglist) ()
  159986. #endif
  159987. /* Short forms of external names for systems with brain-damaged linkers.
  159988. * We shorten external names to be unique in the first six letters, which
  159989. * is good enough for all known systems.
  159990. * (If your compiler itself needs names to be unique in less than 15
  159991. * characters, you are out of luck. Get a better compiler.)
  159992. */
  159993. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159994. #define jpeg_std_error jStdError
  159995. #define jpeg_CreateCompress jCreaCompress
  159996. #define jpeg_CreateDecompress jCreaDecompress
  159997. #define jpeg_destroy_compress jDestCompress
  159998. #define jpeg_destroy_decompress jDestDecompress
  159999. #define jpeg_stdio_dest jStdDest
  160000. #define jpeg_stdio_src jStdSrc
  160001. #define jpeg_set_defaults jSetDefaults
  160002. #define jpeg_set_colorspace jSetColorspace
  160003. #define jpeg_default_colorspace jDefColorspace
  160004. #define jpeg_set_quality jSetQuality
  160005. #define jpeg_set_linear_quality jSetLQuality
  160006. #define jpeg_add_quant_table jAddQuantTable
  160007. #define jpeg_quality_scaling jQualityScaling
  160008. #define jpeg_simple_progression jSimProgress
  160009. #define jpeg_suppress_tables jSuppressTables
  160010. #define jpeg_alloc_quant_table jAlcQTable
  160011. #define jpeg_alloc_huff_table jAlcHTable
  160012. #define jpeg_start_compress jStrtCompress
  160013. #define jpeg_write_scanlines jWrtScanlines
  160014. #define jpeg_finish_compress jFinCompress
  160015. #define jpeg_write_raw_data jWrtRawData
  160016. #define jpeg_write_marker jWrtMarker
  160017. #define jpeg_write_m_header jWrtMHeader
  160018. #define jpeg_write_m_byte jWrtMByte
  160019. #define jpeg_write_tables jWrtTables
  160020. #define jpeg_read_header jReadHeader
  160021. #define jpeg_start_decompress jStrtDecompress
  160022. #define jpeg_read_scanlines jReadScanlines
  160023. #define jpeg_finish_decompress jFinDecompress
  160024. #define jpeg_read_raw_data jReadRawData
  160025. #define jpeg_has_multiple_scans jHasMultScn
  160026. #define jpeg_start_output jStrtOutput
  160027. #define jpeg_finish_output jFinOutput
  160028. #define jpeg_input_complete jInComplete
  160029. #define jpeg_new_colormap jNewCMap
  160030. #define jpeg_consume_input jConsumeInput
  160031. #define jpeg_calc_output_dimensions jCalcDimensions
  160032. #define jpeg_save_markers jSaveMarkers
  160033. #define jpeg_set_marker_processor jSetMarker
  160034. #define jpeg_read_coefficients jReadCoefs
  160035. #define jpeg_write_coefficients jWrtCoefs
  160036. #define jpeg_copy_critical_parameters jCopyCrit
  160037. #define jpeg_abort_compress jAbrtCompress
  160038. #define jpeg_abort_decompress jAbrtDecompress
  160039. #define jpeg_abort jAbort
  160040. #define jpeg_destroy jDestroy
  160041. #define jpeg_resync_to_restart jResyncRestart
  160042. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160043. /* Default error-management setup */
  160044. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160045. JPP((struct jpeg_error_mgr * err));
  160046. /* Initialization of JPEG compression objects.
  160047. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160048. * names that applications should call. These expand to calls on
  160049. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160050. * passed for version mismatch checking.
  160051. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160052. */
  160053. #define jpeg_create_compress(cinfo) \
  160054. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160055. (size_t) sizeof(struct jpeg_compress_struct))
  160056. #define jpeg_create_decompress(cinfo) \
  160057. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160058. (size_t) sizeof(struct jpeg_decompress_struct))
  160059. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160060. int version, size_t structsize));
  160061. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160062. int version, size_t structsize));
  160063. /* Destruction of JPEG compression objects */
  160064. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160065. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160066. /* Standard data source and destination managers: stdio streams. */
  160067. /* Caller is responsible for opening the file before and closing after. */
  160068. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160069. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160070. /* Default parameter setup for compression */
  160071. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160072. /* Compression parameter setup aids */
  160073. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160074. J_COLOR_SPACE colorspace));
  160075. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160076. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160077. boolean force_baseline));
  160078. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160079. int scale_factor,
  160080. boolean force_baseline));
  160081. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160082. const unsigned int *basic_table,
  160083. int scale_factor,
  160084. boolean force_baseline));
  160085. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160086. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160087. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160088. boolean suppress));
  160089. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160090. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160091. /* Main entry points for compression */
  160092. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160093. boolean write_all_tables));
  160094. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160095. JSAMPARRAY scanlines,
  160096. JDIMENSION num_lines));
  160097. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160098. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160099. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160100. JSAMPIMAGE data,
  160101. JDIMENSION num_lines));
  160102. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160103. EXTERN(void) jpeg_write_marker
  160104. JPP((j_compress_ptr cinfo, int marker,
  160105. const JOCTET * dataptr, unsigned int datalen));
  160106. /* Same, but piecemeal. */
  160107. EXTERN(void) jpeg_write_m_header
  160108. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160109. EXTERN(void) jpeg_write_m_byte
  160110. JPP((j_compress_ptr cinfo, int val));
  160111. /* Alternate compression function: just write an abbreviated table file */
  160112. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160113. /* Decompression startup: read start of JPEG datastream to see what's there */
  160114. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160115. boolean require_image));
  160116. /* Return value is one of: */
  160117. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160118. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160119. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160120. /* If you pass require_image = TRUE (normal case), you need not check for
  160121. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160122. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160123. * give a suspension return (the stdio source module doesn't).
  160124. */
  160125. /* Main entry points for decompression */
  160126. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160127. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160128. JSAMPARRAY scanlines,
  160129. JDIMENSION max_lines));
  160130. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160131. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160132. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160133. JSAMPIMAGE data,
  160134. JDIMENSION max_lines));
  160135. /* Additional entry points for buffered-image mode. */
  160136. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160137. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160138. int scan_number));
  160139. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160140. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160141. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160142. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160143. /* Return value is one of: */
  160144. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160145. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160146. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160147. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160148. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160149. /* Precalculate output dimensions for current decompression parameters. */
  160150. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160151. /* Control saving of COM and APPn markers into marker_list. */
  160152. EXTERN(void) jpeg_save_markers
  160153. JPP((j_decompress_ptr cinfo, int marker_code,
  160154. unsigned int length_limit));
  160155. /* Install a special processing method for COM or APPn markers. */
  160156. EXTERN(void) jpeg_set_marker_processor
  160157. JPP((j_decompress_ptr cinfo, int marker_code,
  160158. jpeg_marker_parser_method routine));
  160159. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160160. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160161. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160162. jvirt_barray_ptr * coef_arrays));
  160163. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160164. j_compress_ptr dstinfo));
  160165. /* If you choose to abort compression or decompression before completing
  160166. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160167. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160168. * if you're done with the JPEG object, but if you want to clean it up and
  160169. * reuse it, call this:
  160170. */
  160171. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160172. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160173. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160174. * flavor of JPEG object. These may be more convenient in some places.
  160175. */
  160176. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160177. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160178. /* Default restart-marker-resync procedure for use by data source modules */
  160179. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160180. int desired));
  160181. /* These marker codes are exported since applications and data source modules
  160182. * are likely to want to use them.
  160183. */
  160184. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160185. #define JPEG_EOI 0xD9 /* EOI marker code */
  160186. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160187. #define JPEG_COM 0xFE /* COM marker code */
  160188. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160189. * for structure definitions that are never filled in, keep it quiet by
  160190. * supplying dummy definitions for the various substructures.
  160191. */
  160192. #ifdef INCOMPLETE_TYPES_BROKEN
  160193. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160194. struct jvirt_sarray_control { long dummy; };
  160195. struct jvirt_barray_control { long dummy; };
  160196. struct jpeg_comp_master { long dummy; };
  160197. struct jpeg_c_main_controller { long dummy; };
  160198. struct jpeg_c_prep_controller { long dummy; };
  160199. struct jpeg_c_coef_controller { long dummy; };
  160200. struct jpeg_marker_writer { long dummy; };
  160201. struct jpeg_color_converter { long dummy; };
  160202. struct jpeg_downsampler { long dummy; };
  160203. struct jpeg_forward_dct { long dummy; };
  160204. struct jpeg_entropy_encoder { long dummy; };
  160205. struct jpeg_decomp_master { long dummy; };
  160206. struct jpeg_d_main_controller { long dummy; };
  160207. struct jpeg_d_coef_controller { long dummy; };
  160208. struct jpeg_d_post_controller { long dummy; };
  160209. struct jpeg_input_controller { long dummy; };
  160210. struct jpeg_marker_reader { long dummy; };
  160211. struct jpeg_entropy_decoder { long dummy; };
  160212. struct jpeg_inverse_dct { long dummy; };
  160213. struct jpeg_upsampler { long dummy; };
  160214. struct jpeg_color_deconverter { long dummy; };
  160215. struct jpeg_color_quantizer { long dummy; };
  160216. #endif /* JPEG_INTERNALS */
  160217. #endif /* INCOMPLETE_TYPES_BROKEN */
  160218. /*
  160219. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160220. * The internal structure declarations are read only when that is true.
  160221. * Applications using the library should not include jpegint.h, but may wish
  160222. * to include jerror.h.
  160223. */
  160224. #ifdef JPEG_INTERNALS
  160225. /*** Start of inlined file: jpegint.h ***/
  160226. /* Declarations for both compression & decompression */
  160227. typedef enum { /* Operating modes for buffer controllers */
  160228. JBUF_PASS_THRU, /* Plain stripwise operation */
  160229. /* Remaining modes require a full-image buffer to have been created */
  160230. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160231. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160232. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160233. } J_BUF_MODE;
  160234. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160235. #define CSTATE_START 100 /* after create_compress */
  160236. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160237. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160238. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160239. #define DSTATE_START 200 /* after create_decompress */
  160240. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160241. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160242. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160243. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160244. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160245. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160246. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160247. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160248. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160249. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160250. /* Declarations for compression modules */
  160251. /* Master control module */
  160252. struct jpeg_comp_master {
  160253. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160254. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160255. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160256. /* State variables made visible to other modules */
  160257. boolean call_pass_startup; /* True if pass_startup must be called */
  160258. boolean is_last_pass; /* True during last pass */
  160259. };
  160260. /* Main buffer control (downsampled-data buffer) */
  160261. struct jpeg_c_main_controller {
  160262. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160263. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160264. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160265. JDIMENSION in_rows_avail));
  160266. };
  160267. /* Compression preprocessing (downsampling input buffer control) */
  160268. struct jpeg_c_prep_controller {
  160269. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160270. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160271. JSAMPARRAY input_buf,
  160272. JDIMENSION *in_row_ctr,
  160273. JDIMENSION in_rows_avail,
  160274. JSAMPIMAGE output_buf,
  160275. JDIMENSION *out_row_group_ctr,
  160276. JDIMENSION out_row_groups_avail));
  160277. };
  160278. /* Coefficient buffer control */
  160279. struct jpeg_c_coef_controller {
  160280. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160281. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160282. JSAMPIMAGE input_buf));
  160283. };
  160284. /* Colorspace conversion */
  160285. struct jpeg_color_converter {
  160286. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160287. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160288. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160289. JDIMENSION output_row, int num_rows));
  160290. };
  160291. /* Downsampling */
  160292. struct jpeg_downsampler {
  160293. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160294. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160295. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160296. JSAMPIMAGE output_buf,
  160297. JDIMENSION out_row_group_index));
  160298. boolean need_context_rows; /* TRUE if need rows above & below */
  160299. };
  160300. /* Forward DCT (also controls coefficient quantization) */
  160301. struct jpeg_forward_dct {
  160302. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160303. /* perhaps this should be an array??? */
  160304. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160305. jpeg_component_info * compptr,
  160306. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160307. JDIMENSION start_row, JDIMENSION start_col,
  160308. JDIMENSION num_blocks));
  160309. };
  160310. /* Entropy encoding */
  160311. struct jpeg_entropy_encoder {
  160312. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160313. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160314. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160315. };
  160316. /* Marker writing */
  160317. struct jpeg_marker_writer {
  160318. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160319. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160320. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160321. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160322. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160323. /* These routines are exported to allow insertion of extra markers */
  160324. /* Probably only COM and APPn markers should be written this way */
  160325. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160326. unsigned int datalen));
  160327. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160328. };
  160329. /* Declarations for decompression modules */
  160330. /* Master control module */
  160331. struct jpeg_decomp_master {
  160332. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160333. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160334. /* State variables made visible to other modules */
  160335. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160336. };
  160337. /* Input control module */
  160338. struct jpeg_input_controller {
  160339. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160340. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160341. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160342. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160343. /* State variables made visible to other modules */
  160344. boolean has_multiple_scans; /* True if file has multiple scans */
  160345. boolean eoi_reached; /* True when EOI has been consumed */
  160346. };
  160347. /* Main buffer control (downsampled-data buffer) */
  160348. struct jpeg_d_main_controller {
  160349. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160350. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160351. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160352. JDIMENSION out_rows_avail));
  160353. };
  160354. /* Coefficient buffer control */
  160355. struct jpeg_d_coef_controller {
  160356. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160357. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160358. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160359. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160360. JSAMPIMAGE output_buf));
  160361. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160362. jvirt_barray_ptr *coef_arrays;
  160363. };
  160364. /* Decompression postprocessing (color quantization buffer control) */
  160365. struct jpeg_d_post_controller {
  160366. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160367. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160368. JSAMPIMAGE input_buf,
  160369. JDIMENSION *in_row_group_ctr,
  160370. JDIMENSION in_row_groups_avail,
  160371. JSAMPARRAY output_buf,
  160372. JDIMENSION *out_row_ctr,
  160373. JDIMENSION out_rows_avail));
  160374. };
  160375. /* Marker reading & parsing */
  160376. struct jpeg_marker_reader {
  160377. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160378. /* Read markers until SOS or EOI.
  160379. * Returns same codes as are defined for jpeg_consume_input:
  160380. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160381. */
  160382. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160383. /* Read a restart marker --- exported for use by entropy decoder only */
  160384. jpeg_marker_parser_method read_restart_marker;
  160385. /* State of marker reader --- nominally internal, but applications
  160386. * supplying COM or APPn handlers might like to know the state.
  160387. */
  160388. boolean saw_SOI; /* found SOI? */
  160389. boolean saw_SOF; /* found SOF? */
  160390. int next_restart_num; /* next restart number expected (0-7) */
  160391. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160392. };
  160393. /* Entropy decoding */
  160394. struct jpeg_entropy_decoder {
  160395. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160396. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160397. JBLOCKROW *MCU_data));
  160398. /* This is here to share code between baseline and progressive decoders; */
  160399. /* other modules probably should not use it */
  160400. boolean insufficient_data; /* set TRUE after emitting warning */
  160401. };
  160402. /* Inverse DCT (also performs dequantization) */
  160403. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160404. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160405. JCOEFPTR coef_block,
  160406. JSAMPARRAY output_buf, JDIMENSION output_col));
  160407. struct jpeg_inverse_dct {
  160408. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160409. /* It is useful to allow each component to have a separate IDCT method. */
  160410. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160411. };
  160412. /* Upsampling (note that upsampler must also call color converter) */
  160413. struct jpeg_upsampler {
  160414. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160415. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160416. JSAMPIMAGE input_buf,
  160417. JDIMENSION *in_row_group_ctr,
  160418. JDIMENSION in_row_groups_avail,
  160419. JSAMPARRAY output_buf,
  160420. JDIMENSION *out_row_ctr,
  160421. JDIMENSION out_rows_avail));
  160422. boolean need_context_rows; /* TRUE if need rows above & below */
  160423. };
  160424. /* Colorspace conversion */
  160425. struct jpeg_color_deconverter {
  160426. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160427. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160428. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160429. JSAMPARRAY output_buf, int num_rows));
  160430. };
  160431. /* Color quantization or color precision reduction */
  160432. struct jpeg_color_quantizer {
  160433. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160434. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160435. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160436. int num_rows));
  160437. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160438. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160439. };
  160440. /* Miscellaneous useful macros */
  160441. #undef MAX
  160442. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160443. #undef MIN
  160444. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160445. /* We assume that right shift corresponds to signed division by 2 with
  160446. * rounding towards minus infinity. This is correct for typical "arithmetic
  160447. * shift" instructions that shift in copies of the sign bit. But some
  160448. * C compilers implement >> with an unsigned shift. For these machines you
  160449. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160450. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160451. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160452. * included in the variables of any routine using RIGHT_SHIFT.
  160453. */
  160454. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160455. #define SHIFT_TEMPS INT32 shift_temp;
  160456. #define RIGHT_SHIFT(x,shft) \
  160457. ((shift_temp = (x)) < 0 ? \
  160458. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160459. (shift_temp >> (shft)))
  160460. #else
  160461. #define SHIFT_TEMPS
  160462. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160463. #endif
  160464. /* Short forms of external names for systems with brain-damaged linkers. */
  160465. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160466. #define jinit_compress_master jICompress
  160467. #define jinit_c_master_control jICMaster
  160468. #define jinit_c_main_controller jICMainC
  160469. #define jinit_c_prep_controller jICPrepC
  160470. #define jinit_c_coef_controller jICCoefC
  160471. #define jinit_color_converter jICColor
  160472. #define jinit_downsampler jIDownsampler
  160473. #define jinit_forward_dct jIFDCT
  160474. #define jinit_huff_encoder jIHEncoder
  160475. #define jinit_phuff_encoder jIPHEncoder
  160476. #define jinit_marker_writer jIMWriter
  160477. #define jinit_master_decompress jIDMaster
  160478. #define jinit_d_main_controller jIDMainC
  160479. #define jinit_d_coef_controller jIDCoefC
  160480. #define jinit_d_post_controller jIDPostC
  160481. #define jinit_input_controller jIInCtlr
  160482. #define jinit_marker_reader jIMReader
  160483. #define jinit_huff_decoder jIHDecoder
  160484. #define jinit_phuff_decoder jIPHDecoder
  160485. #define jinit_inverse_dct jIIDCT
  160486. #define jinit_upsampler jIUpsampler
  160487. #define jinit_color_deconverter jIDColor
  160488. #define jinit_1pass_quantizer jI1Quant
  160489. #define jinit_2pass_quantizer jI2Quant
  160490. #define jinit_merged_upsampler jIMUpsampler
  160491. #define jinit_memory_mgr jIMemMgr
  160492. #define jdiv_round_up jDivRound
  160493. #define jround_up jRound
  160494. #define jcopy_sample_rows jCopySamples
  160495. #define jcopy_block_row jCopyBlocks
  160496. #define jzero_far jZeroFar
  160497. #define jpeg_zigzag_order jZIGTable
  160498. #define jpeg_natural_order jZAGTable
  160499. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160500. /* Compression module initialization routines */
  160501. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160502. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160503. boolean transcode_only));
  160504. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160505. boolean need_full_buffer));
  160506. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160507. boolean need_full_buffer));
  160508. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160509. boolean need_full_buffer));
  160510. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160511. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160512. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160513. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160514. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160515. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160516. /* Decompression module initialization routines */
  160517. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160518. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160519. boolean need_full_buffer));
  160520. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160521. boolean need_full_buffer));
  160522. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160523. boolean need_full_buffer));
  160524. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160525. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160526. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160527. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160528. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160529. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160530. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160531. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160532. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160533. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160534. /* Memory manager initialization */
  160535. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160536. /* Utility routines in jutils.c */
  160537. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160538. EXTERN(long) jround_up JPP((long a, long b));
  160539. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160540. JSAMPARRAY output_array, int dest_row,
  160541. int num_rows, JDIMENSION num_cols));
  160542. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160543. JDIMENSION num_blocks));
  160544. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160545. /* Constant tables in jutils.c */
  160546. #if 0 /* This table is not actually needed in v6a */
  160547. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160548. #endif
  160549. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160550. /* Suppress undefined-structure complaints if necessary. */
  160551. #ifdef INCOMPLETE_TYPES_BROKEN
  160552. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160553. struct jvirt_sarray_control { long dummy; };
  160554. struct jvirt_barray_control { long dummy; };
  160555. #endif
  160556. #endif /* INCOMPLETE_TYPES_BROKEN */
  160557. /*** End of inlined file: jpegint.h ***/
  160558. /* fetch private declarations */
  160559. /*** Start of inlined file: jerror.h ***/
  160560. /*
  160561. * To define the enum list of message codes, include this file without
  160562. * defining macro JMESSAGE. To create a message string table, include it
  160563. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160564. */
  160565. #ifndef JMESSAGE
  160566. #ifndef JERROR_H
  160567. /* First time through, define the enum list */
  160568. #define JMAKE_ENUM_LIST
  160569. #else
  160570. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160571. #define JMESSAGE(code,string)
  160572. #endif /* JERROR_H */
  160573. #endif /* JMESSAGE */
  160574. #ifdef JMAKE_ENUM_LIST
  160575. typedef enum {
  160576. #define JMESSAGE(code,string) code ,
  160577. #endif /* JMAKE_ENUM_LIST */
  160578. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160579. /* For maintenance convenience, list is alphabetical by message code name */
  160580. JMESSAGE(JERR_ARITH_NOTIMPL,
  160581. "Sorry, there are legal restrictions on arithmetic coding")
  160582. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160583. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160584. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160585. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160586. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160587. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160588. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160589. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160590. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160591. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160592. JMESSAGE(JERR_BAD_LIB_VERSION,
  160593. "Wrong JPEG library version: library is %d, caller expects %d")
  160594. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160595. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160596. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160597. JMESSAGE(JERR_BAD_PROGRESSION,
  160598. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160599. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160600. "Invalid progressive parameters at scan script entry %d")
  160601. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160602. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160603. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160604. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160605. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160606. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160607. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160608. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160609. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160610. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160611. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160612. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160613. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160614. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160615. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160616. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160617. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160618. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160619. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160620. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160621. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160622. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160623. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160624. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160625. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160626. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160627. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160628. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160629. "Cannot transcode due to multiple use of quantization table %d")
  160630. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160631. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160632. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160633. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160634. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160635. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160636. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160637. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160638. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160639. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160640. JMESSAGE(JERR_QUANT_COMPONENTS,
  160641. "Cannot quantize more than %d color components")
  160642. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160643. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160644. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160645. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160646. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160647. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160648. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160649. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160650. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160651. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160652. JMESSAGE(JERR_TFILE_WRITE,
  160653. "Write failed on temporary file --- out of disk space?")
  160654. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160655. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160656. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160657. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160658. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160659. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160660. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160661. JMESSAGE(JMSG_VERSION, JVERSION)
  160662. JMESSAGE(JTRC_16BIT_TABLES,
  160663. "Caution: quantization tables are too coarse for baseline JPEG")
  160664. JMESSAGE(JTRC_ADOBE,
  160665. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160666. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160667. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160668. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160669. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160670. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160671. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160672. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160673. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160674. JMESSAGE(JTRC_EOI, "End Of Image")
  160675. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160676. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160677. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160678. "Warning: thumbnail image size does not match data length %u")
  160679. JMESSAGE(JTRC_JFIF_EXTENSION,
  160680. "JFIF extension marker: type 0x%02x, length %u")
  160681. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160682. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160683. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160684. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160685. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160686. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160687. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160688. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160689. JMESSAGE(JTRC_RST, "RST%d")
  160690. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160691. "Smoothing not supported with nonstandard sampling ratios")
  160692. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160693. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160694. JMESSAGE(JTRC_SOI, "Start of Image")
  160695. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160696. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160697. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160698. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160699. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160700. JMESSAGE(JTRC_THUMB_JPEG,
  160701. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160702. JMESSAGE(JTRC_THUMB_PALETTE,
  160703. "JFIF extension marker: palette thumbnail image, length %u")
  160704. JMESSAGE(JTRC_THUMB_RGB,
  160705. "JFIF extension marker: RGB thumbnail image, length %u")
  160706. JMESSAGE(JTRC_UNKNOWN_IDS,
  160707. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160708. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160709. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160710. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160711. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160712. "Inconsistent progression sequence for component %d coefficient %d")
  160713. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160714. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160715. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160716. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160717. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160718. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160719. JMESSAGE(JWRN_MUST_RESYNC,
  160720. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160721. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160722. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160723. #ifdef JMAKE_ENUM_LIST
  160724. JMSG_LASTMSGCODE
  160725. } J_MESSAGE_CODE;
  160726. #undef JMAKE_ENUM_LIST
  160727. #endif /* JMAKE_ENUM_LIST */
  160728. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160729. #undef JMESSAGE
  160730. #ifndef JERROR_H
  160731. #define JERROR_H
  160732. /* Macros to simplify using the error and trace message stuff */
  160733. /* The first parameter is either type of cinfo pointer */
  160734. /* Fatal errors (print message and exit) */
  160735. #define ERREXIT(cinfo,code) \
  160736. ((cinfo)->err->msg_code = (code), \
  160737. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160738. #define ERREXIT1(cinfo,code,p1) \
  160739. ((cinfo)->err->msg_code = (code), \
  160740. (cinfo)->err->msg_parm.i[0] = (p1), \
  160741. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160742. #define ERREXIT2(cinfo,code,p1,p2) \
  160743. ((cinfo)->err->msg_code = (code), \
  160744. (cinfo)->err->msg_parm.i[0] = (p1), \
  160745. (cinfo)->err->msg_parm.i[1] = (p2), \
  160746. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160747. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160748. ((cinfo)->err->msg_code = (code), \
  160749. (cinfo)->err->msg_parm.i[0] = (p1), \
  160750. (cinfo)->err->msg_parm.i[1] = (p2), \
  160751. (cinfo)->err->msg_parm.i[2] = (p3), \
  160752. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160753. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160754. ((cinfo)->err->msg_code = (code), \
  160755. (cinfo)->err->msg_parm.i[0] = (p1), \
  160756. (cinfo)->err->msg_parm.i[1] = (p2), \
  160757. (cinfo)->err->msg_parm.i[2] = (p3), \
  160758. (cinfo)->err->msg_parm.i[3] = (p4), \
  160759. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160760. #define ERREXITS(cinfo,code,str) \
  160761. ((cinfo)->err->msg_code = (code), \
  160762. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160763. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160764. #define MAKESTMT(stuff) do { stuff } while (0)
  160765. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160766. #define WARNMS(cinfo,code) \
  160767. ((cinfo)->err->msg_code = (code), \
  160768. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160769. #define WARNMS1(cinfo,code,p1) \
  160770. ((cinfo)->err->msg_code = (code), \
  160771. (cinfo)->err->msg_parm.i[0] = (p1), \
  160772. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160773. #define WARNMS2(cinfo,code,p1,p2) \
  160774. ((cinfo)->err->msg_code = (code), \
  160775. (cinfo)->err->msg_parm.i[0] = (p1), \
  160776. (cinfo)->err->msg_parm.i[1] = (p2), \
  160777. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160778. /* Informational/debugging messages */
  160779. #define TRACEMS(cinfo,lvl,code) \
  160780. ((cinfo)->err->msg_code = (code), \
  160781. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160782. #define TRACEMS1(cinfo,lvl,code,p1) \
  160783. ((cinfo)->err->msg_code = (code), \
  160784. (cinfo)->err->msg_parm.i[0] = (p1), \
  160785. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160786. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160787. ((cinfo)->err->msg_code = (code), \
  160788. (cinfo)->err->msg_parm.i[0] = (p1), \
  160789. (cinfo)->err->msg_parm.i[1] = (p2), \
  160790. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160791. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160792. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160793. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160794. (cinfo)->err->msg_code = (code); \
  160795. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160796. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160797. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160798. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160799. (cinfo)->err->msg_code = (code); \
  160800. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160801. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160802. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160803. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160804. _mp[4] = (p5); \
  160805. (cinfo)->err->msg_code = (code); \
  160806. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160807. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160808. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160809. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160810. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160811. (cinfo)->err->msg_code = (code); \
  160812. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160813. #define TRACEMSS(cinfo,lvl,code,str) \
  160814. ((cinfo)->err->msg_code = (code), \
  160815. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160816. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160817. #endif /* JERROR_H */
  160818. /*** End of inlined file: jerror.h ***/
  160819. /* fetch error codes too */
  160820. #endif
  160821. #endif /* JPEGLIB_H */
  160822. /*** End of inlined file: jpeglib.h ***/
  160823. /*** Start of inlined file: jcapimin.c ***/
  160824. #define JPEG_INTERNALS
  160825. /*** Start of inlined file: jinclude.h ***/
  160826. /* Include auto-config file to find out which system include files we need. */
  160827. #ifndef __jinclude_h__
  160828. #define __jinclude_h__
  160829. /*** Start of inlined file: jconfig.h ***/
  160830. /* see jconfig.doc for explanations */
  160831. // disable all the warnings under MSVC
  160832. #ifdef _MSC_VER
  160833. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160834. #endif
  160835. #ifdef __BORLANDC__
  160836. #pragma warn -8057
  160837. #pragma warn -8019
  160838. #pragma warn -8004
  160839. #pragma warn -8008
  160840. #endif
  160841. #define HAVE_PROTOTYPES
  160842. #define HAVE_UNSIGNED_CHAR
  160843. #define HAVE_UNSIGNED_SHORT
  160844. /* #define void char */
  160845. /* #define const */
  160846. #undef CHAR_IS_UNSIGNED
  160847. #define HAVE_STDDEF_H
  160848. #define HAVE_STDLIB_H
  160849. #undef NEED_BSD_STRINGS
  160850. #undef NEED_SYS_TYPES_H
  160851. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160852. #undef NEED_SHORT_EXTERNAL_NAMES
  160853. #undef INCOMPLETE_TYPES_BROKEN
  160854. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160855. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160856. typedef unsigned char boolean;
  160857. #endif
  160858. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160859. #ifdef JPEG_INTERNALS
  160860. #undef RIGHT_SHIFT_IS_UNSIGNED
  160861. #endif /* JPEG_INTERNALS */
  160862. #ifdef JPEG_CJPEG_DJPEG
  160863. #define BMP_SUPPORTED /* BMP image file format */
  160864. #define GIF_SUPPORTED /* GIF image file format */
  160865. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160866. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160867. #define TARGA_SUPPORTED /* Targa image file format */
  160868. #define TWO_FILE_COMMANDLINE /* optional */
  160869. #define USE_SETMODE /* Microsoft has setmode() */
  160870. #undef NEED_SIGNAL_CATCHER
  160871. #undef DONT_USE_B_MODE
  160872. #undef PROGRESS_REPORT /* optional */
  160873. #endif /* JPEG_CJPEG_DJPEG */
  160874. /*** End of inlined file: jconfig.h ***/
  160875. /* auto configuration options */
  160876. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160877. /*
  160878. * We need the NULL macro and size_t typedef.
  160879. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160880. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160881. * pull in <sys/types.h> as well.
  160882. * Note that the core JPEG library does not require <stdio.h>;
  160883. * only the default error handler and data source/destination modules do.
  160884. * But we must pull it in because of the references to FILE in jpeglib.h.
  160885. * You can remove those references if you want to compile without <stdio.h>.
  160886. */
  160887. #ifdef HAVE_STDDEF_H
  160888. #include <stddef.h>
  160889. #endif
  160890. #ifdef HAVE_STDLIB_H
  160891. #include <stdlib.h>
  160892. #endif
  160893. #ifdef NEED_SYS_TYPES_H
  160894. #include <sys/types.h>
  160895. #endif
  160896. #include <stdio.h>
  160897. /*
  160898. * We need memory copying and zeroing functions, plus strncpy().
  160899. * ANSI and System V implementations declare these in <string.h>.
  160900. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160901. * Some systems may declare memset and memcpy in <memory.h>.
  160902. *
  160903. * NOTE: we assume the size parameters to these functions are of type size_t.
  160904. * Change the casts in these macros if not!
  160905. */
  160906. #ifdef NEED_BSD_STRINGS
  160907. #include <strings.h>
  160908. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160909. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160910. #else /* not BSD, assume ANSI/SysV string lib */
  160911. #include <string.h>
  160912. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160913. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160914. #endif
  160915. /*
  160916. * In ANSI C, and indeed any rational implementation, size_t is also the
  160917. * type returned by sizeof(). However, it seems there are some irrational
  160918. * implementations out there, in which sizeof() returns an int even though
  160919. * size_t is defined as long or unsigned long. To ensure consistent results
  160920. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160921. */
  160922. #define SIZEOF(object) ((size_t) sizeof(object))
  160923. /*
  160924. * The modules that use fread() and fwrite() always invoke them through
  160925. * these macros. On some systems you may need to twiddle the argument casts.
  160926. * CAUTION: argument order is different from underlying functions!
  160927. */
  160928. #define JFREAD(file,buf,sizeofbuf) \
  160929. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160930. #define JFWRITE(file,buf,sizeofbuf) \
  160931. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160932. typedef enum { /* JPEG marker codes */
  160933. M_SOF0 = 0xc0,
  160934. M_SOF1 = 0xc1,
  160935. M_SOF2 = 0xc2,
  160936. M_SOF3 = 0xc3,
  160937. M_SOF5 = 0xc5,
  160938. M_SOF6 = 0xc6,
  160939. M_SOF7 = 0xc7,
  160940. M_JPG = 0xc8,
  160941. M_SOF9 = 0xc9,
  160942. M_SOF10 = 0xca,
  160943. M_SOF11 = 0xcb,
  160944. M_SOF13 = 0xcd,
  160945. M_SOF14 = 0xce,
  160946. M_SOF15 = 0xcf,
  160947. M_DHT = 0xc4,
  160948. M_DAC = 0xcc,
  160949. M_RST0 = 0xd0,
  160950. M_RST1 = 0xd1,
  160951. M_RST2 = 0xd2,
  160952. M_RST3 = 0xd3,
  160953. M_RST4 = 0xd4,
  160954. M_RST5 = 0xd5,
  160955. M_RST6 = 0xd6,
  160956. M_RST7 = 0xd7,
  160957. M_SOI = 0xd8,
  160958. M_EOI = 0xd9,
  160959. M_SOS = 0xda,
  160960. M_DQT = 0xdb,
  160961. M_DNL = 0xdc,
  160962. M_DRI = 0xdd,
  160963. M_DHP = 0xde,
  160964. M_EXP = 0xdf,
  160965. M_APP0 = 0xe0,
  160966. M_APP1 = 0xe1,
  160967. M_APP2 = 0xe2,
  160968. M_APP3 = 0xe3,
  160969. M_APP4 = 0xe4,
  160970. M_APP5 = 0xe5,
  160971. M_APP6 = 0xe6,
  160972. M_APP7 = 0xe7,
  160973. M_APP8 = 0xe8,
  160974. M_APP9 = 0xe9,
  160975. M_APP10 = 0xea,
  160976. M_APP11 = 0xeb,
  160977. M_APP12 = 0xec,
  160978. M_APP13 = 0xed,
  160979. M_APP14 = 0xee,
  160980. M_APP15 = 0xef,
  160981. M_JPG0 = 0xf0,
  160982. M_JPG13 = 0xfd,
  160983. M_COM = 0xfe,
  160984. M_TEM = 0x01,
  160985. M_ERROR = 0x100
  160986. } JPEG_MARKER;
  160987. /*
  160988. * Figure F.12: extend sign bit.
  160989. * On some machines, a shift and add will be faster than a table lookup.
  160990. */
  160991. #ifdef AVOID_TABLES
  160992. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160993. #else
  160994. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160995. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160996. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160997. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160998. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160999. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161000. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161001. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161002. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161003. #endif /* AVOID_TABLES */
  161004. #endif
  161005. /*** End of inlined file: jinclude.h ***/
  161006. /*
  161007. * Initialization of a JPEG compression object.
  161008. * The error manager must already be set up (in case memory manager fails).
  161009. */
  161010. GLOBAL(void)
  161011. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161012. {
  161013. int i;
  161014. /* Guard against version mismatches between library and caller. */
  161015. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161016. if (version != JPEG_LIB_VERSION)
  161017. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161018. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161019. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161020. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161021. /* For debugging purposes, we zero the whole master structure.
  161022. * But the application has already set the err pointer, and may have set
  161023. * client_data, so we have to save and restore those fields.
  161024. * Note: if application hasn't set client_data, tools like Purify may
  161025. * complain here.
  161026. */
  161027. {
  161028. struct jpeg_error_mgr * err = cinfo->err;
  161029. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161030. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161031. cinfo->err = err;
  161032. cinfo->client_data = client_data;
  161033. }
  161034. cinfo->is_decompressor = FALSE;
  161035. /* Initialize a memory manager instance for this object */
  161036. jinit_memory_mgr((j_common_ptr) cinfo);
  161037. /* Zero out pointers to permanent structures. */
  161038. cinfo->progress = NULL;
  161039. cinfo->dest = NULL;
  161040. cinfo->comp_info = NULL;
  161041. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161042. cinfo->quant_tbl_ptrs[i] = NULL;
  161043. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161044. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161045. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161046. }
  161047. cinfo->script_space = NULL;
  161048. cinfo->input_gamma = 1.0; /* in case application forgets */
  161049. /* OK, I'm ready */
  161050. cinfo->global_state = CSTATE_START;
  161051. }
  161052. /*
  161053. * Destruction of a JPEG compression object
  161054. */
  161055. GLOBAL(void)
  161056. jpeg_destroy_compress (j_compress_ptr cinfo)
  161057. {
  161058. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161059. }
  161060. /*
  161061. * Abort processing of a JPEG compression operation,
  161062. * but don't destroy the object itself.
  161063. */
  161064. GLOBAL(void)
  161065. jpeg_abort_compress (j_compress_ptr cinfo)
  161066. {
  161067. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161068. }
  161069. /*
  161070. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161071. * Marks all currently defined tables as already written (if suppress)
  161072. * or not written (if !suppress). This will control whether they get emitted
  161073. * by a subsequent jpeg_start_compress call.
  161074. *
  161075. * This routine is exported for use by applications that want to produce
  161076. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161077. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161078. * jcparam.o would be linked whether the application used it or not.
  161079. */
  161080. GLOBAL(void)
  161081. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161082. {
  161083. int i;
  161084. JQUANT_TBL * qtbl;
  161085. JHUFF_TBL * htbl;
  161086. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161087. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161088. qtbl->sent_table = suppress;
  161089. }
  161090. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161091. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161092. htbl->sent_table = suppress;
  161093. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161094. htbl->sent_table = suppress;
  161095. }
  161096. }
  161097. /*
  161098. * Finish JPEG compression.
  161099. *
  161100. * If a multipass operating mode was selected, this may do a great deal of
  161101. * work including most of the actual output.
  161102. */
  161103. GLOBAL(void)
  161104. jpeg_finish_compress (j_compress_ptr cinfo)
  161105. {
  161106. JDIMENSION iMCU_row;
  161107. if (cinfo->global_state == CSTATE_SCANNING ||
  161108. cinfo->global_state == CSTATE_RAW_OK) {
  161109. /* Terminate first pass */
  161110. if (cinfo->next_scanline < cinfo->image_height)
  161111. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161112. (*cinfo->master->finish_pass) (cinfo);
  161113. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161114. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161115. /* Perform any remaining passes */
  161116. while (! cinfo->master->is_last_pass) {
  161117. (*cinfo->master->prepare_for_pass) (cinfo);
  161118. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161119. if (cinfo->progress != NULL) {
  161120. cinfo->progress->pass_counter = (long) iMCU_row;
  161121. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161122. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161123. }
  161124. /* We bypass the main controller and invoke coef controller directly;
  161125. * all work is being done from the coefficient buffer.
  161126. */
  161127. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161128. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161129. }
  161130. (*cinfo->master->finish_pass) (cinfo);
  161131. }
  161132. /* Write EOI, do final cleanup */
  161133. (*cinfo->marker->write_file_trailer) (cinfo);
  161134. (*cinfo->dest->term_destination) (cinfo);
  161135. /* We can use jpeg_abort to release memory and reset global_state */
  161136. jpeg_abort((j_common_ptr) cinfo);
  161137. }
  161138. /*
  161139. * Write a special marker.
  161140. * This is only recommended for writing COM or APPn markers.
  161141. * Must be called after jpeg_start_compress() and before
  161142. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161143. */
  161144. GLOBAL(void)
  161145. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161146. const JOCTET *dataptr, unsigned int datalen)
  161147. {
  161148. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161149. if (cinfo->next_scanline != 0 ||
  161150. (cinfo->global_state != CSTATE_SCANNING &&
  161151. cinfo->global_state != CSTATE_RAW_OK &&
  161152. cinfo->global_state != CSTATE_WRCOEFS))
  161153. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161154. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161155. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161156. while (datalen--) {
  161157. (*write_marker_byte) (cinfo, *dataptr);
  161158. dataptr++;
  161159. }
  161160. }
  161161. /* Same, but piecemeal. */
  161162. GLOBAL(void)
  161163. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161164. {
  161165. if (cinfo->next_scanline != 0 ||
  161166. (cinfo->global_state != CSTATE_SCANNING &&
  161167. cinfo->global_state != CSTATE_RAW_OK &&
  161168. cinfo->global_state != CSTATE_WRCOEFS))
  161169. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161170. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161171. }
  161172. GLOBAL(void)
  161173. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161174. {
  161175. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161176. }
  161177. /*
  161178. * Alternate compression function: just write an abbreviated table file.
  161179. * Before calling this, all parameters and a data destination must be set up.
  161180. *
  161181. * To produce a pair of files containing abbreviated tables and abbreviated
  161182. * image data, one would proceed as follows:
  161183. *
  161184. * initialize JPEG object
  161185. * set JPEG parameters
  161186. * set destination to table file
  161187. * jpeg_write_tables(cinfo);
  161188. * set destination to image file
  161189. * jpeg_start_compress(cinfo, FALSE);
  161190. * write data...
  161191. * jpeg_finish_compress(cinfo);
  161192. *
  161193. * jpeg_write_tables has the side effect of marking all tables written
  161194. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161195. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161196. */
  161197. GLOBAL(void)
  161198. jpeg_write_tables (j_compress_ptr cinfo)
  161199. {
  161200. if (cinfo->global_state != CSTATE_START)
  161201. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161202. /* (Re)initialize error mgr and destination modules */
  161203. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161204. (*cinfo->dest->init_destination) (cinfo);
  161205. /* Initialize the marker writer ... bit of a crock to do it here. */
  161206. jinit_marker_writer(cinfo);
  161207. /* Write them tables! */
  161208. (*cinfo->marker->write_tables_only) (cinfo);
  161209. /* And clean up. */
  161210. (*cinfo->dest->term_destination) (cinfo);
  161211. /*
  161212. * In library releases up through v6a, we called jpeg_abort() here to free
  161213. * any working memory allocated by the destination manager and marker
  161214. * writer. Some applications had a problem with that: they allocated space
  161215. * of their own from the library memory manager, and didn't want it to go
  161216. * away during write_tables. So now we do nothing. This will cause a
  161217. * memory leak if an app calls write_tables repeatedly without doing a full
  161218. * compression cycle or otherwise resetting the JPEG object. However, that
  161219. * seems less bad than unexpectedly freeing memory in the normal case.
  161220. * An app that prefers the old behavior can call jpeg_abort for itself after
  161221. * each call to jpeg_write_tables().
  161222. */
  161223. }
  161224. /*** End of inlined file: jcapimin.c ***/
  161225. /*** Start of inlined file: jcapistd.c ***/
  161226. #define JPEG_INTERNALS
  161227. /*
  161228. * Compression initialization.
  161229. * Before calling this, all parameters and a data destination must be set up.
  161230. *
  161231. * We require a write_all_tables parameter as a failsafe check when writing
  161232. * multiple datastreams from the same compression object. Since prior runs
  161233. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161234. * would emit an abbreviated stream (no tables) by default. This may be what
  161235. * is wanted, but for safety's sake it should not be the default behavior:
  161236. * programmers should have to make a deliberate choice to emit abbreviated
  161237. * images. Therefore the documentation and examples should encourage people
  161238. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161239. * wrong thing.
  161240. */
  161241. GLOBAL(void)
  161242. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161243. {
  161244. if (cinfo->global_state != CSTATE_START)
  161245. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161246. if (write_all_tables)
  161247. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161248. /* (Re)initialize error mgr and destination modules */
  161249. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161250. (*cinfo->dest->init_destination) (cinfo);
  161251. /* Perform master selection of active modules */
  161252. jinit_compress_master(cinfo);
  161253. /* Set up for the first pass */
  161254. (*cinfo->master->prepare_for_pass) (cinfo);
  161255. /* Ready for application to drive first pass through jpeg_write_scanlines
  161256. * or jpeg_write_raw_data.
  161257. */
  161258. cinfo->next_scanline = 0;
  161259. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161260. }
  161261. /*
  161262. * Write some scanlines of data to the JPEG compressor.
  161263. *
  161264. * The return value will be the number of lines actually written.
  161265. * This should be less than the supplied num_lines only in case that
  161266. * the data destination module has requested suspension of the compressor,
  161267. * or if more than image_height scanlines are passed in.
  161268. *
  161269. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161270. * this likely signals an application programmer error. However,
  161271. * excess scanlines passed in the last valid call are *silently* ignored,
  161272. * so that the application need not adjust num_lines for end-of-image
  161273. * when using a multiple-scanline buffer.
  161274. */
  161275. GLOBAL(JDIMENSION)
  161276. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161277. JDIMENSION num_lines)
  161278. {
  161279. JDIMENSION row_ctr, rows_left;
  161280. if (cinfo->global_state != CSTATE_SCANNING)
  161281. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161282. if (cinfo->next_scanline >= cinfo->image_height)
  161283. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161284. /* Call progress monitor hook if present */
  161285. if (cinfo->progress != NULL) {
  161286. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161287. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161288. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161289. }
  161290. /* Give master control module another chance if this is first call to
  161291. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161292. * delayed so that application can write COM, etc, markers between
  161293. * jpeg_start_compress and jpeg_write_scanlines.
  161294. */
  161295. if (cinfo->master->call_pass_startup)
  161296. (*cinfo->master->pass_startup) (cinfo);
  161297. /* Ignore any extra scanlines at bottom of image. */
  161298. rows_left = cinfo->image_height - cinfo->next_scanline;
  161299. if (num_lines > rows_left)
  161300. num_lines = rows_left;
  161301. row_ctr = 0;
  161302. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161303. cinfo->next_scanline += row_ctr;
  161304. return row_ctr;
  161305. }
  161306. /*
  161307. * Alternate entry point to write raw data.
  161308. * Processes exactly one iMCU row per call, unless suspended.
  161309. */
  161310. GLOBAL(JDIMENSION)
  161311. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161312. JDIMENSION num_lines)
  161313. {
  161314. JDIMENSION lines_per_iMCU_row;
  161315. if (cinfo->global_state != CSTATE_RAW_OK)
  161316. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161317. if (cinfo->next_scanline >= cinfo->image_height) {
  161318. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161319. return 0;
  161320. }
  161321. /* Call progress monitor hook if present */
  161322. if (cinfo->progress != NULL) {
  161323. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161324. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161325. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161326. }
  161327. /* Give master control module another chance if this is first call to
  161328. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161329. * delayed so that application can write COM, etc, markers between
  161330. * jpeg_start_compress and jpeg_write_raw_data.
  161331. */
  161332. if (cinfo->master->call_pass_startup)
  161333. (*cinfo->master->pass_startup) (cinfo);
  161334. /* Verify that at least one iMCU row has been passed. */
  161335. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161336. if (num_lines < lines_per_iMCU_row)
  161337. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161338. /* Directly compress the row. */
  161339. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161340. /* If compressor did not consume the whole row, suspend processing. */
  161341. return 0;
  161342. }
  161343. /* OK, we processed one iMCU row. */
  161344. cinfo->next_scanline += lines_per_iMCU_row;
  161345. return lines_per_iMCU_row;
  161346. }
  161347. /*** End of inlined file: jcapistd.c ***/
  161348. /*** Start of inlined file: jccoefct.c ***/
  161349. #define JPEG_INTERNALS
  161350. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161351. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161352. * step is run during the first pass, and subsequent passes need only read
  161353. * the buffered coefficients.
  161354. */
  161355. #ifdef ENTROPY_OPT_SUPPORTED
  161356. #define FULL_COEF_BUFFER_SUPPORTED
  161357. #else
  161358. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161359. #define FULL_COEF_BUFFER_SUPPORTED
  161360. #endif
  161361. #endif
  161362. /* Private buffer controller object */
  161363. typedef struct {
  161364. struct jpeg_c_coef_controller pub; /* public fields */
  161365. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161366. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161367. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161368. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161369. /* For single-pass compression, it's sufficient to buffer just one MCU
  161370. * (although this may prove a bit slow in practice). We allocate a
  161371. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161372. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161373. * it's not really very big; this is to keep the module interfaces unchanged
  161374. * when a large coefficient buffer is necessary.)
  161375. * In multi-pass modes, this array points to the current MCU's blocks
  161376. * within the virtual arrays.
  161377. */
  161378. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161379. /* In multi-pass modes, we need a virtual block array for each component. */
  161380. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161381. } my_coef_controller;
  161382. typedef my_coef_controller * my_coef_ptr;
  161383. /* Forward declarations */
  161384. METHODDEF(boolean) compress_data
  161385. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161386. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161387. METHODDEF(boolean) compress_first_pass
  161388. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161389. METHODDEF(boolean) compress_output
  161390. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161391. #endif
  161392. LOCAL(void)
  161393. start_iMCU_row (j_compress_ptr cinfo)
  161394. /* Reset within-iMCU-row counters for a new row */
  161395. {
  161396. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161397. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161398. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161399. * But at the bottom of the image, process only what's left.
  161400. */
  161401. if (cinfo->comps_in_scan > 1) {
  161402. coef->MCU_rows_per_iMCU_row = 1;
  161403. } else {
  161404. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161405. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161406. else
  161407. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161408. }
  161409. coef->mcu_ctr = 0;
  161410. coef->MCU_vert_offset = 0;
  161411. }
  161412. /*
  161413. * Initialize for a processing pass.
  161414. */
  161415. METHODDEF(void)
  161416. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161417. {
  161418. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161419. coef->iMCU_row_num = 0;
  161420. start_iMCU_row(cinfo);
  161421. switch (pass_mode) {
  161422. case JBUF_PASS_THRU:
  161423. if (coef->whole_image[0] != NULL)
  161424. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161425. coef->pub.compress_data = compress_data;
  161426. break;
  161427. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161428. case JBUF_SAVE_AND_PASS:
  161429. if (coef->whole_image[0] == NULL)
  161430. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161431. coef->pub.compress_data = compress_first_pass;
  161432. break;
  161433. case JBUF_CRANK_DEST:
  161434. if (coef->whole_image[0] == NULL)
  161435. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161436. coef->pub.compress_data = compress_output;
  161437. break;
  161438. #endif
  161439. default:
  161440. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161441. break;
  161442. }
  161443. }
  161444. /*
  161445. * Process some data in the single-pass case.
  161446. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161447. * per call, ie, v_samp_factor block rows for each component in the image.
  161448. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161449. *
  161450. * NB: input_buf contains a plane for each component in image,
  161451. * which we index according to the component's SOF position.
  161452. */
  161453. METHODDEF(boolean)
  161454. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161455. {
  161456. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161457. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161458. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161459. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161460. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161461. JDIMENSION ypos, xpos;
  161462. jpeg_component_info *compptr;
  161463. /* Loop to write as much as one whole iMCU row */
  161464. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161465. yoffset++) {
  161466. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161467. MCU_col_num++) {
  161468. /* Determine where data comes from in input_buf and do the DCT thing.
  161469. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161470. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161471. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161472. * specially. The data in them does not matter for image reconstruction,
  161473. * so we fill them with values that will encode to the smallest amount of
  161474. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161475. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161476. */
  161477. blkn = 0;
  161478. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161479. compptr = cinfo->cur_comp_info[ci];
  161480. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161481. : compptr->last_col_width;
  161482. xpos = MCU_col_num * compptr->MCU_sample_width;
  161483. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161484. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161485. if (coef->iMCU_row_num < last_iMCU_row ||
  161486. yoffset+yindex < compptr->last_row_height) {
  161487. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161488. input_buf[compptr->component_index],
  161489. coef->MCU_buffer[blkn],
  161490. ypos, xpos, (JDIMENSION) blockcnt);
  161491. if (blockcnt < compptr->MCU_width) {
  161492. /* Create some dummy blocks at the right edge of the image. */
  161493. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161494. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161495. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161496. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161497. }
  161498. }
  161499. } else {
  161500. /* Create a row of dummy blocks at the bottom of the image. */
  161501. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161502. compptr->MCU_width * SIZEOF(JBLOCK));
  161503. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161504. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161505. }
  161506. }
  161507. blkn += compptr->MCU_width;
  161508. ypos += DCTSIZE;
  161509. }
  161510. }
  161511. /* Try to write the MCU. In event of a suspension failure, we will
  161512. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161513. */
  161514. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161515. /* Suspension forced; update state counters and exit */
  161516. coef->MCU_vert_offset = yoffset;
  161517. coef->mcu_ctr = MCU_col_num;
  161518. return FALSE;
  161519. }
  161520. }
  161521. /* Completed an MCU row, but perhaps not an iMCU row */
  161522. coef->mcu_ctr = 0;
  161523. }
  161524. /* Completed the iMCU row, advance counters for next one */
  161525. coef->iMCU_row_num++;
  161526. start_iMCU_row(cinfo);
  161527. return TRUE;
  161528. }
  161529. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161530. /*
  161531. * Process some data in the first pass of a multi-pass case.
  161532. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161533. * per call, ie, v_samp_factor block rows for each component in the image.
  161534. * This amount of data is read from the source buffer, DCT'd and quantized,
  161535. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161536. * as needed at the right and lower edges. (The dummy blocks are constructed
  161537. * in the virtual arrays, which have been padded appropriately.) This makes
  161538. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161539. *
  161540. * We must also emit the data to the entropy encoder. This is conveniently
  161541. * done by calling compress_output() after we've loaded the current strip
  161542. * of the virtual arrays.
  161543. *
  161544. * NB: input_buf contains a plane for each component in image. All
  161545. * components are DCT'd and loaded into the virtual arrays in this pass.
  161546. * However, it may be that only a subset of the components are emitted to
  161547. * the entropy encoder during this first pass; be careful about looking
  161548. * at the scan-dependent variables (MCU dimensions, etc).
  161549. */
  161550. METHODDEF(boolean)
  161551. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161552. {
  161553. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161554. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161555. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161556. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161557. JCOEF lastDC;
  161558. jpeg_component_info *compptr;
  161559. JBLOCKARRAY buffer;
  161560. JBLOCKROW thisblockrow, lastblockrow;
  161561. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161562. ci++, compptr++) {
  161563. /* Align the virtual buffer for this component. */
  161564. buffer = (*cinfo->mem->access_virt_barray)
  161565. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161566. coef->iMCU_row_num * compptr->v_samp_factor,
  161567. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161568. /* Count non-dummy DCT block rows in this iMCU row. */
  161569. if (coef->iMCU_row_num < last_iMCU_row)
  161570. block_rows = compptr->v_samp_factor;
  161571. else {
  161572. /* NB: can't use last_row_height here, since may not be set! */
  161573. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161574. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161575. }
  161576. blocks_across = compptr->width_in_blocks;
  161577. h_samp_factor = compptr->h_samp_factor;
  161578. /* Count number of dummy blocks to be added at the right margin. */
  161579. ndummy = (int) (blocks_across % h_samp_factor);
  161580. if (ndummy > 0)
  161581. ndummy = h_samp_factor - ndummy;
  161582. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161583. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161584. */
  161585. for (block_row = 0; block_row < block_rows; block_row++) {
  161586. thisblockrow = buffer[block_row];
  161587. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161588. input_buf[ci], thisblockrow,
  161589. (JDIMENSION) (block_row * DCTSIZE),
  161590. (JDIMENSION) 0, blocks_across);
  161591. if (ndummy > 0) {
  161592. /* Create dummy blocks at the right edge of the image. */
  161593. thisblockrow += blocks_across; /* => first dummy block */
  161594. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161595. lastDC = thisblockrow[-1][0];
  161596. for (bi = 0; bi < ndummy; bi++) {
  161597. thisblockrow[bi][0] = lastDC;
  161598. }
  161599. }
  161600. }
  161601. /* If at end of image, create dummy block rows as needed.
  161602. * The tricky part here is that within each MCU, we want the DC values
  161603. * of the dummy blocks to match the last real block's DC value.
  161604. * This squeezes a few more bytes out of the resulting file...
  161605. */
  161606. if (coef->iMCU_row_num == last_iMCU_row) {
  161607. blocks_across += ndummy; /* include lower right corner */
  161608. MCUs_across = blocks_across / h_samp_factor;
  161609. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161610. block_row++) {
  161611. thisblockrow = buffer[block_row];
  161612. lastblockrow = buffer[block_row-1];
  161613. jzero_far((void FAR *) thisblockrow,
  161614. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161615. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161616. lastDC = lastblockrow[h_samp_factor-1][0];
  161617. for (bi = 0; bi < h_samp_factor; bi++) {
  161618. thisblockrow[bi][0] = lastDC;
  161619. }
  161620. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161621. lastblockrow += h_samp_factor;
  161622. }
  161623. }
  161624. }
  161625. }
  161626. /* NB: compress_output will increment iMCU_row_num if successful.
  161627. * A suspension return will result in redoing all the work above next time.
  161628. */
  161629. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161630. return compress_output(cinfo, input_buf);
  161631. }
  161632. /*
  161633. * Process some data in subsequent passes of a multi-pass case.
  161634. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161635. * per call, ie, v_samp_factor block rows for each component in the scan.
  161636. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161637. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161638. *
  161639. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161640. */
  161641. METHODDEF(boolean)
  161642. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161643. {
  161644. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161645. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161646. int blkn, ci, xindex, yindex, yoffset;
  161647. JDIMENSION start_col;
  161648. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161649. JBLOCKROW buffer_ptr;
  161650. jpeg_component_info *compptr;
  161651. /* Align the virtual buffers for the components used in this scan.
  161652. * NB: during first pass, this is safe only because the buffers will
  161653. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161654. */
  161655. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161656. compptr = cinfo->cur_comp_info[ci];
  161657. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161658. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161659. coef->iMCU_row_num * compptr->v_samp_factor,
  161660. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161661. }
  161662. /* Loop to process one whole iMCU row */
  161663. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161664. yoffset++) {
  161665. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161666. MCU_col_num++) {
  161667. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161668. blkn = 0; /* index of current DCT block within MCU */
  161669. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161670. compptr = cinfo->cur_comp_info[ci];
  161671. start_col = MCU_col_num * compptr->MCU_width;
  161672. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161673. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161674. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161675. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161676. }
  161677. }
  161678. }
  161679. /* Try to write the MCU. */
  161680. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161681. /* Suspension forced; update state counters and exit */
  161682. coef->MCU_vert_offset = yoffset;
  161683. coef->mcu_ctr = MCU_col_num;
  161684. return FALSE;
  161685. }
  161686. }
  161687. /* Completed an MCU row, but perhaps not an iMCU row */
  161688. coef->mcu_ctr = 0;
  161689. }
  161690. /* Completed the iMCU row, advance counters for next one */
  161691. coef->iMCU_row_num++;
  161692. start_iMCU_row(cinfo);
  161693. return TRUE;
  161694. }
  161695. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161696. /*
  161697. * Initialize coefficient buffer controller.
  161698. */
  161699. GLOBAL(void)
  161700. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161701. {
  161702. my_coef_ptr coef;
  161703. coef = (my_coef_ptr)
  161704. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161705. SIZEOF(my_coef_controller));
  161706. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161707. coef->pub.start_pass = start_pass_coef;
  161708. /* Create the coefficient buffer. */
  161709. if (need_full_buffer) {
  161710. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161711. /* Allocate a full-image virtual array for each component, */
  161712. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161713. int ci;
  161714. jpeg_component_info *compptr;
  161715. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161716. ci++, compptr++) {
  161717. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161718. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161719. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161720. (long) compptr->h_samp_factor),
  161721. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161722. (long) compptr->v_samp_factor),
  161723. (JDIMENSION) compptr->v_samp_factor);
  161724. }
  161725. #else
  161726. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161727. #endif
  161728. } else {
  161729. /* We only need a single-MCU buffer. */
  161730. JBLOCKROW buffer;
  161731. int i;
  161732. buffer = (JBLOCKROW)
  161733. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161734. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161735. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161736. coef->MCU_buffer[i] = buffer + i;
  161737. }
  161738. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161739. }
  161740. }
  161741. /*** End of inlined file: jccoefct.c ***/
  161742. /*** Start of inlined file: jccolor.c ***/
  161743. #define JPEG_INTERNALS
  161744. /* Private subobject */
  161745. typedef struct {
  161746. struct jpeg_color_converter pub; /* public fields */
  161747. /* Private state for RGB->YCC conversion */
  161748. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161749. } my_color_converter;
  161750. typedef my_color_converter * my_cconvert_ptr;
  161751. /**************** RGB -> YCbCr conversion: most common case **************/
  161752. /*
  161753. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161754. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161755. * The conversion equations to be implemented are therefore
  161756. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161757. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161758. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161759. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161760. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161761. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161762. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161763. * were not represented exactly. Now we sacrifice exact representation of
  161764. * maximum red and maximum blue in order to get exact grayscales.
  161765. *
  161766. * To avoid floating-point arithmetic, we represent the fractional constants
  161767. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161768. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161769. *
  161770. * For even more speed, we avoid doing any multiplications in the inner loop
  161771. * by precalculating the constants times R,G,B for all possible values.
  161772. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161773. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161774. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161775. * colorspace anyway.
  161776. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161777. * in the tables to save adding them separately in the inner loop.
  161778. */
  161779. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161780. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161781. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161782. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161783. /* We allocate one big table and divide it up into eight parts, instead of
  161784. * doing eight alloc_small requests. This lets us use a single table base
  161785. * address, which can be held in a register in the inner loops on many
  161786. * machines (more than can hold all eight addresses, anyway).
  161787. */
  161788. #define R_Y_OFF 0 /* offset to R => Y section */
  161789. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161790. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161791. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161792. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161793. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161794. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161795. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161796. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161797. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161798. /*
  161799. * Initialize for RGB->YCC colorspace conversion.
  161800. */
  161801. METHODDEF(void)
  161802. rgb_ycc_start (j_compress_ptr cinfo)
  161803. {
  161804. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161805. INT32 * rgb_ycc_tab;
  161806. INT32 i;
  161807. /* Allocate and fill in the conversion tables. */
  161808. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161809. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161810. (TABLE_SIZE * SIZEOF(INT32)));
  161811. for (i = 0; i <= MAXJSAMPLE; i++) {
  161812. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161813. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161814. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161815. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161816. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161817. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161818. * This ensures that the maximum output will round to MAXJSAMPLE
  161819. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161820. */
  161821. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161822. /* B=>Cb and R=>Cr tables are the same
  161823. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161824. */
  161825. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161826. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161827. }
  161828. }
  161829. /*
  161830. * Convert some rows of samples to the JPEG colorspace.
  161831. *
  161832. * Note that we change from the application's interleaved-pixel format
  161833. * to our internal noninterleaved, one-plane-per-component format.
  161834. * The input buffer is therefore three times as wide as the output buffer.
  161835. *
  161836. * A starting row offset is provided only for the output buffer. The caller
  161837. * can easily adjust the passed input_buf value to accommodate any row
  161838. * offset required on that side.
  161839. */
  161840. METHODDEF(void)
  161841. rgb_ycc_convert (j_compress_ptr cinfo,
  161842. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161843. JDIMENSION output_row, int num_rows)
  161844. {
  161845. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161846. register int r, g, b;
  161847. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161848. register JSAMPROW inptr;
  161849. register JSAMPROW outptr0, outptr1, outptr2;
  161850. register JDIMENSION col;
  161851. JDIMENSION num_cols = cinfo->image_width;
  161852. while (--num_rows >= 0) {
  161853. inptr = *input_buf++;
  161854. outptr0 = output_buf[0][output_row];
  161855. outptr1 = output_buf[1][output_row];
  161856. outptr2 = output_buf[2][output_row];
  161857. output_row++;
  161858. for (col = 0; col < num_cols; col++) {
  161859. r = GETJSAMPLE(inptr[RGB_RED]);
  161860. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161861. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161862. inptr += RGB_PIXELSIZE;
  161863. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161864. * must be too; we do not need an explicit range-limiting operation.
  161865. * Hence the value being shifted is never negative, and we don't
  161866. * need the general RIGHT_SHIFT macro.
  161867. */
  161868. /* Y */
  161869. outptr0[col] = (JSAMPLE)
  161870. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161871. >> SCALEBITS);
  161872. /* Cb */
  161873. outptr1[col] = (JSAMPLE)
  161874. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161875. >> SCALEBITS);
  161876. /* Cr */
  161877. outptr2[col] = (JSAMPLE)
  161878. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161879. >> SCALEBITS);
  161880. }
  161881. }
  161882. }
  161883. /**************** Cases other than RGB -> YCbCr **************/
  161884. /*
  161885. * Convert some rows of samples to the JPEG colorspace.
  161886. * This version handles RGB->grayscale conversion, which is the same
  161887. * as the RGB->Y portion of RGB->YCbCr.
  161888. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161889. */
  161890. METHODDEF(void)
  161891. rgb_gray_convert (j_compress_ptr cinfo,
  161892. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161893. JDIMENSION output_row, int num_rows)
  161894. {
  161895. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161896. register int r, g, b;
  161897. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161898. register JSAMPROW inptr;
  161899. register JSAMPROW outptr;
  161900. register JDIMENSION col;
  161901. JDIMENSION num_cols = cinfo->image_width;
  161902. while (--num_rows >= 0) {
  161903. inptr = *input_buf++;
  161904. outptr = output_buf[0][output_row];
  161905. output_row++;
  161906. for (col = 0; col < num_cols; col++) {
  161907. r = GETJSAMPLE(inptr[RGB_RED]);
  161908. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161909. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161910. inptr += RGB_PIXELSIZE;
  161911. /* Y */
  161912. outptr[col] = (JSAMPLE)
  161913. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161914. >> SCALEBITS);
  161915. }
  161916. }
  161917. }
  161918. /*
  161919. * Convert some rows of samples to the JPEG colorspace.
  161920. * This version handles Adobe-style CMYK->YCCK conversion,
  161921. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161922. * conversion as above, while passing K (black) unchanged.
  161923. * We assume rgb_ycc_start has been called.
  161924. */
  161925. METHODDEF(void)
  161926. cmyk_ycck_convert (j_compress_ptr cinfo,
  161927. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161928. JDIMENSION output_row, int num_rows)
  161929. {
  161930. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161931. register int r, g, b;
  161932. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161933. register JSAMPROW inptr;
  161934. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161935. register JDIMENSION col;
  161936. JDIMENSION num_cols = cinfo->image_width;
  161937. while (--num_rows >= 0) {
  161938. inptr = *input_buf++;
  161939. outptr0 = output_buf[0][output_row];
  161940. outptr1 = output_buf[1][output_row];
  161941. outptr2 = output_buf[2][output_row];
  161942. outptr3 = output_buf[3][output_row];
  161943. output_row++;
  161944. for (col = 0; col < num_cols; col++) {
  161945. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161946. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161947. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161948. /* K passes through as-is */
  161949. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161950. inptr += 4;
  161951. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161952. * must be too; we do not need an explicit range-limiting operation.
  161953. * Hence the value being shifted is never negative, and we don't
  161954. * need the general RIGHT_SHIFT macro.
  161955. */
  161956. /* Y */
  161957. outptr0[col] = (JSAMPLE)
  161958. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161959. >> SCALEBITS);
  161960. /* Cb */
  161961. outptr1[col] = (JSAMPLE)
  161962. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161963. >> SCALEBITS);
  161964. /* Cr */
  161965. outptr2[col] = (JSAMPLE)
  161966. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161967. >> SCALEBITS);
  161968. }
  161969. }
  161970. }
  161971. /*
  161972. * Convert some rows of samples to the JPEG colorspace.
  161973. * This version handles grayscale output with no conversion.
  161974. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161975. */
  161976. METHODDEF(void)
  161977. grayscale_convert (j_compress_ptr cinfo,
  161978. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161979. JDIMENSION output_row, int num_rows)
  161980. {
  161981. register JSAMPROW inptr;
  161982. register JSAMPROW outptr;
  161983. register JDIMENSION col;
  161984. JDIMENSION num_cols = cinfo->image_width;
  161985. int instride = cinfo->input_components;
  161986. while (--num_rows >= 0) {
  161987. inptr = *input_buf++;
  161988. outptr = output_buf[0][output_row];
  161989. output_row++;
  161990. for (col = 0; col < num_cols; col++) {
  161991. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161992. inptr += instride;
  161993. }
  161994. }
  161995. }
  161996. /*
  161997. * Convert some rows of samples to the JPEG colorspace.
  161998. * This version handles multi-component colorspaces without conversion.
  161999. * We assume input_components == num_components.
  162000. */
  162001. METHODDEF(void)
  162002. null_convert (j_compress_ptr cinfo,
  162003. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162004. JDIMENSION output_row, int num_rows)
  162005. {
  162006. register JSAMPROW inptr;
  162007. register JSAMPROW outptr;
  162008. register JDIMENSION col;
  162009. register int ci;
  162010. int nc = cinfo->num_components;
  162011. JDIMENSION num_cols = cinfo->image_width;
  162012. while (--num_rows >= 0) {
  162013. /* It seems fastest to make a separate pass for each component. */
  162014. for (ci = 0; ci < nc; ci++) {
  162015. inptr = *input_buf;
  162016. outptr = output_buf[ci][output_row];
  162017. for (col = 0; col < num_cols; col++) {
  162018. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162019. inptr += nc;
  162020. }
  162021. }
  162022. input_buf++;
  162023. output_row++;
  162024. }
  162025. }
  162026. /*
  162027. * Empty method for start_pass.
  162028. */
  162029. METHODDEF(void)
  162030. null_method (j_compress_ptr)
  162031. {
  162032. /* no work needed */
  162033. }
  162034. /*
  162035. * Module initialization routine for input colorspace conversion.
  162036. */
  162037. GLOBAL(void)
  162038. jinit_color_converter (j_compress_ptr cinfo)
  162039. {
  162040. my_cconvert_ptr cconvert;
  162041. cconvert = (my_cconvert_ptr)
  162042. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162043. SIZEOF(my_color_converter));
  162044. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162045. /* set start_pass to null method until we find out differently */
  162046. cconvert->pub.start_pass = null_method;
  162047. /* Make sure input_components agrees with in_color_space */
  162048. switch (cinfo->in_color_space) {
  162049. case JCS_GRAYSCALE:
  162050. if (cinfo->input_components != 1)
  162051. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162052. break;
  162053. case JCS_RGB:
  162054. #if RGB_PIXELSIZE != 3
  162055. if (cinfo->input_components != RGB_PIXELSIZE)
  162056. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162057. break;
  162058. #endif /* else share code with YCbCr */
  162059. case JCS_YCbCr:
  162060. if (cinfo->input_components != 3)
  162061. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162062. break;
  162063. case JCS_CMYK:
  162064. case JCS_YCCK:
  162065. if (cinfo->input_components != 4)
  162066. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162067. break;
  162068. default: /* JCS_UNKNOWN can be anything */
  162069. if (cinfo->input_components < 1)
  162070. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162071. break;
  162072. }
  162073. /* Check num_components, set conversion method based on requested space */
  162074. switch (cinfo->jpeg_color_space) {
  162075. case JCS_GRAYSCALE:
  162076. if (cinfo->num_components != 1)
  162077. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162078. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162079. cconvert->pub.color_convert = grayscale_convert;
  162080. else if (cinfo->in_color_space == JCS_RGB) {
  162081. cconvert->pub.start_pass = rgb_ycc_start;
  162082. cconvert->pub.color_convert = rgb_gray_convert;
  162083. } else if (cinfo->in_color_space == JCS_YCbCr)
  162084. cconvert->pub.color_convert = grayscale_convert;
  162085. else
  162086. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162087. break;
  162088. case JCS_RGB:
  162089. if (cinfo->num_components != 3)
  162090. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162091. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162092. cconvert->pub.color_convert = null_convert;
  162093. else
  162094. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162095. break;
  162096. case JCS_YCbCr:
  162097. if (cinfo->num_components != 3)
  162098. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162099. if (cinfo->in_color_space == JCS_RGB) {
  162100. cconvert->pub.start_pass = rgb_ycc_start;
  162101. cconvert->pub.color_convert = rgb_ycc_convert;
  162102. } else if (cinfo->in_color_space == JCS_YCbCr)
  162103. cconvert->pub.color_convert = null_convert;
  162104. else
  162105. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162106. break;
  162107. case JCS_CMYK:
  162108. if (cinfo->num_components != 4)
  162109. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162110. if (cinfo->in_color_space == JCS_CMYK)
  162111. cconvert->pub.color_convert = null_convert;
  162112. else
  162113. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162114. break;
  162115. case JCS_YCCK:
  162116. if (cinfo->num_components != 4)
  162117. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162118. if (cinfo->in_color_space == JCS_CMYK) {
  162119. cconvert->pub.start_pass = rgb_ycc_start;
  162120. cconvert->pub.color_convert = cmyk_ycck_convert;
  162121. } else if (cinfo->in_color_space == JCS_YCCK)
  162122. cconvert->pub.color_convert = null_convert;
  162123. else
  162124. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162125. break;
  162126. default: /* allow null conversion of JCS_UNKNOWN */
  162127. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162128. cinfo->num_components != cinfo->input_components)
  162129. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162130. cconvert->pub.color_convert = null_convert;
  162131. break;
  162132. }
  162133. }
  162134. /*** End of inlined file: jccolor.c ***/
  162135. #undef FIX
  162136. /*** Start of inlined file: jcdctmgr.c ***/
  162137. #define JPEG_INTERNALS
  162138. /*** Start of inlined file: jdct.h ***/
  162139. /*
  162140. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162141. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162142. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162143. * implementations use an array of type FAST_FLOAT, instead.)
  162144. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162145. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162146. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162147. * convention improves accuracy in integer implementations and saves some
  162148. * work in floating-point ones.
  162149. * Quantization of the output coefficients is done by jcdctmgr.c.
  162150. */
  162151. #ifndef __jdct_h__
  162152. #define __jdct_h__
  162153. #if BITS_IN_JSAMPLE == 8
  162154. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162155. #else
  162156. typedef INT32 DCTELEM; /* must have 32 bits */
  162157. #endif
  162158. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162159. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162160. /*
  162161. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162162. * to an output sample array. The routine must dequantize the input data as
  162163. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162164. * pointed to by compptr->dct_table. The output data is to be placed into the
  162165. * sample array starting at a specified column. (Any row offset needed will
  162166. * be applied to the array pointer before it is passed to the IDCT code.)
  162167. * Note that the number of samples emitted by the IDCT routine is
  162168. * DCT_scaled_size * DCT_scaled_size.
  162169. */
  162170. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162171. /*
  162172. * Each IDCT routine has its own ideas about the best dct_table element type.
  162173. */
  162174. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162175. #if BITS_IN_JSAMPLE == 8
  162176. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162177. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162178. #else
  162179. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162180. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162181. #endif
  162182. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162183. /*
  162184. * Each IDCT routine is responsible for range-limiting its results and
  162185. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162186. * be quite far out of range if the input data is corrupt, so a bulletproof
  162187. * range-limiting step is required. We use a mask-and-table-lookup method
  162188. * to do the combined operations quickly. See the comments with
  162189. * prepare_range_limit_table (in jdmaster.c) for more info.
  162190. */
  162191. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162192. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162193. /* Short forms of external names for systems with brain-damaged linkers. */
  162194. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162195. #define jpeg_fdct_islow jFDislow
  162196. #define jpeg_fdct_ifast jFDifast
  162197. #define jpeg_fdct_float jFDfloat
  162198. #define jpeg_idct_islow jRDislow
  162199. #define jpeg_idct_ifast jRDifast
  162200. #define jpeg_idct_float jRDfloat
  162201. #define jpeg_idct_4x4 jRD4x4
  162202. #define jpeg_idct_2x2 jRD2x2
  162203. #define jpeg_idct_1x1 jRD1x1
  162204. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162205. /* Extern declarations for the forward and inverse DCT routines. */
  162206. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162207. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162208. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162209. EXTERN(void) jpeg_idct_islow
  162210. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162211. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162212. EXTERN(void) jpeg_idct_ifast
  162213. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162214. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162215. EXTERN(void) jpeg_idct_float
  162216. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162217. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162218. EXTERN(void) jpeg_idct_4x4
  162219. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162220. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162221. EXTERN(void) jpeg_idct_2x2
  162222. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162223. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162224. EXTERN(void) jpeg_idct_1x1
  162225. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162226. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162227. /*
  162228. * Macros for handling fixed-point arithmetic; these are used by many
  162229. * but not all of the DCT/IDCT modules.
  162230. *
  162231. * All values are expected to be of type INT32.
  162232. * Fractional constants are scaled left by CONST_BITS bits.
  162233. * CONST_BITS is defined within each module using these macros,
  162234. * and may differ from one module to the next.
  162235. */
  162236. #define ONE ((INT32) 1)
  162237. #define CONST_SCALE (ONE << CONST_BITS)
  162238. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162239. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162240. * thus causing a lot of useless floating-point operations at run time.
  162241. */
  162242. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162243. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162244. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162245. * the fudge factor is correct for either sign of X.
  162246. */
  162247. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162248. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162249. * This macro is used only when the two inputs will actually be no more than
  162250. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162251. * full 32x32 multiply. This provides a useful speedup on many machines.
  162252. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162253. * in C, but some C compilers will do the right thing if you provide the
  162254. * correct combination of casts.
  162255. */
  162256. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162257. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162258. #endif
  162259. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162260. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162261. #endif
  162262. #ifndef MULTIPLY16C16 /* default definition */
  162263. #define MULTIPLY16C16(var,const) ((var) * (const))
  162264. #endif
  162265. /* Same except both inputs are variables. */
  162266. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162267. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162268. #endif
  162269. #ifndef MULTIPLY16V16 /* default definition */
  162270. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162271. #endif
  162272. #endif
  162273. /*** End of inlined file: jdct.h ***/
  162274. /* Private declarations for DCT subsystem */
  162275. /* Private subobject for this module */
  162276. typedef struct {
  162277. struct jpeg_forward_dct pub; /* public fields */
  162278. /* Pointer to the DCT routine actually in use */
  162279. forward_DCT_method_ptr do_dct;
  162280. /* The actual post-DCT divisors --- not identical to the quant table
  162281. * entries, because of scaling (especially for an unnormalized DCT).
  162282. * Each table is given in normal array order.
  162283. */
  162284. DCTELEM * divisors[NUM_QUANT_TBLS];
  162285. #ifdef DCT_FLOAT_SUPPORTED
  162286. /* Same as above for the floating-point case. */
  162287. float_DCT_method_ptr do_float_dct;
  162288. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162289. #endif
  162290. } my_fdct_controller;
  162291. typedef my_fdct_controller * my_fdct_ptr;
  162292. /*
  162293. * Initialize for a processing pass.
  162294. * Verify that all referenced Q-tables are present, and set up
  162295. * the divisor table for each one.
  162296. * In the current implementation, DCT of all components is done during
  162297. * the first pass, even if only some components will be output in the
  162298. * first scan. Hence all components should be examined here.
  162299. */
  162300. METHODDEF(void)
  162301. start_pass_fdctmgr (j_compress_ptr cinfo)
  162302. {
  162303. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162304. int ci, qtblno, i;
  162305. jpeg_component_info *compptr;
  162306. JQUANT_TBL * qtbl;
  162307. DCTELEM * dtbl;
  162308. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162309. ci++, compptr++) {
  162310. qtblno = compptr->quant_tbl_no;
  162311. /* Make sure specified quantization table is present */
  162312. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162313. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162314. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162315. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162316. /* Compute divisors for this quant table */
  162317. /* We may do this more than once for same table, but it's not a big deal */
  162318. switch (cinfo->dct_method) {
  162319. #ifdef DCT_ISLOW_SUPPORTED
  162320. case JDCT_ISLOW:
  162321. /* For LL&M IDCT method, divisors are equal to raw quantization
  162322. * coefficients multiplied by 8 (to counteract scaling).
  162323. */
  162324. if (fdct->divisors[qtblno] == NULL) {
  162325. fdct->divisors[qtblno] = (DCTELEM *)
  162326. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162327. DCTSIZE2 * SIZEOF(DCTELEM));
  162328. }
  162329. dtbl = fdct->divisors[qtblno];
  162330. for (i = 0; i < DCTSIZE2; i++) {
  162331. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162332. }
  162333. break;
  162334. #endif
  162335. #ifdef DCT_IFAST_SUPPORTED
  162336. case JDCT_IFAST:
  162337. {
  162338. /* For AA&N IDCT method, divisors are equal to quantization
  162339. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162340. * scalefactor[0] = 1
  162341. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162342. * We apply a further scale factor of 8.
  162343. */
  162344. #define CONST_BITS 14
  162345. static const INT16 aanscales[DCTSIZE2] = {
  162346. /* precomputed values scaled up by 14 bits */
  162347. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162348. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162349. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162350. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162351. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162352. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162353. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162354. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162355. };
  162356. SHIFT_TEMPS
  162357. if (fdct->divisors[qtblno] == NULL) {
  162358. fdct->divisors[qtblno] = (DCTELEM *)
  162359. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162360. DCTSIZE2 * SIZEOF(DCTELEM));
  162361. }
  162362. dtbl = fdct->divisors[qtblno];
  162363. for (i = 0; i < DCTSIZE2; i++) {
  162364. dtbl[i] = (DCTELEM)
  162365. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162366. (INT32) aanscales[i]),
  162367. CONST_BITS-3);
  162368. }
  162369. }
  162370. break;
  162371. #endif
  162372. #ifdef DCT_FLOAT_SUPPORTED
  162373. case JDCT_FLOAT:
  162374. {
  162375. /* For float AA&N IDCT method, divisors are equal to quantization
  162376. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162377. * scalefactor[0] = 1
  162378. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162379. * We apply a further scale factor of 8.
  162380. * What's actually stored is 1/divisor so that the inner loop can
  162381. * use a multiplication rather than a division.
  162382. */
  162383. FAST_FLOAT * fdtbl;
  162384. int row, col;
  162385. static const double aanscalefactor[DCTSIZE] = {
  162386. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162387. 1.0, 0.785694958, 0.541196100, 0.275899379
  162388. };
  162389. if (fdct->float_divisors[qtblno] == NULL) {
  162390. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162391. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162392. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162393. }
  162394. fdtbl = fdct->float_divisors[qtblno];
  162395. i = 0;
  162396. for (row = 0; row < DCTSIZE; row++) {
  162397. for (col = 0; col < DCTSIZE; col++) {
  162398. fdtbl[i] = (FAST_FLOAT)
  162399. (1.0 / (((double) qtbl->quantval[i] *
  162400. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162401. i++;
  162402. }
  162403. }
  162404. }
  162405. break;
  162406. #endif
  162407. default:
  162408. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162409. break;
  162410. }
  162411. }
  162412. }
  162413. /*
  162414. * Perform forward DCT on one or more blocks of a component.
  162415. *
  162416. * The input samples are taken from the sample_data[] array starting at
  162417. * position start_row/start_col, and moving to the right for any additional
  162418. * blocks. The quantized coefficients are returned in coef_blocks[].
  162419. */
  162420. METHODDEF(void)
  162421. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162422. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162423. JDIMENSION start_row, JDIMENSION start_col,
  162424. JDIMENSION num_blocks)
  162425. /* This version is used for integer DCT implementations. */
  162426. {
  162427. /* This routine is heavily used, so it's worth coding it tightly. */
  162428. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162429. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162430. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162431. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162432. JDIMENSION bi;
  162433. sample_data += start_row; /* fold in the vertical offset once */
  162434. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162435. /* Load data into workspace, applying unsigned->signed conversion */
  162436. { register DCTELEM *workspaceptr;
  162437. register JSAMPROW elemptr;
  162438. register int elemr;
  162439. workspaceptr = workspace;
  162440. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162441. elemptr = sample_data[elemr] + start_col;
  162442. #if DCTSIZE == 8 /* unroll the inner loop */
  162443. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162444. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162445. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162446. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162447. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162448. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162449. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162450. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162451. #else
  162452. { register int elemc;
  162453. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162454. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162455. }
  162456. }
  162457. #endif
  162458. }
  162459. }
  162460. /* Perform the DCT */
  162461. (*do_dct) (workspace);
  162462. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162463. { register DCTELEM temp, qval;
  162464. register int i;
  162465. register JCOEFPTR output_ptr = coef_blocks[bi];
  162466. for (i = 0; i < DCTSIZE2; i++) {
  162467. qval = divisors[i];
  162468. temp = workspace[i];
  162469. /* Divide the coefficient value by qval, ensuring proper rounding.
  162470. * Since C does not specify the direction of rounding for negative
  162471. * quotients, we have to force the dividend positive for portability.
  162472. *
  162473. * In most files, at least half of the output values will be zero
  162474. * (at default quantization settings, more like three-quarters...)
  162475. * so we should ensure that this case is fast. On many machines,
  162476. * a comparison is enough cheaper than a divide to make a special test
  162477. * a win. Since both inputs will be nonnegative, we need only test
  162478. * for a < b to discover whether a/b is 0.
  162479. * If your machine's division is fast enough, define FAST_DIVIDE.
  162480. */
  162481. #ifdef FAST_DIVIDE
  162482. #define DIVIDE_BY(a,b) a /= b
  162483. #else
  162484. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162485. #endif
  162486. if (temp < 0) {
  162487. temp = -temp;
  162488. temp += qval>>1; /* for rounding */
  162489. DIVIDE_BY(temp, qval);
  162490. temp = -temp;
  162491. } else {
  162492. temp += qval>>1; /* for rounding */
  162493. DIVIDE_BY(temp, qval);
  162494. }
  162495. output_ptr[i] = (JCOEF) temp;
  162496. }
  162497. }
  162498. }
  162499. }
  162500. #ifdef DCT_FLOAT_SUPPORTED
  162501. METHODDEF(void)
  162502. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162503. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162504. JDIMENSION start_row, JDIMENSION start_col,
  162505. JDIMENSION num_blocks)
  162506. /* This version is used for floating-point DCT implementations. */
  162507. {
  162508. /* This routine is heavily used, so it's worth coding it tightly. */
  162509. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162510. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162511. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162512. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162513. JDIMENSION bi;
  162514. sample_data += start_row; /* fold in the vertical offset once */
  162515. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162516. /* Load data into workspace, applying unsigned->signed conversion */
  162517. { register FAST_FLOAT *workspaceptr;
  162518. register JSAMPROW elemptr;
  162519. register int elemr;
  162520. workspaceptr = workspace;
  162521. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162522. elemptr = sample_data[elemr] + start_col;
  162523. #if DCTSIZE == 8 /* unroll the inner loop */
  162524. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162525. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162526. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162527. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162528. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162529. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162530. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162531. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162532. #else
  162533. { register int elemc;
  162534. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162535. *workspaceptr++ = (FAST_FLOAT)
  162536. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162537. }
  162538. }
  162539. #endif
  162540. }
  162541. }
  162542. /* Perform the DCT */
  162543. (*do_dct) (workspace);
  162544. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162545. { register FAST_FLOAT temp;
  162546. register int i;
  162547. register JCOEFPTR output_ptr = coef_blocks[bi];
  162548. for (i = 0; i < DCTSIZE2; i++) {
  162549. /* Apply the quantization and scaling factor */
  162550. temp = workspace[i] * divisors[i];
  162551. /* Round to nearest integer.
  162552. * Since C does not specify the direction of rounding for negative
  162553. * quotients, we have to force the dividend positive for portability.
  162554. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162555. * code should work for either 16-bit or 32-bit ints.
  162556. */
  162557. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162558. }
  162559. }
  162560. }
  162561. }
  162562. #endif /* DCT_FLOAT_SUPPORTED */
  162563. /*
  162564. * Initialize FDCT manager.
  162565. */
  162566. GLOBAL(void)
  162567. jinit_forward_dct (j_compress_ptr cinfo)
  162568. {
  162569. my_fdct_ptr fdct;
  162570. int i;
  162571. fdct = (my_fdct_ptr)
  162572. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162573. SIZEOF(my_fdct_controller));
  162574. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162575. fdct->pub.start_pass = start_pass_fdctmgr;
  162576. switch (cinfo->dct_method) {
  162577. #ifdef DCT_ISLOW_SUPPORTED
  162578. case JDCT_ISLOW:
  162579. fdct->pub.forward_DCT = forward_DCT;
  162580. fdct->do_dct = jpeg_fdct_islow;
  162581. break;
  162582. #endif
  162583. #ifdef DCT_IFAST_SUPPORTED
  162584. case JDCT_IFAST:
  162585. fdct->pub.forward_DCT = forward_DCT;
  162586. fdct->do_dct = jpeg_fdct_ifast;
  162587. break;
  162588. #endif
  162589. #ifdef DCT_FLOAT_SUPPORTED
  162590. case JDCT_FLOAT:
  162591. fdct->pub.forward_DCT = forward_DCT_float;
  162592. fdct->do_float_dct = jpeg_fdct_float;
  162593. break;
  162594. #endif
  162595. default:
  162596. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162597. break;
  162598. }
  162599. /* Mark divisor tables unallocated */
  162600. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162601. fdct->divisors[i] = NULL;
  162602. #ifdef DCT_FLOAT_SUPPORTED
  162603. fdct->float_divisors[i] = NULL;
  162604. #endif
  162605. }
  162606. }
  162607. /*** End of inlined file: jcdctmgr.c ***/
  162608. #undef CONST_BITS
  162609. /*** Start of inlined file: jchuff.c ***/
  162610. #define JPEG_INTERNALS
  162611. /*** Start of inlined file: jchuff.h ***/
  162612. /* The legal range of a DCT coefficient is
  162613. * -1024 .. +1023 for 8-bit data;
  162614. * -16384 .. +16383 for 12-bit data.
  162615. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162616. */
  162617. #ifndef _jchuff_h_
  162618. #define _jchuff_h_
  162619. #if BITS_IN_JSAMPLE == 8
  162620. #define MAX_COEF_BITS 10
  162621. #else
  162622. #define MAX_COEF_BITS 14
  162623. #endif
  162624. /* Derived data constructed for each Huffman table */
  162625. typedef struct {
  162626. unsigned int ehufco[256]; /* code for each symbol */
  162627. char ehufsi[256]; /* length of code for each symbol */
  162628. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162629. } c_derived_tbl;
  162630. /* Short forms of external names for systems with brain-damaged linkers. */
  162631. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162632. #define jpeg_make_c_derived_tbl jMkCDerived
  162633. #define jpeg_gen_optimal_table jGenOptTbl
  162634. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162635. /* Expand a Huffman table definition into the derived format */
  162636. EXTERN(void) jpeg_make_c_derived_tbl
  162637. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162638. c_derived_tbl ** pdtbl));
  162639. /* Generate an optimal table definition given the specified counts */
  162640. EXTERN(void) jpeg_gen_optimal_table
  162641. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162642. #endif
  162643. /*** End of inlined file: jchuff.h ***/
  162644. /* Declarations shared with jcphuff.c */
  162645. /* Expanded entropy encoder object for Huffman encoding.
  162646. *
  162647. * The savable_state subrecord contains fields that change within an MCU,
  162648. * but must not be updated permanently until we complete the MCU.
  162649. */
  162650. typedef struct {
  162651. INT32 put_buffer; /* current bit-accumulation buffer */
  162652. int put_bits; /* # of bits now in it */
  162653. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162654. } savable_state;
  162655. /* This macro is to work around compilers with missing or broken
  162656. * structure assignment. You'll need to fix this code if you have
  162657. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162658. */
  162659. #ifndef NO_STRUCT_ASSIGN
  162660. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162661. #else
  162662. #if MAX_COMPS_IN_SCAN == 4
  162663. #define ASSIGN_STATE(dest,src) \
  162664. ((dest).put_buffer = (src).put_buffer, \
  162665. (dest).put_bits = (src).put_bits, \
  162666. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162667. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162668. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162669. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162670. #endif
  162671. #endif
  162672. typedef struct {
  162673. struct jpeg_entropy_encoder pub; /* public fields */
  162674. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162675. /* These fields are NOT loaded into local working state. */
  162676. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162677. int next_restart_num; /* next restart number to write (0-7) */
  162678. /* Pointers to derived tables (these workspaces have image lifespan) */
  162679. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162680. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162681. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162682. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162683. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162684. #endif
  162685. } huff_entropy_encoder;
  162686. typedef huff_entropy_encoder * huff_entropy_ptr;
  162687. /* Working state while writing an MCU.
  162688. * This struct contains all the fields that are needed by subroutines.
  162689. */
  162690. typedef struct {
  162691. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162692. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162693. savable_state cur; /* Current bit buffer & DC state */
  162694. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162695. } working_state;
  162696. /* Forward declarations */
  162697. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162698. JBLOCKROW *MCU_data));
  162699. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162700. #ifdef ENTROPY_OPT_SUPPORTED
  162701. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162702. JBLOCKROW *MCU_data));
  162703. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162704. #endif
  162705. /*
  162706. * Initialize for a Huffman-compressed scan.
  162707. * If gather_statistics is TRUE, we do not output anything during the scan,
  162708. * just count the Huffman symbols used and generate Huffman code tables.
  162709. */
  162710. METHODDEF(void)
  162711. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162712. {
  162713. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162714. int ci, dctbl, actbl;
  162715. jpeg_component_info * compptr;
  162716. if (gather_statistics) {
  162717. #ifdef ENTROPY_OPT_SUPPORTED
  162718. entropy->pub.encode_mcu = encode_mcu_gather;
  162719. entropy->pub.finish_pass = finish_pass_gather;
  162720. #else
  162721. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162722. #endif
  162723. } else {
  162724. entropy->pub.encode_mcu = encode_mcu_huff;
  162725. entropy->pub.finish_pass = finish_pass_huff;
  162726. }
  162727. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162728. compptr = cinfo->cur_comp_info[ci];
  162729. dctbl = compptr->dc_tbl_no;
  162730. actbl = compptr->ac_tbl_no;
  162731. if (gather_statistics) {
  162732. #ifdef ENTROPY_OPT_SUPPORTED
  162733. /* Check for invalid table indexes */
  162734. /* (make_c_derived_tbl does this in the other path) */
  162735. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162736. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162737. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162738. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162739. /* Allocate and zero the statistics tables */
  162740. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162741. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162742. entropy->dc_count_ptrs[dctbl] = (long *)
  162743. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162744. 257 * SIZEOF(long));
  162745. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162746. if (entropy->ac_count_ptrs[actbl] == NULL)
  162747. entropy->ac_count_ptrs[actbl] = (long *)
  162748. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162749. 257 * SIZEOF(long));
  162750. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162751. #endif
  162752. } else {
  162753. /* Compute derived values for Huffman tables */
  162754. /* We may do this more than once for a table, but it's not expensive */
  162755. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162756. & entropy->dc_derived_tbls[dctbl]);
  162757. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162758. & entropy->ac_derived_tbls[actbl]);
  162759. }
  162760. /* Initialize DC predictions to 0 */
  162761. entropy->saved.last_dc_val[ci] = 0;
  162762. }
  162763. /* Initialize bit buffer to empty */
  162764. entropy->saved.put_buffer = 0;
  162765. entropy->saved.put_bits = 0;
  162766. /* Initialize restart stuff */
  162767. entropy->restarts_to_go = cinfo->restart_interval;
  162768. entropy->next_restart_num = 0;
  162769. }
  162770. /*
  162771. * Compute the derived values for a Huffman table.
  162772. * This routine also performs some validation checks on the table.
  162773. *
  162774. * Note this is also used by jcphuff.c.
  162775. */
  162776. GLOBAL(void)
  162777. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162778. c_derived_tbl ** pdtbl)
  162779. {
  162780. JHUFF_TBL *htbl;
  162781. c_derived_tbl *dtbl;
  162782. int p, i, l, lastp, si, maxsymbol;
  162783. char huffsize[257];
  162784. unsigned int huffcode[257];
  162785. unsigned int code;
  162786. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162787. * paralleling the order of the symbols themselves in htbl->huffval[].
  162788. */
  162789. /* Find the input Huffman table */
  162790. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162791. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162792. htbl =
  162793. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162794. if (htbl == NULL)
  162795. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162796. /* Allocate a workspace if we haven't already done so. */
  162797. if (*pdtbl == NULL)
  162798. *pdtbl = (c_derived_tbl *)
  162799. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162800. SIZEOF(c_derived_tbl));
  162801. dtbl = *pdtbl;
  162802. /* Figure C.1: make table of Huffman code length for each symbol */
  162803. p = 0;
  162804. for (l = 1; l <= 16; l++) {
  162805. i = (int) htbl->bits[l];
  162806. if (i < 0 || p + i > 256) /* protect against table overrun */
  162807. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162808. while (i--)
  162809. huffsize[p++] = (char) l;
  162810. }
  162811. huffsize[p] = 0;
  162812. lastp = p;
  162813. /* Figure C.2: generate the codes themselves */
  162814. /* We also validate that the counts represent a legal Huffman code tree. */
  162815. code = 0;
  162816. si = huffsize[0];
  162817. p = 0;
  162818. while (huffsize[p]) {
  162819. while (((int) huffsize[p]) == si) {
  162820. huffcode[p++] = code;
  162821. code++;
  162822. }
  162823. /* code is now 1 more than the last code used for codelength si; but
  162824. * it must still fit in si bits, since no code is allowed to be all ones.
  162825. */
  162826. if (((INT32) code) >= (((INT32) 1) << si))
  162827. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162828. code <<= 1;
  162829. si++;
  162830. }
  162831. /* Figure C.3: generate encoding tables */
  162832. /* These are code and size indexed by symbol value */
  162833. /* Set all codeless symbols to have code length 0;
  162834. * this lets us detect duplicate VAL entries here, and later
  162835. * allows emit_bits to detect any attempt to emit such symbols.
  162836. */
  162837. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162838. /* This is also a convenient place to check for out-of-range
  162839. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162840. * but only 0..15 for DC. (We could constrain them further
  162841. * based on data depth and mode, but this seems enough.)
  162842. */
  162843. maxsymbol = isDC ? 15 : 255;
  162844. for (p = 0; p < lastp; p++) {
  162845. i = htbl->huffval[p];
  162846. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162847. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162848. dtbl->ehufco[i] = huffcode[p];
  162849. dtbl->ehufsi[i] = huffsize[p];
  162850. }
  162851. }
  162852. /* Outputting bytes to the file */
  162853. /* Emit a byte, taking 'action' if must suspend. */
  162854. #define emit_byte(state,val,action) \
  162855. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162856. if (--(state)->free_in_buffer == 0) \
  162857. if (! dump_buffer(state)) \
  162858. { action; } }
  162859. LOCAL(boolean)
  162860. dump_buffer (working_state * state)
  162861. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162862. {
  162863. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162864. if (! (*dest->empty_output_buffer) (state->cinfo))
  162865. return FALSE;
  162866. /* After a successful buffer dump, must reset buffer pointers */
  162867. state->next_output_byte = dest->next_output_byte;
  162868. state->free_in_buffer = dest->free_in_buffer;
  162869. return TRUE;
  162870. }
  162871. /* Outputting bits to the file */
  162872. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162873. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162874. * in one call, and we never retain more than 7 bits in put_buffer
  162875. * between calls, so 24 bits are sufficient.
  162876. */
  162877. INLINE
  162878. LOCAL(boolean)
  162879. emit_bits (working_state * state, unsigned int code, int size)
  162880. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162881. {
  162882. /* This routine is heavily used, so it's worth coding tightly. */
  162883. register INT32 put_buffer = (INT32) code;
  162884. register int put_bits = state->cur.put_bits;
  162885. /* if size is 0, caller used an invalid Huffman table entry */
  162886. if (size == 0)
  162887. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162888. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162889. put_bits += size; /* new number of bits in buffer */
  162890. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162891. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162892. while (put_bits >= 8) {
  162893. int c = (int) ((put_buffer >> 16) & 0xFF);
  162894. emit_byte(state, c, return FALSE);
  162895. if (c == 0xFF) { /* need to stuff a zero byte? */
  162896. emit_byte(state, 0, return FALSE);
  162897. }
  162898. put_buffer <<= 8;
  162899. put_bits -= 8;
  162900. }
  162901. state->cur.put_buffer = put_buffer; /* update state variables */
  162902. state->cur.put_bits = put_bits;
  162903. return TRUE;
  162904. }
  162905. LOCAL(boolean)
  162906. flush_bits (working_state * state)
  162907. {
  162908. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162909. return FALSE;
  162910. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162911. state->cur.put_bits = 0;
  162912. return TRUE;
  162913. }
  162914. /* Encode a single block's worth of coefficients */
  162915. LOCAL(boolean)
  162916. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162917. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162918. {
  162919. register int temp, temp2;
  162920. register int nbits;
  162921. register int k, r, i;
  162922. /* Encode the DC coefficient difference per section F.1.2.1 */
  162923. temp = temp2 = block[0] - last_dc_val;
  162924. if (temp < 0) {
  162925. temp = -temp; /* temp is abs value of input */
  162926. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162927. /* This code assumes we are on a two's complement machine */
  162928. temp2--;
  162929. }
  162930. /* Find the number of bits needed for the magnitude of the coefficient */
  162931. nbits = 0;
  162932. while (temp) {
  162933. nbits++;
  162934. temp >>= 1;
  162935. }
  162936. /* Check for out-of-range coefficient values.
  162937. * Since we're encoding a difference, the range limit is twice as much.
  162938. */
  162939. if (nbits > MAX_COEF_BITS+1)
  162940. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162941. /* Emit the Huffman-coded symbol for the number of bits */
  162942. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162943. return FALSE;
  162944. /* Emit that number of bits of the value, if positive, */
  162945. /* or the complement of its magnitude, if negative. */
  162946. if (nbits) /* emit_bits rejects calls with size 0 */
  162947. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162948. return FALSE;
  162949. /* Encode the AC coefficients per section F.1.2.2 */
  162950. r = 0; /* r = run length of zeros */
  162951. for (k = 1; k < DCTSIZE2; k++) {
  162952. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162953. r++;
  162954. } else {
  162955. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162956. while (r > 15) {
  162957. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162958. return FALSE;
  162959. r -= 16;
  162960. }
  162961. temp2 = temp;
  162962. if (temp < 0) {
  162963. temp = -temp; /* temp is abs value of input */
  162964. /* This code assumes we are on a two's complement machine */
  162965. temp2--;
  162966. }
  162967. /* Find the number of bits needed for the magnitude of the coefficient */
  162968. nbits = 1; /* there must be at least one 1 bit */
  162969. while ((temp >>= 1))
  162970. nbits++;
  162971. /* Check for out-of-range coefficient values */
  162972. if (nbits > MAX_COEF_BITS)
  162973. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162974. /* Emit Huffman symbol for run length / number of bits */
  162975. i = (r << 4) + nbits;
  162976. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162977. return FALSE;
  162978. /* Emit that number of bits of the value, if positive, */
  162979. /* or the complement of its magnitude, if negative. */
  162980. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162981. return FALSE;
  162982. r = 0;
  162983. }
  162984. }
  162985. /* If the last coef(s) were zero, emit an end-of-block code */
  162986. if (r > 0)
  162987. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162988. return FALSE;
  162989. return TRUE;
  162990. }
  162991. /*
  162992. * Emit a restart marker & resynchronize predictions.
  162993. */
  162994. LOCAL(boolean)
  162995. emit_restart (working_state * state, int restart_num)
  162996. {
  162997. int ci;
  162998. if (! flush_bits(state))
  162999. return FALSE;
  163000. emit_byte(state, 0xFF, return FALSE);
  163001. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163002. /* Re-initialize DC predictions to 0 */
  163003. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163004. state->cur.last_dc_val[ci] = 0;
  163005. /* The restart counter is not updated until we successfully write the MCU. */
  163006. return TRUE;
  163007. }
  163008. /*
  163009. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163010. */
  163011. METHODDEF(boolean)
  163012. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163013. {
  163014. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163015. working_state state;
  163016. int blkn, ci;
  163017. jpeg_component_info * compptr;
  163018. /* Load up working state */
  163019. state.next_output_byte = cinfo->dest->next_output_byte;
  163020. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163021. ASSIGN_STATE(state.cur, entropy->saved);
  163022. state.cinfo = cinfo;
  163023. /* Emit restart marker if needed */
  163024. if (cinfo->restart_interval) {
  163025. if (entropy->restarts_to_go == 0)
  163026. if (! emit_restart(&state, entropy->next_restart_num))
  163027. return FALSE;
  163028. }
  163029. /* Encode the MCU data blocks */
  163030. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163031. ci = cinfo->MCU_membership[blkn];
  163032. compptr = cinfo->cur_comp_info[ci];
  163033. if (! encode_one_block(&state,
  163034. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163035. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163036. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163037. return FALSE;
  163038. /* Update last_dc_val */
  163039. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163040. }
  163041. /* Completed MCU, so update state */
  163042. cinfo->dest->next_output_byte = state.next_output_byte;
  163043. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163044. ASSIGN_STATE(entropy->saved, state.cur);
  163045. /* Update restart-interval state too */
  163046. if (cinfo->restart_interval) {
  163047. if (entropy->restarts_to_go == 0) {
  163048. entropy->restarts_to_go = cinfo->restart_interval;
  163049. entropy->next_restart_num++;
  163050. entropy->next_restart_num &= 7;
  163051. }
  163052. entropy->restarts_to_go--;
  163053. }
  163054. return TRUE;
  163055. }
  163056. /*
  163057. * Finish up at the end of a Huffman-compressed scan.
  163058. */
  163059. METHODDEF(void)
  163060. finish_pass_huff (j_compress_ptr cinfo)
  163061. {
  163062. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163063. working_state state;
  163064. /* Load up working state ... flush_bits needs it */
  163065. state.next_output_byte = cinfo->dest->next_output_byte;
  163066. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163067. ASSIGN_STATE(state.cur, entropy->saved);
  163068. state.cinfo = cinfo;
  163069. /* Flush out the last data */
  163070. if (! flush_bits(&state))
  163071. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163072. /* Update state */
  163073. cinfo->dest->next_output_byte = state.next_output_byte;
  163074. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163075. ASSIGN_STATE(entropy->saved, state.cur);
  163076. }
  163077. /*
  163078. * Huffman coding optimization.
  163079. *
  163080. * We first scan the supplied data and count the number of uses of each symbol
  163081. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163082. * Then we build a Huffman coding tree for the observed counts.
  163083. * Symbols which are not needed at all for the particular image are not
  163084. * assigned any code, which saves space in the DHT marker as well as in
  163085. * the compressed data.
  163086. */
  163087. #ifdef ENTROPY_OPT_SUPPORTED
  163088. /* Process a single block's worth of coefficients */
  163089. LOCAL(void)
  163090. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163091. long dc_counts[], long ac_counts[])
  163092. {
  163093. register int temp;
  163094. register int nbits;
  163095. register int k, r;
  163096. /* Encode the DC coefficient difference per section F.1.2.1 */
  163097. temp = block[0] - last_dc_val;
  163098. if (temp < 0)
  163099. temp = -temp;
  163100. /* Find the number of bits needed for the magnitude of the coefficient */
  163101. nbits = 0;
  163102. while (temp) {
  163103. nbits++;
  163104. temp >>= 1;
  163105. }
  163106. /* Check for out-of-range coefficient values.
  163107. * Since we're encoding a difference, the range limit is twice as much.
  163108. */
  163109. if (nbits > MAX_COEF_BITS+1)
  163110. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163111. /* Count the Huffman symbol for the number of bits */
  163112. dc_counts[nbits]++;
  163113. /* Encode the AC coefficients per section F.1.2.2 */
  163114. r = 0; /* r = run length of zeros */
  163115. for (k = 1; k < DCTSIZE2; k++) {
  163116. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163117. r++;
  163118. } else {
  163119. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163120. while (r > 15) {
  163121. ac_counts[0xF0]++;
  163122. r -= 16;
  163123. }
  163124. /* Find the number of bits needed for the magnitude of the coefficient */
  163125. if (temp < 0)
  163126. temp = -temp;
  163127. /* Find the number of bits needed for the magnitude of the coefficient */
  163128. nbits = 1; /* there must be at least one 1 bit */
  163129. while ((temp >>= 1))
  163130. nbits++;
  163131. /* Check for out-of-range coefficient values */
  163132. if (nbits > MAX_COEF_BITS)
  163133. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163134. /* Count Huffman symbol for run length / number of bits */
  163135. ac_counts[(r << 4) + nbits]++;
  163136. r = 0;
  163137. }
  163138. }
  163139. /* If the last coef(s) were zero, emit an end-of-block code */
  163140. if (r > 0)
  163141. ac_counts[0]++;
  163142. }
  163143. /*
  163144. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163145. * No data is actually output, so no suspension return is possible.
  163146. */
  163147. METHODDEF(boolean)
  163148. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163149. {
  163150. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163151. int blkn, ci;
  163152. jpeg_component_info * compptr;
  163153. /* Take care of restart intervals if needed */
  163154. if (cinfo->restart_interval) {
  163155. if (entropy->restarts_to_go == 0) {
  163156. /* Re-initialize DC predictions to 0 */
  163157. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163158. entropy->saved.last_dc_val[ci] = 0;
  163159. /* Update restart state */
  163160. entropy->restarts_to_go = cinfo->restart_interval;
  163161. }
  163162. entropy->restarts_to_go--;
  163163. }
  163164. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163165. ci = cinfo->MCU_membership[blkn];
  163166. compptr = cinfo->cur_comp_info[ci];
  163167. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163168. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163169. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163170. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163171. }
  163172. return TRUE;
  163173. }
  163174. /*
  163175. * Generate the best Huffman code table for the given counts, fill htbl.
  163176. * Note this is also used by jcphuff.c.
  163177. *
  163178. * The JPEG standard requires that no symbol be assigned a codeword of all
  163179. * one bits (so that padding bits added at the end of a compressed segment
  163180. * can't look like a valid code). Because of the canonical ordering of
  163181. * codewords, this just means that there must be an unused slot in the
  163182. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163183. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163184. * with count 1. In theory that's not optimal; giving it count zero but
  163185. * including it in the symbol set anyway should give a better Huffman code.
  163186. * But the theoretically better code actually seems to come out worse in
  163187. * practice, because it produces more all-ones bytes (which incur stuffed
  163188. * zero bytes in the final file). In any case the difference is tiny.
  163189. *
  163190. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163191. * If some symbols have a very small but nonzero probability, the Huffman tree
  163192. * must be adjusted to meet the code length restriction. We currently use
  163193. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163194. * optimal; it may not choose the best possible limited-length code. But
  163195. * typically only very-low-frequency symbols will be given less-than-optimal
  163196. * lengths, so the code is almost optimal. Experimental comparisons against
  163197. * an optimal limited-length-code algorithm indicate that the difference is
  163198. * microscopic --- usually less than a hundredth of a percent of total size.
  163199. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163200. */
  163201. GLOBAL(void)
  163202. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163203. {
  163204. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163205. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163206. int codesize[257]; /* codesize[k] = code length of symbol k */
  163207. int others[257]; /* next symbol in current branch of tree */
  163208. int c1, c2;
  163209. int p, i, j;
  163210. long v;
  163211. /* This algorithm is explained in section K.2 of the JPEG standard */
  163212. MEMZERO(bits, SIZEOF(bits));
  163213. MEMZERO(codesize, SIZEOF(codesize));
  163214. for (i = 0; i < 257; i++)
  163215. others[i] = -1; /* init links to empty */
  163216. freq[256] = 1; /* make sure 256 has a nonzero count */
  163217. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163218. * that no real symbol is given code-value of all ones, because 256
  163219. * will be placed last in the largest codeword category.
  163220. */
  163221. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163222. for (;;) {
  163223. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163224. /* In case of ties, take the larger symbol number */
  163225. c1 = -1;
  163226. v = 1000000000L;
  163227. for (i = 0; i <= 256; i++) {
  163228. if (freq[i] && freq[i] <= v) {
  163229. v = freq[i];
  163230. c1 = i;
  163231. }
  163232. }
  163233. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163234. /* In case of ties, take the larger symbol number */
  163235. c2 = -1;
  163236. v = 1000000000L;
  163237. for (i = 0; i <= 256; i++) {
  163238. if (freq[i] && freq[i] <= v && i != c1) {
  163239. v = freq[i];
  163240. c2 = i;
  163241. }
  163242. }
  163243. /* Done if we've merged everything into one frequency */
  163244. if (c2 < 0)
  163245. break;
  163246. /* Else merge the two counts/trees */
  163247. freq[c1] += freq[c2];
  163248. freq[c2] = 0;
  163249. /* Increment the codesize of everything in c1's tree branch */
  163250. codesize[c1]++;
  163251. while (others[c1] >= 0) {
  163252. c1 = others[c1];
  163253. codesize[c1]++;
  163254. }
  163255. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163256. /* Increment the codesize of everything in c2's tree branch */
  163257. codesize[c2]++;
  163258. while (others[c2] >= 0) {
  163259. c2 = others[c2];
  163260. codesize[c2]++;
  163261. }
  163262. }
  163263. /* Now count the number of symbols of each code length */
  163264. for (i = 0; i <= 256; i++) {
  163265. if (codesize[i]) {
  163266. /* The JPEG standard seems to think that this can't happen, */
  163267. /* but I'm paranoid... */
  163268. if (codesize[i] > MAX_CLEN)
  163269. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163270. bits[codesize[i]]++;
  163271. }
  163272. }
  163273. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163274. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163275. * Here is what the JPEG spec says about how this next bit works:
  163276. * Since symbols are paired for the longest Huffman code, the symbols are
  163277. * removed from this length category two at a time. The prefix for the pair
  163278. * (which is one bit shorter) is allocated to one of the pair; then,
  163279. * skipping the BITS entry for that prefix length, a code word from the next
  163280. * shortest nonzero BITS entry is converted into a prefix for two code words
  163281. * one bit longer.
  163282. */
  163283. for (i = MAX_CLEN; i > 16; i--) {
  163284. while (bits[i] > 0) {
  163285. j = i - 2; /* find length of new prefix to be used */
  163286. while (bits[j] == 0)
  163287. j--;
  163288. bits[i] -= 2; /* remove two symbols */
  163289. bits[i-1]++; /* one goes in this length */
  163290. bits[j+1] += 2; /* two new symbols in this length */
  163291. bits[j]--; /* symbol of this length is now a prefix */
  163292. }
  163293. }
  163294. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163295. while (bits[i] == 0) /* find largest codelength still in use */
  163296. i--;
  163297. bits[i]--;
  163298. /* Return final symbol counts (only for lengths 0..16) */
  163299. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163300. /* Return a list of the symbols sorted by code length */
  163301. /* It's not real clear to me why we don't need to consider the codelength
  163302. * changes made above, but the JPEG spec seems to think this works.
  163303. */
  163304. p = 0;
  163305. for (i = 1; i <= MAX_CLEN; i++) {
  163306. for (j = 0; j <= 255; j++) {
  163307. if (codesize[j] == i) {
  163308. htbl->huffval[p] = (UINT8) j;
  163309. p++;
  163310. }
  163311. }
  163312. }
  163313. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163314. htbl->sent_table = FALSE;
  163315. }
  163316. /*
  163317. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163318. */
  163319. METHODDEF(void)
  163320. finish_pass_gather (j_compress_ptr cinfo)
  163321. {
  163322. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163323. int ci, dctbl, actbl;
  163324. jpeg_component_info * compptr;
  163325. JHUFF_TBL **htblptr;
  163326. boolean did_dc[NUM_HUFF_TBLS];
  163327. boolean did_ac[NUM_HUFF_TBLS];
  163328. /* It's important not to apply jpeg_gen_optimal_table more than once
  163329. * per table, because it clobbers the input frequency counts!
  163330. */
  163331. MEMZERO(did_dc, SIZEOF(did_dc));
  163332. MEMZERO(did_ac, SIZEOF(did_ac));
  163333. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163334. compptr = cinfo->cur_comp_info[ci];
  163335. dctbl = compptr->dc_tbl_no;
  163336. actbl = compptr->ac_tbl_no;
  163337. if (! did_dc[dctbl]) {
  163338. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163339. if (*htblptr == NULL)
  163340. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163341. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163342. did_dc[dctbl] = TRUE;
  163343. }
  163344. if (! did_ac[actbl]) {
  163345. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163346. if (*htblptr == NULL)
  163347. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163348. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163349. did_ac[actbl] = TRUE;
  163350. }
  163351. }
  163352. }
  163353. #endif /* ENTROPY_OPT_SUPPORTED */
  163354. /*
  163355. * Module initialization routine for Huffman entropy encoding.
  163356. */
  163357. GLOBAL(void)
  163358. jinit_huff_encoder (j_compress_ptr cinfo)
  163359. {
  163360. huff_entropy_ptr entropy;
  163361. int i;
  163362. entropy = (huff_entropy_ptr)
  163363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163364. SIZEOF(huff_entropy_encoder));
  163365. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163366. entropy->pub.start_pass = start_pass_huff;
  163367. /* Mark tables unallocated */
  163368. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163369. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163370. #ifdef ENTROPY_OPT_SUPPORTED
  163371. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163372. #endif
  163373. }
  163374. }
  163375. /*** End of inlined file: jchuff.c ***/
  163376. #undef emit_byte
  163377. /*** Start of inlined file: jcinit.c ***/
  163378. #define JPEG_INTERNALS
  163379. /*
  163380. * Master selection of compression modules.
  163381. * This is done once at the start of processing an image. We determine
  163382. * which modules will be used and give them appropriate initialization calls.
  163383. */
  163384. GLOBAL(void)
  163385. jinit_compress_master (j_compress_ptr cinfo)
  163386. {
  163387. /* Initialize master control (includes parameter checking/processing) */
  163388. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163389. /* Preprocessing */
  163390. if (! cinfo->raw_data_in) {
  163391. jinit_color_converter(cinfo);
  163392. jinit_downsampler(cinfo);
  163393. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163394. }
  163395. /* Forward DCT */
  163396. jinit_forward_dct(cinfo);
  163397. /* Entropy encoding: either Huffman or arithmetic coding. */
  163398. if (cinfo->arith_code) {
  163399. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163400. } else {
  163401. if (cinfo->progressive_mode) {
  163402. #ifdef C_PROGRESSIVE_SUPPORTED
  163403. jinit_phuff_encoder(cinfo);
  163404. #else
  163405. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163406. #endif
  163407. } else
  163408. jinit_huff_encoder(cinfo);
  163409. }
  163410. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163411. jinit_c_coef_controller(cinfo,
  163412. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163413. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163414. jinit_marker_writer(cinfo);
  163415. /* We can now tell the memory manager to allocate virtual arrays. */
  163416. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163417. /* Write the datastream header (SOI) immediately.
  163418. * Frame and scan headers are postponed till later.
  163419. * This lets application insert special markers after the SOI.
  163420. */
  163421. (*cinfo->marker->write_file_header) (cinfo);
  163422. }
  163423. /*** End of inlined file: jcinit.c ***/
  163424. /*** Start of inlined file: jcmainct.c ***/
  163425. #define JPEG_INTERNALS
  163426. /* Note: currently, there is no operating mode in which a full-image buffer
  163427. * is needed at this step. If there were, that mode could not be used with
  163428. * "raw data" input, since this module is bypassed in that case. However,
  163429. * we've left the code here for possible use in special applications.
  163430. */
  163431. #undef FULL_MAIN_BUFFER_SUPPORTED
  163432. /* Private buffer controller object */
  163433. typedef struct {
  163434. struct jpeg_c_main_controller pub; /* public fields */
  163435. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163436. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163437. boolean suspended; /* remember if we suspended output */
  163438. J_BUF_MODE pass_mode; /* current operating mode */
  163439. /* If using just a strip buffer, this points to the entire set of buffers
  163440. * (we allocate one for each component). In the full-image case, this
  163441. * points to the currently accessible strips of the virtual arrays.
  163442. */
  163443. JSAMPARRAY buffer[MAX_COMPONENTS];
  163444. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163445. /* If using full-image storage, this array holds pointers to virtual-array
  163446. * control blocks for each component. Unused if not full-image storage.
  163447. */
  163448. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163449. #endif
  163450. } my_main_controller;
  163451. typedef my_main_controller * my_main_ptr;
  163452. /* Forward declarations */
  163453. METHODDEF(void) process_data_simple_main
  163454. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163455. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163456. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163457. METHODDEF(void) process_data_buffer_main
  163458. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163459. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163460. #endif
  163461. /*
  163462. * Initialize for a processing pass.
  163463. */
  163464. METHODDEF(void)
  163465. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163466. {
  163467. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163468. /* Do nothing in raw-data mode. */
  163469. if (cinfo->raw_data_in)
  163470. return;
  163471. main_->cur_iMCU_row = 0; /* initialize counters */
  163472. main_->rowgroup_ctr = 0;
  163473. main_->suspended = FALSE;
  163474. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163475. switch (pass_mode) {
  163476. case JBUF_PASS_THRU:
  163477. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163478. if (main_->whole_image[0] != NULL)
  163479. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163480. #endif
  163481. main_->pub.process_data = process_data_simple_main;
  163482. break;
  163483. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163484. case JBUF_SAVE_SOURCE:
  163485. case JBUF_CRANK_DEST:
  163486. case JBUF_SAVE_AND_PASS:
  163487. if (main_->whole_image[0] == NULL)
  163488. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163489. main_->pub.process_data = process_data_buffer_main;
  163490. break;
  163491. #endif
  163492. default:
  163493. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163494. break;
  163495. }
  163496. }
  163497. /*
  163498. * Process some data.
  163499. * This routine handles the simple pass-through mode,
  163500. * where we have only a strip buffer.
  163501. */
  163502. METHODDEF(void)
  163503. process_data_simple_main (j_compress_ptr cinfo,
  163504. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163505. JDIMENSION in_rows_avail)
  163506. {
  163507. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163508. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163509. /* Read input data if we haven't filled the main buffer yet */
  163510. if (main_->rowgroup_ctr < DCTSIZE)
  163511. (*cinfo->prep->pre_process_data) (cinfo,
  163512. input_buf, in_row_ctr, in_rows_avail,
  163513. main_->buffer, &main_->rowgroup_ctr,
  163514. (JDIMENSION) DCTSIZE);
  163515. /* If we don't have a full iMCU row buffered, return to application for
  163516. * more data. Note that preprocessor will always pad to fill the iMCU row
  163517. * at the bottom of the image.
  163518. */
  163519. if (main_->rowgroup_ctr != DCTSIZE)
  163520. return;
  163521. /* Send the completed row to the compressor */
  163522. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163523. /* If compressor did not consume the whole row, then we must need to
  163524. * suspend processing and return to the application. In this situation
  163525. * we pretend we didn't yet consume the last input row; otherwise, if
  163526. * it happened to be the last row of the image, the application would
  163527. * think we were done.
  163528. */
  163529. if (! main_->suspended) {
  163530. (*in_row_ctr)--;
  163531. main_->suspended = TRUE;
  163532. }
  163533. return;
  163534. }
  163535. /* We did finish the row. Undo our little suspension hack if a previous
  163536. * call suspended; then mark the main buffer empty.
  163537. */
  163538. if (main_->suspended) {
  163539. (*in_row_ctr)++;
  163540. main_->suspended = FALSE;
  163541. }
  163542. main_->rowgroup_ctr = 0;
  163543. main_->cur_iMCU_row++;
  163544. }
  163545. }
  163546. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163547. /*
  163548. * Process some data.
  163549. * This routine handles all of the modes that use a full-size buffer.
  163550. */
  163551. METHODDEF(void)
  163552. process_data_buffer_main (j_compress_ptr cinfo,
  163553. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163554. JDIMENSION in_rows_avail)
  163555. {
  163556. my_main_ptr main = (my_main_ptr) cinfo->main;
  163557. int ci;
  163558. jpeg_component_info *compptr;
  163559. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163560. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163561. /* Realign the virtual buffers if at the start of an iMCU row. */
  163562. if (main->rowgroup_ctr == 0) {
  163563. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163564. ci++, compptr++) {
  163565. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163566. ((j_common_ptr) cinfo, main->whole_image[ci],
  163567. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163568. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163569. }
  163570. /* In a read pass, pretend we just read some source data. */
  163571. if (! writing) {
  163572. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163573. main->rowgroup_ctr = DCTSIZE;
  163574. }
  163575. }
  163576. /* If a write pass, read input data until the current iMCU row is full. */
  163577. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163578. if (writing) {
  163579. (*cinfo->prep->pre_process_data) (cinfo,
  163580. input_buf, in_row_ctr, in_rows_avail,
  163581. main->buffer, &main->rowgroup_ctr,
  163582. (JDIMENSION) DCTSIZE);
  163583. /* Return to application if we need more data to fill the iMCU row. */
  163584. if (main->rowgroup_ctr < DCTSIZE)
  163585. return;
  163586. }
  163587. /* Emit data, unless this is a sink-only pass. */
  163588. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163589. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163590. /* If compressor did not consume the whole row, then we must need to
  163591. * suspend processing and return to the application. In this situation
  163592. * we pretend we didn't yet consume the last input row; otherwise, if
  163593. * it happened to be the last row of the image, the application would
  163594. * think we were done.
  163595. */
  163596. if (! main->suspended) {
  163597. (*in_row_ctr)--;
  163598. main->suspended = TRUE;
  163599. }
  163600. return;
  163601. }
  163602. /* We did finish the row. Undo our little suspension hack if a previous
  163603. * call suspended; then mark the main buffer empty.
  163604. */
  163605. if (main->suspended) {
  163606. (*in_row_ctr)++;
  163607. main->suspended = FALSE;
  163608. }
  163609. }
  163610. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163611. main->rowgroup_ctr = 0;
  163612. main->cur_iMCU_row++;
  163613. }
  163614. }
  163615. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163616. /*
  163617. * Initialize main buffer controller.
  163618. */
  163619. GLOBAL(void)
  163620. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163621. {
  163622. my_main_ptr main_;
  163623. int ci;
  163624. jpeg_component_info *compptr;
  163625. main_ = (my_main_ptr)
  163626. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163627. SIZEOF(my_main_controller));
  163628. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163629. main_->pub.start_pass = start_pass_main;
  163630. /* We don't need to create a buffer in raw-data mode. */
  163631. if (cinfo->raw_data_in)
  163632. return;
  163633. /* Create the buffer. It holds downsampled data, so each component
  163634. * may be of a different size.
  163635. */
  163636. if (need_full_buffer) {
  163637. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163638. /* Allocate a full-image virtual array for each component */
  163639. /* Note we pad the bottom to a multiple of the iMCU height */
  163640. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163641. ci++, compptr++) {
  163642. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163643. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163644. compptr->width_in_blocks * DCTSIZE,
  163645. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163646. (long) compptr->v_samp_factor) * DCTSIZE,
  163647. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163648. }
  163649. #else
  163650. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163651. #endif
  163652. } else {
  163653. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163654. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163655. #endif
  163656. /* Allocate a strip buffer for each component */
  163657. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163658. ci++, compptr++) {
  163659. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163660. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163661. compptr->width_in_blocks * DCTSIZE,
  163662. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163663. }
  163664. }
  163665. }
  163666. /*** End of inlined file: jcmainct.c ***/
  163667. /*** Start of inlined file: jcmarker.c ***/
  163668. #define JPEG_INTERNALS
  163669. /* Private state */
  163670. typedef struct {
  163671. struct jpeg_marker_writer pub; /* public fields */
  163672. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163673. } my_marker_writer;
  163674. typedef my_marker_writer * my_marker_ptr;
  163675. /*
  163676. * Basic output routines.
  163677. *
  163678. * Note that we do not support suspension while writing a marker.
  163679. * Therefore, an application using suspension must ensure that there is
  163680. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163681. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163682. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163683. * modes are not supported at all with suspension, so those two are the only
  163684. * points where markers will be written.
  163685. */
  163686. LOCAL(void)
  163687. emit_byte (j_compress_ptr cinfo, int val)
  163688. /* Emit a byte */
  163689. {
  163690. struct jpeg_destination_mgr * dest = cinfo->dest;
  163691. *(dest->next_output_byte)++ = (JOCTET) val;
  163692. if (--dest->free_in_buffer == 0) {
  163693. if (! (*dest->empty_output_buffer) (cinfo))
  163694. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163695. }
  163696. }
  163697. LOCAL(void)
  163698. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163699. /* Emit a marker code */
  163700. {
  163701. emit_byte(cinfo, 0xFF);
  163702. emit_byte(cinfo, (int) mark);
  163703. }
  163704. LOCAL(void)
  163705. emit_2bytes (j_compress_ptr cinfo, int value)
  163706. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163707. {
  163708. emit_byte(cinfo, (value >> 8) & 0xFF);
  163709. emit_byte(cinfo, value & 0xFF);
  163710. }
  163711. /*
  163712. * Routines to write specific marker types.
  163713. */
  163714. LOCAL(int)
  163715. emit_dqt (j_compress_ptr cinfo, int index)
  163716. /* Emit a DQT marker */
  163717. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163718. {
  163719. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163720. int prec;
  163721. int i;
  163722. if (qtbl == NULL)
  163723. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163724. prec = 0;
  163725. for (i = 0; i < DCTSIZE2; i++) {
  163726. if (qtbl->quantval[i] > 255)
  163727. prec = 1;
  163728. }
  163729. if (! qtbl->sent_table) {
  163730. emit_marker(cinfo, M_DQT);
  163731. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163732. emit_byte(cinfo, index + (prec<<4));
  163733. for (i = 0; i < DCTSIZE2; i++) {
  163734. /* The table entries must be emitted in zigzag order. */
  163735. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163736. if (prec)
  163737. emit_byte(cinfo, (int) (qval >> 8));
  163738. emit_byte(cinfo, (int) (qval & 0xFF));
  163739. }
  163740. qtbl->sent_table = TRUE;
  163741. }
  163742. return prec;
  163743. }
  163744. LOCAL(void)
  163745. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163746. /* Emit a DHT marker */
  163747. {
  163748. JHUFF_TBL * htbl;
  163749. int length, i;
  163750. if (is_ac) {
  163751. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163752. index += 0x10; /* output index has AC bit set */
  163753. } else {
  163754. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163755. }
  163756. if (htbl == NULL)
  163757. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163758. if (! htbl->sent_table) {
  163759. emit_marker(cinfo, M_DHT);
  163760. length = 0;
  163761. for (i = 1; i <= 16; i++)
  163762. length += htbl->bits[i];
  163763. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163764. emit_byte(cinfo, index);
  163765. for (i = 1; i <= 16; i++)
  163766. emit_byte(cinfo, htbl->bits[i]);
  163767. for (i = 0; i < length; i++)
  163768. emit_byte(cinfo, htbl->huffval[i]);
  163769. htbl->sent_table = TRUE;
  163770. }
  163771. }
  163772. LOCAL(void)
  163773. emit_dac (j_compress_ptr)
  163774. /* Emit a DAC marker */
  163775. /* Since the useful info is so small, we want to emit all the tables in */
  163776. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163777. {
  163778. #ifdef C_ARITH_CODING_SUPPORTED
  163779. char dc_in_use[NUM_ARITH_TBLS];
  163780. char ac_in_use[NUM_ARITH_TBLS];
  163781. int length, i;
  163782. jpeg_component_info *compptr;
  163783. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163784. dc_in_use[i] = ac_in_use[i] = 0;
  163785. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163786. compptr = cinfo->cur_comp_info[i];
  163787. dc_in_use[compptr->dc_tbl_no] = 1;
  163788. ac_in_use[compptr->ac_tbl_no] = 1;
  163789. }
  163790. length = 0;
  163791. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163792. length += dc_in_use[i] + ac_in_use[i];
  163793. emit_marker(cinfo, M_DAC);
  163794. emit_2bytes(cinfo, length*2 + 2);
  163795. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163796. if (dc_in_use[i]) {
  163797. emit_byte(cinfo, i);
  163798. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163799. }
  163800. if (ac_in_use[i]) {
  163801. emit_byte(cinfo, i + 0x10);
  163802. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163803. }
  163804. }
  163805. #endif /* C_ARITH_CODING_SUPPORTED */
  163806. }
  163807. LOCAL(void)
  163808. emit_dri (j_compress_ptr cinfo)
  163809. /* Emit a DRI marker */
  163810. {
  163811. emit_marker(cinfo, M_DRI);
  163812. emit_2bytes(cinfo, 4); /* fixed length */
  163813. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163814. }
  163815. LOCAL(void)
  163816. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163817. /* Emit a SOF marker */
  163818. {
  163819. int ci;
  163820. jpeg_component_info *compptr;
  163821. emit_marker(cinfo, code);
  163822. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163823. /* Make sure image isn't bigger than SOF field can handle */
  163824. if ((long) cinfo->image_height > 65535L ||
  163825. (long) cinfo->image_width > 65535L)
  163826. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163827. emit_byte(cinfo, cinfo->data_precision);
  163828. emit_2bytes(cinfo, (int) cinfo->image_height);
  163829. emit_2bytes(cinfo, (int) cinfo->image_width);
  163830. emit_byte(cinfo, cinfo->num_components);
  163831. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163832. ci++, compptr++) {
  163833. emit_byte(cinfo, compptr->component_id);
  163834. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163835. emit_byte(cinfo, compptr->quant_tbl_no);
  163836. }
  163837. }
  163838. LOCAL(void)
  163839. emit_sos (j_compress_ptr cinfo)
  163840. /* Emit a SOS marker */
  163841. {
  163842. int i, td, ta;
  163843. jpeg_component_info *compptr;
  163844. emit_marker(cinfo, M_SOS);
  163845. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163846. emit_byte(cinfo, cinfo->comps_in_scan);
  163847. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163848. compptr = cinfo->cur_comp_info[i];
  163849. emit_byte(cinfo, compptr->component_id);
  163850. td = compptr->dc_tbl_no;
  163851. ta = compptr->ac_tbl_no;
  163852. if (cinfo->progressive_mode) {
  163853. /* Progressive mode: only DC or only AC tables are used in one scan;
  163854. * furthermore, Huffman coding of DC refinement uses no table at all.
  163855. * We emit 0 for unused field(s); this is recommended by the P&M text
  163856. * but does not seem to be specified in the standard.
  163857. */
  163858. if (cinfo->Ss == 0) {
  163859. ta = 0; /* DC scan */
  163860. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163861. td = 0; /* no DC table either */
  163862. } else {
  163863. td = 0; /* AC scan */
  163864. }
  163865. }
  163866. emit_byte(cinfo, (td << 4) + ta);
  163867. }
  163868. emit_byte(cinfo, cinfo->Ss);
  163869. emit_byte(cinfo, cinfo->Se);
  163870. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163871. }
  163872. LOCAL(void)
  163873. emit_jfif_app0 (j_compress_ptr cinfo)
  163874. /* Emit a JFIF-compliant APP0 marker */
  163875. {
  163876. /*
  163877. * Length of APP0 block (2 bytes)
  163878. * Block ID (4 bytes - ASCII "JFIF")
  163879. * Zero byte (1 byte to terminate the ID string)
  163880. * Version Major, Minor (2 bytes - major first)
  163881. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163882. * Xdpu (2 bytes - dots per unit horizontal)
  163883. * Ydpu (2 bytes - dots per unit vertical)
  163884. * Thumbnail X size (1 byte)
  163885. * Thumbnail Y size (1 byte)
  163886. */
  163887. emit_marker(cinfo, M_APP0);
  163888. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163889. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163890. emit_byte(cinfo, 0x46);
  163891. emit_byte(cinfo, 0x49);
  163892. emit_byte(cinfo, 0x46);
  163893. emit_byte(cinfo, 0);
  163894. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163895. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163896. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163897. emit_2bytes(cinfo, (int) cinfo->X_density);
  163898. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163899. emit_byte(cinfo, 0); /* No thumbnail image */
  163900. emit_byte(cinfo, 0);
  163901. }
  163902. LOCAL(void)
  163903. emit_adobe_app14 (j_compress_ptr cinfo)
  163904. /* Emit an Adobe APP14 marker */
  163905. {
  163906. /*
  163907. * Length of APP14 block (2 bytes)
  163908. * Block ID (5 bytes - ASCII "Adobe")
  163909. * Version Number (2 bytes - currently 100)
  163910. * Flags0 (2 bytes - currently 0)
  163911. * Flags1 (2 bytes - currently 0)
  163912. * Color transform (1 byte)
  163913. *
  163914. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163915. * now in circulation seem to use Version = 100, so that's what we write.
  163916. *
  163917. * We write the color transform byte as 1 if the JPEG color space is
  163918. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163919. * whether the encoder performed a transformation, which is pretty useless.
  163920. */
  163921. emit_marker(cinfo, M_APP14);
  163922. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163923. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163924. emit_byte(cinfo, 0x64);
  163925. emit_byte(cinfo, 0x6F);
  163926. emit_byte(cinfo, 0x62);
  163927. emit_byte(cinfo, 0x65);
  163928. emit_2bytes(cinfo, 100); /* Version */
  163929. emit_2bytes(cinfo, 0); /* Flags0 */
  163930. emit_2bytes(cinfo, 0); /* Flags1 */
  163931. switch (cinfo->jpeg_color_space) {
  163932. case JCS_YCbCr:
  163933. emit_byte(cinfo, 1); /* Color transform = 1 */
  163934. break;
  163935. case JCS_YCCK:
  163936. emit_byte(cinfo, 2); /* Color transform = 2 */
  163937. break;
  163938. default:
  163939. emit_byte(cinfo, 0); /* Color transform = 0 */
  163940. break;
  163941. }
  163942. }
  163943. /*
  163944. * These routines allow writing an arbitrary marker with parameters.
  163945. * The only intended use is to emit COM or APPn markers after calling
  163946. * write_file_header and before calling write_frame_header.
  163947. * Other uses are not guaranteed to produce desirable results.
  163948. * Counting the parameter bytes properly is the caller's responsibility.
  163949. */
  163950. METHODDEF(void)
  163951. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163952. /* Emit an arbitrary marker header */
  163953. {
  163954. if (datalen > (unsigned int) 65533) /* safety check */
  163955. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163956. emit_marker(cinfo, (JPEG_MARKER) marker);
  163957. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163958. }
  163959. METHODDEF(void)
  163960. write_marker_byte (j_compress_ptr cinfo, int val)
  163961. /* Emit one byte of marker parameters following write_marker_header */
  163962. {
  163963. emit_byte(cinfo, val);
  163964. }
  163965. /*
  163966. * Write datastream header.
  163967. * This consists of an SOI and optional APPn markers.
  163968. * We recommend use of the JFIF marker, but not the Adobe marker,
  163969. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163970. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163971. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163972. * Note that an application can write additional header markers after
  163973. * jpeg_start_compress returns.
  163974. */
  163975. METHODDEF(void)
  163976. write_file_header (j_compress_ptr cinfo)
  163977. {
  163978. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163979. emit_marker(cinfo, M_SOI); /* first the SOI */
  163980. /* SOI is defined to reset restart interval to 0 */
  163981. marker->last_restart_interval = 0;
  163982. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163983. emit_jfif_app0(cinfo);
  163984. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163985. emit_adobe_app14(cinfo);
  163986. }
  163987. /*
  163988. * Write frame header.
  163989. * This consists of DQT and SOFn markers.
  163990. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163991. * This avoids compatibility problems with incorrect implementations that
  163992. * try to error-check the quant table numbers as soon as they see the SOF.
  163993. */
  163994. METHODDEF(void)
  163995. write_frame_header (j_compress_ptr cinfo)
  163996. {
  163997. int ci, prec;
  163998. boolean is_baseline;
  163999. jpeg_component_info *compptr;
  164000. /* Emit DQT for each quantization table.
  164001. * Note that emit_dqt() suppresses any duplicate tables.
  164002. */
  164003. prec = 0;
  164004. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164005. ci++, compptr++) {
  164006. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164007. }
  164008. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164009. /* Check for a non-baseline specification.
  164010. * Note we assume that Huffman table numbers won't be changed later.
  164011. */
  164012. if (cinfo->arith_code || cinfo->progressive_mode ||
  164013. cinfo->data_precision != 8) {
  164014. is_baseline = FALSE;
  164015. } else {
  164016. is_baseline = TRUE;
  164017. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164018. ci++, compptr++) {
  164019. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164020. is_baseline = FALSE;
  164021. }
  164022. if (prec && is_baseline) {
  164023. is_baseline = FALSE;
  164024. /* If it's baseline except for quantizer size, warn the user */
  164025. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164026. }
  164027. }
  164028. /* Emit the proper SOF marker */
  164029. if (cinfo->arith_code) {
  164030. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164031. } else {
  164032. if (cinfo->progressive_mode)
  164033. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164034. else if (is_baseline)
  164035. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164036. else
  164037. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164038. }
  164039. }
  164040. /*
  164041. * Write scan header.
  164042. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164043. * Compressed data will be written following the SOS.
  164044. */
  164045. METHODDEF(void)
  164046. write_scan_header (j_compress_ptr cinfo)
  164047. {
  164048. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164049. int i;
  164050. jpeg_component_info *compptr;
  164051. if (cinfo->arith_code) {
  164052. /* Emit arith conditioning info. We may have some duplication
  164053. * if the file has multiple scans, but it's so small it's hardly
  164054. * worth worrying about.
  164055. */
  164056. emit_dac(cinfo);
  164057. } else {
  164058. /* Emit Huffman tables.
  164059. * Note that emit_dht() suppresses any duplicate tables.
  164060. */
  164061. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164062. compptr = cinfo->cur_comp_info[i];
  164063. if (cinfo->progressive_mode) {
  164064. /* Progressive mode: only DC or only AC tables are used in one scan */
  164065. if (cinfo->Ss == 0) {
  164066. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164067. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164068. } else {
  164069. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164070. }
  164071. } else {
  164072. /* Sequential mode: need both DC and AC tables */
  164073. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164074. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164075. }
  164076. }
  164077. }
  164078. /* Emit DRI if required --- note that DRI value could change for each scan.
  164079. * We avoid wasting space with unnecessary DRIs, however.
  164080. */
  164081. if (cinfo->restart_interval != marker->last_restart_interval) {
  164082. emit_dri(cinfo);
  164083. marker->last_restart_interval = cinfo->restart_interval;
  164084. }
  164085. emit_sos(cinfo);
  164086. }
  164087. /*
  164088. * Write datastream trailer.
  164089. */
  164090. METHODDEF(void)
  164091. write_file_trailer (j_compress_ptr cinfo)
  164092. {
  164093. emit_marker(cinfo, M_EOI);
  164094. }
  164095. /*
  164096. * Write an abbreviated table-specification datastream.
  164097. * This consists of SOI, DQT and DHT tables, and EOI.
  164098. * Any table that is defined and not marked sent_table = TRUE will be
  164099. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164100. */
  164101. METHODDEF(void)
  164102. write_tables_only (j_compress_ptr cinfo)
  164103. {
  164104. int i;
  164105. emit_marker(cinfo, M_SOI);
  164106. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164107. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164108. (void) emit_dqt(cinfo, i);
  164109. }
  164110. if (! cinfo->arith_code) {
  164111. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164112. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164113. emit_dht(cinfo, i, FALSE);
  164114. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164115. emit_dht(cinfo, i, TRUE);
  164116. }
  164117. }
  164118. emit_marker(cinfo, M_EOI);
  164119. }
  164120. /*
  164121. * Initialize the marker writer module.
  164122. */
  164123. GLOBAL(void)
  164124. jinit_marker_writer (j_compress_ptr cinfo)
  164125. {
  164126. my_marker_ptr marker;
  164127. /* Create the subobject */
  164128. marker = (my_marker_ptr)
  164129. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164130. SIZEOF(my_marker_writer));
  164131. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164132. /* Initialize method pointers */
  164133. marker->pub.write_file_header = write_file_header;
  164134. marker->pub.write_frame_header = write_frame_header;
  164135. marker->pub.write_scan_header = write_scan_header;
  164136. marker->pub.write_file_trailer = write_file_trailer;
  164137. marker->pub.write_tables_only = write_tables_only;
  164138. marker->pub.write_marker_header = write_marker_header;
  164139. marker->pub.write_marker_byte = write_marker_byte;
  164140. /* Initialize private state */
  164141. marker->last_restart_interval = 0;
  164142. }
  164143. /*** End of inlined file: jcmarker.c ***/
  164144. /*** Start of inlined file: jcmaster.c ***/
  164145. #define JPEG_INTERNALS
  164146. /* Private state */
  164147. typedef enum {
  164148. main_pass, /* input data, also do first output step */
  164149. huff_opt_pass, /* Huffman code optimization pass */
  164150. output_pass /* data output pass */
  164151. } c_pass_type;
  164152. typedef struct {
  164153. struct jpeg_comp_master pub; /* public fields */
  164154. c_pass_type pass_type; /* the type of the current pass */
  164155. int pass_number; /* # of passes completed */
  164156. int total_passes; /* total # of passes needed */
  164157. int scan_number; /* current index in scan_info[] */
  164158. } my_comp_master;
  164159. typedef my_comp_master * my_master_ptr;
  164160. /*
  164161. * Support routines that do various essential calculations.
  164162. */
  164163. LOCAL(void)
  164164. initial_setup (j_compress_ptr cinfo)
  164165. /* Do computations that are needed before master selection phase */
  164166. {
  164167. int ci;
  164168. jpeg_component_info *compptr;
  164169. long samplesperrow;
  164170. JDIMENSION jd_samplesperrow;
  164171. /* Sanity check on image dimensions */
  164172. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164173. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164174. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164175. /* Make sure image isn't bigger than I can handle */
  164176. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164177. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164178. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164179. /* Width of an input scanline must be representable as JDIMENSION. */
  164180. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164181. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164182. if ((long) jd_samplesperrow != samplesperrow)
  164183. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164184. /* For now, precision must match compiled-in value... */
  164185. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164186. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164187. /* Check that number of components won't exceed internal array sizes */
  164188. if (cinfo->num_components > MAX_COMPONENTS)
  164189. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164190. MAX_COMPONENTS);
  164191. /* Compute maximum sampling factors; check factor validity */
  164192. cinfo->max_h_samp_factor = 1;
  164193. cinfo->max_v_samp_factor = 1;
  164194. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164195. ci++, compptr++) {
  164196. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164197. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164198. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164199. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164200. compptr->h_samp_factor);
  164201. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164202. compptr->v_samp_factor);
  164203. }
  164204. /* Compute dimensions of components */
  164205. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164206. ci++, compptr++) {
  164207. /* Fill in the correct component_index value; don't rely on application */
  164208. compptr->component_index = ci;
  164209. /* For compression, we never do DCT scaling. */
  164210. compptr->DCT_scaled_size = DCTSIZE;
  164211. /* Size in DCT blocks */
  164212. compptr->width_in_blocks = (JDIMENSION)
  164213. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164214. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164215. compptr->height_in_blocks = (JDIMENSION)
  164216. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164217. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164218. /* Size in samples */
  164219. compptr->downsampled_width = (JDIMENSION)
  164220. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164221. (long) cinfo->max_h_samp_factor);
  164222. compptr->downsampled_height = (JDIMENSION)
  164223. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164224. (long) cinfo->max_v_samp_factor);
  164225. /* Mark component needed (this flag isn't actually used for compression) */
  164226. compptr->component_needed = TRUE;
  164227. }
  164228. /* Compute number of fully interleaved MCU rows (number of times that
  164229. * main controller will call coefficient controller).
  164230. */
  164231. cinfo->total_iMCU_rows = (JDIMENSION)
  164232. jdiv_round_up((long) cinfo->image_height,
  164233. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164234. }
  164235. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164236. LOCAL(void)
  164237. validate_script (j_compress_ptr cinfo)
  164238. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164239. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164240. */
  164241. {
  164242. const jpeg_scan_info * scanptr;
  164243. int scanno, ncomps, ci, coefi, thisi;
  164244. int Ss, Se, Ah, Al;
  164245. boolean component_sent[MAX_COMPONENTS];
  164246. #ifdef C_PROGRESSIVE_SUPPORTED
  164247. int * last_bitpos_ptr;
  164248. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164249. /* -1 until that coefficient has been seen; then last Al for it */
  164250. #endif
  164251. if (cinfo->num_scans <= 0)
  164252. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164253. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164254. * for progressive JPEG, no scan can have this.
  164255. */
  164256. scanptr = cinfo->scan_info;
  164257. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164258. #ifdef C_PROGRESSIVE_SUPPORTED
  164259. cinfo->progressive_mode = TRUE;
  164260. last_bitpos_ptr = & last_bitpos[0][0];
  164261. for (ci = 0; ci < cinfo->num_components; ci++)
  164262. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164263. *last_bitpos_ptr++ = -1;
  164264. #else
  164265. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164266. #endif
  164267. } else {
  164268. cinfo->progressive_mode = FALSE;
  164269. for (ci = 0; ci < cinfo->num_components; ci++)
  164270. component_sent[ci] = FALSE;
  164271. }
  164272. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164273. /* Validate component indexes */
  164274. ncomps = scanptr->comps_in_scan;
  164275. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164276. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164277. for (ci = 0; ci < ncomps; ci++) {
  164278. thisi = scanptr->component_index[ci];
  164279. if (thisi < 0 || thisi >= cinfo->num_components)
  164280. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164281. /* Components must appear in SOF order within each scan */
  164282. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164283. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164284. }
  164285. /* Validate progression parameters */
  164286. Ss = scanptr->Ss;
  164287. Se = scanptr->Se;
  164288. Ah = scanptr->Ah;
  164289. Al = scanptr->Al;
  164290. if (cinfo->progressive_mode) {
  164291. #ifdef C_PROGRESSIVE_SUPPORTED
  164292. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164293. * seems wrong: the upper bound ought to depend on data precision.
  164294. * Perhaps they really meant 0..N+1 for N-bit precision.
  164295. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164296. * out-of-range reconstructed DC values during the first DC scan,
  164297. * which might cause problems for some decoders.
  164298. */
  164299. #if BITS_IN_JSAMPLE == 8
  164300. #define MAX_AH_AL 10
  164301. #else
  164302. #define MAX_AH_AL 13
  164303. #endif
  164304. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164305. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164306. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164307. if (Ss == 0) {
  164308. if (Se != 0) /* DC and AC together not OK */
  164309. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164310. } else {
  164311. if (ncomps != 1) /* AC scans must be for only one component */
  164312. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164313. }
  164314. for (ci = 0; ci < ncomps; ci++) {
  164315. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164316. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164317. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164318. for (coefi = Ss; coefi <= Se; coefi++) {
  164319. if (last_bitpos_ptr[coefi] < 0) {
  164320. /* first scan of this coefficient */
  164321. if (Ah != 0)
  164322. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164323. } else {
  164324. /* not first scan */
  164325. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164326. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164327. }
  164328. last_bitpos_ptr[coefi] = Al;
  164329. }
  164330. }
  164331. #endif
  164332. } else {
  164333. /* For sequential JPEG, all progression parameters must be these: */
  164334. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164335. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164336. /* Make sure components are not sent twice */
  164337. for (ci = 0; ci < ncomps; ci++) {
  164338. thisi = scanptr->component_index[ci];
  164339. if (component_sent[thisi])
  164340. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164341. component_sent[thisi] = TRUE;
  164342. }
  164343. }
  164344. }
  164345. /* Now verify that everything got sent. */
  164346. if (cinfo->progressive_mode) {
  164347. #ifdef C_PROGRESSIVE_SUPPORTED
  164348. /* For progressive mode, we only check that at least some DC data
  164349. * got sent for each component; the spec does not require that all bits
  164350. * of all coefficients be transmitted. Would it be wiser to enforce
  164351. * transmission of all coefficient bits??
  164352. */
  164353. for (ci = 0; ci < cinfo->num_components; ci++) {
  164354. if (last_bitpos[ci][0] < 0)
  164355. ERREXIT(cinfo, JERR_MISSING_DATA);
  164356. }
  164357. #endif
  164358. } else {
  164359. for (ci = 0; ci < cinfo->num_components; ci++) {
  164360. if (! component_sent[ci])
  164361. ERREXIT(cinfo, JERR_MISSING_DATA);
  164362. }
  164363. }
  164364. }
  164365. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164366. LOCAL(void)
  164367. select_scan_parameters (j_compress_ptr cinfo)
  164368. /* Set up the scan parameters for the current scan */
  164369. {
  164370. int ci;
  164371. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164372. if (cinfo->scan_info != NULL) {
  164373. /* Prepare for current scan --- the script is already validated */
  164374. my_master_ptr master = (my_master_ptr) cinfo->master;
  164375. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164376. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164377. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164378. cinfo->cur_comp_info[ci] =
  164379. &cinfo->comp_info[scanptr->component_index[ci]];
  164380. }
  164381. cinfo->Ss = scanptr->Ss;
  164382. cinfo->Se = scanptr->Se;
  164383. cinfo->Ah = scanptr->Ah;
  164384. cinfo->Al = scanptr->Al;
  164385. }
  164386. else
  164387. #endif
  164388. {
  164389. /* Prepare for single sequential-JPEG scan containing all components */
  164390. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164391. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164392. MAX_COMPS_IN_SCAN);
  164393. cinfo->comps_in_scan = cinfo->num_components;
  164394. for (ci = 0; ci < cinfo->num_components; ci++) {
  164395. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164396. }
  164397. cinfo->Ss = 0;
  164398. cinfo->Se = DCTSIZE2-1;
  164399. cinfo->Ah = 0;
  164400. cinfo->Al = 0;
  164401. }
  164402. }
  164403. LOCAL(void)
  164404. per_scan_setup (j_compress_ptr cinfo)
  164405. /* Do computations that are needed before processing a JPEG scan */
  164406. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164407. {
  164408. int ci, mcublks, tmp;
  164409. jpeg_component_info *compptr;
  164410. if (cinfo->comps_in_scan == 1) {
  164411. /* Noninterleaved (single-component) scan */
  164412. compptr = cinfo->cur_comp_info[0];
  164413. /* Overall image size in MCUs */
  164414. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164415. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164416. /* For noninterleaved scan, always one block per MCU */
  164417. compptr->MCU_width = 1;
  164418. compptr->MCU_height = 1;
  164419. compptr->MCU_blocks = 1;
  164420. compptr->MCU_sample_width = DCTSIZE;
  164421. compptr->last_col_width = 1;
  164422. /* For noninterleaved scans, it is convenient to define last_row_height
  164423. * as the number of block rows present in the last iMCU row.
  164424. */
  164425. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164426. if (tmp == 0) tmp = compptr->v_samp_factor;
  164427. compptr->last_row_height = tmp;
  164428. /* Prepare array describing MCU composition */
  164429. cinfo->blocks_in_MCU = 1;
  164430. cinfo->MCU_membership[0] = 0;
  164431. } else {
  164432. /* Interleaved (multi-component) scan */
  164433. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164434. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164435. MAX_COMPS_IN_SCAN);
  164436. /* Overall image size in MCUs */
  164437. cinfo->MCUs_per_row = (JDIMENSION)
  164438. jdiv_round_up((long) cinfo->image_width,
  164439. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164440. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164441. jdiv_round_up((long) cinfo->image_height,
  164442. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164443. cinfo->blocks_in_MCU = 0;
  164444. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164445. compptr = cinfo->cur_comp_info[ci];
  164446. /* Sampling factors give # of blocks of component in each MCU */
  164447. compptr->MCU_width = compptr->h_samp_factor;
  164448. compptr->MCU_height = compptr->v_samp_factor;
  164449. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164450. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164451. /* Figure number of non-dummy blocks in last MCU column & row */
  164452. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164453. if (tmp == 0) tmp = compptr->MCU_width;
  164454. compptr->last_col_width = tmp;
  164455. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164456. if (tmp == 0) tmp = compptr->MCU_height;
  164457. compptr->last_row_height = tmp;
  164458. /* Prepare array describing MCU composition */
  164459. mcublks = compptr->MCU_blocks;
  164460. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164461. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164462. while (mcublks-- > 0) {
  164463. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164464. }
  164465. }
  164466. }
  164467. /* Convert restart specified in rows to actual MCU count. */
  164468. /* Note that count must fit in 16 bits, so we provide limiting. */
  164469. if (cinfo->restart_in_rows > 0) {
  164470. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164471. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164472. }
  164473. }
  164474. /*
  164475. * Per-pass setup.
  164476. * This is called at the beginning of each pass. We determine which modules
  164477. * will be active during this pass and give them appropriate start_pass calls.
  164478. * We also set is_last_pass to indicate whether any more passes will be
  164479. * required.
  164480. */
  164481. METHODDEF(void)
  164482. prepare_for_pass (j_compress_ptr cinfo)
  164483. {
  164484. my_master_ptr master = (my_master_ptr) cinfo->master;
  164485. switch (master->pass_type) {
  164486. case main_pass:
  164487. /* Initial pass: will collect input data, and do either Huffman
  164488. * optimization or data output for the first scan.
  164489. */
  164490. select_scan_parameters(cinfo);
  164491. per_scan_setup(cinfo);
  164492. if (! cinfo->raw_data_in) {
  164493. (*cinfo->cconvert->start_pass) (cinfo);
  164494. (*cinfo->downsample->start_pass) (cinfo);
  164495. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164496. }
  164497. (*cinfo->fdct->start_pass) (cinfo);
  164498. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164499. (*cinfo->coef->start_pass) (cinfo,
  164500. (master->total_passes > 1 ?
  164501. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164502. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164503. if (cinfo->optimize_coding) {
  164504. /* No immediate data output; postpone writing frame/scan headers */
  164505. master->pub.call_pass_startup = FALSE;
  164506. } else {
  164507. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164508. master->pub.call_pass_startup = TRUE;
  164509. }
  164510. break;
  164511. #ifdef ENTROPY_OPT_SUPPORTED
  164512. case huff_opt_pass:
  164513. /* Do Huffman optimization for a scan after the first one. */
  164514. select_scan_parameters(cinfo);
  164515. per_scan_setup(cinfo);
  164516. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164517. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164518. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164519. master->pub.call_pass_startup = FALSE;
  164520. break;
  164521. }
  164522. /* Special case: Huffman DC refinement scans need no Huffman table
  164523. * and therefore we can skip the optimization pass for them.
  164524. */
  164525. master->pass_type = output_pass;
  164526. master->pass_number++;
  164527. /*FALLTHROUGH*/
  164528. #endif
  164529. case output_pass:
  164530. /* Do a data-output pass. */
  164531. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164532. if (! cinfo->optimize_coding) {
  164533. select_scan_parameters(cinfo);
  164534. per_scan_setup(cinfo);
  164535. }
  164536. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164537. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164538. /* We emit frame/scan headers now */
  164539. if (master->scan_number == 0)
  164540. (*cinfo->marker->write_frame_header) (cinfo);
  164541. (*cinfo->marker->write_scan_header) (cinfo);
  164542. master->pub.call_pass_startup = FALSE;
  164543. break;
  164544. default:
  164545. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164546. }
  164547. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164548. /* Set up progress monitor's pass info if present */
  164549. if (cinfo->progress != NULL) {
  164550. cinfo->progress->completed_passes = master->pass_number;
  164551. cinfo->progress->total_passes = master->total_passes;
  164552. }
  164553. }
  164554. /*
  164555. * Special start-of-pass hook.
  164556. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164557. * In single-pass processing, we need this hook because we don't want to
  164558. * write frame/scan headers during jpeg_start_compress; we want to let the
  164559. * application write COM markers etc. between jpeg_start_compress and the
  164560. * jpeg_write_scanlines loop.
  164561. * In multi-pass processing, this routine is not used.
  164562. */
  164563. METHODDEF(void)
  164564. pass_startup (j_compress_ptr cinfo)
  164565. {
  164566. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164567. (*cinfo->marker->write_frame_header) (cinfo);
  164568. (*cinfo->marker->write_scan_header) (cinfo);
  164569. }
  164570. /*
  164571. * Finish up at end of pass.
  164572. */
  164573. METHODDEF(void)
  164574. finish_pass_master (j_compress_ptr cinfo)
  164575. {
  164576. my_master_ptr master = (my_master_ptr) cinfo->master;
  164577. /* The entropy coder always needs an end-of-pass call,
  164578. * either to analyze statistics or to flush its output buffer.
  164579. */
  164580. (*cinfo->entropy->finish_pass) (cinfo);
  164581. /* Update state for next pass */
  164582. switch (master->pass_type) {
  164583. case main_pass:
  164584. /* next pass is either output of scan 0 (after optimization)
  164585. * or output of scan 1 (if no optimization).
  164586. */
  164587. master->pass_type = output_pass;
  164588. if (! cinfo->optimize_coding)
  164589. master->scan_number++;
  164590. break;
  164591. case huff_opt_pass:
  164592. /* next pass is always output of current scan */
  164593. master->pass_type = output_pass;
  164594. break;
  164595. case output_pass:
  164596. /* next pass is either optimization or output of next scan */
  164597. if (cinfo->optimize_coding)
  164598. master->pass_type = huff_opt_pass;
  164599. master->scan_number++;
  164600. break;
  164601. }
  164602. master->pass_number++;
  164603. }
  164604. /*
  164605. * Initialize master compression control.
  164606. */
  164607. GLOBAL(void)
  164608. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164609. {
  164610. my_master_ptr master;
  164611. master = (my_master_ptr)
  164612. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164613. SIZEOF(my_comp_master));
  164614. cinfo->master = (struct jpeg_comp_master *) master;
  164615. master->pub.prepare_for_pass = prepare_for_pass;
  164616. master->pub.pass_startup = pass_startup;
  164617. master->pub.finish_pass = finish_pass_master;
  164618. master->pub.is_last_pass = FALSE;
  164619. /* Validate parameters, determine derived values */
  164620. initial_setup(cinfo);
  164621. if (cinfo->scan_info != NULL) {
  164622. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164623. validate_script(cinfo);
  164624. #else
  164625. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164626. #endif
  164627. } else {
  164628. cinfo->progressive_mode = FALSE;
  164629. cinfo->num_scans = 1;
  164630. }
  164631. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164632. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164633. /* Initialize my private state */
  164634. if (transcode_only) {
  164635. /* no main pass in transcoding */
  164636. if (cinfo->optimize_coding)
  164637. master->pass_type = huff_opt_pass;
  164638. else
  164639. master->pass_type = output_pass;
  164640. } else {
  164641. /* for normal compression, first pass is always this type: */
  164642. master->pass_type = main_pass;
  164643. }
  164644. master->scan_number = 0;
  164645. master->pass_number = 0;
  164646. if (cinfo->optimize_coding)
  164647. master->total_passes = cinfo->num_scans * 2;
  164648. else
  164649. master->total_passes = cinfo->num_scans;
  164650. }
  164651. /*** End of inlined file: jcmaster.c ***/
  164652. /*** Start of inlined file: jcomapi.c ***/
  164653. #define JPEG_INTERNALS
  164654. /*
  164655. * Abort processing of a JPEG compression or decompression operation,
  164656. * but don't destroy the object itself.
  164657. *
  164658. * For this, we merely clean up all the nonpermanent memory pools.
  164659. * Note that temp files (virtual arrays) are not allowed to belong to
  164660. * the permanent pool, so we will be able to close all temp files here.
  164661. * Closing a data source or destination, if necessary, is the application's
  164662. * responsibility.
  164663. */
  164664. GLOBAL(void)
  164665. jpeg_abort (j_common_ptr cinfo)
  164666. {
  164667. int pool;
  164668. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164669. if (cinfo->mem == NULL)
  164670. return;
  164671. /* Releasing pools in reverse order might help avoid fragmentation
  164672. * with some (brain-damaged) malloc libraries.
  164673. */
  164674. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164675. (*cinfo->mem->free_pool) (cinfo, pool);
  164676. }
  164677. /* Reset overall state for possible reuse of object */
  164678. if (cinfo->is_decompressor) {
  164679. cinfo->global_state = DSTATE_START;
  164680. /* Try to keep application from accessing now-deleted marker list.
  164681. * A bit kludgy to do it here, but this is the most central place.
  164682. */
  164683. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164684. } else {
  164685. cinfo->global_state = CSTATE_START;
  164686. }
  164687. }
  164688. /*
  164689. * Destruction of a JPEG object.
  164690. *
  164691. * Everything gets deallocated except the master jpeg_compress_struct itself
  164692. * and the error manager struct. Both of these are supplied by the application
  164693. * and must be freed, if necessary, by the application. (Often they are on
  164694. * the stack and so don't need to be freed anyway.)
  164695. * Closing a data source or destination, if necessary, is the application's
  164696. * responsibility.
  164697. */
  164698. GLOBAL(void)
  164699. jpeg_destroy (j_common_ptr cinfo)
  164700. {
  164701. /* We need only tell the memory manager to release everything. */
  164702. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164703. if (cinfo->mem != NULL)
  164704. (*cinfo->mem->self_destruct) (cinfo);
  164705. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164706. cinfo->global_state = 0; /* mark it destroyed */
  164707. }
  164708. /*
  164709. * Convenience routines for allocating quantization and Huffman tables.
  164710. * (Would jutils.c be a more reasonable place to put these?)
  164711. */
  164712. GLOBAL(JQUANT_TBL *)
  164713. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164714. {
  164715. JQUANT_TBL *tbl;
  164716. tbl = (JQUANT_TBL *)
  164717. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164718. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164719. return tbl;
  164720. }
  164721. GLOBAL(JHUFF_TBL *)
  164722. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164723. {
  164724. JHUFF_TBL *tbl;
  164725. tbl = (JHUFF_TBL *)
  164726. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164727. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164728. return tbl;
  164729. }
  164730. /*** End of inlined file: jcomapi.c ***/
  164731. /*** Start of inlined file: jcparam.c ***/
  164732. #define JPEG_INTERNALS
  164733. /*
  164734. * Quantization table setup routines
  164735. */
  164736. GLOBAL(void)
  164737. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164738. const unsigned int *basic_table,
  164739. int scale_factor, boolean force_baseline)
  164740. /* Define a quantization table equal to the basic_table times
  164741. * a scale factor (given as a percentage).
  164742. * If force_baseline is TRUE, the computed quantization table entries
  164743. * are limited to 1..255 for JPEG baseline compatibility.
  164744. */
  164745. {
  164746. JQUANT_TBL ** qtblptr;
  164747. int i;
  164748. long temp;
  164749. /* Safety check to ensure start_compress not called yet. */
  164750. if (cinfo->global_state != CSTATE_START)
  164751. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164752. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164753. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164754. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164755. if (*qtblptr == NULL)
  164756. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164757. for (i = 0; i < DCTSIZE2; i++) {
  164758. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164759. /* limit the values to the valid range */
  164760. if (temp <= 0L) temp = 1L;
  164761. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164762. if (force_baseline && temp > 255L)
  164763. temp = 255L; /* limit to baseline range if requested */
  164764. (*qtblptr)->quantval[i] = (UINT16) temp;
  164765. }
  164766. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164767. (*qtblptr)->sent_table = FALSE;
  164768. }
  164769. GLOBAL(void)
  164770. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164771. boolean force_baseline)
  164772. /* Set or change the 'quality' (quantization) setting, using default tables
  164773. * and a straight percentage-scaling quality scale. In most cases it's better
  164774. * to use jpeg_set_quality (below); this entry point is provided for
  164775. * applications that insist on a linear percentage scaling.
  164776. */
  164777. {
  164778. /* These are the sample quantization tables given in JPEG spec section K.1.
  164779. * The spec says that the values given produce "good" quality, and
  164780. * when divided by 2, "very good" quality.
  164781. */
  164782. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164783. 16, 11, 10, 16, 24, 40, 51, 61,
  164784. 12, 12, 14, 19, 26, 58, 60, 55,
  164785. 14, 13, 16, 24, 40, 57, 69, 56,
  164786. 14, 17, 22, 29, 51, 87, 80, 62,
  164787. 18, 22, 37, 56, 68, 109, 103, 77,
  164788. 24, 35, 55, 64, 81, 104, 113, 92,
  164789. 49, 64, 78, 87, 103, 121, 120, 101,
  164790. 72, 92, 95, 98, 112, 100, 103, 99
  164791. };
  164792. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164793. 17, 18, 24, 47, 99, 99, 99, 99,
  164794. 18, 21, 26, 66, 99, 99, 99, 99,
  164795. 24, 26, 56, 99, 99, 99, 99, 99,
  164796. 47, 66, 99, 99, 99, 99, 99, 99,
  164797. 99, 99, 99, 99, 99, 99, 99, 99,
  164798. 99, 99, 99, 99, 99, 99, 99, 99,
  164799. 99, 99, 99, 99, 99, 99, 99, 99,
  164800. 99, 99, 99, 99, 99, 99, 99, 99
  164801. };
  164802. /* Set up two quantization tables using the specified scaling */
  164803. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164804. scale_factor, force_baseline);
  164805. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164806. scale_factor, force_baseline);
  164807. }
  164808. GLOBAL(int)
  164809. jpeg_quality_scaling (int quality)
  164810. /* Convert a user-specified quality rating to a percentage scaling factor
  164811. * for an underlying quantization table, using our recommended scaling curve.
  164812. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164813. */
  164814. {
  164815. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164816. if (quality <= 0) quality = 1;
  164817. if (quality > 100) quality = 100;
  164818. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164819. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164820. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164821. * to make all the table entries 1 (hence, minimum quantization loss).
  164822. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164823. */
  164824. if (quality < 50)
  164825. quality = 5000 / quality;
  164826. else
  164827. quality = 200 - quality*2;
  164828. return quality;
  164829. }
  164830. GLOBAL(void)
  164831. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164832. /* Set or change the 'quality' (quantization) setting, using default tables.
  164833. * This is the standard quality-adjusting entry point for typical user
  164834. * interfaces; only those who want detailed control over quantization tables
  164835. * would use the preceding three routines directly.
  164836. */
  164837. {
  164838. /* Convert user 0-100 rating to percentage scaling */
  164839. quality = jpeg_quality_scaling(quality);
  164840. /* Set up standard quality tables */
  164841. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164842. }
  164843. /*
  164844. * Huffman table setup routines
  164845. */
  164846. LOCAL(void)
  164847. add_huff_table (j_compress_ptr cinfo,
  164848. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164849. /* Define a Huffman table */
  164850. {
  164851. int nsymbols, len;
  164852. if (*htblptr == NULL)
  164853. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164854. /* Copy the number-of-symbols-of-each-code-length counts */
  164855. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164856. /* Validate the counts. We do this here mainly so we can copy the right
  164857. * number of symbols from the val[] array, without risking marching off
  164858. * the end of memory. jchuff.c will do a more thorough test later.
  164859. */
  164860. nsymbols = 0;
  164861. for (len = 1; len <= 16; len++)
  164862. nsymbols += bits[len];
  164863. if (nsymbols < 1 || nsymbols > 256)
  164864. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164865. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164866. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164867. (*htblptr)->sent_table = FALSE;
  164868. }
  164869. LOCAL(void)
  164870. std_huff_tables (j_compress_ptr cinfo)
  164871. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164872. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164873. {
  164874. static const UINT8 bits_dc_luminance[17] =
  164875. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164876. static const UINT8 val_dc_luminance[] =
  164877. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164878. static const UINT8 bits_dc_chrominance[17] =
  164879. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164880. static const UINT8 val_dc_chrominance[] =
  164881. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164882. static const UINT8 bits_ac_luminance[17] =
  164883. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164884. static const UINT8 val_ac_luminance[] =
  164885. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164886. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164887. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164888. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164889. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164890. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164891. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164892. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164893. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164894. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164895. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164896. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164897. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164898. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164899. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164900. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164901. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164902. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164903. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164904. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164905. 0xf9, 0xfa };
  164906. static const UINT8 bits_ac_chrominance[17] =
  164907. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164908. static const UINT8 val_ac_chrominance[] =
  164909. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164910. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164911. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164912. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164913. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164914. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164915. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164916. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164917. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164918. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164919. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164920. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164921. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164922. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164923. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164924. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164925. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164926. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164927. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164928. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164929. 0xf9, 0xfa };
  164930. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164931. bits_dc_luminance, val_dc_luminance);
  164932. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164933. bits_ac_luminance, val_ac_luminance);
  164934. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164935. bits_dc_chrominance, val_dc_chrominance);
  164936. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164937. bits_ac_chrominance, val_ac_chrominance);
  164938. }
  164939. /*
  164940. * Default parameter setup for compression.
  164941. *
  164942. * Applications that don't choose to use this routine must do their
  164943. * own setup of all these parameters. Alternately, you can call this
  164944. * to establish defaults and then alter parameters selectively. This
  164945. * is the recommended approach since, if we add any new parameters,
  164946. * your code will still work (they'll be set to reasonable defaults).
  164947. */
  164948. GLOBAL(void)
  164949. jpeg_set_defaults (j_compress_ptr cinfo)
  164950. {
  164951. int i;
  164952. /* Safety check to ensure start_compress not called yet. */
  164953. if (cinfo->global_state != CSTATE_START)
  164954. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164955. /* Allocate comp_info array large enough for maximum component count.
  164956. * Array is made permanent in case application wants to compress
  164957. * multiple images at same param settings.
  164958. */
  164959. if (cinfo->comp_info == NULL)
  164960. cinfo->comp_info = (jpeg_component_info *)
  164961. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164962. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164963. /* Initialize everything not dependent on the color space */
  164964. cinfo->data_precision = BITS_IN_JSAMPLE;
  164965. /* Set up two quantization tables using default quality of 75 */
  164966. jpeg_set_quality(cinfo, 75, TRUE);
  164967. /* Set up two Huffman tables */
  164968. std_huff_tables(cinfo);
  164969. /* Initialize default arithmetic coding conditioning */
  164970. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164971. cinfo->arith_dc_L[i] = 0;
  164972. cinfo->arith_dc_U[i] = 1;
  164973. cinfo->arith_ac_K[i] = 5;
  164974. }
  164975. /* Default is no multiple-scan output */
  164976. cinfo->scan_info = NULL;
  164977. cinfo->num_scans = 0;
  164978. /* Expect normal source image, not raw downsampled data */
  164979. cinfo->raw_data_in = FALSE;
  164980. /* Use Huffman coding, not arithmetic coding, by default */
  164981. cinfo->arith_code = FALSE;
  164982. /* By default, don't do extra passes to optimize entropy coding */
  164983. cinfo->optimize_coding = FALSE;
  164984. /* The standard Huffman tables are only valid for 8-bit data precision.
  164985. * If the precision is higher, force optimization on so that usable
  164986. * tables will be computed. This test can be removed if default tables
  164987. * are supplied that are valid for the desired precision.
  164988. */
  164989. if (cinfo->data_precision > 8)
  164990. cinfo->optimize_coding = TRUE;
  164991. /* By default, use the simpler non-cosited sampling alignment */
  164992. cinfo->CCIR601_sampling = FALSE;
  164993. /* No input smoothing */
  164994. cinfo->smoothing_factor = 0;
  164995. /* DCT algorithm preference */
  164996. cinfo->dct_method = JDCT_DEFAULT;
  164997. /* No restart markers */
  164998. cinfo->restart_interval = 0;
  164999. cinfo->restart_in_rows = 0;
  165000. /* Fill in default JFIF marker parameters. Note that whether the marker
  165001. * will actually be written is determined by jpeg_set_colorspace.
  165002. *
  165003. * By default, the library emits JFIF version code 1.01.
  165004. * An application that wants to emit JFIF 1.02 extension markers should set
  165005. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165006. * to 1.02, but there may still be some decoders in use that will complain
  165007. * about that; saying 1.01 should minimize compatibility problems.
  165008. */
  165009. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165010. cinfo->JFIF_minor_version = 1;
  165011. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165012. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165013. cinfo->Y_density = 1;
  165014. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165015. jpeg_default_colorspace(cinfo);
  165016. }
  165017. /*
  165018. * Select an appropriate JPEG colorspace for in_color_space.
  165019. */
  165020. GLOBAL(void)
  165021. jpeg_default_colorspace (j_compress_ptr cinfo)
  165022. {
  165023. switch (cinfo->in_color_space) {
  165024. case JCS_GRAYSCALE:
  165025. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165026. break;
  165027. case JCS_RGB:
  165028. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165029. break;
  165030. case JCS_YCbCr:
  165031. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165032. break;
  165033. case JCS_CMYK:
  165034. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165035. break;
  165036. case JCS_YCCK:
  165037. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165038. break;
  165039. case JCS_UNKNOWN:
  165040. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165041. break;
  165042. default:
  165043. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165044. }
  165045. }
  165046. /*
  165047. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165048. */
  165049. GLOBAL(void)
  165050. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165051. {
  165052. jpeg_component_info * compptr;
  165053. int ci;
  165054. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165055. (compptr = &cinfo->comp_info[index], \
  165056. compptr->component_id = (id), \
  165057. compptr->h_samp_factor = (hsamp), \
  165058. compptr->v_samp_factor = (vsamp), \
  165059. compptr->quant_tbl_no = (quant), \
  165060. compptr->dc_tbl_no = (dctbl), \
  165061. compptr->ac_tbl_no = (actbl) )
  165062. /* Safety check to ensure start_compress not called yet. */
  165063. if (cinfo->global_state != CSTATE_START)
  165064. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165065. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165066. * tables 1 for chrominance components.
  165067. */
  165068. cinfo->jpeg_color_space = colorspace;
  165069. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165070. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165071. switch (colorspace) {
  165072. case JCS_GRAYSCALE:
  165073. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165074. cinfo->num_components = 1;
  165075. /* JFIF specifies component ID 1 */
  165076. SET_COMP(0, 1, 1,1, 0, 0,0);
  165077. break;
  165078. case JCS_RGB:
  165079. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165080. cinfo->num_components = 3;
  165081. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165082. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165083. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165084. break;
  165085. case JCS_YCbCr:
  165086. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165087. cinfo->num_components = 3;
  165088. /* JFIF specifies component IDs 1,2,3 */
  165089. /* We default to 2x2 subsamples of chrominance */
  165090. SET_COMP(0, 1, 2,2, 0, 0,0);
  165091. SET_COMP(1, 2, 1,1, 1, 1,1);
  165092. SET_COMP(2, 3, 1,1, 1, 1,1);
  165093. break;
  165094. case JCS_CMYK:
  165095. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165096. cinfo->num_components = 4;
  165097. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165098. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165099. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165100. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165101. break;
  165102. case JCS_YCCK:
  165103. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165104. cinfo->num_components = 4;
  165105. SET_COMP(0, 1, 2,2, 0, 0,0);
  165106. SET_COMP(1, 2, 1,1, 1, 1,1);
  165107. SET_COMP(2, 3, 1,1, 1, 1,1);
  165108. SET_COMP(3, 4, 2,2, 0, 0,0);
  165109. break;
  165110. case JCS_UNKNOWN:
  165111. cinfo->num_components = cinfo->input_components;
  165112. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165113. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165114. MAX_COMPONENTS);
  165115. for (ci = 0; ci < cinfo->num_components; ci++) {
  165116. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165117. }
  165118. break;
  165119. default:
  165120. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165121. }
  165122. }
  165123. #ifdef C_PROGRESSIVE_SUPPORTED
  165124. LOCAL(jpeg_scan_info *)
  165125. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165126. int Ss, int Se, int Ah, int Al)
  165127. /* Support routine: generate one scan for specified component */
  165128. {
  165129. scanptr->comps_in_scan = 1;
  165130. scanptr->component_index[0] = ci;
  165131. scanptr->Ss = Ss;
  165132. scanptr->Se = Se;
  165133. scanptr->Ah = Ah;
  165134. scanptr->Al = Al;
  165135. scanptr++;
  165136. return scanptr;
  165137. }
  165138. LOCAL(jpeg_scan_info *)
  165139. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165140. int Ss, int Se, int Ah, int Al)
  165141. /* Support routine: generate one scan for each component */
  165142. {
  165143. int ci;
  165144. for (ci = 0; ci < ncomps; ci++) {
  165145. scanptr->comps_in_scan = 1;
  165146. scanptr->component_index[0] = ci;
  165147. scanptr->Ss = Ss;
  165148. scanptr->Se = Se;
  165149. scanptr->Ah = Ah;
  165150. scanptr->Al = Al;
  165151. scanptr++;
  165152. }
  165153. return scanptr;
  165154. }
  165155. LOCAL(jpeg_scan_info *)
  165156. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165157. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165158. {
  165159. int ci;
  165160. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165161. /* Single interleaved DC scan */
  165162. scanptr->comps_in_scan = ncomps;
  165163. for (ci = 0; ci < ncomps; ci++)
  165164. scanptr->component_index[ci] = ci;
  165165. scanptr->Ss = scanptr->Se = 0;
  165166. scanptr->Ah = Ah;
  165167. scanptr->Al = Al;
  165168. scanptr++;
  165169. } else {
  165170. /* Noninterleaved DC scan for each component */
  165171. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165172. }
  165173. return scanptr;
  165174. }
  165175. /*
  165176. * Create a recommended progressive-JPEG script.
  165177. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165178. */
  165179. GLOBAL(void)
  165180. jpeg_simple_progression (j_compress_ptr cinfo)
  165181. {
  165182. int ncomps = cinfo->num_components;
  165183. int nscans;
  165184. jpeg_scan_info * scanptr;
  165185. /* Safety check to ensure start_compress not called yet. */
  165186. if (cinfo->global_state != CSTATE_START)
  165187. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165188. /* Figure space needed for script. Calculation must match code below! */
  165189. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165190. /* Custom script for YCbCr color images. */
  165191. nscans = 10;
  165192. } else {
  165193. /* All-purpose script for other color spaces. */
  165194. if (ncomps > MAX_COMPS_IN_SCAN)
  165195. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165196. else
  165197. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165198. }
  165199. /* Allocate space for script.
  165200. * We need to put it in the permanent pool in case the application performs
  165201. * multiple compressions without changing the settings. To avoid a memory
  165202. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165203. * object, we try to re-use previously allocated space, and we allocate
  165204. * enough space to handle YCbCr even if initially asked for grayscale.
  165205. */
  165206. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165207. cinfo->script_space_size = MAX(nscans, 10);
  165208. cinfo->script_space = (jpeg_scan_info *)
  165209. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165210. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165211. }
  165212. scanptr = cinfo->script_space;
  165213. cinfo->scan_info = scanptr;
  165214. cinfo->num_scans = nscans;
  165215. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165216. /* Custom script for YCbCr color images. */
  165217. /* Initial DC scan */
  165218. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165219. /* Initial AC scan: get some luma data out in a hurry */
  165220. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165221. /* Chroma data is too small to be worth expending many scans on */
  165222. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165223. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165224. /* Complete spectral selection for luma AC */
  165225. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165226. /* Refine next bit of luma AC */
  165227. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165228. /* Finish DC successive approximation */
  165229. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165230. /* Finish AC successive approximation */
  165231. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165232. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165233. /* Luma bottom bit comes last since it's usually largest scan */
  165234. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165235. } else {
  165236. /* All-purpose script for other color spaces. */
  165237. /* Successive approximation first pass */
  165238. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165239. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165240. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165241. /* Successive approximation second pass */
  165242. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165243. /* Successive approximation final pass */
  165244. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165245. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165246. }
  165247. }
  165248. #endif /* C_PROGRESSIVE_SUPPORTED */
  165249. /*** End of inlined file: jcparam.c ***/
  165250. /*** Start of inlined file: jcphuff.c ***/
  165251. #define JPEG_INTERNALS
  165252. #ifdef C_PROGRESSIVE_SUPPORTED
  165253. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165254. typedef struct {
  165255. struct jpeg_entropy_encoder pub; /* public fields */
  165256. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165257. boolean gather_statistics;
  165258. /* Bit-level coding status.
  165259. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165260. */
  165261. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165262. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165263. INT32 put_buffer; /* current bit-accumulation buffer */
  165264. int put_bits; /* # of bits now in it */
  165265. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165266. /* Coding status for DC components */
  165267. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165268. /* Coding status for AC components */
  165269. int ac_tbl_no; /* the table number of the single component */
  165270. unsigned int EOBRUN; /* run length of EOBs */
  165271. unsigned int BE; /* # of buffered correction bits before MCU */
  165272. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165273. /* packing correction bits tightly would save some space but cost time... */
  165274. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165275. int next_restart_num; /* next restart number to write (0-7) */
  165276. /* Pointers to derived tables (these workspaces have image lifespan).
  165277. * Since any one scan codes only DC or only AC, we only need one set
  165278. * of tables, not one for DC and one for AC.
  165279. */
  165280. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165281. /* Statistics tables for optimization; again, one set is enough */
  165282. long * count_ptrs[NUM_HUFF_TBLS];
  165283. } phuff_entropy_encoder;
  165284. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165285. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165286. * buffer can hold. Larger sizes may slightly improve compression, but
  165287. * 1000 is already well into the realm of overkill.
  165288. * The minimum safe size is 64 bits.
  165289. */
  165290. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165291. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165292. * We assume that int right shift is unsigned if INT32 right shift is,
  165293. * which should be safe.
  165294. */
  165295. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165296. #define ISHIFT_TEMPS int ishift_temp;
  165297. #define IRIGHT_SHIFT(x,shft) \
  165298. ((ishift_temp = (x)) < 0 ? \
  165299. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165300. (ishift_temp >> (shft)))
  165301. #else
  165302. #define ISHIFT_TEMPS
  165303. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165304. #endif
  165305. /* Forward declarations */
  165306. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165307. JBLOCKROW *MCU_data));
  165308. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165309. JBLOCKROW *MCU_data));
  165310. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165311. JBLOCKROW *MCU_data));
  165312. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165313. JBLOCKROW *MCU_data));
  165314. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165315. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165316. /*
  165317. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165318. */
  165319. METHODDEF(void)
  165320. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165321. {
  165322. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165323. boolean is_DC_band;
  165324. int ci, tbl;
  165325. jpeg_component_info * compptr;
  165326. entropy->cinfo = cinfo;
  165327. entropy->gather_statistics = gather_statistics;
  165328. is_DC_band = (cinfo->Ss == 0);
  165329. /* We assume jcmaster.c already validated the scan parameters. */
  165330. /* Select execution routines */
  165331. if (cinfo->Ah == 0) {
  165332. if (is_DC_band)
  165333. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165334. else
  165335. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165336. } else {
  165337. if (is_DC_band)
  165338. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165339. else {
  165340. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165341. /* AC refinement needs a correction bit buffer */
  165342. if (entropy->bit_buffer == NULL)
  165343. entropy->bit_buffer = (char *)
  165344. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165345. MAX_CORR_BITS * SIZEOF(char));
  165346. }
  165347. }
  165348. if (gather_statistics)
  165349. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165350. else
  165351. entropy->pub.finish_pass = finish_pass_phuff;
  165352. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165353. * for AC coefficients.
  165354. */
  165355. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165356. compptr = cinfo->cur_comp_info[ci];
  165357. /* Initialize DC predictions to 0 */
  165358. entropy->last_dc_val[ci] = 0;
  165359. /* Get table index */
  165360. if (is_DC_band) {
  165361. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165362. continue;
  165363. tbl = compptr->dc_tbl_no;
  165364. } else {
  165365. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165366. }
  165367. if (gather_statistics) {
  165368. /* Check for invalid table index */
  165369. /* (make_c_derived_tbl does this in the other path) */
  165370. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165371. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165372. /* Allocate and zero the statistics tables */
  165373. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165374. if (entropy->count_ptrs[tbl] == NULL)
  165375. entropy->count_ptrs[tbl] = (long *)
  165376. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165377. 257 * SIZEOF(long));
  165378. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165379. } else {
  165380. /* Compute derived values for Huffman table */
  165381. /* We may do this more than once for a table, but it's not expensive */
  165382. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165383. & entropy->derived_tbls[tbl]);
  165384. }
  165385. }
  165386. /* Initialize AC stuff */
  165387. entropy->EOBRUN = 0;
  165388. entropy->BE = 0;
  165389. /* Initialize bit buffer to empty */
  165390. entropy->put_buffer = 0;
  165391. entropy->put_bits = 0;
  165392. /* Initialize restart stuff */
  165393. entropy->restarts_to_go = cinfo->restart_interval;
  165394. entropy->next_restart_num = 0;
  165395. }
  165396. /* Outputting bytes to the file.
  165397. * NB: these must be called only when actually outputting,
  165398. * that is, entropy->gather_statistics == FALSE.
  165399. */
  165400. /* Emit a byte */
  165401. #define emit_byte(entropy,val) \
  165402. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165403. if (--(entropy)->free_in_buffer == 0) \
  165404. dump_buffer_p(entropy); }
  165405. LOCAL(void)
  165406. dump_buffer_p (phuff_entropy_ptr entropy)
  165407. /* Empty the output buffer; we do not support suspension in this module. */
  165408. {
  165409. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165410. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165411. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165412. /* After a successful buffer dump, must reset buffer pointers */
  165413. entropy->next_output_byte = dest->next_output_byte;
  165414. entropy->free_in_buffer = dest->free_in_buffer;
  165415. }
  165416. /* Outputting bits to the file */
  165417. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165418. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165419. * in one call, and we never retain more than 7 bits in put_buffer
  165420. * between calls, so 24 bits are sufficient.
  165421. */
  165422. INLINE
  165423. LOCAL(void)
  165424. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165425. /* Emit some bits, unless we are in gather mode */
  165426. {
  165427. /* This routine is heavily used, so it's worth coding tightly. */
  165428. register INT32 put_buffer = (INT32) code;
  165429. register int put_bits = entropy->put_bits;
  165430. /* if size is 0, caller used an invalid Huffman table entry */
  165431. if (size == 0)
  165432. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165433. if (entropy->gather_statistics)
  165434. return; /* do nothing if we're only getting stats */
  165435. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165436. put_bits += size; /* new number of bits in buffer */
  165437. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165438. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165439. while (put_bits >= 8) {
  165440. int c = (int) ((put_buffer >> 16) & 0xFF);
  165441. emit_byte(entropy, c);
  165442. if (c == 0xFF) { /* need to stuff a zero byte? */
  165443. emit_byte(entropy, 0);
  165444. }
  165445. put_buffer <<= 8;
  165446. put_bits -= 8;
  165447. }
  165448. entropy->put_buffer = put_buffer; /* update variables */
  165449. entropy->put_bits = put_bits;
  165450. }
  165451. LOCAL(void)
  165452. flush_bits_p (phuff_entropy_ptr entropy)
  165453. {
  165454. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165455. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165456. entropy->put_bits = 0;
  165457. }
  165458. /*
  165459. * Emit (or just count) a Huffman symbol.
  165460. */
  165461. INLINE
  165462. LOCAL(void)
  165463. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165464. {
  165465. if (entropy->gather_statistics)
  165466. entropy->count_ptrs[tbl_no][symbol]++;
  165467. else {
  165468. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165469. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165470. }
  165471. }
  165472. /*
  165473. * Emit bits from a correction bit buffer.
  165474. */
  165475. LOCAL(void)
  165476. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165477. unsigned int nbits)
  165478. {
  165479. if (entropy->gather_statistics)
  165480. return; /* no real work */
  165481. while (nbits > 0) {
  165482. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165483. bufstart++;
  165484. nbits--;
  165485. }
  165486. }
  165487. /*
  165488. * Emit any pending EOBRUN symbol.
  165489. */
  165490. LOCAL(void)
  165491. emit_eobrun (phuff_entropy_ptr entropy)
  165492. {
  165493. register int temp, nbits;
  165494. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165495. temp = entropy->EOBRUN;
  165496. nbits = 0;
  165497. while ((temp >>= 1))
  165498. nbits++;
  165499. /* safety check: shouldn't happen given limited correction-bit buffer */
  165500. if (nbits > 14)
  165501. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165502. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165503. if (nbits)
  165504. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165505. entropy->EOBRUN = 0;
  165506. /* Emit any buffered correction bits */
  165507. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165508. entropy->BE = 0;
  165509. }
  165510. }
  165511. /*
  165512. * Emit a restart marker & resynchronize predictions.
  165513. */
  165514. LOCAL(void)
  165515. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165516. {
  165517. int ci;
  165518. emit_eobrun(entropy);
  165519. if (! entropy->gather_statistics) {
  165520. flush_bits_p(entropy);
  165521. emit_byte(entropy, 0xFF);
  165522. emit_byte(entropy, JPEG_RST0 + restart_num);
  165523. }
  165524. if (entropy->cinfo->Ss == 0) {
  165525. /* Re-initialize DC predictions to 0 */
  165526. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165527. entropy->last_dc_val[ci] = 0;
  165528. } else {
  165529. /* Re-initialize all AC-related fields to 0 */
  165530. entropy->EOBRUN = 0;
  165531. entropy->BE = 0;
  165532. }
  165533. }
  165534. /*
  165535. * MCU encoding for DC initial scan (either spectral selection,
  165536. * or first pass of successive approximation).
  165537. */
  165538. METHODDEF(boolean)
  165539. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165540. {
  165541. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165542. register int temp, temp2;
  165543. register int nbits;
  165544. int blkn, ci;
  165545. int Al = cinfo->Al;
  165546. JBLOCKROW block;
  165547. jpeg_component_info * compptr;
  165548. ISHIFT_TEMPS
  165549. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165550. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165551. /* Emit restart marker if needed */
  165552. if (cinfo->restart_interval)
  165553. if (entropy->restarts_to_go == 0)
  165554. emit_restart_p(entropy, entropy->next_restart_num);
  165555. /* Encode the MCU data blocks */
  165556. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165557. block = MCU_data[blkn];
  165558. ci = cinfo->MCU_membership[blkn];
  165559. compptr = cinfo->cur_comp_info[ci];
  165560. /* Compute the DC value after the required point transform by Al.
  165561. * This is simply an arithmetic right shift.
  165562. */
  165563. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165564. /* DC differences are figured on the point-transformed values. */
  165565. temp = temp2 - entropy->last_dc_val[ci];
  165566. entropy->last_dc_val[ci] = temp2;
  165567. /* Encode the DC coefficient difference per section G.1.2.1 */
  165568. temp2 = temp;
  165569. if (temp < 0) {
  165570. temp = -temp; /* temp is abs value of input */
  165571. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165572. /* This code assumes we are on a two's complement machine */
  165573. temp2--;
  165574. }
  165575. /* Find the number of bits needed for the magnitude of the coefficient */
  165576. nbits = 0;
  165577. while (temp) {
  165578. nbits++;
  165579. temp >>= 1;
  165580. }
  165581. /* Check for out-of-range coefficient values.
  165582. * Since we're encoding a difference, the range limit is twice as much.
  165583. */
  165584. if (nbits > MAX_COEF_BITS+1)
  165585. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165586. /* Count/emit the Huffman-coded symbol for the number of bits */
  165587. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165588. /* Emit that number of bits of the value, if positive, */
  165589. /* or the complement of its magnitude, if negative. */
  165590. if (nbits) /* emit_bits rejects calls with size 0 */
  165591. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165592. }
  165593. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165594. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165595. /* Update restart-interval state too */
  165596. if (cinfo->restart_interval) {
  165597. if (entropy->restarts_to_go == 0) {
  165598. entropy->restarts_to_go = cinfo->restart_interval;
  165599. entropy->next_restart_num++;
  165600. entropy->next_restart_num &= 7;
  165601. }
  165602. entropy->restarts_to_go--;
  165603. }
  165604. return TRUE;
  165605. }
  165606. /*
  165607. * MCU encoding for AC initial scan (either spectral selection,
  165608. * or first pass of successive approximation).
  165609. */
  165610. METHODDEF(boolean)
  165611. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165612. {
  165613. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165614. register int temp, temp2;
  165615. register int nbits;
  165616. register int r, k;
  165617. int Se = cinfo->Se;
  165618. int Al = cinfo->Al;
  165619. JBLOCKROW block;
  165620. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165621. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165622. /* Emit restart marker if needed */
  165623. if (cinfo->restart_interval)
  165624. if (entropy->restarts_to_go == 0)
  165625. emit_restart_p(entropy, entropy->next_restart_num);
  165626. /* Encode the MCU data block */
  165627. block = MCU_data[0];
  165628. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165629. r = 0; /* r = run length of zeros */
  165630. for (k = cinfo->Ss; k <= Se; k++) {
  165631. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165632. r++;
  165633. continue;
  165634. }
  165635. /* We must apply the point transform by Al. For AC coefficients this
  165636. * is an integer division with rounding towards 0. To do this portably
  165637. * in C, we shift after obtaining the absolute value; so the code is
  165638. * interwoven with finding the abs value (temp) and output bits (temp2).
  165639. */
  165640. if (temp < 0) {
  165641. temp = -temp; /* temp is abs value of input */
  165642. temp >>= Al; /* apply the point transform */
  165643. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165644. temp2 = ~temp;
  165645. } else {
  165646. temp >>= Al; /* apply the point transform */
  165647. temp2 = temp;
  165648. }
  165649. /* Watch out for case that nonzero coef is zero after point transform */
  165650. if (temp == 0) {
  165651. r++;
  165652. continue;
  165653. }
  165654. /* Emit any pending EOBRUN */
  165655. if (entropy->EOBRUN > 0)
  165656. emit_eobrun(entropy);
  165657. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165658. while (r > 15) {
  165659. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165660. r -= 16;
  165661. }
  165662. /* Find the number of bits needed for the magnitude of the coefficient */
  165663. nbits = 1; /* there must be at least one 1 bit */
  165664. while ((temp >>= 1))
  165665. nbits++;
  165666. /* Check for out-of-range coefficient values */
  165667. if (nbits > MAX_COEF_BITS)
  165668. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165669. /* Count/emit Huffman symbol for run length / number of bits */
  165670. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165671. /* Emit that number of bits of the value, if positive, */
  165672. /* or the complement of its magnitude, if negative. */
  165673. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165674. r = 0; /* reset zero run length */
  165675. }
  165676. if (r > 0) { /* If there are trailing zeroes, */
  165677. entropy->EOBRUN++; /* count an EOB */
  165678. if (entropy->EOBRUN == 0x7FFF)
  165679. emit_eobrun(entropy); /* force it out to avoid overflow */
  165680. }
  165681. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165682. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165683. /* Update restart-interval state too */
  165684. if (cinfo->restart_interval) {
  165685. if (entropy->restarts_to_go == 0) {
  165686. entropy->restarts_to_go = cinfo->restart_interval;
  165687. entropy->next_restart_num++;
  165688. entropy->next_restart_num &= 7;
  165689. }
  165690. entropy->restarts_to_go--;
  165691. }
  165692. return TRUE;
  165693. }
  165694. /*
  165695. * MCU encoding for DC successive approximation refinement scan.
  165696. * Note: we assume such scans can be multi-component, although the spec
  165697. * is not very clear on the point.
  165698. */
  165699. METHODDEF(boolean)
  165700. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165701. {
  165702. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165703. register int temp;
  165704. int blkn;
  165705. int Al = cinfo->Al;
  165706. JBLOCKROW block;
  165707. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165708. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165709. /* Emit restart marker if needed */
  165710. if (cinfo->restart_interval)
  165711. if (entropy->restarts_to_go == 0)
  165712. emit_restart_p(entropy, entropy->next_restart_num);
  165713. /* Encode the MCU data blocks */
  165714. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165715. block = MCU_data[blkn];
  165716. /* We simply emit the Al'th bit of the DC coefficient value. */
  165717. temp = (*block)[0];
  165718. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165719. }
  165720. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165721. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165722. /* Update restart-interval state too */
  165723. if (cinfo->restart_interval) {
  165724. if (entropy->restarts_to_go == 0) {
  165725. entropy->restarts_to_go = cinfo->restart_interval;
  165726. entropy->next_restart_num++;
  165727. entropy->next_restart_num &= 7;
  165728. }
  165729. entropy->restarts_to_go--;
  165730. }
  165731. return TRUE;
  165732. }
  165733. /*
  165734. * MCU encoding for AC successive approximation refinement scan.
  165735. */
  165736. METHODDEF(boolean)
  165737. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165738. {
  165739. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165740. register int temp;
  165741. register int r, k;
  165742. int EOB;
  165743. char *BR_buffer;
  165744. unsigned int BR;
  165745. int Se = cinfo->Se;
  165746. int Al = cinfo->Al;
  165747. JBLOCKROW block;
  165748. int absvalues[DCTSIZE2];
  165749. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165750. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165751. /* Emit restart marker if needed */
  165752. if (cinfo->restart_interval)
  165753. if (entropy->restarts_to_go == 0)
  165754. emit_restart_p(entropy, entropy->next_restart_num);
  165755. /* Encode the MCU data block */
  165756. block = MCU_data[0];
  165757. /* It is convenient to make a pre-pass to determine the transformed
  165758. * coefficients' absolute values and the EOB position.
  165759. */
  165760. EOB = 0;
  165761. for (k = cinfo->Ss; k <= Se; k++) {
  165762. temp = (*block)[jpeg_natural_order[k]];
  165763. /* We must apply the point transform by Al. For AC coefficients this
  165764. * is an integer division with rounding towards 0. To do this portably
  165765. * in C, we shift after obtaining the absolute value.
  165766. */
  165767. if (temp < 0)
  165768. temp = -temp; /* temp is abs value of input */
  165769. temp >>= Al; /* apply the point transform */
  165770. absvalues[k] = temp; /* save abs value for main pass */
  165771. if (temp == 1)
  165772. EOB = k; /* EOB = index of last newly-nonzero coef */
  165773. }
  165774. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165775. r = 0; /* r = run length of zeros */
  165776. BR = 0; /* BR = count of buffered bits added now */
  165777. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165778. for (k = cinfo->Ss; k <= Se; k++) {
  165779. if ((temp = absvalues[k]) == 0) {
  165780. r++;
  165781. continue;
  165782. }
  165783. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165784. while (r > 15 && k <= EOB) {
  165785. /* emit any pending EOBRUN and the BE correction bits */
  165786. emit_eobrun(entropy);
  165787. /* Emit ZRL */
  165788. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165789. r -= 16;
  165790. /* Emit buffered correction bits that must be associated with ZRL */
  165791. emit_buffered_bits(entropy, BR_buffer, BR);
  165792. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165793. BR = 0;
  165794. }
  165795. /* If the coef was previously nonzero, it only needs a correction bit.
  165796. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165797. * that we also need to test r > 15. But if r > 15, we can only get here
  165798. * if k > EOB, which implies that this coefficient is not 1.
  165799. */
  165800. if (temp > 1) {
  165801. /* The correction bit is the next bit of the absolute value. */
  165802. BR_buffer[BR++] = (char) (temp & 1);
  165803. continue;
  165804. }
  165805. /* Emit any pending EOBRUN and the BE correction bits */
  165806. emit_eobrun(entropy);
  165807. /* Count/emit Huffman symbol for run length / number of bits */
  165808. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165809. /* Emit output bit for newly-nonzero coef */
  165810. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165811. emit_bits_p(entropy, (unsigned int) temp, 1);
  165812. /* Emit buffered correction bits that must be associated with this code */
  165813. emit_buffered_bits(entropy, BR_buffer, BR);
  165814. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165815. BR = 0;
  165816. r = 0; /* reset zero run length */
  165817. }
  165818. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165819. entropy->EOBRUN++; /* count an EOB */
  165820. entropy->BE += BR; /* concat my correction bits to older ones */
  165821. /* We force out the EOB if we risk either:
  165822. * 1. overflow of the EOB counter;
  165823. * 2. overflow of the correction bit buffer during the next MCU.
  165824. */
  165825. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165826. emit_eobrun(entropy);
  165827. }
  165828. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165829. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165830. /* Update restart-interval state too */
  165831. if (cinfo->restart_interval) {
  165832. if (entropy->restarts_to_go == 0) {
  165833. entropy->restarts_to_go = cinfo->restart_interval;
  165834. entropy->next_restart_num++;
  165835. entropy->next_restart_num &= 7;
  165836. }
  165837. entropy->restarts_to_go--;
  165838. }
  165839. return TRUE;
  165840. }
  165841. /*
  165842. * Finish up at the end of a Huffman-compressed progressive scan.
  165843. */
  165844. METHODDEF(void)
  165845. finish_pass_phuff (j_compress_ptr cinfo)
  165846. {
  165847. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165848. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165849. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165850. /* Flush out any buffered data */
  165851. emit_eobrun(entropy);
  165852. flush_bits_p(entropy);
  165853. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165854. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165855. }
  165856. /*
  165857. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165858. */
  165859. METHODDEF(void)
  165860. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165861. {
  165862. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165863. boolean is_DC_band;
  165864. int ci, tbl;
  165865. jpeg_component_info * compptr;
  165866. JHUFF_TBL **htblptr;
  165867. boolean did[NUM_HUFF_TBLS];
  165868. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165869. emit_eobrun(entropy);
  165870. is_DC_band = (cinfo->Ss == 0);
  165871. /* It's important not to apply jpeg_gen_optimal_table more than once
  165872. * per table, because it clobbers the input frequency counts!
  165873. */
  165874. MEMZERO(did, SIZEOF(did));
  165875. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165876. compptr = cinfo->cur_comp_info[ci];
  165877. if (is_DC_band) {
  165878. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165879. continue;
  165880. tbl = compptr->dc_tbl_no;
  165881. } else {
  165882. tbl = compptr->ac_tbl_no;
  165883. }
  165884. if (! did[tbl]) {
  165885. if (is_DC_band)
  165886. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165887. else
  165888. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165889. if (*htblptr == NULL)
  165890. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165891. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165892. did[tbl] = TRUE;
  165893. }
  165894. }
  165895. }
  165896. /*
  165897. * Module initialization routine for progressive Huffman entropy encoding.
  165898. */
  165899. GLOBAL(void)
  165900. jinit_phuff_encoder (j_compress_ptr cinfo)
  165901. {
  165902. phuff_entropy_ptr entropy;
  165903. int i;
  165904. entropy = (phuff_entropy_ptr)
  165905. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165906. SIZEOF(phuff_entropy_encoder));
  165907. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165908. entropy->pub.start_pass = start_pass_phuff;
  165909. /* Mark tables unallocated */
  165910. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165911. entropy->derived_tbls[i] = NULL;
  165912. entropy->count_ptrs[i] = NULL;
  165913. }
  165914. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165915. }
  165916. #endif /* C_PROGRESSIVE_SUPPORTED */
  165917. /*** End of inlined file: jcphuff.c ***/
  165918. /*** Start of inlined file: jcprepct.c ***/
  165919. #define JPEG_INTERNALS
  165920. /* At present, jcsample.c can request context rows only for smoothing.
  165921. * In the future, we might also need context rows for CCIR601 sampling
  165922. * or other more-complex downsampling procedures. The code to support
  165923. * context rows should be compiled only if needed.
  165924. */
  165925. #ifdef INPUT_SMOOTHING_SUPPORTED
  165926. #define CONTEXT_ROWS_SUPPORTED
  165927. #endif
  165928. /*
  165929. * For the simple (no-context-row) case, we just need to buffer one
  165930. * row group's worth of pixels for the downsampling step. At the bottom of
  165931. * the image, we pad to a full row group by replicating the last pixel row.
  165932. * The downsampler's last output row is then replicated if needed to pad
  165933. * out to a full iMCU row.
  165934. *
  165935. * When providing context rows, we must buffer three row groups' worth of
  165936. * pixels. Three row groups are physically allocated, but the row pointer
  165937. * arrays are made five row groups high, with the extra pointers above and
  165938. * below "wrapping around" to point to the last and first real row groups.
  165939. * This allows the downsampler to access the proper context rows.
  165940. * At the top and bottom of the image, we create dummy context rows by
  165941. * copying the first or last real pixel row. This copying could be avoided
  165942. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165943. * trouble on the compression side.
  165944. */
  165945. /* Private buffer controller object */
  165946. typedef struct {
  165947. struct jpeg_c_prep_controller pub; /* public fields */
  165948. /* Downsampling input buffer. This buffer holds color-converted data
  165949. * until we have enough to do a downsample step.
  165950. */
  165951. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165952. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165953. int next_buf_row; /* index of next row to store in color_buf */
  165954. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165955. int this_row_group; /* starting row index of group to process */
  165956. int next_buf_stop; /* downsample when we reach this index */
  165957. #endif
  165958. } my_prep_controller;
  165959. typedef my_prep_controller * my_prep_ptr;
  165960. /*
  165961. * Initialize for a processing pass.
  165962. */
  165963. METHODDEF(void)
  165964. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165965. {
  165966. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165967. if (pass_mode != JBUF_PASS_THRU)
  165968. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165969. /* Initialize total-height counter for detecting bottom of image */
  165970. prep->rows_to_go = cinfo->image_height;
  165971. /* Mark the conversion buffer empty */
  165972. prep->next_buf_row = 0;
  165973. #ifdef CONTEXT_ROWS_SUPPORTED
  165974. /* Preset additional state variables for context mode.
  165975. * These aren't used in non-context mode, so we needn't test which mode.
  165976. */
  165977. prep->this_row_group = 0;
  165978. /* Set next_buf_stop to stop after two row groups have been read in. */
  165979. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165980. #endif
  165981. }
  165982. /*
  165983. * Expand an image vertically from height input_rows to height output_rows,
  165984. * by duplicating the bottom row.
  165985. */
  165986. LOCAL(void)
  165987. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165988. int input_rows, int output_rows)
  165989. {
  165990. register int row;
  165991. for (row = input_rows; row < output_rows; row++) {
  165992. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165993. 1, num_cols);
  165994. }
  165995. }
  165996. /*
  165997. * Process some data in the simple no-context case.
  165998. *
  165999. * Preprocessor output data is counted in "row groups". A row group
  166000. * is defined to be v_samp_factor sample rows of each component.
  166001. * Downsampling will produce this much data from each max_v_samp_factor
  166002. * input rows.
  166003. */
  166004. METHODDEF(void)
  166005. pre_process_data (j_compress_ptr cinfo,
  166006. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166007. JDIMENSION in_rows_avail,
  166008. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166009. JDIMENSION out_row_groups_avail)
  166010. {
  166011. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166012. int numrows, ci;
  166013. JDIMENSION inrows;
  166014. jpeg_component_info * compptr;
  166015. while (*in_row_ctr < in_rows_avail &&
  166016. *out_row_group_ctr < out_row_groups_avail) {
  166017. /* Do color conversion to fill the conversion buffer. */
  166018. inrows = in_rows_avail - *in_row_ctr;
  166019. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166020. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166021. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166022. prep->color_buf,
  166023. (JDIMENSION) prep->next_buf_row,
  166024. numrows);
  166025. *in_row_ctr += numrows;
  166026. prep->next_buf_row += numrows;
  166027. prep->rows_to_go -= numrows;
  166028. /* If at bottom of image, pad to fill the conversion buffer. */
  166029. if (prep->rows_to_go == 0 &&
  166030. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166031. for (ci = 0; ci < cinfo->num_components; ci++) {
  166032. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166033. prep->next_buf_row, cinfo->max_v_samp_factor);
  166034. }
  166035. prep->next_buf_row = cinfo->max_v_samp_factor;
  166036. }
  166037. /* If we've filled the conversion buffer, empty it. */
  166038. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166039. (*cinfo->downsample->downsample) (cinfo,
  166040. prep->color_buf, (JDIMENSION) 0,
  166041. output_buf, *out_row_group_ctr);
  166042. prep->next_buf_row = 0;
  166043. (*out_row_group_ctr)++;
  166044. }
  166045. /* If at bottom of image, pad the output to a full iMCU height.
  166046. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166047. */
  166048. if (prep->rows_to_go == 0 &&
  166049. *out_row_group_ctr < out_row_groups_avail) {
  166050. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166051. ci++, compptr++) {
  166052. expand_bottom_edge(output_buf[ci],
  166053. compptr->width_in_blocks * DCTSIZE,
  166054. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166055. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166056. }
  166057. *out_row_group_ctr = out_row_groups_avail;
  166058. break; /* can exit outer loop without test */
  166059. }
  166060. }
  166061. }
  166062. #ifdef CONTEXT_ROWS_SUPPORTED
  166063. /*
  166064. * Process some data in the context case.
  166065. */
  166066. METHODDEF(void)
  166067. pre_process_context (j_compress_ptr cinfo,
  166068. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166069. JDIMENSION in_rows_avail,
  166070. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166071. JDIMENSION out_row_groups_avail)
  166072. {
  166073. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166074. int numrows, ci;
  166075. int buf_height = cinfo->max_v_samp_factor * 3;
  166076. JDIMENSION inrows;
  166077. while (*out_row_group_ctr < out_row_groups_avail) {
  166078. if (*in_row_ctr < in_rows_avail) {
  166079. /* Do color conversion to fill the conversion buffer. */
  166080. inrows = in_rows_avail - *in_row_ctr;
  166081. numrows = prep->next_buf_stop - prep->next_buf_row;
  166082. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166083. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166084. prep->color_buf,
  166085. (JDIMENSION) prep->next_buf_row,
  166086. numrows);
  166087. /* Pad at top of image, if first time through */
  166088. if (prep->rows_to_go == cinfo->image_height) {
  166089. for (ci = 0; ci < cinfo->num_components; ci++) {
  166090. int row;
  166091. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166092. jcopy_sample_rows(prep->color_buf[ci], 0,
  166093. prep->color_buf[ci], -row,
  166094. 1, cinfo->image_width);
  166095. }
  166096. }
  166097. }
  166098. *in_row_ctr += numrows;
  166099. prep->next_buf_row += numrows;
  166100. prep->rows_to_go -= numrows;
  166101. } else {
  166102. /* Return for more data, unless we are at the bottom of the image. */
  166103. if (prep->rows_to_go != 0)
  166104. break;
  166105. /* When at bottom of image, pad to fill the conversion buffer. */
  166106. if (prep->next_buf_row < prep->next_buf_stop) {
  166107. for (ci = 0; ci < cinfo->num_components; ci++) {
  166108. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166109. prep->next_buf_row, prep->next_buf_stop);
  166110. }
  166111. prep->next_buf_row = prep->next_buf_stop;
  166112. }
  166113. }
  166114. /* If we've gotten enough data, downsample a row group. */
  166115. if (prep->next_buf_row == prep->next_buf_stop) {
  166116. (*cinfo->downsample->downsample) (cinfo,
  166117. prep->color_buf,
  166118. (JDIMENSION) prep->this_row_group,
  166119. output_buf, *out_row_group_ctr);
  166120. (*out_row_group_ctr)++;
  166121. /* Advance pointers with wraparound as necessary. */
  166122. prep->this_row_group += cinfo->max_v_samp_factor;
  166123. if (prep->this_row_group >= buf_height)
  166124. prep->this_row_group = 0;
  166125. if (prep->next_buf_row >= buf_height)
  166126. prep->next_buf_row = 0;
  166127. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166128. }
  166129. }
  166130. }
  166131. /*
  166132. * Create the wrapped-around downsampling input buffer needed for context mode.
  166133. */
  166134. LOCAL(void)
  166135. create_context_buffer (j_compress_ptr cinfo)
  166136. {
  166137. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166138. int rgroup_height = cinfo->max_v_samp_factor;
  166139. int ci, i;
  166140. jpeg_component_info * compptr;
  166141. JSAMPARRAY true_buffer, fake_buffer;
  166142. /* Grab enough space for fake row pointers for all the components;
  166143. * we need five row groups' worth of pointers for each component.
  166144. */
  166145. fake_buffer = (JSAMPARRAY)
  166146. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166147. (cinfo->num_components * 5 * rgroup_height) *
  166148. SIZEOF(JSAMPROW));
  166149. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166150. ci++, compptr++) {
  166151. /* Allocate the actual buffer space (3 row groups) for this component.
  166152. * We make the buffer wide enough to allow the downsampler to edge-expand
  166153. * horizontally within the buffer, if it so chooses.
  166154. */
  166155. true_buffer = (*cinfo->mem->alloc_sarray)
  166156. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166157. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166158. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166159. (JDIMENSION) (3 * rgroup_height));
  166160. /* Copy true buffer row pointers into the middle of the fake row array */
  166161. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166162. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166163. /* Fill in the above and below wraparound pointers */
  166164. for (i = 0; i < rgroup_height; i++) {
  166165. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166166. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166167. }
  166168. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166169. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166170. }
  166171. }
  166172. #endif /* CONTEXT_ROWS_SUPPORTED */
  166173. /*
  166174. * Initialize preprocessing controller.
  166175. */
  166176. GLOBAL(void)
  166177. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166178. {
  166179. my_prep_ptr prep;
  166180. int ci;
  166181. jpeg_component_info * compptr;
  166182. if (need_full_buffer) /* safety check */
  166183. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166184. prep = (my_prep_ptr)
  166185. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166186. SIZEOF(my_prep_controller));
  166187. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166188. prep->pub.start_pass = start_pass_prep;
  166189. /* Allocate the color conversion buffer.
  166190. * We make the buffer wide enough to allow the downsampler to edge-expand
  166191. * horizontally within the buffer, if it so chooses.
  166192. */
  166193. if (cinfo->downsample->need_context_rows) {
  166194. /* Set up to provide context rows */
  166195. #ifdef CONTEXT_ROWS_SUPPORTED
  166196. prep->pub.pre_process_data = pre_process_context;
  166197. create_context_buffer(cinfo);
  166198. #else
  166199. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166200. #endif
  166201. } else {
  166202. /* No context, just make it tall enough for one row group */
  166203. prep->pub.pre_process_data = pre_process_data;
  166204. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166205. ci++, compptr++) {
  166206. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166207. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166208. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166209. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166210. (JDIMENSION) cinfo->max_v_samp_factor);
  166211. }
  166212. }
  166213. }
  166214. /*** End of inlined file: jcprepct.c ***/
  166215. /*** Start of inlined file: jcsample.c ***/
  166216. #define JPEG_INTERNALS
  166217. /* Pointer to routine to downsample a single component */
  166218. typedef JMETHOD(void, downsample1_ptr,
  166219. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166220. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166221. /* Private subobject */
  166222. typedef struct {
  166223. struct jpeg_downsampler pub; /* public fields */
  166224. /* Downsampling method pointers, one per component */
  166225. downsample1_ptr methods[MAX_COMPONENTS];
  166226. } my_downsampler;
  166227. typedef my_downsampler * my_downsample_ptr;
  166228. /*
  166229. * Initialize for a downsampling pass.
  166230. */
  166231. METHODDEF(void)
  166232. start_pass_downsample (j_compress_ptr)
  166233. {
  166234. /* no work for now */
  166235. }
  166236. /*
  166237. * Expand a component horizontally from width input_cols to width output_cols,
  166238. * by duplicating the rightmost samples.
  166239. */
  166240. LOCAL(void)
  166241. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166242. JDIMENSION input_cols, JDIMENSION output_cols)
  166243. {
  166244. register JSAMPROW ptr;
  166245. register JSAMPLE pixval;
  166246. register int count;
  166247. int row;
  166248. int numcols = (int) (output_cols - input_cols);
  166249. if (numcols > 0) {
  166250. for (row = 0; row < num_rows; row++) {
  166251. ptr = image_data[row] + input_cols;
  166252. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166253. for (count = numcols; count > 0; count--)
  166254. *ptr++ = pixval;
  166255. }
  166256. }
  166257. }
  166258. /*
  166259. * Do downsampling for a whole row group (all components).
  166260. *
  166261. * In this version we simply downsample each component independently.
  166262. */
  166263. METHODDEF(void)
  166264. sep_downsample (j_compress_ptr cinfo,
  166265. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166266. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166267. {
  166268. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166269. int ci;
  166270. jpeg_component_info * compptr;
  166271. JSAMPARRAY in_ptr, out_ptr;
  166272. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166273. ci++, compptr++) {
  166274. in_ptr = input_buf[ci] + in_row_index;
  166275. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166276. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166277. }
  166278. }
  166279. /*
  166280. * Downsample pixel values of a single component.
  166281. * One row group is processed per call.
  166282. * This version handles arbitrary integral sampling ratios, without smoothing.
  166283. * Note that this version is not actually used for customary sampling ratios.
  166284. */
  166285. METHODDEF(void)
  166286. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166287. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166288. {
  166289. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166290. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166291. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166292. JSAMPROW inptr, outptr;
  166293. INT32 outvalue;
  166294. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166295. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166296. numpix = h_expand * v_expand;
  166297. numpix2 = numpix/2;
  166298. /* Expand input data enough to let all the output samples be generated
  166299. * by the standard loop. Special-casing padded output would be more
  166300. * efficient.
  166301. */
  166302. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166303. cinfo->image_width, output_cols * h_expand);
  166304. inrow = 0;
  166305. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166306. outptr = output_data[outrow];
  166307. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166308. outcol++, outcol_h += h_expand) {
  166309. outvalue = 0;
  166310. for (v = 0; v < v_expand; v++) {
  166311. inptr = input_data[inrow+v] + outcol_h;
  166312. for (h = 0; h < h_expand; h++) {
  166313. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166314. }
  166315. }
  166316. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166317. }
  166318. inrow += v_expand;
  166319. }
  166320. }
  166321. /*
  166322. * Downsample pixel values of a single component.
  166323. * This version handles the special case of a full-size component,
  166324. * without smoothing.
  166325. */
  166326. METHODDEF(void)
  166327. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166328. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166329. {
  166330. /* Copy the data */
  166331. jcopy_sample_rows(input_data, 0, output_data, 0,
  166332. cinfo->max_v_samp_factor, cinfo->image_width);
  166333. /* Edge-expand */
  166334. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166335. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166336. }
  166337. /*
  166338. * Downsample pixel values of a single component.
  166339. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166340. * without smoothing.
  166341. *
  166342. * A note about the "bias" calculations: when rounding fractional values to
  166343. * integer, we do not want to always round 0.5 up to the next integer.
  166344. * If we did that, we'd introduce a noticeable bias towards larger values.
  166345. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166346. * alternate pixel locations (a simple ordered dither pattern).
  166347. */
  166348. METHODDEF(void)
  166349. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166350. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166351. {
  166352. int outrow;
  166353. JDIMENSION outcol;
  166354. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166355. register JSAMPROW inptr, outptr;
  166356. register int bias;
  166357. /* Expand input data enough to let all the output samples be generated
  166358. * by the standard loop. Special-casing padded output would be more
  166359. * efficient.
  166360. */
  166361. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166362. cinfo->image_width, output_cols * 2);
  166363. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166364. outptr = output_data[outrow];
  166365. inptr = input_data[outrow];
  166366. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166367. for (outcol = 0; outcol < output_cols; outcol++) {
  166368. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166369. + bias) >> 1);
  166370. bias ^= 1; /* 0=>1, 1=>0 */
  166371. inptr += 2;
  166372. }
  166373. }
  166374. }
  166375. /*
  166376. * Downsample pixel values of a single component.
  166377. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166378. * without smoothing.
  166379. */
  166380. METHODDEF(void)
  166381. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166382. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166383. {
  166384. int inrow, outrow;
  166385. JDIMENSION outcol;
  166386. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166387. register JSAMPROW inptr0, inptr1, outptr;
  166388. register int bias;
  166389. /* Expand input data enough to let all the output samples be generated
  166390. * by the standard loop. Special-casing padded output would be more
  166391. * efficient.
  166392. */
  166393. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166394. cinfo->image_width, output_cols * 2);
  166395. inrow = 0;
  166396. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166397. outptr = output_data[outrow];
  166398. inptr0 = input_data[inrow];
  166399. inptr1 = input_data[inrow+1];
  166400. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166401. for (outcol = 0; outcol < output_cols; outcol++) {
  166402. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166403. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166404. + bias) >> 2);
  166405. bias ^= 3; /* 1=>2, 2=>1 */
  166406. inptr0 += 2; inptr1 += 2;
  166407. }
  166408. inrow += 2;
  166409. }
  166410. }
  166411. #ifdef INPUT_SMOOTHING_SUPPORTED
  166412. /*
  166413. * Downsample pixel values of a single component.
  166414. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166415. * with smoothing. One row of context is required.
  166416. */
  166417. METHODDEF(void)
  166418. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166419. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166420. {
  166421. int inrow, outrow;
  166422. JDIMENSION colctr;
  166423. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166424. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166425. INT32 membersum, neighsum, memberscale, neighscale;
  166426. /* Expand input data enough to let all the output samples be generated
  166427. * by the standard loop. Special-casing padded output would be more
  166428. * efficient.
  166429. */
  166430. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166431. cinfo->image_width, output_cols * 2);
  166432. /* We don't bother to form the individual "smoothed" input pixel values;
  166433. * we can directly compute the output which is the average of the four
  166434. * smoothed values. Each of the four member pixels contributes a fraction
  166435. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166436. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166437. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166438. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166439. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166440. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166441. * factors are scaled by 2^16 = 65536.
  166442. * Also recall that SF = smoothing_factor / 1024.
  166443. */
  166444. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166445. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166446. inrow = 0;
  166447. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166448. outptr = output_data[outrow];
  166449. inptr0 = input_data[inrow];
  166450. inptr1 = input_data[inrow+1];
  166451. above_ptr = input_data[inrow-1];
  166452. below_ptr = input_data[inrow+2];
  166453. /* Special case for first column: pretend column -1 is same as column 0 */
  166454. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166455. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166456. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166457. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166458. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166459. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166460. neighsum += neighsum;
  166461. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166462. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166463. membersum = membersum * memberscale + neighsum * neighscale;
  166464. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166465. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166466. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166467. /* sum of pixels directly mapped to this output element */
  166468. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166469. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166470. /* sum of edge-neighbor pixels */
  166471. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166472. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166473. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166474. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166475. /* The edge-neighbors count twice as much as corner-neighbors */
  166476. neighsum += neighsum;
  166477. /* Add in the corner-neighbors */
  166478. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166479. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166480. /* form final output scaled up by 2^16 */
  166481. membersum = membersum * memberscale + neighsum * neighscale;
  166482. /* round, descale and output it */
  166483. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166484. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166485. }
  166486. /* Special case for last column */
  166487. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166488. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166489. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166490. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166491. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166492. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166493. neighsum += neighsum;
  166494. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166495. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166496. membersum = membersum * memberscale + neighsum * neighscale;
  166497. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166498. inrow += 2;
  166499. }
  166500. }
  166501. /*
  166502. * Downsample pixel values of a single component.
  166503. * This version handles the special case of a full-size component,
  166504. * with smoothing. One row of context is required.
  166505. */
  166506. METHODDEF(void)
  166507. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166508. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166509. {
  166510. int outrow;
  166511. JDIMENSION colctr;
  166512. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166513. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166514. INT32 membersum, neighsum, memberscale, neighscale;
  166515. int colsum, lastcolsum, nextcolsum;
  166516. /* Expand input data enough to let all the output samples be generated
  166517. * by the standard loop. Special-casing padded output would be more
  166518. * efficient.
  166519. */
  166520. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166521. cinfo->image_width, output_cols);
  166522. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166523. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166524. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166525. * Also recall that SF = smoothing_factor / 1024.
  166526. */
  166527. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166528. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166529. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166530. outptr = output_data[outrow];
  166531. inptr = input_data[outrow];
  166532. above_ptr = input_data[outrow-1];
  166533. below_ptr = input_data[outrow+1];
  166534. /* Special case for first column */
  166535. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166536. GETJSAMPLE(*inptr);
  166537. membersum = GETJSAMPLE(*inptr++);
  166538. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166539. GETJSAMPLE(*inptr);
  166540. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166541. membersum = membersum * memberscale + neighsum * neighscale;
  166542. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166543. lastcolsum = colsum; colsum = nextcolsum;
  166544. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166545. membersum = GETJSAMPLE(*inptr++);
  166546. above_ptr++; below_ptr++;
  166547. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166548. GETJSAMPLE(*inptr);
  166549. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166550. membersum = membersum * memberscale + neighsum * neighscale;
  166551. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166552. lastcolsum = colsum; colsum = nextcolsum;
  166553. }
  166554. /* Special case for last column */
  166555. membersum = GETJSAMPLE(*inptr);
  166556. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166557. membersum = membersum * memberscale + neighsum * neighscale;
  166558. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166559. }
  166560. }
  166561. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166562. /*
  166563. * Module initialization routine for downsampling.
  166564. * Note that we must select a routine for each component.
  166565. */
  166566. GLOBAL(void)
  166567. jinit_downsampler (j_compress_ptr cinfo)
  166568. {
  166569. my_downsample_ptr downsample;
  166570. int ci;
  166571. jpeg_component_info * compptr;
  166572. boolean smoothok = TRUE;
  166573. downsample = (my_downsample_ptr)
  166574. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166575. SIZEOF(my_downsampler));
  166576. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166577. downsample->pub.start_pass = start_pass_downsample;
  166578. downsample->pub.downsample = sep_downsample;
  166579. downsample->pub.need_context_rows = FALSE;
  166580. if (cinfo->CCIR601_sampling)
  166581. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166582. /* Verify we can handle the sampling factors, and set up method pointers */
  166583. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166584. ci++, compptr++) {
  166585. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166586. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166587. #ifdef INPUT_SMOOTHING_SUPPORTED
  166588. if (cinfo->smoothing_factor) {
  166589. downsample->methods[ci] = fullsize_smooth_downsample;
  166590. downsample->pub.need_context_rows = TRUE;
  166591. } else
  166592. #endif
  166593. downsample->methods[ci] = fullsize_downsample;
  166594. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166595. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166596. smoothok = FALSE;
  166597. downsample->methods[ci] = h2v1_downsample;
  166598. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166599. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166600. #ifdef INPUT_SMOOTHING_SUPPORTED
  166601. if (cinfo->smoothing_factor) {
  166602. downsample->methods[ci] = h2v2_smooth_downsample;
  166603. downsample->pub.need_context_rows = TRUE;
  166604. } else
  166605. #endif
  166606. downsample->methods[ci] = h2v2_downsample;
  166607. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166608. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166609. smoothok = FALSE;
  166610. downsample->methods[ci] = int_downsample;
  166611. } else
  166612. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166613. }
  166614. #ifdef INPUT_SMOOTHING_SUPPORTED
  166615. if (cinfo->smoothing_factor && !smoothok)
  166616. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166617. #endif
  166618. }
  166619. /*** End of inlined file: jcsample.c ***/
  166620. /*** Start of inlined file: jctrans.c ***/
  166621. #define JPEG_INTERNALS
  166622. /* Forward declarations */
  166623. LOCAL(void) transencode_master_selection
  166624. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166625. LOCAL(void) transencode_coef_controller
  166626. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166627. /*
  166628. * Compression initialization for writing raw-coefficient data.
  166629. * Before calling this, all parameters and a data destination must be set up.
  166630. * Call jpeg_finish_compress() to actually write the data.
  166631. *
  166632. * The number of passed virtual arrays must match cinfo->num_components.
  166633. * Note that the virtual arrays need not be filled or even realized at
  166634. * the time write_coefficients is called; indeed, if the virtual arrays
  166635. * were requested from this compression object's memory manager, they
  166636. * typically will be realized during this routine and filled afterwards.
  166637. */
  166638. GLOBAL(void)
  166639. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166640. {
  166641. if (cinfo->global_state != CSTATE_START)
  166642. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166643. /* Mark all tables to be written */
  166644. jpeg_suppress_tables(cinfo, FALSE);
  166645. /* (Re)initialize error mgr and destination modules */
  166646. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166647. (*cinfo->dest->init_destination) (cinfo);
  166648. /* Perform master selection of active modules */
  166649. transencode_master_selection(cinfo, coef_arrays);
  166650. /* Wait for jpeg_finish_compress() call */
  166651. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166652. cinfo->global_state = CSTATE_WRCOEFS;
  166653. }
  166654. /*
  166655. * Initialize the compression object with default parameters,
  166656. * then copy from the source object all parameters needed for lossless
  166657. * transcoding. Parameters that can be varied without loss (such as
  166658. * scan script and Huffman optimization) are left in their default states.
  166659. */
  166660. GLOBAL(void)
  166661. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166662. j_compress_ptr dstinfo)
  166663. {
  166664. JQUANT_TBL ** qtblptr;
  166665. jpeg_component_info *incomp, *outcomp;
  166666. JQUANT_TBL *c_quant, *slot_quant;
  166667. int tblno, ci, coefi;
  166668. /* Safety check to ensure start_compress not called yet. */
  166669. if (dstinfo->global_state != CSTATE_START)
  166670. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166671. /* Copy fundamental image dimensions */
  166672. dstinfo->image_width = srcinfo->image_width;
  166673. dstinfo->image_height = srcinfo->image_height;
  166674. dstinfo->input_components = srcinfo->num_components;
  166675. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166676. /* Initialize all parameters to default values */
  166677. jpeg_set_defaults(dstinfo);
  166678. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166679. * Fix it to get the right header markers for the image colorspace.
  166680. */
  166681. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166682. dstinfo->data_precision = srcinfo->data_precision;
  166683. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166684. /* Copy the source's quantization tables. */
  166685. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166686. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166687. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166688. if (*qtblptr == NULL)
  166689. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166690. MEMCOPY((*qtblptr)->quantval,
  166691. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166692. SIZEOF((*qtblptr)->quantval));
  166693. (*qtblptr)->sent_table = FALSE;
  166694. }
  166695. }
  166696. /* Copy the source's per-component info.
  166697. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166698. */
  166699. dstinfo->num_components = srcinfo->num_components;
  166700. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166701. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166702. MAX_COMPONENTS);
  166703. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166704. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166705. outcomp->component_id = incomp->component_id;
  166706. outcomp->h_samp_factor = incomp->h_samp_factor;
  166707. outcomp->v_samp_factor = incomp->v_samp_factor;
  166708. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166709. /* Make sure saved quantization table for component matches the qtable
  166710. * slot. If not, the input file re-used this qtable slot.
  166711. * IJG encoder currently cannot duplicate this.
  166712. */
  166713. tblno = outcomp->quant_tbl_no;
  166714. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166715. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166716. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166717. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166718. c_quant = incomp->quant_table;
  166719. if (c_quant != NULL) {
  166720. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166721. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166722. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166723. }
  166724. }
  166725. /* Note: we do not copy the source's Huffman table assignments;
  166726. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166727. */
  166728. }
  166729. /* Also copy JFIF version and resolution information, if available.
  166730. * Strictly speaking this isn't "critical" info, but it's nearly
  166731. * always appropriate to copy it if available. In particular,
  166732. * if the application chooses to copy JFIF 1.02 extension markers from
  166733. * the source file, we need to copy the version to make sure we don't
  166734. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166735. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166736. */
  166737. if (srcinfo->saw_JFIF_marker) {
  166738. if (srcinfo->JFIF_major_version == 1) {
  166739. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166740. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166741. }
  166742. dstinfo->density_unit = srcinfo->density_unit;
  166743. dstinfo->X_density = srcinfo->X_density;
  166744. dstinfo->Y_density = srcinfo->Y_density;
  166745. }
  166746. }
  166747. /*
  166748. * Master selection of compression modules for transcoding.
  166749. * This substitutes for jcinit.c's initialization of the full compressor.
  166750. */
  166751. LOCAL(void)
  166752. transencode_master_selection (j_compress_ptr cinfo,
  166753. jvirt_barray_ptr * coef_arrays)
  166754. {
  166755. /* Although we don't actually use input_components for transcoding,
  166756. * jcmaster.c's initial_setup will complain if input_components is 0.
  166757. */
  166758. cinfo->input_components = 1;
  166759. /* Initialize master control (includes parameter checking/processing) */
  166760. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166761. /* Entropy encoding: either Huffman or arithmetic coding. */
  166762. if (cinfo->arith_code) {
  166763. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166764. } else {
  166765. if (cinfo->progressive_mode) {
  166766. #ifdef C_PROGRESSIVE_SUPPORTED
  166767. jinit_phuff_encoder(cinfo);
  166768. #else
  166769. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166770. #endif
  166771. } else
  166772. jinit_huff_encoder(cinfo);
  166773. }
  166774. /* We need a special coefficient buffer controller. */
  166775. transencode_coef_controller(cinfo, coef_arrays);
  166776. jinit_marker_writer(cinfo);
  166777. /* We can now tell the memory manager to allocate virtual arrays. */
  166778. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166779. /* Write the datastream header (SOI, JFIF) immediately.
  166780. * Frame and scan headers are postponed till later.
  166781. * This lets application insert special markers after the SOI.
  166782. */
  166783. (*cinfo->marker->write_file_header) (cinfo);
  166784. }
  166785. /*
  166786. * The rest of this file is a special implementation of the coefficient
  166787. * buffer controller. This is similar to jccoefct.c, but it handles only
  166788. * output from presupplied virtual arrays. Furthermore, we generate any
  166789. * dummy padding blocks on-the-fly rather than expecting them to be present
  166790. * in the arrays.
  166791. */
  166792. /* Private buffer controller object */
  166793. typedef struct {
  166794. struct jpeg_c_coef_controller pub; /* public fields */
  166795. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166796. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166797. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166798. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166799. /* Virtual block array for each component. */
  166800. jvirt_barray_ptr * whole_image;
  166801. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166802. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166803. } my_coef_controller2;
  166804. typedef my_coef_controller2 * my_coef_ptr2;
  166805. LOCAL(void)
  166806. start_iMCU_row2 (j_compress_ptr cinfo)
  166807. /* Reset within-iMCU-row counters for a new row */
  166808. {
  166809. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166810. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166811. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166812. * But at the bottom of the image, process only what's left.
  166813. */
  166814. if (cinfo->comps_in_scan > 1) {
  166815. coef->MCU_rows_per_iMCU_row = 1;
  166816. } else {
  166817. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166818. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166819. else
  166820. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166821. }
  166822. coef->mcu_ctr = 0;
  166823. coef->MCU_vert_offset = 0;
  166824. }
  166825. /*
  166826. * Initialize for a processing pass.
  166827. */
  166828. METHODDEF(void)
  166829. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166830. {
  166831. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166832. if (pass_mode != JBUF_CRANK_DEST)
  166833. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166834. coef->iMCU_row_num = 0;
  166835. start_iMCU_row2(cinfo);
  166836. }
  166837. /*
  166838. * Process some data.
  166839. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166840. * per call, ie, v_samp_factor block rows for each component in the scan.
  166841. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166842. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166843. *
  166844. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166845. */
  166846. METHODDEF(boolean)
  166847. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166848. {
  166849. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166850. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166851. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166852. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166853. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166854. JDIMENSION start_col;
  166855. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166856. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166857. JBLOCKROW buffer_ptr;
  166858. jpeg_component_info *compptr;
  166859. /* Align the virtual buffers for the components used in this scan. */
  166860. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166861. compptr = cinfo->cur_comp_info[ci];
  166862. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166863. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166864. coef->iMCU_row_num * compptr->v_samp_factor,
  166865. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166866. }
  166867. /* Loop to process one whole iMCU row */
  166868. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166869. yoffset++) {
  166870. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166871. MCU_col_num++) {
  166872. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166873. blkn = 0; /* index of current DCT block within MCU */
  166874. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166875. compptr = cinfo->cur_comp_info[ci];
  166876. start_col = MCU_col_num * compptr->MCU_width;
  166877. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166878. : compptr->last_col_width;
  166879. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166880. if (coef->iMCU_row_num < last_iMCU_row ||
  166881. yindex+yoffset < compptr->last_row_height) {
  166882. /* Fill in pointers to real blocks in this row */
  166883. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166884. for (xindex = 0; xindex < blockcnt; xindex++)
  166885. MCU_buffer[blkn++] = buffer_ptr++;
  166886. } else {
  166887. /* At bottom of image, need a whole row of dummy blocks */
  166888. xindex = 0;
  166889. }
  166890. /* Fill in any dummy blocks needed in this row.
  166891. * Dummy blocks are filled in the same way as in jccoefct.c:
  166892. * all zeroes in the AC entries, DC entries equal to previous
  166893. * block's DC value. The init routine has already zeroed the
  166894. * AC entries, so we need only set the DC entries correctly.
  166895. */
  166896. for (; xindex < compptr->MCU_width; xindex++) {
  166897. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166898. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166899. blkn++;
  166900. }
  166901. }
  166902. }
  166903. /* Try to write the MCU. */
  166904. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166905. /* Suspension forced; update state counters and exit */
  166906. coef->MCU_vert_offset = yoffset;
  166907. coef->mcu_ctr = MCU_col_num;
  166908. return FALSE;
  166909. }
  166910. }
  166911. /* Completed an MCU row, but perhaps not an iMCU row */
  166912. coef->mcu_ctr = 0;
  166913. }
  166914. /* Completed the iMCU row, advance counters for next one */
  166915. coef->iMCU_row_num++;
  166916. start_iMCU_row2(cinfo);
  166917. return TRUE;
  166918. }
  166919. /*
  166920. * Initialize coefficient buffer controller.
  166921. *
  166922. * Each passed coefficient array must be the right size for that
  166923. * coefficient: width_in_blocks wide and height_in_blocks high,
  166924. * with unitheight at least v_samp_factor.
  166925. */
  166926. LOCAL(void)
  166927. transencode_coef_controller (j_compress_ptr cinfo,
  166928. jvirt_barray_ptr * coef_arrays)
  166929. {
  166930. my_coef_ptr2 coef;
  166931. JBLOCKROW buffer;
  166932. int i;
  166933. coef = (my_coef_ptr2)
  166934. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166935. SIZEOF(my_coef_controller2));
  166936. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166937. coef->pub.start_pass = start_pass_coef2;
  166938. coef->pub.compress_data = compress_output2;
  166939. /* Save pointer to virtual arrays */
  166940. coef->whole_image = coef_arrays;
  166941. /* Allocate and pre-zero space for dummy DCT blocks. */
  166942. buffer = (JBLOCKROW)
  166943. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166944. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166945. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166946. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166947. coef->dummy_buffer[i] = buffer + i;
  166948. }
  166949. }
  166950. /*** End of inlined file: jctrans.c ***/
  166951. /*** Start of inlined file: jdapistd.c ***/
  166952. #define JPEG_INTERNALS
  166953. /* Forward declarations */
  166954. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166955. /*
  166956. * Decompression initialization.
  166957. * jpeg_read_header must be completed before calling this.
  166958. *
  166959. * If a multipass operating mode was selected, this will do all but the
  166960. * last pass, and thus may take a great deal of time.
  166961. *
  166962. * Returns FALSE if suspended. The return value need be inspected only if
  166963. * a suspending data source is used.
  166964. */
  166965. GLOBAL(boolean)
  166966. jpeg_start_decompress (j_decompress_ptr cinfo)
  166967. {
  166968. if (cinfo->global_state == DSTATE_READY) {
  166969. /* First call: initialize master control, select active modules */
  166970. jinit_master_decompress(cinfo);
  166971. if (cinfo->buffered_image) {
  166972. /* No more work here; expecting jpeg_start_output next */
  166973. cinfo->global_state = DSTATE_BUFIMAGE;
  166974. return TRUE;
  166975. }
  166976. cinfo->global_state = DSTATE_PRELOAD;
  166977. }
  166978. if (cinfo->global_state == DSTATE_PRELOAD) {
  166979. /* If file has multiple scans, absorb them all into the coef buffer */
  166980. if (cinfo->inputctl->has_multiple_scans) {
  166981. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166982. for (;;) {
  166983. int retcode;
  166984. /* Call progress monitor hook if present */
  166985. if (cinfo->progress != NULL)
  166986. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166987. /* Absorb some more input */
  166988. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166989. if (retcode == JPEG_SUSPENDED)
  166990. return FALSE;
  166991. if (retcode == JPEG_REACHED_EOI)
  166992. break;
  166993. /* Advance progress counter if appropriate */
  166994. if (cinfo->progress != NULL &&
  166995. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166996. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166997. /* jdmaster underestimated number of scans; ratchet up one scan */
  166998. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166999. }
  167000. }
  167001. }
  167002. #else
  167003. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167004. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167005. }
  167006. cinfo->output_scan_number = cinfo->input_scan_number;
  167007. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167008. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167009. /* Perform any dummy output passes, and set up for the final pass */
  167010. return output_pass_setup(cinfo);
  167011. }
  167012. /*
  167013. * Set up for an output pass, and perform any dummy pass(es) needed.
  167014. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167015. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167016. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167017. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167018. */
  167019. LOCAL(boolean)
  167020. output_pass_setup (j_decompress_ptr cinfo)
  167021. {
  167022. if (cinfo->global_state != DSTATE_PRESCAN) {
  167023. /* First call: do pass setup */
  167024. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167025. cinfo->output_scanline = 0;
  167026. cinfo->global_state = DSTATE_PRESCAN;
  167027. }
  167028. /* Loop over any required dummy passes */
  167029. while (cinfo->master->is_dummy_pass) {
  167030. #ifdef QUANT_2PASS_SUPPORTED
  167031. /* Crank through the dummy pass */
  167032. while (cinfo->output_scanline < cinfo->output_height) {
  167033. JDIMENSION last_scanline;
  167034. /* Call progress monitor hook if present */
  167035. if (cinfo->progress != NULL) {
  167036. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167037. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167038. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167039. }
  167040. /* Process some data */
  167041. last_scanline = cinfo->output_scanline;
  167042. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167043. &cinfo->output_scanline, (JDIMENSION) 0);
  167044. if (cinfo->output_scanline == last_scanline)
  167045. return FALSE; /* No progress made, must suspend */
  167046. }
  167047. /* Finish up dummy pass, and set up for another one */
  167048. (*cinfo->master->finish_output_pass) (cinfo);
  167049. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167050. cinfo->output_scanline = 0;
  167051. #else
  167052. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167053. #endif /* QUANT_2PASS_SUPPORTED */
  167054. }
  167055. /* Ready for application to drive output pass through
  167056. * jpeg_read_scanlines or jpeg_read_raw_data.
  167057. */
  167058. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167059. return TRUE;
  167060. }
  167061. /*
  167062. * Read some scanlines of data from the JPEG decompressor.
  167063. *
  167064. * The return value will be the number of lines actually read.
  167065. * This may be less than the number requested in several cases,
  167066. * including bottom of image, data source suspension, and operating
  167067. * modes that emit multiple scanlines at a time.
  167068. *
  167069. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167070. * this likely signals an application programmer error. However,
  167071. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167072. */
  167073. GLOBAL(JDIMENSION)
  167074. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167075. JDIMENSION max_lines)
  167076. {
  167077. JDIMENSION row_ctr;
  167078. if (cinfo->global_state != DSTATE_SCANNING)
  167079. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167080. if (cinfo->output_scanline >= cinfo->output_height) {
  167081. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167082. return 0;
  167083. }
  167084. /* Call progress monitor hook if present */
  167085. if (cinfo->progress != NULL) {
  167086. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167087. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167088. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167089. }
  167090. /* Process some data */
  167091. row_ctr = 0;
  167092. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167093. cinfo->output_scanline += row_ctr;
  167094. return row_ctr;
  167095. }
  167096. /*
  167097. * Alternate entry point to read raw data.
  167098. * Processes exactly one iMCU row per call, unless suspended.
  167099. */
  167100. GLOBAL(JDIMENSION)
  167101. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167102. JDIMENSION max_lines)
  167103. {
  167104. JDIMENSION lines_per_iMCU_row;
  167105. if (cinfo->global_state != DSTATE_RAW_OK)
  167106. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167107. if (cinfo->output_scanline >= cinfo->output_height) {
  167108. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167109. return 0;
  167110. }
  167111. /* Call progress monitor hook if present */
  167112. if (cinfo->progress != NULL) {
  167113. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167114. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167115. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167116. }
  167117. /* Verify that at least one iMCU row can be returned. */
  167118. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167119. if (max_lines < lines_per_iMCU_row)
  167120. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167121. /* Decompress directly into user's buffer. */
  167122. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167123. return 0; /* suspension forced, can do nothing more */
  167124. /* OK, we processed one iMCU row. */
  167125. cinfo->output_scanline += lines_per_iMCU_row;
  167126. return lines_per_iMCU_row;
  167127. }
  167128. /* Additional entry points for buffered-image mode. */
  167129. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167130. /*
  167131. * Initialize for an output pass in buffered-image mode.
  167132. */
  167133. GLOBAL(boolean)
  167134. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167135. {
  167136. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167137. cinfo->global_state != DSTATE_PRESCAN)
  167138. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167139. /* Limit scan number to valid range */
  167140. if (scan_number <= 0)
  167141. scan_number = 1;
  167142. if (cinfo->inputctl->eoi_reached &&
  167143. scan_number > cinfo->input_scan_number)
  167144. scan_number = cinfo->input_scan_number;
  167145. cinfo->output_scan_number = scan_number;
  167146. /* Perform any dummy output passes, and set up for the real pass */
  167147. return output_pass_setup(cinfo);
  167148. }
  167149. /*
  167150. * Finish up after an output pass in buffered-image mode.
  167151. *
  167152. * Returns FALSE if suspended. The return value need be inspected only if
  167153. * a suspending data source is used.
  167154. */
  167155. GLOBAL(boolean)
  167156. jpeg_finish_output (j_decompress_ptr cinfo)
  167157. {
  167158. if ((cinfo->global_state == DSTATE_SCANNING ||
  167159. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167160. /* Terminate this pass. */
  167161. /* We do not require the whole pass to have been completed. */
  167162. (*cinfo->master->finish_output_pass) (cinfo);
  167163. cinfo->global_state = DSTATE_BUFPOST;
  167164. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167165. /* BUFPOST = repeat call after a suspension, anything else is error */
  167166. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167167. }
  167168. /* Read markers looking for SOS or EOI */
  167169. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167170. ! cinfo->inputctl->eoi_reached) {
  167171. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167172. return FALSE; /* Suspend, come back later */
  167173. }
  167174. cinfo->global_state = DSTATE_BUFIMAGE;
  167175. return TRUE;
  167176. }
  167177. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167178. /*** End of inlined file: jdapistd.c ***/
  167179. /*** Start of inlined file: jdapimin.c ***/
  167180. #define JPEG_INTERNALS
  167181. /*
  167182. * Initialization of a JPEG decompression object.
  167183. * The error manager must already be set up (in case memory manager fails).
  167184. */
  167185. GLOBAL(void)
  167186. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167187. {
  167188. int i;
  167189. /* Guard against version mismatches between library and caller. */
  167190. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167191. if (version != JPEG_LIB_VERSION)
  167192. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167193. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167194. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167195. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167196. /* For debugging purposes, we zero the whole master structure.
  167197. * But the application has already set the err pointer, and may have set
  167198. * client_data, so we have to save and restore those fields.
  167199. * Note: if application hasn't set client_data, tools like Purify may
  167200. * complain here.
  167201. */
  167202. {
  167203. struct jpeg_error_mgr * err = cinfo->err;
  167204. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167205. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167206. cinfo->err = err;
  167207. cinfo->client_data = client_data;
  167208. }
  167209. cinfo->is_decompressor = TRUE;
  167210. /* Initialize a memory manager instance for this object */
  167211. jinit_memory_mgr((j_common_ptr) cinfo);
  167212. /* Zero out pointers to permanent structures. */
  167213. cinfo->progress = NULL;
  167214. cinfo->src = NULL;
  167215. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167216. cinfo->quant_tbl_ptrs[i] = NULL;
  167217. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167218. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167219. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167220. }
  167221. /* Initialize marker processor so application can override methods
  167222. * for COM, APPn markers before calling jpeg_read_header.
  167223. */
  167224. cinfo->marker_list = NULL;
  167225. jinit_marker_reader(cinfo);
  167226. /* And initialize the overall input controller. */
  167227. jinit_input_controller(cinfo);
  167228. /* OK, I'm ready */
  167229. cinfo->global_state = DSTATE_START;
  167230. }
  167231. /*
  167232. * Destruction of a JPEG decompression object
  167233. */
  167234. GLOBAL(void)
  167235. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167236. {
  167237. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167238. }
  167239. /*
  167240. * Abort processing of a JPEG decompression operation,
  167241. * but don't destroy the object itself.
  167242. */
  167243. GLOBAL(void)
  167244. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167245. {
  167246. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167247. }
  167248. /*
  167249. * Set default decompression parameters.
  167250. */
  167251. LOCAL(void)
  167252. default_decompress_parms (j_decompress_ptr cinfo)
  167253. {
  167254. /* Guess the input colorspace, and set output colorspace accordingly. */
  167255. /* (Wish JPEG committee had provided a real way to specify this...) */
  167256. /* Note application may override our guesses. */
  167257. switch (cinfo->num_components) {
  167258. case 1:
  167259. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167260. cinfo->out_color_space = JCS_GRAYSCALE;
  167261. break;
  167262. case 3:
  167263. if (cinfo->saw_JFIF_marker) {
  167264. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167265. } else if (cinfo->saw_Adobe_marker) {
  167266. switch (cinfo->Adobe_transform) {
  167267. case 0:
  167268. cinfo->jpeg_color_space = JCS_RGB;
  167269. break;
  167270. case 1:
  167271. cinfo->jpeg_color_space = JCS_YCbCr;
  167272. break;
  167273. default:
  167274. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167275. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167276. break;
  167277. }
  167278. } else {
  167279. /* Saw no special markers, try to guess from the component IDs */
  167280. int cid0 = cinfo->comp_info[0].component_id;
  167281. int cid1 = cinfo->comp_info[1].component_id;
  167282. int cid2 = cinfo->comp_info[2].component_id;
  167283. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167284. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167285. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167286. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167287. else {
  167288. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167289. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167290. }
  167291. }
  167292. /* Always guess RGB is proper output colorspace. */
  167293. cinfo->out_color_space = JCS_RGB;
  167294. break;
  167295. case 4:
  167296. if (cinfo->saw_Adobe_marker) {
  167297. switch (cinfo->Adobe_transform) {
  167298. case 0:
  167299. cinfo->jpeg_color_space = JCS_CMYK;
  167300. break;
  167301. case 2:
  167302. cinfo->jpeg_color_space = JCS_YCCK;
  167303. break;
  167304. default:
  167305. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167306. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167307. break;
  167308. }
  167309. } else {
  167310. /* No special markers, assume straight CMYK. */
  167311. cinfo->jpeg_color_space = JCS_CMYK;
  167312. }
  167313. cinfo->out_color_space = JCS_CMYK;
  167314. break;
  167315. default:
  167316. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167317. cinfo->out_color_space = JCS_UNKNOWN;
  167318. break;
  167319. }
  167320. /* Set defaults for other decompression parameters. */
  167321. cinfo->scale_num = 1; /* 1:1 scaling */
  167322. cinfo->scale_denom = 1;
  167323. cinfo->output_gamma = 1.0;
  167324. cinfo->buffered_image = FALSE;
  167325. cinfo->raw_data_out = FALSE;
  167326. cinfo->dct_method = JDCT_DEFAULT;
  167327. cinfo->do_fancy_upsampling = TRUE;
  167328. cinfo->do_block_smoothing = TRUE;
  167329. cinfo->quantize_colors = FALSE;
  167330. /* We set these in case application only sets quantize_colors. */
  167331. cinfo->dither_mode = JDITHER_FS;
  167332. #ifdef QUANT_2PASS_SUPPORTED
  167333. cinfo->two_pass_quantize = TRUE;
  167334. #else
  167335. cinfo->two_pass_quantize = FALSE;
  167336. #endif
  167337. cinfo->desired_number_of_colors = 256;
  167338. cinfo->colormap = NULL;
  167339. /* Initialize for no mode change in buffered-image mode. */
  167340. cinfo->enable_1pass_quant = FALSE;
  167341. cinfo->enable_external_quant = FALSE;
  167342. cinfo->enable_2pass_quant = FALSE;
  167343. }
  167344. /*
  167345. * Decompression startup: read start of JPEG datastream to see what's there.
  167346. * Need only initialize JPEG object and supply a data source before calling.
  167347. *
  167348. * This routine will read as far as the first SOS marker (ie, actual start of
  167349. * compressed data), and will save all tables and parameters in the JPEG
  167350. * object. It will also initialize the decompression parameters to default
  167351. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167352. * adjust the decompression parameters and then call jpeg_start_decompress.
  167353. * (Or, if the application only wanted to determine the image parameters,
  167354. * the data need not be decompressed. In that case, call jpeg_abort or
  167355. * jpeg_destroy to release any temporary space.)
  167356. * If an abbreviated (tables only) datastream is presented, the routine will
  167357. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167358. * re-use the JPEG object to read the abbreviated image datastream(s).
  167359. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167360. * The JPEG_SUSPENDED return code only occurs if the data source module
  167361. * requests suspension of the decompressor. In this case the application
  167362. * should load more source data and then re-call jpeg_read_header to resume
  167363. * processing.
  167364. * If a non-suspending data source is used and require_image is TRUE, then the
  167365. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167366. *
  167367. * This routine is now just a front end to jpeg_consume_input, with some
  167368. * extra error checking.
  167369. */
  167370. GLOBAL(int)
  167371. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167372. {
  167373. int retcode;
  167374. if (cinfo->global_state != DSTATE_START &&
  167375. cinfo->global_state != DSTATE_INHEADER)
  167376. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167377. retcode = jpeg_consume_input(cinfo);
  167378. switch (retcode) {
  167379. case JPEG_REACHED_SOS:
  167380. retcode = JPEG_HEADER_OK;
  167381. break;
  167382. case JPEG_REACHED_EOI:
  167383. if (require_image) /* Complain if application wanted an image */
  167384. ERREXIT(cinfo, JERR_NO_IMAGE);
  167385. /* Reset to start state; it would be safer to require the application to
  167386. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167387. * A side effect is to free any temporary memory (there shouldn't be any).
  167388. */
  167389. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167390. retcode = JPEG_HEADER_TABLES_ONLY;
  167391. break;
  167392. case JPEG_SUSPENDED:
  167393. /* no work */
  167394. break;
  167395. }
  167396. return retcode;
  167397. }
  167398. /*
  167399. * Consume data in advance of what the decompressor requires.
  167400. * This can be called at any time once the decompressor object has
  167401. * been created and a data source has been set up.
  167402. *
  167403. * This routine is essentially a state machine that handles a couple
  167404. * of critical state-transition actions, namely initial setup and
  167405. * transition from header scanning to ready-for-start_decompress.
  167406. * All the actual input is done via the input controller's consume_input
  167407. * method.
  167408. */
  167409. GLOBAL(int)
  167410. jpeg_consume_input (j_decompress_ptr cinfo)
  167411. {
  167412. int retcode = JPEG_SUSPENDED;
  167413. /* NB: every possible DSTATE value should be listed in this switch */
  167414. switch (cinfo->global_state) {
  167415. case DSTATE_START:
  167416. /* Start-of-datastream actions: reset appropriate modules */
  167417. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167418. /* Initialize application's data source module */
  167419. (*cinfo->src->init_source) (cinfo);
  167420. cinfo->global_state = DSTATE_INHEADER;
  167421. /*FALLTHROUGH*/
  167422. case DSTATE_INHEADER:
  167423. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167424. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167425. /* Set up default parameters based on header data */
  167426. default_decompress_parms(cinfo);
  167427. /* Set global state: ready for start_decompress */
  167428. cinfo->global_state = DSTATE_READY;
  167429. }
  167430. break;
  167431. case DSTATE_READY:
  167432. /* Can't advance past first SOS until start_decompress is called */
  167433. retcode = JPEG_REACHED_SOS;
  167434. break;
  167435. case DSTATE_PRELOAD:
  167436. case DSTATE_PRESCAN:
  167437. case DSTATE_SCANNING:
  167438. case DSTATE_RAW_OK:
  167439. case DSTATE_BUFIMAGE:
  167440. case DSTATE_BUFPOST:
  167441. case DSTATE_STOPPING:
  167442. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167443. break;
  167444. default:
  167445. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167446. }
  167447. return retcode;
  167448. }
  167449. /*
  167450. * Have we finished reading the input file?
  167451. */
  167452. GLOBAL(boolean)
  167453. jpeg_input_complete (j_decompress_ptr cinfo)
  167454. {
  167455. /* Check for valid jpeg object */
  167456. if (cinfo->global_state < DSTATE_START ||
  167457. cinfo->global_state > DSTATE_STOPPING)
  167458. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167459. return cinfo->inputctl->eoi_reached;
  167460. }
  167461. /*
  167462. * Is there more than one scan?
  167463. */
  167464. GLOBAL(boolean)
  167465. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167466. {
  167467. /* Only valid after jpeg_read_header completes */
  167468. if (cinfo->global_state < DSTATE_READY ||
  167469. cinfo->global_state > DSTATE_STOPPING)
  167470. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167471. return cinfo->inputctl->has_multiple_scans;
  167472. }
  167473. /*
  167474. * Finish JPEG decompression.
  167475. *
  167476. * This will normally just verify the file trailer and release temp storage.
  167477. *
  167478. * Returns FALSE if suspended. The return value need be inspected only if
  167479. * a suspending data source is used.
  167480. */
  167481. GLOBAL(boolean)
  167482. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167483. {
  167484. if ((cinfo->global_state == DSTATE_SCANNING ||
  167485. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167486. /* Terminate final pass of non-buffered mode */
  167487. if (cinfo->output_scanline < cinfo->output_height)
  167488. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167489. (*cinfo->master->finish_output_pass) (cinfo);
  167490. cinfo->global_state = DSTATE_STOPPING;
  167491. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167492. /* Finishing after a buffered-image operation */
  167493. cinfo->global_state = DSTATE_STOPPING;
  167494. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167495. /* STOPPING = repeat call after a suspension, anything else is error */
  167496. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167497. }
  167498. /* Read until EOI */
  167499. while (! cinfo->inputctl->eoi_reached) {
  167500. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167501. return FALSE; /* Suspend, come back later */
  167502. }
  167503. /* Do final cleanup */
  167504. (*cinfo->src->term_source) (cinfo);
  167505. /* We can use jpeg_abort to release memory and reset global_state */
  167506. jpeg_abort((j_common_ptr) cinfo);
  167507. return TRUE;
  167508. }
  167509. /*** End of inlined file: jdapimin.c ***/
  167510. /*** Start of inlined file: jdatasrc.c ***/
  167511. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167512. /*** Start of inlined file: jerror.h ***/
  167513. /*
  167514. * To define the enum list of message codes, include this file without
  167515. * defining macro JMESSAGE. To create a message string table, include it
  167516. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167517. */
  167518. #ifndef JMESSAGE
  167519. #ifndef JERROR_H
  167520. /* First time through, define the enum list */
  167521. #define JMAKE_ENUM_LIST
  167522. #else
  167523. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167524. #define JMESSAGE(code,string)
  167525. #endif /* JERROR_H */
  167526. #endif /* JMESSAGE */
  167527. #ifdef JMAKE_ENUM_LIST
  167528. typedef enum {
  167529. #define JMESSAGE(code,string) code ,
  167530. #endif /* JMAKE_ENUM_LIST */
  167531. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167532. /* For maintenance convenience, list is alphabetical by message code name */
  167533. JMESSAGE(JERR_ARITH_NOTIMPL,
  167534. "Sorry, there are legal restrictions on arithmetic coding")
  167535. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167536. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167537. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167538. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167539. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167540. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167541. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167542. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167543. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167544. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167545. JMESSAGE(JERR_BAD_LIB_VERSION,
  167546. "Wrong JPEG library version: library is %d, caller expects %d")
  167547. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167548. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167549. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167550. JMESSAGE(JERR_BAD_PROGRESSION,
  167551. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167552. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167553. "Invalid progressive parameters at scan script entry %d")
  167554. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167555. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167556. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167557. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167558. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167559. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167560. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167561. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167562. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167563. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167564. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167565. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167566. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167567. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167568. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167569. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167570. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167571. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167572. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167573. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167574. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167575. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167576. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167577. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167578. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167579. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167580. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167581. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167582. "Cannot transcode due to multiple use of quantization table %d")
  167583. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167584. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167585. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167586. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167587. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167588. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167589. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167590. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167591. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167592. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167593. JMESSAGE(JERR_QUANT_COMPONENTS,
  167594. "Cannot quantize more than %d color components")
  167595. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167596. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167597. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167598. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167599. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167600. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167601. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167602. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167603. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167604. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167605. JMESSAGE(JERR_TFILE_WRITE,
  167606. "Write failed on temporary file --- out of disk space?")
  167607. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167608. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167609. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167610. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167611. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167612. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167613. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167614. JMESSAGE(JMSG_VERSION, JVERSION)
  167615. JMESSAGE(JTRC_16BIT_TABLES,
  167616. "Caution: quantization tables are too coarse for baseline JPEG")
  167617. JMESSAGE(JTRC_ADOBE,
  167618. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167619. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167620. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167621. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167622. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167623. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167624. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167625. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167626. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167627. JMESSAGE(JTRC_EOI, "End Of Image")
  167628. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167629. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167630. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167631. "Warning: thumbnail image size does not match data length %u")
  167632. JMESSAGE(JTRC_JFIF_EXTENSION,
  167633. "JFIF extension marker: type 0x%02x, length %u")
  167634. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167635. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167636. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167637. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167638. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167639. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167640. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167641. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167642. JMESSAGE(JTRC_RST, "RST%d")
  167643. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167644. "Smoothing not supported with nonstandard sampling ratios")
  167645. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167646. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167647. JMESSAGE(JTRC_SOI, "Start of Image")
  167648. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167649. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167650. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167651. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167652. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167653. JMESSAGE(JTRC_THUMB_JPEG,
  167654. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167655. JMESSAGE(JTRC_THUMB_PALETTE,
  167656. "JFIF extension marker: palette thumbnail image, length %u")
  167657. JMESSAGE(JTRC_THUMB_RGB,
  167658. "JFIF extension marker: RGB thumbnail image, length %u")
  167659. JMESSAGE(JTRC_UNKNOWN_IDS,
  167660. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167661. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167662. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167663. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167664. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167665. "Inconsistent progression sequence for component %d coefficient %d")
  167666. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167667. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167668. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167669. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167670. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167671. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167672. JMESSAGE(JWRN_MUST_RESYNC,
  167673. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167674. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167675. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167676. #ifdef JMAKE_ENUM_LIST
  167677. JMSG_LASTMSGCODE
  167678. } J_MESSAGE_CODE;
  167679. #undef JMAKE_ENUM_LIST
  167680. #endif /* JMAKE_ENUM_LIST */
  167681. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167682. #undef JMESSAGE
  167683. #ifndef JERROR_H
  167684. #define JERROR_H
  167685. /* Macros to simplify using the error and trace message stuff */
  167686. /* The first parameter is either type of cinfo pointer */
  167687. /* Fatal errors (print message and exit) */
  167688. #define ERREXIT(cinfo,code) \
  167689. ((cinfo)->err->msg_code = (code), \
  167690. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167691. #define ERREXIT1(cinfo,code,p1) \
  167692. ((cinfo)->err->msg_code = (code), \
  167693. (cinfo)->err->msg_parm.i[0] = (p1), \
  167694. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167695. #define ERREXIT2(cinfo,code,p1,p2) \
  167696. ((cinfo)->err->msg_code = (code), \
  167697. (cinfo)->err->msg_parm.i[0] = (p1), \
  167698. (cinfo)->err->msg_parm.i[1] = (p2), \
  167699. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167700. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167701. ((cinfo)->err->msg_code = (code), \
  167702. (cinfo)->err->msg_parm.i[0] = (p1), \
  167703. (cinfo)->err->msg_parm.i[1] = (p2), \
  167704. (cinfo)->err->msg_parm.i[2] = (p3), \
  167705. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167706. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167707. ((cinfo)->err->msg_code = (code), \
  167708. (cinfo)->err->msg_parm.i[0] = (p1), \
  167709. (cinfo)->err->msg_parm.i[1] = (p2), \
  167710. (cinfo)->err->msg_parm.i[2] = (p3), \
  167711. (cinfo)->err->msg_parm.i[3] = (p4), \
  167712. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167713. #define ERREXITS(cinfo,code,str) \
  167714. ((cinfo)->err->msg_code = (code), \
  167715. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167716. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167717. #define MAKESTMT(stuff) do { stuff } while (0)
  167718. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167719. #define WARNMS(cinfo,code) \
  167720. ((cinfo)->err->msg_code = (code), \
  167721. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167722. #define WARNMS1(cinfo,code,p1) \
  167723. ((cinfo)->err->msg_code = (code), \
  167724. (cinfo)->err->msg_parm.i[0] = (p1), \
  167725. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167726. #define WARNMS2(cinfo,code,p1,p2) \
  167727. ((cinfo)->err->msg_code = (code), \
  167728. (cinfo)->err->msg_parm.i[0] = (p1), \
  167729. (cinfo)->err->msg_parm.i[1] = (p2), \
  167730. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167731. /* Informational/debugging messages */
  167732. #define TRACEMS(cinfo,lvl,code) \
  167733. ((cinfo)->err->msg_code = (code), \
  167734. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167735. #define TRACEMS1(cinfo,lvl,code,p1) \
  167736. ((cinfo)->err->msg_code = (code), \
  167737. (cinfo)->err->msg_parm.i[0] = (p1), \
  167738. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167739. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167740. ((cinfo)->err->msg_code = (code), \
  167741. (cinfo)->err->msg_parm.i[0] = (p1), \
  167742. (cinfo)->err->msg_parm.i[1] = (p2), \
  167743. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167744. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167745. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167746. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167747. (cinfo)->err->msg_code = (code); \
  167748. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167749. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167750. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167751. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167752. (cinfo)->err->msg_code = (code); \
  167753. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167754. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167755. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167756. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167757. _mp[4] = (p5); \
  167758. (cinfo)->err->msg_code = (code); \
  167759. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167760. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167761. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167762. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167763. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167764. (cinfo)->err->msg_code = (code); \
  167765. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167766. #define TRACEMSS(cinfo,lvl,code,str) \
  167767. ((cinfo)->err->msg_code = (code), \
  167768. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167769. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167770. #endif /* JERROR_H */
  167771. /*** End of inlined file: jerror.h ***/
  167772. /* Expanded data source object for stdio input */
  167773. typedef struct {
  167774. struct jpeg_source_mgr pub; /* public fields */
  167775. FILE * infile; /* source stream */
  167776. JOCTET * buffer; /* start of buffer */
  167777. boolean start_of_file; /* have we gotten any data yet? */
  167778. } my_source_mgr;
  167779. typedef my_source_mgr * my_src_ptr;
  167780. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167781. /*
  167782. * Initialize source --- called by jpeg_read_header
  167783. * before any data is actually read.
  167784. */
  167785. METHODDEF(void)
  167786. init_source (j_decompress_ptr cinfo)
  167787. {
  167788. my_src_ptr src = (my_src_ptr) cinfo->src;
  167789. /* We reset the empty-input-file flag for each image,
  167790. * but we don't clear the input buffer.
  167791. * This is correct behavior for reading a series of images from one source.
  167792. */
  167793. src->start_of_file = TRUE;
  167794. }
  167795. /*
  167796. * Fill the input buffer --- called whenever buffer is emptied.
  167797. *
  167798. * In typical applications, this should read fresh data into the buffer
  167799. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167800. * reset the pointer & count to the start of the buffer, and return TRUE
  167801. * indicating that the buffer has been reloaded. It is not necessary to
  167802. * fill the buffer entirely, only to obtain at least one more byte.
  167803. *
  167804. * There is no such thing as an EOF return. If the end of the file has been
  167805. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167806. * the buffer. In most cases, generating a warning message and inserting a
  167807. * fake EOI marker is the best course of action --- this will allow the
  167808. * decompressor to output however much of the image is there. However,
  167809. * the resulting error message is misleading if the real problem is an empty
  167810. * input file, so we handle that case specially.
  167811. *
  167812. * In applications that need to be able to suspend compression due to input
  167813. * not being available yet, a FALSE return indicates that no more data can be
  167814. * obtained right now, but more may be forthcoming later. In this situation,
  167815. * the decompressor will return to its caller (with an indication of the
  167816. * number of scanlines it has read, if any). The application should resume
  167817. * decompression after it has loaded more data into the input buffer. Note
  167818. * that there are substantial restrictions on the use of suspension --- see
  167819. * the documentation.
  167820. *
  167821. * When suspending, the decompressor will back up to a convenient restart point
  167822. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167823. * indicate where the restart point will be if the current call returns FALSE.
  167824. * Data beyond this point must be rescanned after resumption, so move it to
  167825. * the front of the buffer rather than discarding it.
  167826. */
  167827. METHODDEF(boolean)
  167828. fill_input_buffer (j_decompress_ptr cinfo)
  167829. {
  167830. my_src_ptr src = (my_src_ptr) cinfo->src;
  167831. size_t nbytes;
  167832. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167833. if (nbytes <= 0) {
  167834. if (src->start_of_file) /* Treat empty input file as fatal error */
  167835. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167836. WARNMS(cinfo, JWRN_JPEG_EOF);
  167837. /* Insert a fake EOI marker */
  167838. src->buffer[0] = (JOCTET) 0xFF;
  167839. src->buffer[1] = (JOCTET) JPEG_EOI;
  167840. nbytes = 2;
  167841. }
  167842. src->pub.next_input_byte = src->buffer;
  167843. src->pub.bytes_in_buffer = nbytes;
  167844. src->start_of_file = FALSE;
  167845. return TRUE;
  167846. }
  167847. /*
  167848. * Skip data --- used to skip over a potentially large amount of
  167849. * uninteresting data (such as an APPn marker).
  167850. *
  167851. * Writers of suspendable-input applications must note that skip_input_data
  167852. * is not granted the right to give a suspension return. If the skip extends
  167853. * beyond the data currently in the buffer, the buffer can be marked empty so
  167854. * that the next read will cause a fill_input_buffer call that can suspend.
  167855. * Arranging for additional bytes to be discarded before reloading the input
  167856. * buffer is the application writer's problem.
  167857. */
  167858. METHODDEF(void)
  167859. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167860. {
  167861. my_src_ptr src = (my_src_ptr) cinfo->src;
  167862. /* Just a dumb implementation for now. Could use fseek() except
  167863. * it doesn't work on pipes. Not clear that being smart is worth
  167864. * any trouble anyway --- large skips are infrequent.
  167865. */
  167866. if (num_bytes > 0) {
  167867. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167868. num_bytes -= (long) src->pub.bytes_in_buffer;
  167869. (void) fill_input_buffer(cinfo);
  167870. /* note we assume that fill_input_buffer will never return FALSE,
  167871. * so suspension need not be handled.
  167872. */
  167873. }
  167874. src->pub.next_input_byte += (size_t) num_bytes;
  167875. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167876. }
  167877. }
  167878. /*
  167879. * An additional method that can be provided by data source modules is the
  167880. * resync_to_restart method for error recovery in the presence of RST markers.
  167881. * For the moment, this source module just uses the default resync method
  167882. * provided by the JPEG library. That method assumes that no backtracking
  167883. * is possible.
  167884. */
  167885. /*
  167886. * Terminate source --- called by jpeg_finish_decompress
  167887. * after all data has been read. Often a no-op.
  167888. *
  167889. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167890. * application must deal with any cleanup that should happen even
  167891. * for error exit.
  167892. */
  167893. METHODDEF(void)
  167894. term_source (j_decompress_ptr)
  167895. {
  167896. /* no work necessary here */
  167897. }
  167898. /*
  167899. * Prepare for input from a stdio stream.
  167900. * The caller must have already opened the stream, and is responsible
  167901. * for closing it after finishing decompression.
  167902. */
  167903. GLOBAL(void)
  167904. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167905. {
  167906. my_src_ptr src;
  167907. /* The source object and input buffer are made permanent so that a series
  167908. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167909. * only before the first one. (If we discarded the buffer at the end of
  167910. * one image, we'd likely lose the start of the next one.)
  167911. * This makes it unsafe to use this manager and a different source
  167912. * manager serially with the same JPEG object. Caveat programmer.
  167913. */
  167914. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167915. cinfo->src = (struct jpeg_source_mgr *)
  167916. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167917. SIZEOF(my_source_mgr));
  167918. src = (my_src_ptr) cinfo->src;
  167919. src->buffer = (JOCTET *)
  167920. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167921. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167922. }
  167923. src = (my_src_ptr) cinfo->src;
  167924. src->pub.init_source = init_source;
  167925. src->pub.fill_input_buffer = fill_input_buffer;
  167926. src->pub.skip_input_data = skip_input_data;
  167927. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167928. src->pub.term_source = term_source;
  167929. src->infile = infile;
  167930. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167931. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167932. }
  167933. /*** End of inlined file: jdatasrc.c ***/
  167934. /*** Start of inlined file: jdcoefct.c ***/
  167935. #define JPEG_INTERNALS
  167936. /* Block smoothing is only applicable for progressive JPEG, so: */
  167937. #ifndef D_PROGRESSIVE_SUPPORTED
  167938. #undef BLOCK_SMOOTHING_SUPPORTED
  167939. #endif
  167940. /* Private buffer controller object */
  167941. typedef struct {
  167942. struct jpeg_d_coef_controller pub; /* public fields */
  167943. /* These variables keep track of the current location of the input side. */
  167944. /* cinfo->input_iMCU_row is also used for this. */
  167945. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167946. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167947. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167948. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167949. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167950. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167951. * and let the entropy decoder write into that workspace each time.
  167952. * (On 80x86, the workspace is FAR even though it's not really very big;
  167953. * this is to keep the module interfaces unchanged when a large coefficient
  167954. * buffer is necessary.)
  167955. * In multi-pass modes, this array points to the current MCU's blocks
  167956. * within the virtual arrays; it is used only by the input side.
  167957. */
  167958. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167959. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167960. /* In multi-pass modes, we need a virtual block array for each component. */
  167961. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167962. #endif
  167963. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167964. /* When doing block smoothing, we latch coefficient Al values here */
  167965. int * coef_bits_latch;
  167966. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167967. #endif
  167968. } my_coef_controller3;
  167969. typedef my_coef_controller3 * my_coef_ptr3;
  167970. /* Forward declarations */
  167971. METHODDEF(int) decompress_onepass
  167972. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167973. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167974. METHODDEF(int) decompress_data
  167975. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167976. #endif
  167977. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167978. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167979. METHODDEF(int) decompress_smooth_data
  167980. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167981. #endif
  167982. LOCAL(void)
  167983. start_iMCU_row3 (j_decompress_ptr cinfo)
  167984. /* Reset within-iMCU-row counters for a new row (input side) */
  167985. {
  167986. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167987. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167988. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167989. * But at the bottom of the image, process only what's left.
  167990. */
  167991. if (cinfo->comps_in_scan > 1) {
  167992. coef->MCU_rows_per_iMCU_row = 1;
  167993. } else {
  167994. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167995. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167996. else
  167997. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167998. }
  167999. coef->MCU_ctr = 0;
  168000. coef->MCU_vert_offset = 0;
  168001. }
  168002. /*
  168003. * Initialize for an input processing pass.
  168004. */
  168005. METHODDEF(void)
  168006. start_input_pass (j_decompress_ptr cinfo)
  168007. {
  168008. cinfo->input_iMCU_row = 0;
  168009. start_iMCU_row3(cinfo);
  168010. }
  168011. /*
  168012. * Initialize for an output processing pass.
  168013. */
  168014. METHODDEF(void)
  168015. start_output_pass (j_decompress_ptr cinfo)
  168016. {
  168017. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168018. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168019. /* If multipass, check to see whether to use block smoothing on this pass */
  168020. if (coef->pub.coef_arrays != NULL) {
  168021. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168022. coef->pub.decompress_data = decompress_smooth_data;
  168023. else
  168024. coef->pub.decompress_data = decompress_data;
  168025. }
  168026. #endif
  168027. cinfo->output_iMCU_row = 0;
  168028. }
  168029. /*
  168030. * Decompress and return some data in the single-pass case.
  168031. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168032. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168033. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168034. *
  168035. * NB: output_buf contains a plane for each component in image,
  168036. * which we index according to the component's SOF position.
  168037. */
  168038. METHODDEF(int)
  168039. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168040. {
  168041. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168042. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168043. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168044. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168045. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168046. JSAMPARRAY output_ptr;
  168047. JDIMENSION start_col, output_col;
  168048. jpeg_component_info *compptr;
  168049. inverse_DCT_method_ptr inverse_DCT;
  168050. /* Loop to process as much as one whole iMCU row */
  168051. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168052. yoffset++) {
  168053. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168054. MCU_col_num++) {
  168055. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168056. jzero_far((void FAR *) coef->MCU_buffer[0],
  168057. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168058. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168059. /* Suspension forced; update state counters and exit */
  168060. coef->MCU_vert_offset = yoffset;
  168061. coef->MCU_ctr = MCU_col_num;
  168062. return JPEG_SUSPENDED;
  168063. }
  168064. /* Determine where data should go in output_buf and do the IDCT thing.
  168065. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168066. * incremented past them!). Note the inner loop relies on having
  168067. * allocated the MCU_buffer[] blocks sequentially.
  168068. */
  168069. blkn = 0; /* index of current DCT block within MCU */
  168070. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168071. compptr = cinfo->cur_comp_info[ci];
  168072. /* Don't bother to IDCT an uninteresting component. */
  168073. if (! compptr->component_needed) {
  168074. blkn += compptr->MCU_blocks;
  168075. continue;
  168076. }
  168077. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168078. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168079. : compptr->last_col_width;
  168080. output_ptr = output_buf[compptr->component_index] +
  168081. yoffset * compptr->DCT_scaled_size;
  168082. start_col = MCU_col_num * compptr->MCU_sample_width;
  168083. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168084. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168085. yoffset+yindex < compptr->last_row_height) {
  168086. output_col = start_col;
  168087. for (xindex = 0; xindex < useful_width; xindex++) {
  168088. (*inverse_DCT) (cinfo, compptr,
  168089. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168090. output_ptr, output_col);
  168091. output_col += compptr->DCT_scaled_size;
  168092. }
  168093. }
  168094. blkn += compptr->MCU_width;
  168095. output_ptr += compptr->DCT_scaled_size;
  168096. }
  168097. }
  168098. }
  168099. /* Completed an MCU row, but perhaps not an iMCU row */
  168100. coef->MCU_ctr = 0;
  168101. }
  168102. /* Completed the iMCU row, advance counters for next one */
  168103. cinfo->output_iMCU_row++;
  168104. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168105. start_iMCU_row3(cinfo);
  168106. return JPEG_ROW_COMPLETED;
  168107. }
  168108. /* Completed the scan */
  168109. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168110. return JPEG_SCAN_COMPLETED;
  168111. }
  168112. /*
  168113. * Dummy consume-input routine for single-pass operation.
  168114. */
  168115. METHODDEF(int)
  168116. dummy_consume_data (j_decompress_ptr)
  168117. {
  168118. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168119. }
  168120. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168121. /*
  168122. * Consume input data and store it in the full-image coefficient buffer.
  168123. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168124. * ie, v_samp_factor block rows for each component in the scan.
  168125. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168126. */
  168127. METHODDEF(int)
  168128. consume_data (j_decompress_ptr cinfo)
  168129. {
  168130. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168131. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168132. int blkn, ci, xindex, yindex, yoffset;
  168133. JDIMENSION start_col;
  168134. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168135. JBLOCKROW buffer_ptr;
  168136. jpeg_component_info *compptr;
  168137. /* Align the virtual buffers for the components used in this scan. */
  168138. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168139. compptr = cinfo->cur_comp_info[ci];
  168140. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168141. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168142. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168143. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168144. /* Note: entropy decoder expects buffer to be zeroed,
  168145. * but this is handled automatically by the memory manager
  168146. * because we requested a pre-zeroed array.
  168147. */
  168148. }
  168149. /* Loop to process one whole iMCU row */
  168150. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168151. yoffset++) {
  168152. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168153. MCU_col_num++) {
  168154. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168155. blkn = 0; /* index of current DCT block within MCU */
  168156. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168157. compptr = cinfo->cur_comp_info[ci];
  168158. start_col = MCU_col_num * compptr->MCU_width;
  168159. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168160. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168161. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168162. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168163. }
  168164. }
  168165. }
  168166. /* Try to fetch the MCU. */
  168167. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168168. /* Suspension forced; update state counters and exit */
  168169. coef->MCU_vert_offset = yoffset;
  168170. coef->MCU_ctr = MCU_col_num;
  168171. return JPEG_SUSPENDED;
  168172. }
  168173. }
  168174. /* Completed an MCU row, but perhaps not an iMCU row */
  168175. coef->MCU_ctr = 0;
  168176. }
  168177. /* Completed the iMCU row, advance counters for next one */
  168178. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168179. start_iMCU_row3(cinfo);
  168180. return JPEG_ROW_COMPLETED;
  168181. }
  168182. /* Completed the scan */
  168183. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168184. return JPEG_SCAN_COMPLETED;
  168185. }
  168186. /*
  168187. * Decompress and return some data in the multi-pass case.
  168188. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168189. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168190. *
  168191. * NB: output_buf contains a plane for each component in image.
  168192. */
  168193. METHODDEF(int)
  168194. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168195. {
  168196. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168197. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168198. JDIMENSION block_num;
  168199. int ci, block_row, block_rows;
  168200. JBLOCKARRAY buffer;
  168201. JBLOCKROW buffer_ptr;
  168202. JSAMPARRAY output_ptr;
  168203. JDIMENSION output_col;
  168204. jpeg_component_info *compptr;
  168205. inverse_DCT_method_ptr inverse_DCT;
  168206. /* Force some input to be done if we are getting ahead of the input. */
  168207. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168208. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168209. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168210. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168211. return JPEG_SUSPENDED;
  168212. }
  168213. /* OK, output from the virtual arrays. */
  168214. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168215. ci++, compptr++) {
  168216. /* Don't bother to IDCT an uninteresting component. */
  168217. if (! compptr->component_needed)
  168218. continue;
  168219. /* Align the virtual buffer for this component. */
  168220. buffer = (*cinfo->mem->access_virt_barray)
  168221. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168222. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168223. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168224. /* Count non-dummy DCT block rows in this iMCU row. */
  168225. if (cinfo->output_iMCU_row < last_iMCU_row)
  168226. block_rows = compptr->v_samp_factor;
  168227. else {
  168228. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168229. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168230. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168231. }
  168232. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168233. output_ptr = output_buf[ci];
  168234. /* Loop over all DCT blocks to be processed. */
  168235. for (block_row = 0; block_row < block_rows; block_row++) {
  168236. buffer_ptr = buffer[block_row];
  168237. output_col = 0;
  168238. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168239. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168240. output_ptr, output_col);
  168241. buffer_ptr++;
  168242. output_col += compptr->DCT_scaled_size;
  168243. }
  168244. output_ptr += compptr->DCT_scaled_size;
  168245. }
  168246. }
  168247. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168248. return JPEG_ROW_COMPLETED;
  168249. return JPEG_SCAN_COMPLETED;
  168250. }
  168251. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168252. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168253. /*
  168254. * This code applies interblock smoothing as described by section K.8
  168255. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168256. * the DC values of a DCT block and its 8 neighboring blocks.
  168257. * We apply smoothing only for progressive JPEG decoding, and only if
  168258. * the coefficients it can estimate are not yet known to full precision.
  168259. */
  168260. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168261. #define Q01_POS 1
  168262. #define Q10_POS 8
  168263. #define Q20_POS 16
  168264. #define Q11_POS 9
  168265. #define Q02_POS 2
  168266. /*
  168267. * Determine whether block smoothing is applicable and safe.
  168268. * We also latch the current states of the coef_bits[] entries for the
  168269. * AC coefficients; otherwise, if the input side of the decompressor
  168270. * advances into a new scan, we might think the coefficients are known
  168271. * more accurately than they really are.
  168272. */
  168273. LOCAL(boolean)
  168274. smoothing_ok (j_decompress_ptr cinfo)
  168275. {
  168276. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168277. boolean smoothing_useful = FALSE;
  168278. int ci, coefi;
  168279. jpeg_component_info *compptr;
  168280. JQUANT_TBL * qtable;
  168281. int * coef_bits;
  168282. int * coef_bits_latch;
  168283. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168284. return FALSE;
  168285. /* Allocate latch area if not already done */
  168286. if (coef->coef_bits_latch == NULL)
  168287. coef->coef_bits_latch = (int *)
  168288. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168289. cinfo->num_components *
  168290. (SAVED_COEFS * SIZEOF(int)));
  168291. coef_bits_latch = coef->coef_bits_latch;
  168292. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168293. ci++, compptr++) {
  168294. /* All components' quantization values must already be latched. */
  168295. if ((qtable = compptr->quant_table) == NULL)
  168296. return FALSE;
  168297. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168298. if (qtable->quantval[0] == 0 ||
  168299. qtable->quantval[Q01_POS] == 0 ||
  168300. qtable->quantval[Q10_POS] == 0 ||
  168301. qtable->quantval[Q20_POS] == 0 ||
  168302. qtable->quantval[Q11_POS] == 0 ||
  168303. qtable->quantval[Q02_POS] == 0)
  168304. return FALSE;
  168305. /* DC values must be at least partly known for all components. */
  168306. coef_bits = cinfo->coef_bits[ci];
  168307. if (coef_bits[0] < 0)
  168308. return FALSE;
  168309. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168310. for (coefi = 1; coefi <= 5; coefi++) {
  168311. coef_bits_latch[coefi] = coef_bits[coefi];
  168312. if (coef_bits[coefi] != 0)
  168313. smoothing_useful = TRUE;
  168314. }
  168315. coef_bits_latch += SAVED_COEFS;
  168316. }
  168317. return smoothing_useful;
  168318. }
  168319. /*
  168320. * Variant of decompress_data for use when doing block smoothing.
  168321. */
  168322. METHODDEF(int)
  168323. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168324. {
  168325. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168326. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168327. JDIMENSION block_num, last_block_column;
  168328. int ci, block_row, block_rows, access_rows;
  168329. JBLOCKARRAY buffer;
  168330. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168331. JSAMPARRAY output_ptr;
  168332. JDIMENSION output_col;
  168333. jpeg_component_info *compptr;
  168334. inverse_DCT_method_ptr inverse_DCT;
  168335. boolean first_row, last_row;
  168336. JBLOCK workspace;
  168337. int *coef_bits;
  168338. JQUANT_TBL *quanttbl;
  168339. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168340. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168341. int Al, pred;
  168342. /* Force some input to be done if we are getting ahead of the input. */
  168343. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168344. ! cinfo->inputctl->eoi_reached) {
  168345. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168346. /* If input is working on current scan, we ordinarily want it to
  168347. * have completed the current row. But if input scan is DC,
  168348. * we want it to keep one row ahead so that next block row's DC
  168349. * values are up to date.
  168350. */
  168351. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168352. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168353. break;
  168354. }
  168355. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168356. return JPEG_SUSPENDED;
  168357. }
  168358. /* OK, output from the virtual arrays. */
  168359. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168360. ci++, compptr++) {
  168361. /* Don't bother to IDCT an uninteresting component. */
  168362. if (! compptr->component_needed)
  168363. continue;
  168364. /* Count non-dummy DCT block rows in this iMCU row. */
  168365. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168366. block_rows = compptr->v_samp_factor;
  168367. access_rows = block_rows * 2; /* this and next iMCU row */
  168368. last_row = FALSE;
  168369. } else {
  168370. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168371. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168372. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168373. access_rows = block_rows; /* this iMCU row only */
  168374. last_row = TRUE;
  168375. }
  168376. /* Align the virtual buffer for this component. */
  168377. if (cinfo->output_iMCU_row > 0) {
  168378. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168379. buffer = (*cinfo->mem->access_virt_barray)
  168380. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168381. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168382. (JDIMENSION) access_rows, FALSE);
  168383. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168384. first_row = FALSE;
  168385. } else {
  168386. buffer = (*cinfo->mem->access_virt_barray)
  168387. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168388. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168389. first_row = TRUE;
  168390. }
  168391. /* Fetch component-dependent info */
  168392. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168393. quanttbl = compptr->quant_table;
  168394. Q00 = quanttbl->quantval[0];
  168395. Q01 = quanttbl->quantval[Q01_POS];
  168396. Q10 = quanttbl->quantval[Q10_POS];
  168397. Q20 = quanttbl->quantval[Q20_POS];
  168398. Q11 = quanttbl->quantval[Q11_POS];
  168399. Q02 = quanttbl->quantval[Q02_POS];
  168400. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168401. output_ptr = output_buf[ci];
  168402. /* Loop over all DCT blocks to be processed. */
  168403. for (block_row = 0; block_row < block_rows; block_row++) {
  168404. buffer_ptr = buffer[block_row];
  168405. if (first_row && block_row == 0)
  168406. prev_block_row = buffer_ptr;
  168407. else
  168408. prev_block_row = buffer[block_row-1];
  168409. if (last_row && block_row == block_rows-1)
  168410. next_block_row = buffer_ptr;
  168411. else
  168412. next_block_row = buffer[block_row+1];
  168413. /* We fetch the surrounding DC values using a sliding-register approach.
  168414. * Initialize all nine here so as to do the right thing on narrow pics.
  168415. */
  168416. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168417. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168418. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168419. output_col = 0;
  168420. last_block_column = compptr->width_in_blocks - 1;
  168421. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168422. /* Fetch current DCT block into workspace so we can modify it. */
  168423. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168424. /* Update DC values */
  168425. if (block_num < last_block_column) {
  168426. DC3 = (int) prev_block_row[1][0];
  168427. DC6 = (int) buffer_ptr[1][0];
  168428. DC9 = (int) next_block_row[1][0];
  168429. }
  168430. /* Compute coefficient estimates per K.8.
  168431. * An estimate is applied only if coefficient is still zero,
  168432. * and is not known to be fully accurate.
  168433. */
  168434. /* AC01 */
  168435. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168436. num = 36 * Q00 * (DC4 - DC6);
  168437. if (num >= 0) {
  168438. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168439. if (Al > 0 && pred >= (1<<Al))
  168440. pred = (1<<Al)-1;
  168441. } else {
  168442. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168443. if (Al > 0 && pred >= (1<<Al))
  168444. pred = (1<<Al)-1;
  168445. pred = -pred;
  168446. }
  168447. workspace[1] = (JCOEF) pred;
  168448. }
  168449. /* AC10 */
  168450. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168451. num = 36 * Q00 * (DC2 - DC8);
  168452. if (num >= 0) {
  168453. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168454. if (Al > 0 && pred >= (1<<Al))
  168455. pred = (1<<Al)-1;
  168456. } else {
  168457. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168458. if (Al > 0 && pred >= (1<<Al))
  168459. pred = (1<<Al)-1;
  168460. pred = -pred;
  168461. }
  168462. workspace[8] = (JCOEF) pred;
  168463. }
  168464. /* AC20 */
  168465. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168466. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168467. if (num >= 0) {
  168468. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168469. if (Al > 0 && pred >= (1<<Al))
  168470. pred = (1<<Al)-1;
  168471. } else {
  168472. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168473. if (Al > 0 && pred >= (1<<Al))
  168474. pred = (1<<Al)-1;
  168475. pred = -pred;
  168476. }
  168477. workspace[16] = (JCOEF) pred;
  168478. }
  168479. /* AC11 */
  168480. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168481. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168482. if (num >= 0) {
  168483. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168484. if (Al > 0 && pred >= (1<<Al))
  168485. pred = (1<<Al)-1;
  168486. } else {
  168487. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168488. if (Al > 0 && pred >= (1<<Al))
  168489. pred = (1<<Al)-1;
  168490. pred = -pred;
  168491. }
  168492. workspace[9] = (JCOEF) pred;
  168493. }
  168494. /* AC02 */
  168495. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168496. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168497. if (num >= 0) {
  168498. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168499. if (Al > 0 && pred >= (1<<Al))
  168500. pred = (1<<Al)-1;
  168501. } else {
  168502. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168503. if (Al > 0 && pred >= (1<<Al))
  168504. pred = (1<<Al)-1;
  168505. pred = -pred;
  168506. }
  168507. workspace[2] = (JCOEF) pred;
  168508. }
  168509. /* OK, do the IDCT */
  168510. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168511. output_ptr, output_col);
  168512. /* Advance for next column */
  168513. DC1 = DC2; DC2 = DC3;
  168514. DC4 = DC5; DC5 = DC6;
  168515. DC7 = DC8; DC8 = DC9;
  168516. buffer_ptr++, prev_block_row++, next_block_row++;
  168517. output_col += compptr->DCT_scaled_size;
  168518. }
  168519. output_ptr += compptr->DCT_scaled_size;
  168520. }
  168521. }
  168522. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168523. return JPEG_ROW_COMPLETED;
  168524. return JPEG_SCAN_COMPLETED;
  168525. }
  168526. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168527. /*
  168528. * Initialize coefficient buffer controller.
  168529. */
  168530. GLOBAL(void)
  168531. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168532. {
  168533. my_coef_ptr3 coef;
  168534. coef = (my_coef_ptr3)
  168535. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168536. SIZEOF(my_coef_controller3));
  168537. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168538. coef->pub.start_input_pass = start_input_pass;
  168539. coef->pub.start_output_pass = start_output_pass;
  168540. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168541. coef->coef_bits_latch = NULL;
  168542. #endif
  168543. /* Create the coefficient buffer. */
  168544. if (need_full_buffer) {
  168545. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168546. /* Allocate a full-image virtual array for each component, */
  168547. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168548. /* Note we ask for a pre-zeroed array. */
  168549. int ci, access_rows;
  168550. jpeg_component_info *compptr;
  168551. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168552. ci++, compptr++) {
  168553. access_rows = compptr->v_samp_factor;
  168554. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168555. /* If block smoothing could be used, need a bigger window */
  168556. if (cinfo->progressive_mode)
  168557. access_rows *= 3;
  168558. #endif
  168559. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168560. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168561. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168562. (long) compptr->h_samp_factor),
  168563. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168564. (long) compptr->v_samp_factor),
  168565. (JDIMENSION) access_rows);
  168566. }
  168567. coef->pub.consume_data = consume_data;
  168568. coef->pub.decompress_data = decompress_data;
  168569. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168570. #else
  168571. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168572. #endif
  168573. } else {
  168574. /* We only need a single-MCU buffer. */
  168575. JBLOCKROW buffer;
  168576. int i;
  168577. buffer = (JBLOCKROW)
  168578. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168579. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168580. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168581. coef->MCU_buffer[i] = buffer + i;
  168582. }
  168583. coef->pub.consume_data = dummy_consume_data;
  168584. coef->pub.decompress_data = decompress_onepass;
  168585. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168586. }
  168587. }
  168588. /*** End of inlined file: jdcoefct.c ***/
  168589. #undef FIX
  168590. /*** Start of inlined file: jdcolor.c ***/
  168591. #define JPEG_INTERNALS
  168592. /* Private subobject */
  168593. typedef struct {
  168594. struct jpeg_color_deconverter pub; /* public fields */
  168595. /* Private state for YCC->RGB conversion */
  168596. int * Cr_r_tab; /* => table for Cr to R conversion */
  168597. int * Cb_b_tab; /* => table for Cb to B conversion */
  168598. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168599. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168600. } my_color_deconverter2;
  168601. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168602. /**************** YCbCr -> RGB conversion: most common case **************/
  168603. /*
  168604. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168605. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168606. * The conversion equations to be implemented are therefore
  168607. * R = Y + 1.40200 * Cr
  168608. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168609. * B = Y + 1.77200 * Cb
  168610. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168611. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168612. *
  168613. * To avoid floating-point arithmetic, we represent the fractional constants
  168614. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168615. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168616. * Notice that Y, being an integral input, does not contribute any fraction
  168617. * so it need not participate in the rounding.
  168618. *
  168619. * For even more speed, we avoid doing any multiplications in the inner loop
  168620. * by precalculating the constants times Cb and Cr for all possible values.
  168621. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168622. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168623. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168624. * colorspace anyway.
  168625. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168626. * values for the G calculation are left scaled up, since we must add them
  168627. * together before rounding.
  168628. */
  168629. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168630. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168631. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168632. /*
  168633. * Initialize tables for YCC->RGB colorspace conversion.
  168634. */
  168635. LOCAL(void)
  168636. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168637. {
  168638. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168639. int i;
  168640. INT32 x;
  168641. SHIFT_TEMPS
  168642. cconvert->Cr_r_tab = (int *)
  168643. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168644. (MAXJSAMPLE+1) * SIZEOF(int));
  168645. cconvert->Cb_b_tab = (int *)
  168646. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168647. (MAXJSAMPLE+1) * SIZEOF(int));
  168648. cconvert->Cr_g_tab = (INT32 *)
  168649. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168650. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168651. cconvert->Cb_g_tab = (INT32 *)
  168652. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168653. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168654. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168655. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168656. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168657. /* Cr=>R value is nearest int to 1.40200 * x */
  168658. cconvert->Cr_r_tab[i] = (int)
  168659. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168660. /* Cb=>B value is nearest int to 1.77200 * x */
  168661. cconvert->Cb_b_tab[i] = (int)
  168662. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168663. /* Cr=>G value is scaled-up -0.71414 * x */
  168664. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168665. /* Cb=>G value is scaled-up -0.34414 * x */
  168666. /* We also add in ONE_HALF so that need not do it in inner loop */
  168667. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168668. }
  168669. }
  168670. /*
  168671. * Convert some rows of samples to the output colorspace.
  168672. *
  168673. * Note that we change from noninterleaved, one-plane-per-component format
  168674. * to interleaved-pixel format. The output buffer is therefore three times
  168675. * as wide as the input buffer.
  168676. * A starting row offset is provided only for the input buffer. The caller
  168677. * can easily adjust the passed output_buf value to accommodate any row
  168678. * offset required on that side.
  168679. */
  168680. METHODDEF(void)
  168681. ycc_rgb_convert (j_decompress_ptr cinfo,
  168682. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168683. JSAMPARRAY output_buf, int num_rows)
  168684. {
  168685. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168686. register int y, cb, cr;
  168687. register JSAMPROW outptr;
  168688. register JSAMPROW inptr0, inptr1, inptr2;
  168689. register JDIMENSION col;
  168690. JDIMENSION num_cols = cinfo->output_width;
  168691. /* copy these pointers into registers if possible */
  168692. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168693. register int * Crrtab = cconvert->Cr_r_tab;
  168694. register int * Cbbtab = cconvert->Cb_b_tab;
  168695. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168696. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168697. SHIFT_TEMPS
  168698. while (--num_rows >= 0) {
  168699. inptr0 = input_buf[0][input_row];
  168700. inptr1 = input_buf[1][input_row];
  168701. inptr2 = input_buf[2][input_row];
  168702. input_row++;
  168703. outptr = *output_buf++;
  168704. for (col = 0; col < num_cols; col++) {
  168705. y = GETJSAMPLE(inptr0[col]);
  168706. cb = GETJSAMPLE(inptr1[col]);
  168707. cr = GETJSAMPLE(inptr2[col]);
  168708. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168709. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168710. outptr[RGB_GREEN] = range_limit[y +
  168711. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168712. SCALEBITS))];
  168713. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168714. outptr += RGB_PIXELSIZE;
  168715. }
  168716. }
  168717. }
  168718. /**************** Cases other than YCbCr -> RGB **************/
  168719. /*
  168720. * Color conversion for no colorspace change: just copy the data,
  168721. * converting from separate-planes to interleaved representation.
  168722. */
  168723. METHODDEF(void)
  168724. null_convert2 (j_decompress_ptr cinfo,
  168725. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168726. JSAMPARRAY output_buf, int num_rows)
  168727. {
  168728. register JSAMPROW inptr, outptr;
  168729. register JDIMENSION count;
  168730. register int num_components = cinfo->num_components;
  168731. JDIMENSION num_cols = cinfo->output_width;
  168732. int ci;
  168733. while (--num_rows >= 0) {
  168734. for (ci = 0; ci < num_components; ci++) {
  168735. inptr = input_buf[ci][input_row];
  168736. outptr = output_buf[0] + ci;
  168737. for (count = num_cols; count > 0; count--) {
  168738. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168739. outptr += num_components;
  168740. }
  168741. }
  168742. input_row++;
  168743. output_buf++;
  168744. }
  168745. }
  168746. /*
  168747. * Color conversion for grayscale: just copy the data.
  168748. * This also works for YCbCr -> grayscale conversion, in which
  168749. * we just copy the Y (luminance) component and ignore chrominance.
  168750. */
  168751. METHODDEF(void)
  168752. grayscale_convert2 (j_decompress_ptr cinfo,
  168753. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168754. JSAMPARRAY output_buf, int num_rows)
  168755. {
  168756. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168757. num_rows, cinfo->output_width);
  168758. }
  168759. /*
  168760. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168761. * This is provided to support applications that don't want to cope
  168762. * with grayscale as a separate case.
  168763. */
  168764. METHODDEF(void)
  168765. gray_rgb_convert (j_decompress_ptr cinfo,
  168766. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168767. JSAMPARRAY output_buf, int num_rows)
  168768. {
  168769. register JSAMPROW inptr, outptr;
  168770. register JDIMENSION col;
  168771. JDIMENSION num_cols = cinfo->output_width;
  168772. while (--num_rows >= 0) {
  168773. inptr = input_buf[0][input_row++];
  168774. outptr = *output_buf++;
  168775. for (col = 0; col < num_cols; col++) {
  168776. /* We can dispense with GETJSAMPLE() here */
  168777. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168778. outptr += RGB_PIXELSIZE;
  168779. }
  168780. }
  168781. }
  168782. /*
  168783. * Adobe-style YCCK->CMYK conversion.
  168784. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168785. * conversion as above, while passing K (black) unchanged.
  168786. * We assume build_ycc_rgb_table has been called.
  168787. */
  168788. METHODDEF(void)
  168789. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168790. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168791. JSAMPARRAY output_buf, int num_rows)
  168792. {
  168793. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168794. register int y, cb, cr;
  168795. register JSAMPROW outptr;
  168796. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168797. register JDIMENSION col;
  168798. JDIMENSION num_cols = cinfo->output_width;
  168799. /* copy these pointers into registers if possible */
  168800. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168801. register int * Crrtab = cconvert->Cr_r_tab;
  168802. register int * Cbbtab = cconvert->Cb_b_tab;
  168803. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168804. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168805. SHIFT_TEMPS
  168806. while (--num_rows >= 0) {
  168807. inptr0 = input_buf[0][input_row];
  168808. inptr1 = input_buf[1][input_row];
  168809. inptr2 = input_buf[2][input_row];
  168810. inptr3 = input_buf[3][input_row];
  168811. input_row++;
  168812. outptr = *output_buf++;
  168813. for (col = 0; col < num_cols; col++) {
  168814. y = GETJSAMPLE(inptr0[col]);
  168815. cb = GETJSAMPLE(inptr1[col]);
  168816. cr = GETJSAMPLE(inptr2[col]);
  168817. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168818. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168819. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168820. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168821. SCALEBITS)))];
  168822. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168823. /* K passes through unchanged */
  168824. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168825. outptr += 4;
  168826. }
  168827. }
  168828. }
  168829. /*
  168830. * Empty method for start_pass.
  168831. */
  168832. METHODDEF(void)
  168833. start_pass_dcolor (j_decompress_ptr)
  168834. {
  168835. /* no work needed */
  168836. }
  168837. /*
  168838. * Module initialization routine for output colorspace conversion.
  168839. */
  168840. GLOBAL(void)
  168841. jinit_color_deconverter (j_decompress_ptr cinfo)
  168842. {
  168843. my_cconvert_ptr2 cconvert;
  168844. int ci;
  168845. cconvert = (my_cconvert_ptr2)
  168846. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168847. SIZEOF(my_color_deconverter2));
  168848. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168849. cconvert->pub.start_pass = start_pass_dcolor;
  168850. /* Make sure num_components agrees with jpeg_color_space */
  168851. switch (cinfo->jpeg_color_space) {
  168852. case JCS_GRAYSCALE:
  168853. if (cinfo->num_components != 1)
  168854. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168855. break;
  168856. case JCS_RGB:
  168857. case JCS_YCbCr:
  168858. if (cinfo->num_components != 3)
  168859. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168860. break;
  168861. case JCS_CMYK:
  168862. case JCS_YCCK:
  168863. if (cinfo->num_components != 4)
  168864. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168865. break;
  168866. default: /* JCS_UNKNOWN can be anything */
  168867. if (cinfo->num_components < 1)
  168868. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168869. break;
  168870. }
  168871. /* Set out_color_components and conversion method based on requested space.
  168872. * Also clear the component_needed flags for any unused components,
  168873. * so that earlier pipeline stages can avoid useless computation.
  168874. */
  168875. switch (cinfo->out_color_space) {
  168876. case JCS_GRAYSCALE:
  168877. cinfo->out_color_components = 1;
  168878. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168879. cinfo->jpeg_color_space == JCS_YCbCr) {
  168880. cconvert->pub.color_convert = grayscale_convert2;
  168881. /* For color->grayscale conversion, only the Y (0) component is needed */
  168882. for (ci = 1; ci < cinfo->num_components; ci++)
  168883. cinfo->comp_info[ci].component_needed = FALSE;
  168884. } else
  168885. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168886. break;
  168887. case JCS_RGB:
  168888. cinfo->out_color_components = RGB_PIXELSIZE;
  168889. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168890. cconvert->pub.color_convert = ycc_rgb_convert;
  168891. build_ycc_rgb_table(cinfo);
  168892. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168893. cconvert->pub.color_convert = gray_rgb_convert;
  168894. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168895. cconvert->pub.color_convert = null_convert2;
  168896. } else
  168897. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168898. break;
  168899. case JCS_CMYK:
  168900. cinfo->out_color_components = 4;
  168901. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168902. cconvert->pub.color_convert = ycck_cmyk_convert;
  168903. build_ycc_rgb_table(cinfo);
  168904. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168905. cconvert->pub.color_convert = null_convert2;
  168906. } else
  168907. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168908. break;
  168909. default:
  168910. /* Permit null conversion to same output space */
  168911. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168912. cinfo->out_color_components = cinfo->num_components;
  168913. cconvert->pub.color_convert = null_convert2;
  168914. } else /* unsupported non-null conversion */
  168915. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168916. break;
  168917. }
  168918. if (cinfo->quantize_colors)
  168919. cinfo->output_components = 1; /* single colormapped output component */
  168920. else
  168921. cinfo->output_components = cinfo->out_color_components;
  168922. }
  168923. /*** End of inlined file: jdcolor.c ***/
  168924. #undef FIX
  168925. /*** Start of inlined file: jddctmgr.c ***/
  168926. #define JPEG_INTERNALS
  168927. /*
  168928. * The decompressor input side (jdinput.c) saves away the appropriate
  168929. * quantization table for each component at the start of the first scan
  168930. * involving that component. (This is necessary in order to correctly
  168931. * decode files that reuse Q-table slots.)
  168932. * When we are ready to make an output pass, the saved Q-table is converted
  168933. * to a multiplier table that will actually be used by the IDCT routine.
  168934. * The multiplier table contents are IDCT-method-dependent. To support
  168935. * application changes in IDCT method between scans, we can remake the
  168936. * multiplier tables if necessary.
  168937. * In buffered-image mode, the first output pass may occur before any data
  168938. * has been seen for some components, and thus before their Q-tables have
  168939. * been saved away. To handle this case, multiplier tables are preset
  168940. * to zeroes; the result of the IDCT will be a neutral gray level.
  168941. */
  168942. /* Private subobject for this module */
  168943. typedef struct {
  168944. struct jpeg_inverse_dct pub; /* public fields */
  168945. /* This array contains the IDCT method code that each multiplier table
  168946. * is currently set up for, or -1 if it's not yet set up.
  168947. * The actual multiplier tables are pointed to by dct_table in the
  168948. * per-component comp_info structures.
  168949. */
  168950. int cur_method[MAX_COMPONENTS];
  168951. } my_idct_controller;
  168952. typedef my_idct_controller * my_idct_ptr;
  168953. /* Allocated multiplier tables: big enough for any supported variant */
  168954. typedef union {
  168955. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168956. #ifdef DCT_IFAST_SUPPORTED
  168957. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168958. #endif
  168959. #ifdef DCT_FLOAT_SUPPORTED
  168960. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168961. #endif
  168962. } multiplier_table;
  168963. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168964. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168965. */
  168966. #ifdef DCT_ISLOW_SUPPORTED
  168967. #define PROVIDE_ISLOW_TABLES
  168968. #else
  168969. #ifdef IDCT_SCALING_SUPPORTED
  168970. #define PROVIDE_ISLOW_TABLES
  168971. #endif
  168972. #endif
  168973. /*
  168974. * Prepare for an output pass.
  168975. * Here we select the proper IDCT routine for each component and build
  168976. * a matching multiplier table.
  168977. */
  168978. METHODDEF(void)
  168979. start_pass (j_decompress_ptr cinfo)
  168980. {
  168981. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168982. int ci, i;
  168983. jpeg_component_info *compptr;
  168984. int method = 0;
  168985. inverse_DCT_method_ptr method_ptr = NULL;
  168986. JQUANT_TBL * qtbl;
  168987. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168988. ci++, compptr++) {
  168989. /* Select the proper IDCT routine for this component's scaling */
  168990. switch (compptr->DCT_scaled_size) {
  168991. #ifdef IDCT_SCALING_SUPPORTED
  168992. case 1:
  168993. method_ptr = jpeg_idct_1x1;
  168994. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168995. break;
  168996. case 2:
  168997. method_ptr = jpeg_idct_2x2;
  168998. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168999. break;
  169000. case 4:
  169001. method_ptr = jpeg_idct_4x4;
  169002. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169003. break;
  169004. #endif
  169005. case DCTSIZE:
  169006. switch (cinfo->dct_method) {
  169007. #ifdef DCT_ISLOW_SUPPORTED
  169008. case JDCT_ISLOW:
  169009. method_ptr = jpeg_idct_islow;
  169010. method = JDCT_ISLOW;
  169011. break;
  169012. #endif
  169013. #ifdef DCT_IFAST_SUPPORTED
  169014. case JDCT_IFAST:
  169015. method_ptr = jpeg_idct_ifast;
  169016. method = JDCT_IFAST;
  169017. break;
  169018. #endif
  169019. #ifdef DCT_FLOAT_SUPPORTED
  169020. case JDCT_FLOAT:
  169021. method_ptr = jpeg_idct_float;
  169022. method = JDCT_FLOAT;
  169023. break;
  169024. #endif
  169025. default:
  169026. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169027. break;
  169028. }
  169029. break;
  169030. default:
  169031. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169032. break;
  169033. }
  169034. idct->pub.inverse_DCT[ci] = method_ptr;
  169035. /* Create multiplier table from quant table.
  169036. * However, we can skip this if the component is uninteresting
  169037. * or if we already built the table. Also, if no quant table
  169038. * has yet been saved for the component, we leave the
  169039. * multiplier table all-zero; we'll be reading zeroes from the
  169040. * coefficient controller's buffer anyway.
  169041. */
  169042. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169043. continue;
  169044. qtbl = compptr->quant_table;
  169045. if (qtbl == NULL) /* happens if no data yet for component */
  169046. continue;
  169047. idct->cur_method[ci] = method;
  169048. switch (method) {
  169049. #ifdef PROVIDE_ISLOW_TABLES
  169050. case JDCT_ISLOW:
  169051. {
  169052. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169053. * coefficients, but are stored as ints to ensure access efficiency.
  169054. */
  169055. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169056. for (i = 0; i < DCTSIZE2; i++) {
  169057. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169058. }
  169059. }
  169060. break;
  169061. #endif
  169062. #ifdef DCT_IFAST_SUPPORTED
  169063. case JDCT_IFAST:
  169064. {
  169065. /* For AA&N IDCT method, multipliers are equal to quantization
  169066. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169067. * scalefactor[0] = 1
  169068. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169069. * For integer operation, the multiplier table is to be scaled by
  169070. * IFAST_SCALE_BITS.
  169071. */
  169072. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169073. #define CONST_BITS 14
  169074. static const INT16 aanscales[DCTSIZE2] = {
  169075. /* precomputed values scaled up by 14 bits */
  169076. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169077. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169078. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169079. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169080. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169081. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169082. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169083. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169084. };
  169085. SHIFT_TEMPS
  169086. for (i = 0; i < DCTSIZE2; i++) {
  169087. ifmtbl[i] = (IFAST_MULT_TYPE)
  169088. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169089. (INT32) aanscales[i]),
  169090. CONST_BITS-IFAST_SCALE_BITS);
  169091. }
  169092. }
  169093. break;
  169094. #endif
  169095. #ifdef DCT_FLOAT_SUPPORTED
  169096. case JDCT_FLOAT:
  169097. {
  169098. /* For float AA&N IDCT method, multipliers are equal to quantization
  169099. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169100. * scalefactor[0] = 1
  169101. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169102. */
  169103. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169104. int row, col;
  169105. static const double aanscalefactor[DCTSIZE] = {
  169106. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169107. 1.0, 0.785694958, 0.541196100, 0.275899379
  169108. };
  169109. i = 0;
  169110. for (row = 0; row < DCTSIZE; row++) {
  169111. for (col = 0; col < DCTSIZE; col++) {
  169112. fmtbl[i] = (FLOAT_MULT_TYPE)
  169113. ((double) qtbl->quantval[i] *
  169114. aanscalefactor[row] * aanscalefactor[col]);
  169115. i++;
  169116. }
  169117. }
  169118. }
  169119. break;
  169120. #endif
  169121. default:
  169122. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169123. break;
  169124. }
  169125. }
  169126. }
  169127. /*
  169128. * Initialize IDCT manager.
  169129. */
  169130. GLOBAL(void)
  169131. jinit_inverse_dct (j_decompress_ptr cinfo)
  169132. {
  169133. my_idct_ptr idct;
  169134. int ci;
  169135. jpeg_component_info *compptr;
  169136. idct = (my_idct_ptr)
  169137. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169138. SIZEOF(my_idct_controller));
  169139. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169140. idct->pub.start_pass = start_pass;
  169141. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169142. ci++, compptr++) {
  169143. /* Allocate and pre-zero a multiplier table for each component */
  169144. compptr->dct_table =
  169145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169146. SIZEOF(multiplier_table));
  169147. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169148. /* Mark multiplier table not yet set up for any method */
  169149. idct->cur_method[ci] = -1;
  169150. }
  169151. }
  169152. /*** End of inlined file: jddctmgr.c ***/
  169153. #undef CONST_BITS
  169154. #undef ASSIGN_STATE
  169155. /*** Start of inlined file: jdhuff.c ***/
  169156. #define JPEG_INTERNALS
  169157. /*** Start of inlined file: jdhuff.h ***/
  169158. /* Short forms of external names for systems with brain-damaged linkers. */
  169159. #ifndef __jdhuff_h__
  169160. #define __jdhuff_h__
  169161. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169162. #define jpeg_make_d_derived_tbl jMkDDerived
  169163. #define jpeg_fill_bit_buffer jFilBitBuf
  169164. #define jpeg_huff_decode jHufDecode
  169165. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169166. /* Derived data constructed for each Huffman table */
  169167. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169168. typedef struct {
  169169. /* Basic tables: (element [0] of each array is unused) */
  169170. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169171. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169172. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169173. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169174. * the smallest code of length k; so given a code of length k, the
  169175. * corresponding symbol is huffval[code + valoffset[k]]
  169176. */
  169177. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169178. JHUFF_TBL *pub;
  169179. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169180. * the input data stream. If the next Huffman code is no more
  169181. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169182. * the corresponding symbol directly from these tables.
  169183. */
  169184. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169185. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169186. } d_derived_tbl;
  169187. /* Expand a Huffman table definition into the derived format */
  169188. EXTERN(void) jpeg_make_d_derived_tbl
  169189. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169190. d_derived_tbl ** pdtbl));
  169191. /*
  169192. * Fetching the next N bits from the input stream is a time-critical operation
  169193. * for the Huffman decoders. We implement it with a combination of inline
  169194. * macros and out-of-line subroutines. Note that N (the number of bits
  169195. * demanded at one time) never exceeds 15 for JPEG use.
  169196. *
  169197. * We read source bytes into get_buffer and dole out bits as needed.
  169198. * If get_buffer already contains enough bits, they are fetched in-line
  169199. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169200. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169201. * as full as possible (not just to the number of bits needed; this
  169202. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169203. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169204. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169205. * at least the requested number of bits --- dummy zeroes are inserted if
  169206. * necessary.
  169207. */
  169208. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169209. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169210. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169211. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169212. * appropriately should be a win. Unfortunately we can't define the size
  169213. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169214. * because not all machines measure sizeof in 8-bit bytes.
  169215. */
  169216. typedef struct { /* Bitreading state saved across MCUs */
  169217. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169218. int bits_left; /* # of unused bits in it */
  169219. } bitread_perm_state;
  169220. typedef struct { /* Bitreading working state within an MCU */
  169221. /* Current data source location */
  169222. /* We need a copy, rather than munging the original, in case of suspension */
  169223. const JOCTET * next_input_byte; /* => next byte to read from source */
  169224. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169225. /* Bit input buffer --- note these values are kept in register variables,
  169226. * not in this struct, inside the inner loops.
  169227. */
  169228. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169229. int bits_left; /* # of unused bits in it */
  169230. /* Pointer needed by jpeg_fill_bit_buffer. */
  169231. j_decompress_ptr cinfo; /* back link to decompress master record */
  169232. } bitread_working_state;
  169233. /* Macros to declare and load/save bitread local variables. */
  169234. #define BITREAD_STATE_VARS \
  169235. register bit_buf_type get_buffer; \
  169236. register int bits_left; \
  169237. bitread_working_state br_state
  169238. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169239. br_state.cinfo = cinfop; \
  169240. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169241. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169242. get_buffer = permstate.get_buffer; \
  169243. bits_left = permstate.bits_left;
  169244. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169245. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169246. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169247. permstate.get_buffer = get_buffer; \
  169248. permstate.bits_left = bits_left
  169249. /*
  169250. * These macros provide the in-line portion of bit fetching.
  169251. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169252. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169253. * The variables get_buffer and bits_left are assumed to be locals,
  169254. * but the state struct might not be (jpeg_huff_decode needs this).
  169255. * CHECK_BIT_BUFFER(state,n,action);
  169256. * Ensure there are N bits in get_buffer; if suspend, take action.
  169257. * val = GET_BITS(n);
  169258. * Fetch next N bits.
  169259. * val = PEEK_BITS(n);
  169260. * Fetch next N bits without removing them from the buffer.
  169261. * DROP_BITS(n);
  169262. * Discard next N bits.
  169263. * The value N should be a simple variable, not an expression, because it
  169264. * is evaluated multiple times.
  169265. */
  169266. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169267. { if (bits_left < (nbits)) { \
  169268. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169269. { action; } \
  169270. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169271. #define GET_BITS(nbits) \
  169272. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169273. #define PEEK_BITS(nbits) \
  169274. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169275. #define DROP_BITS(nbits) \
  169276. (bits_left -= (nbits))
  169277. /* Load up the bit buffer to a depth of at least nbits */
  169278. EXTERN(boolean) jpeg_fill_bit_buffer
  169279. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169280. register int bits_left, int nbits));
  169281. /*
  169282. * Code for extracting next Huffman-coded symbol from input bit stream.
  169283. * Again, this is time-critical and we make the main paths be macros.
  169284. *
  169285. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169286. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169287. * or fewer bits long. The few overlength codes are handled with a loop,
  169288. * which need not be inline code.
  169289. *
  169290. * Notes about the HUFF_DECODE macro:
  169291. * 1. Near the end of the data segment, we may fail to get enough bits
  169292. * for a lookahead. In that case, we do it the hard way.
  169293. * 2. If the lookahead table contains no entry, the next code must be
  169294. * more than HUFF_LOOKAHEAD bits long.
  169295. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169296. */
  169297. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169298. { register int nb, look; \
  169299. if (bits_left < HUFF_LOOKAHEAD) { \
  169300. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169301. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169302. if (bits_left < HUFF_LOOKAHEAD) { \
  169303. nb = 1; goto slowlabel; \
  169304. } \
  169305. } \
  169306. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169307. if ((nb = htbl->look_nbits[look]) != 0) { \
  169308. DROP_BITS(nb); \
  169309. result = htbl->look_sym[look]; \
  169310. } else { \
  169311. nb = HUFF_LOOKAHEAD+1; \
  169312. slowlabel: \
  169313. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169314. { failaction; } \
  169315. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169316. } \
  169317. }
  169318. /* Out-of-line case for Huffman code fetching */
  169319. EXTERN(int) jpeg_huff_decode
  169320. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169321. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169322. #endif
  169323. /*** End of inlined file: jdhuff.h ***/
  169324. /* Declarations shared with jdphuff.c */
  169325. /*
  169326. * Expanded entropy decoder object for Huffman decoding.
  169327. *
  169328. * The savable_state subrecord contains fields that change within an MCU,
  169329. * but must not be updated permanently until we complete the MCU.
  169330. */
  169331. typedef struct {
  169332. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169333. } savable_state2;
  169334. /* This macro is to work around compilers with missing or broken
  169335. * structure assignment. You'll need to fix this code if you have
  169336. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169337. */
  169338. #ifndef NO_STRUCT_ASSIGN
  169339. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169340. #else
  169341. #if MAX_COMPS_IN_SCAN == 4
  169342. #define ASSIGN_STATE(dest,src) \
  169343. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169344. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169345. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169346. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169347. #endif
  169348. #endif
  169349. typedef struct {
  169350. struct jpeg_entropy_decoder pub; /* public fields */
  169351. /* These fields are loaded into local variables at start of each MCU.
  169352. * In case of suspension, we exit WITHOUT updating them.
  169353. */
  169354. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169355. savable_state2 saved; /* Other state at start of MCU */
  169356. /* These fields are NOT loaded into local working state. */
  169357. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169358. /* Pointers to derived tables (these workspaces have image lifespan) */
  169359. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169360. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169361. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169362. /* Pointers to derived tables to be used for each block within an MCU */
  169363. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169364. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169365. /* Whether we care about the DC and AC coefficient values for each block */
  169366. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169367. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169368. } huff_entropy_decoder2;
  169369. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169370. /*
  169371. * Initialize for a Huffman-compressed scan.
  169372. */
  169373. METHODDEF(void)
  169374. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169375. {
  169376. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169377. int ci, blkn, dctbl, actbl;
  169378. jpeg_component_info * compptr;
  169379. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169380. * This ought to be an error condition, but we make it a warning because
  169381. * there are some baseline files out there with all zeroes in these bytes.
  169382. */
  169383. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169384. cinfo->Ah != 0 || cinfo->Al != 0)
  169385. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169386. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169387. compptr = cinfo->cur_comp_info[ci];
  169388. dctbl = compptr->dc_tbl_no;
  169389. actbl = compptr->ac_tbl_no;
  169390. /* Compute derived values for Huffman tables */
  169391. /* We may do this more than once for a table, but it's not expensive */
  169392. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169393. & entropy->dc_derived_tbls[dctbl]);
  169394. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169395. & entropy->ac_derived_tbls[actbl]);
  169396. /* Initialize DC predictions to 0 */
  169397. entropy->saved.last_dc_val[ci] = 0;
  169398. }
  169399. /* Precalculate decoding info for each block in an MCU of this scan */
  169400. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169401. ci = cinfo->MCU_membership[blkn];
  169402. compptr = cinfo->cur_comp_info[ci];
  169403. /* Precalculate which table to use for each block */
  169404. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169405. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169406. /* Decide whether we really care about the coefficient values */
  169407. if (compptr->component_needed) {
  169408. entropy->dc_needed[blkn] = TRUE;
  169409. /* we don't need the ACs if producing a 1/8th-size image */
  169410. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169411. } else {
  169412. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169413. }
  169414. }
  169415. /* Initialize bitread state variables */
  169416. entropy->bitstate.bits_left = 0;
  169417. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169418. entropy->pub.insufficient_data = FALSE;
  169419. /* Initialize restart counter */
  169420. entropy->restarts_to_go = cinfo->restart_interval;
  169421. }
  169422. /*
  169423. * Compute the derived values for a Huffman table.
  169424. * This routine also performs some validation checks on the table.
  169425. *
  169426. * Note this is also used by jdphuff.c.
  169427. */
  169428. GLOBAL(void)
  169429. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169430. d_derived_tbl ** pdtbl)
  169431. {
  169432. JHUFF_TBL *htbl;
  169433. d_derived_tbl *dtbl;
  169434. int p, i, l, si, numsymbols;
  169435. int lookbits, ctr;
  169436. char huffsize[257];
  169437. unsigned int huffcode[257];
  169438. unsigned int code;
  169439. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169440. * paralleling the order of the symbols themselves in htbl->huffval[].
  169441. */
  169442. /* Find the input Huffman table */
  169443. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169444. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169445. htbl =
  169446. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169447. if (htbl == NULL)
  169448. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169449. /* Allocate a workspace if we haven't already done so. */
  169450. if (*pdtbl == NULL)
  169451. *pdtbl = (d_derived_tbl *)
  169452. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169453. SIZEOF(d_derived_tbl));
  169454. dtbl = *pdtbl;
  169455. dtbl->pub = htbl; /* fill in back link */
  169456. /* Figure C.1: make table of Huffman code length for each symbol */
  169457. p = 0;
  169458. for (l = 1; l <= 16; l++) {
  169459. i = (int) htbl->bits[l];
  169460. if (i < 0 || p + i > 256) /* protect against table overrun */
  169461. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169462. while (i--)
  169463. huffsize[p++] = (char) l;
  169464. }
  169465. huffsize[p] = 0;
  169466. numsymbols = p;
  169467. /* Figure C.2: generate the codes themselves */
  169468. /* We also validate that the counts represent a legal Huffman code tree. */
  169469. code = 0;
  169470. si = huffsize[0];
  169471. p = 0;
  169472. while (huffsize[p]) {
  169473. while (((int) huffsize[p]) == si) {
  169474. huffcode[p++] = code;
  169475. code++;
  169476. }
  169477. /* code is now 1 more than the last code used for codelength si; but
  169478. * it must still fit in si bits, since no code is allowed to be all ones.
  169479. */
  169480. if (((INT32) code) >= (((INT32) 1) << si))
  169481. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169482. code <<= 1;
  169483. si++;
  169484. }
  169485. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169486. p = 0;
  169487. for (l = 1; l <= 16; l++) {
  169488. if (htbl->bits[l]) {
  169489. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169490. * minus the minimum code of length l
  169491. */
  169492. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169493. p += htbl->bits[l];
  169494. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169495. } else {
  169496. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169497. }
  169498. }
  169499. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169500. /* Compute lookahead tables to speed up decoding.
  169501. * First we set all the table entries to 0, indicating "too long";
  169502. * then we iterate through the Huffman codes that are short enough and
  169503. * fill in all the entries that correspond to bit sequences starting
  169504. * with that code.
  169505. */
  169506. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169507. p = 0;
  169508. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169509. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169510. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169511. /* Generate left-justified code followed by all possible bit sequences */
  169512. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169513. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169514. dtbl->look_nbits[lookbits] = l;
  169515. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169516. lookbits++;
  169517. }
  169518. }
  169519. }
  169520. /* Validate symbols as being reasonable.
  169521. * For AC tables, we make no check, but accept all byte values 0..255.
  169522. * For DC tables, we require the symbols to be in range 0..15.
  169523. * (Tighter bounds could be applied depending on the data depth and mode,
  169524. * but this is sufficient to ensure safe decoding.)
  169525. */
  169526. if (isDC) {
  169527. for (i = 0; i < numsymbols; i++) {
  169528. int sym = htbl->huffval[i];
  169529. if (sym < 0 || sym > 15)
  169530. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169531. }
  169532. }
  169533. }
  169534. /*
  169535. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169536. * See jdhuff.h for info about usage.
  169537. * Note: current values of get_buffer and bits_left are passed as parameters,
  169538. * but are returned in the corresponding fields of the state struct.
  169539. *
  169540. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169541. * of get_buffer to be used. (On machines with wider words, an even larger
  169542. * buffer could be used.) However, on some machines 32-bit shifts are
  169543. * quite slow and take time proportional to the number of places shifted.
  169544. * (This is true with most PC compilers, for instance.) In this case it may
  169545. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169546. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169547. */
  169548. #ifdef SLOW_SHIFT_32
  169549. #define MIN_GET_BITS 15 /* minimum allowable value */
  169550. #else
  169551. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169552. #endif
  169553. GLOBAL(boolean)
  169554. jpeg_fill_bit_buffer (bitread_working_state * state,
  169555. register bit_buf_type get_buffer, register int bits_left,
  169556. int nbits)
  169557. /* Load up the bit buffer to a depth of at least nbits */
  169558. {
  169559. /* Copy heavily used state fields into locals (hopefully registers) */
  169560. register const JOCTET * next_input_byte = state->next_input_byte;
  169561. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169562. j_decompress_ptr cinfo = state->cinfo;
  169563. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169564. /* (It is assumed that no request will be for more than that many bits.) */
  169565. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169566. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169567. while (bits_left < MIN_GET_BITS) {
  169568. register int c;
  169569. /* Attempt to read a byte */
  169570. if (bytes_in_buffer == 0) {
  169571. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169572. return FALSE;
  169573. next_input_byte = cinfo->src->next_input_byte;
  169574. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169575. }
  169576. bytes_in_buffer--;
  169577. c = GETJOCTET(*next_input_byte++);
  169578. /* If it's 0xFF, check and discard stuffed zero byte */
  169579. if (c == 0xFF) {
  169580. /* Loop here to discard any padding FF's on terminating marker,
  169581. * so that we can save a valid unread_marker value. NOTE: we will
  169582. * accept multiple FF's followed by a 0 as meaning a single FF data
  169583. * byte. This data pattern is not valid according to the standard.
  169584. */
  169585. do {
  169586. if (bytes_in_buffer == 0) {
  169587. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169588. return FALSE;
  169589. next_input_byte = cinfo->src->next_input_byte;
  169590. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169591. }
  169592. bytes_in_buffer--;
  169593. c = GETJOCTET(*next_input_byte++);
  169594. } while (c == 0xFF);
  169595. if (c == 0) {
  169596. /* Found FF/00, which represents an FF data byte */
  169597. c = 0xFF;
  169598. } else {
  169599. /* Oops, it's actually a marker indicating end of compressed data.
  169600. * Save the marker code for later use.
  169601. * Fine point: it might appear that we should save the marker into
  169602. * bitread working state, not straight into permanent state. But
  169603. * once we have hit a marker, we cannot need to suspend within the
  169604. * current MCU, because we will read no more bytes from the data
  169605. * source. So it is OK to update permanent state right away.
  169606. */
  169607. cinfo->unread_marker = c;
  169608. /* See if we need to insert some fake zero bits. */
  169609. goto no_more_bytes;
  169610. }
  169611. }
  169612. /* OK, load c into get_buffer */
  169613. get_buffer = (get_buffer << 8) | c;
  169614. bits_left += 8;
  169615. } /* end while */
  169616. } else {
  169617. no_more_bytes:
  169618. /* We get here if we've read the marker that terminates the compressed
  169619. * data segment. There should be enough bits in the buffer register
  169620. * to satisfy the request; if so, no problem.
  169621. */
  169622. if (nbits > bits_left) {
  169623. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169624. * the data stream, so that we can produce some kind of image.
  169625. * We use a nonvolatile flag to ensure that only one warning message
  169626. * appears per data segment.
  169627. */
  169628. if (! cinfo->entropy->insufficient_data) {
  169629. WARNMS(cinfo, JWRN_HIT_MARKER);
  169630. cinfo->entropy->insufficient_data = TRUE;
  169631. }
  169632. /* Fill the buffer with zero bits */
  169633. get_buffer <<= MIN_GET_BITS - bits_left;
  169634. bits_left = MIN_GET_BITS;
  169635. }
  169636. }
  169637. /* Unload the local registers */
  169638. state->next_input_byte = next_input_byte;
  169639. state->bytes_in_buffer = bytes_in_buffer;
  169640. state->get_buffer = get_buffer;
  169641. state->bits_left = bits_left;
  169642. return TRUE;
  169643. }
  169644. /*
  169645. * Out-of-line code for Huffman code decoding.
  169646. * See jdhuff.h for info about usage.
  169647. */
  169648. GLOBAL(int)
  169649. jpeg_huff_decode (bitread_working_state * state,
  169650. register bit_buf_type get_buffer, register int bits_left,
  169651. d_derived_tbl * htbl, int min_bits)
  169652. {
  169653. register int l = min_bits;
  169654. register INT32 code;
  169655. /* HUFF_DECODE has determined that the code is at least min_bits */
  169656. /* bits long, so fetch that many bits in one swoop. */
  169657. CHECK_BIT_BUFFER(*state, l, return -1);
  169658. code = GET_BITS(l);
  169659. /* Collect the rest of the Huffman code one bit at a time. */
  169660. /* This is per Figure F.16 in the JPEG spec. */
  169661. while (code > htbl->maxcode[l]) {
  169662. code <<= 1;
  169663. CHECK_BIT_BUFFER(*state, 1, return -1);
  169664. code |= GET_BITS(1);
  169665. l++;
  169666. }
  169667. /* Unload the local registers */
  169668. state->get_buffer = get_buffer;
  169669. state->bits_left = bits_left;
  169670. /* With garbage input we may reach the sentinel value l = 17. */
  169671. if (l > 16) {
  169672. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169673. return 0; /* fake a zero as the safest result */
  169674. }
  169675. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169676. }
  169677. /*
  169678. * Check for a restart marker & resynchronize decoder.
  169679. * Returns FALSE if must suspend.
  169680. */
  169681. LOCAL(boolean)
  169682. process_restart (j_decompress_ptr cinfo)
  169683. {
  169684. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169685. int ci;
  169686. /* Throw away any unused bits remaining in bit buffer; */
  169687. /* include any full bytes in next_marker's count of discarded bytes */
  169688. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169689. entropy->bitstate.bits_left = 0;
  169690. /* Advance past the RSTn marker */
  169691. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169692. return FALSE;
  169693. /* Re-initialize DC predictions to 0 */
  169694. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169695. entropy->saved.last_dc_val[ci] = 0;
  169696. /* Reset restart counter */
  169697. entropy->restarts_to_go = cinfo->restart_interval;
  169698. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169699. * against a marker. In that case we will end up treating the next data
  169700. * segment as empty, and we can avoid producing bogus output pixels by
  169701. * leaving the flag set.
  169702. */
  169703. if (cinfo->unread_marker == 0)
  169704. entropy->pub.insufficient_data = FALSE;
  169705. return TRUE;
  169706. }
  169707. /*
  169708. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169709. * The coefficients are reordered from zigzag order into natural array order,
  169710. * but are not dequantized.
  169711. *
  169712. * The i'th block of the MCU is stored into the block pointed to by
  169713. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169714. * (Wholesale zeroing is usually a little faster than retail...)
  169715. *
  169716. * Returns FALSE if data source requested suspension. In that case no
  169717. * changes have been made to permanent state. (Exception: some output
  169718. * coefficients may already have been assigned. This is harmless for
  169719. * this module, since we'll just re-assign them on the next call.)
  169720. */
  169721. METHODDEF(boolean)
  169722. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169723. {
  169724. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169725. int blkn;
  169726. BITREAD_STATE_VARS;
  169727. savable_state2 state;
  169728. /* Process restart marker if needed; may have to suspend */
  169729. if (cinfo->restart_interval) {
  169730. if (entropy->restarts_to_go == 0)
  169731. if (! process_restart(cinfo))
  169732. return FALSE;
  169733. }
  169734. /* If we've run out of data, just leave the MCU set to zeroes.
  169735. * This way, we return uniform gray for the remainder of the segment.
  169736. */
  169737. if (! entropy->pub.insufficient_data) {
  169738. /* Load up working state */
  169739. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169740. ASSIGN_STATE(state, entropy->saved);
  169741. /* Outer loop handles each block in the MCU */
  169742. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169743. JBLOCKROW block = MCU_data[blkn];
  169744. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169745. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169746. register int s, k, r;
  169747. /* Decode a single block's worth of coefficients */
  169748. /* Section F.2.2.1: decode the DC coefficient difference */
  169749. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169750. if (s) {
  169751. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169752. r = GET_BITS(s);
  169753. s = HUFF_EXTEND(r, s);
  169754. }
  169755. if (entropy->dc_needed[blkn]) {
  169756. /* Convert DC difference to actual value, update last_dc_val */
  169757. int ci = cinfo->MCU_membership[blkn];
  169758. s += state.last_dc_val[ci];
  169759. state.last_dc_val[ci] = s;
  169760. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169761. (*block)[0] = (JCOEF) s;
  169762. }
  169763. if (entropy->ac_needed[blkn]) {
  169764. /* Section F.2.2.2: decode the AC coefficients */
  169765. /* Since zeroes are skipped, output area must be cleared beforehand */
  169766. for (k = 1; k < DCTSIZE2; k++) {
  169767. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169768. r = s >> 4;
  169769. s &= 15;
  169770. if (s) {
  169771. k += r;
  169772. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169773. r = GET_BITS(s);
  169774. s = HUFF_EXTEND(r, s);
  169775. /* Output coefficient in natural (dezigzagged) order.
  169776. * Note: the extra entries in jpeg_natural_order[] will save us
  169777. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169778. */
  169779. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169780. } else {
  169781. if (r != 15)
  169782. break;
  169783. k += 15;
  169784. }
  169785. }
  169786. } else {
  169787. /* Section F.2.2.2: decode the AC coefficients */
  169788. /* In this path we just discard the values */
  169789. for (k = 1; k < DCTSIZE2; k++) {
  169790. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169791. r = s >> 4;
  169792. s &= 15;
  169793. if (s) {
  169794. k += r;
  169795. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169796. DROP_BITS(s);
  169797. } else {
  169798. if (r != 15)
  169799. break;
  169800. k += 15;
  169801. }
  169802. }
  169803. }
  169804. }
  169805. /* Completed MCU, so update state */
  169806. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169807. ASSIGN_STATE(entropy->saved, state);
  169808. }
  169809. /* Account for restart interval (no-op if not using restarts) */
  169810. entropy->restarts_to_go--;
  169811. return TRUE;
  169812. }
  169813. /*
  169814. * Module initialization routine for Huffman entropy decoding.
  169815. */
  169816. GLOBAL(void)
  169817. jinit_huff_decoder (j_decompress_ptr cinfo)
  169818. {
  169819. huff_entropy_ptr2 entropy;
  169820. int i;
  169821. entropy = (huff_entropy_ptr2)
  169822. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169823. SIZEOF(huff_entropy_decoder2));
  169824. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169825. entropy->pub.start_pass = start_pass_huff_decoder;
  169826. entropy->pub.decode_mcu = decode_mcu;
  169827. /* Mark tables unallocated */
  169828. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169829. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169830. }
  169831. }
  169832. /*** End of inlined file: jdhuff.c ***/
  169833. /*** Start of inlined file: jdinput.c ***/
  169834. #define JPEG_INTERNALS
  169835. /* Private state */
  169836. typedef struct {
  169837. struct jpeg_input_controller pub; /* public fields */
  169838. boolean inheaders; /* TRUE until first SOS is reached */
  169839. } my_input_controller;
  169840. typedef my_input_controller * my_inputctl_ptr;
  169841. /* Forward declarations */
  169842. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169843. /*
  169844. * Routines to calculate various quantities related to the size of the image.
  169845. */
  169846. LOCAL(void)
  169847. initial_setup2 (j_decompress_ptr cinfo)
  169848. /* Called once, when first SOS marker is reached */
  169849. {
  169850. int ci;
  169851. jpeg_component_info *compptr;
  169852. /* Make sure image isn't bigger than I can handle */
  169853. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169854. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169855. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169856. /* For now, precision must match compiled-in value... */
  169857. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169858. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169859. /* Check that number of components won't exceed internal array sizes */
  169860. if (cinfo->num_components > MAX_COMPONENTS)
  169861. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169862. MAX_COMPONENTS);
  169863. /* Compute maximum sampling factors; check factor validity */
  169864. cinfo->max_h_samp_factor = 1;
  169865. cinfo->max_v_samp_factor = 1;
  169866. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169867. ci++, compptr++) {
  169868. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169869. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169870. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169871. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169872. compptr->h_samp_factor);
  169873. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169874. compptr->v_samp_factor);
  169875. }
  169876. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169877. * In the full decompressor, this will be overridden by jdmaster.c;
  169878. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169879. */
  169880. cinfo->min_DCT_scaled_size = DCTSIZE;
  169881. /* Compute dimensions of components */
  169882. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169883. ci++, compptr++) {
  169884. compptr->DCT_scaled_size = DCTSIZE;
  169885. /* Size in DCT blocks */
  169886. compptr->width_in_blocks = (JDIMENSION)
  169887. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169888. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169889. compptr->height_in_blocks = (JDIMENSION)
  169890. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169891. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169892. /* downsampled_width and downsampled_height will also be overridden by
  169893. * jdmaster.c if we are doing full decompression. The transcoder library
  169894. * doesn't use these values, but the calling application might.
  169895. */
  169896. /* Size in samples */
  169897. compptr->downsampled_width = (JDIMENSION)
  169898. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169899. (long) cinfo->max_h_samp_factor);
  169900. compptr->downsampled_height = (JDIMENSION)
  169901. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169902. (long) cinfo->max_v_samp_factor);
  169903. /* Mark component needed, until color conversion says otherwise */
  169904. compptr->component_needed = TRUE;
  169905. /* Mark no quantization table yet saved for component */
  169906. compptr->quant_table = NULL;
  169907. }
  169908. /* Compute number of fully interleaved MCU rows. */
  169909. cinfo->total_iMCU_rows = (JDIMENSION)
  169910. jdiv_round_up((long) cinfo->image_height,
  169911. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169912. /* Decide whether file contains multiple scans */
  169913. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169914. cinfo->inputctl->has_multiple_scans = TRUE;
  169915. else
  169916. cinfo->inputctl->has_multiple_scans = FALSE;
  169917. }
  169918. LOCAL(void)
  169919. per_scan_setup2 (j_decompress_ptr cinfo)
  169920. /* Do computations that are needed before processing a JPEG scan */
  169921. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169922. {
  169923. int ci, mcublks, tmp;
  169924. jpeg_component_info *compptr;
  169925. if (cinfo->comps_in_scan == 1) {
  169926. /* Noninterleaved (single-component) scan */
  169927. compptr = cinfo->cur_comp_info[0];
  169928. /* Overall image size in MCUs */
  169929. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169930. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169931. /* For noninterleaved scan, always one block per MCU */
  169932. compptr->MCU_width = 1;
  169933. compptr->MCU_height = 1;
  169934. compptr->MCU_blocks = 1;
  169935. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169936. compptr->last_col_width = 1;
  169937. /* For noninterleaved scans, it is convenient to define last_row_height
  169938. * as the number of block rows present in the last iMCU row.
  169939. */
  169940. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169941. if (tmp == 0) tmp = compptr->v_samp_factor;
  169942. compptr->last_row_height = tmp;
  169943. /* Prepare array describing MCU composition */
  169944. cinfo->blocks_in_MCU = 1;
  169945. cinfo->MCU_membership[0] = 0;
  169946. } else {
  169947. /* Interleaved (multi-component) scan */
  169948. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169949. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169950. MAX_COMPS_IN_SCAN);
  169951. /* Overall image size in MCUs */
  169952. cinfo->MCUs_per_row = (JDIMENSION)
  169953. jdiv_round_up((long) cinfo->image_width,
  169954. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169955. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169956. jdiv_round_up((long) cinfo->image_height,
  169957. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169958. cinfo->blocks_in_MCU = 0;
  169959. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169960. compptr = cinfo->cur_comp_info[ci];
  169961. /* Sampling factors give # of blocks of component in each MCU */
  169962. compptr->MCU_width = compptr->h_samp_factor;
  169963. compptr->MCU_height = compptr->v_samp_factor;
  169964. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169965. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169966. /* Figure number of non-dummy blocks in last MCU column & row */
  169967. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169968. if (tmp == 0) tmp = compptr->MCU_width;
  169969. compptr->last_col_width = tmp;
  169970. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169971. if (tmp == 0) tmp = compptr->MCU_height;
  169972. compptr->last_row_height = tmp;
  169973. /* Prepare array describing MCU composition */
  169974. mcublks = compptr->MCU_blocks;
  169975. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169976. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169977. while (mcublks-- > 0) {
  169978. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169979. }
  169980. }
  169981. }
  169982. }
  169983. /*
  169984. * Save away a copy of the Q-table referenced by each component present
  169985. * in the current scan, unless already saved during a prior scan.
  169986. *
  169987. * In a multiple-scan JPEG file, the encoder could assign different components
  169988. * the same Q-table slot number, but change table definitions between scans
  169989. * so that each component uses a different Q-table. (The IJG encoder is not
  169990. * currently capable of doing this, but other encoders might.) Since we want
  169991. * to be able to dequantize all the components at the end of the file, this
  169992. * means that we have to save away the table actually used for each component.
  169993. * We do this by copying the table at the start of the first scan containing
  169994. * the component.
  169995. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169996. * slot between scans of a component using that slot. If the encoder does so
  169997. * anyway, this decoder will simply use the Q-table values that were current
  169998. * at the start of the first scan for the component.
  169999. *
  170000. * The decompressor output side looks only at the saved quant tables,
  170001. * not at the current Q-table slots.
  170002. */
  170003. LOCAL(void)
  170004. latch_quant_tables (j_decompress_ptr cinfo)
  170005. {
  170006. int ci, qtblno;
  170007. jpeg_component_info *compptr;
  170008. JQUANT_TBL * qtbl;
  170009. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170010. compptr = cinfo->cur_comp_info[ci];
  170011. /* No work if we already saved Q-table for this component */
  170012. if (compptr->quant_table != NULL)
  170013. continue;
  170014. /* Make sure specified quantization table is present */
  170015. qtblno = compptr->quant_tbl_no;
  170016. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170017. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170018. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170019. /* OK, save away the quantization table */
  170020. qtbl = (JQUANT_TBL *)
  170021. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170022. SIZEOF(JQUANT_TBL));
  170023. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170024. compptr->quant_table = qtbl;
  170025. }
  170026. }
  170027. /*
  170028. * Initialize the input modules to read a scan of compressed data.
  170029. * The first call to this is done by jdmaster.c after initializing
  170030. * the entire decompressor (during jpeg_start_decompress).
  170031. * Subsequent calls come from consume_markers, below.
  170032. */
  170033. METHODDEF(void)
  170034. start_input_pass2 (j_decompress_ptr cinfo)
  170035. {
  170036. per_scan_setup2(cinfo);
  170037. latch_quant_tables(cinfo);
  170038. (*cinfo->entropy->start_pass) (cinfo);
  170039. (*cinfo->coef->start_input_pass) (cinfo);
  170040. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170041. }
  170042. /*
  170043. * Finish up after inputting a compressed-data scan.
  170044. * This is called by the coefficient controller after it's read all
  170045. * the expected data of the scan.
  170046. */
  170047. METHODDEF(void)
  170048. finish_input_pass (j_decompress_ptr cinfo)
  170049. {
  170050. cinfo->inputctl->consume_input = consume_markers;
  170051. }
  170052. /*
  170053. * Read JPEG markers before, between, or after compressed-data scans.
  170054. * Change state as necessary when a new scan is reached.
  170055. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170056. *
  170057. * The consume_input method pointer points either here or to the
  170058. * coefficient controller's consume_data routine, depending on whether
  170059. * we are reading a compressed data segment or inter-segment markers.
  170060. */
  170061. METHODDEF(int)
  170062. consume_markers (j_decompress_ptr cinfo)
  170063. {
  170064. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170065. int val;
  170066. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170067. return JPEG_REACHED_EOI;
  170068. val = (*cinfo->marker->read_markers) (cinfo);
  170069. switch (val) {
  170070. case JPEG_REACHED_SOS: /* Found SOS */
  170071. if (inputctl->inheaders) { /* 1st SOS */
  170072. initial_setup2(cinfo);
  170073. inputctl->inheaders = FALSE;
  170074. /* Note: start_input_pass must be called by jdmaster.c
  170075. * before any more input can be consumed. jdapimin.c is
  170076. * responsible for enforcing this sequencing.
  170077. */
  170078. } else { /* 2nd or later SOS marker */
  170079. if (! inputctl->pub.has_multiple_scans)
  170080. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170081. start_input_pass2(cinfo);
  170082. }
  170083. break;
  170084. case JPEG_REACHED_EOI: /* Found EOI */
  170085. inputctl->pub.eoi_reached = TRUE;
  170086. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170087. if (cinfo->marker->saw_SOF)
  170088. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170089. } else {
  170090. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170091. * if user set output_scan_number larger than number of scans.
  170092. */
  170093. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170094. cinfo->output_scan_number = cinfo->input_scan_number;
  170095. }
  170096. break;
  170097. case JPEG_SUSPENDED:
  170098. break;
  170099. }
  170100. return val;
  170101. }
  170102. /*
  170103. * Reset state to begin a fresh datastream.
  170104. */
  170105. METHODDEF(void)
  170106. reset_input_controller (j_decompress_ptr cinfo)
  170107. {
  170108. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170109. inputctl->pub.consume_input = consume_markers;
  170110. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170111. inputctl->pub.eoi_reached = FALSE;
  170112. inputctl->inheaders = TRUE;
  170113. /* Reset other modules */
  170114. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170115. (*cinfo->marker->reset_marker_reader) (cinfo);
  170116. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170117. cinfo->coef_bits = NULL;
  170118. }
  170119. /*
  170120. * Initialize the input controller module.
  170121. * This is called only once, when the decompression object is created.
  170122. */
  170123. GLOBAL(void)
  170124. jinit_input_controller (j_decompress_ptr cinfo)
  170125. {
  170126. my_inputctl_ptr inputctl;
  170127. /* Create subobject in permanent pool */
  170128. inputctl = (my_inputctl_ptr)
  170129. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170130. SIZEOF(my_input_controller));
  170131. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170132. /* Initialize method pointers */
  170133. inputctl->pub.consume_input = consume_markers;
  170134. inputctl->pub.reset_input_controller = reset_input_controller;
  170135. inputctl->pub.start_input_pass = start_input_pass2;
  170136. inputctl->pub.finish_input_pass = finish_input_pass;
  170137. /* Initialize state: can't use reset_input_controller since we don't
  170138. * want to try to reset other modules yet.
  170139. */
  170140. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170141. inputctl->pub.eoi_reached = FALSE;
  170142. inputctl->inheaders = TRUE;
  170143. }
  170144. /*** End of inlined file: jdinput.c ***/
  170145. /*** Start of inlined file: jdmainct.c ***/
  170146. #define JPEG_INTERNALS
  170147. /*
  170148. * In the current system design, the main buffer need never be a full-image
  170149. * buffer; any full-height buffers will be found inside the coefficient or
  170150. * postprocessing controllers. Nonetheless, the main controller is not
  170151. * trivial. Its responsibility is to provide context rows for upsampling/
  170152. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170153. *
  170154. * Postprocessor input data is counted in "row groups". A row group
  170155. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170156. * sample rows of each component. (We require DCT_scaled_size values to be
  170157. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170158. * values will likely be powers of two, so we actually have the stronger
  170159. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170160. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170161. * row group (times any additional scale factor that the upsampler is
  170162. * applying).
  170163. *
  170164. * The coefficient controller will deliver data to us one iMCU row at a time;
  170165. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170166. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170167. * to one row of MCUs when the image is fully interleaved.) Note that the
  170168. * number of sample rows varies across components, but the number of row
  170169. * groups does not. Some garbage sample rows may be included in the last iMCU
  170170. * row at the bottom of the image.
  170171. *
  170172. * Depending on the vertical scaling algorithm used, the upsampler may need
  170173. * access to the sample row(s) above and below its current input row group.
  170174. * The upsampler is required to set need_context_rows TRUE at global selection
  170175. * time if so. When need_context_rows is FALSE, this controller can simply
  170176. * obtain one iMCU row at a time from the coefficient controller and dole it
  170177. * out as row groups to the postprocessor.
  170178. *
  170179. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170180. * passed to postprocessing contains at least one row group's worth of samples
  170181. * above and below the row group(s) being processed. Note that the context
  170182. * rows "above" the first passed row group appear at negative row offsets in
  170183. * the passed buffer. At the top and bottom of the image, the required
  170184. * context rows are manufactured by duplicating the first or last real sample
  170185. * row; this avoids having special cases in the upsampling inner loops.
  170186. *
  170187. * The amount of context is fixed at one row group just because that's a
  170188. * convenient number for this controller to work with. The existing
  170189. * upsamplers really only need one sample row of context. An upsampler
  170190. * supporting arbitrary output rescaling might wish for more than one row
  170191. * group of context when shrinking the image; tough, we don't handle that.
  170192. * (This is justified by the assumption that downsizing will be handled mostly
  170193. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170194. * the upsample step needn't be much less than one.)
  170195. *
  170196. * To provide the desired context, we have to retain the last two row groups
  170197. * of one iMCU row while reading in the next iMCU row. (The last row group
  170198. * can't be processed until we have another row group for its below-context,
  170199. * and so we have to save the next-to-last group too for its above-context.)
  170200. * We could do this most simply by copying data around in our buffer, but
  170201. * that'd be very slow. We can avoid copying any data by creating a rather
  170202. * strange pointer structure. Here's how it works. We allocate a workspace
  170203. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170204. * of row groups per iMCU row). We create two sets of redundant pointers to
  170205. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170206. * pointer lists look like this:
  170207. * M+1 M-1
  170208. * master pointer --> 0 master pointer --> 0
  170209. * 1 1
  170210. * ... ...
  170211. * M-3 M-3
  170212. * M-2 M
  170213. * M-1 M+1
  170214. * M M-2
  170215. * M+1 M-1
  170216. * 0 0
  170217. * We read alternate iMCU rows using each master pointer; thus the last two
  170218. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170219. * The pointer lists are set up so that the required context rows appear to
  170220. * be adjacent to the proper places when we pass the pointer lists to the
  170221. * upsampler.
  170222. *
  170223. * The above pictures describe the normal state of the pointer lists.
  170224. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170225. * the first or last sample row as necessary (this is cheaper than copying
  170226. * sample rows around).
  170227. *
  170228. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170229. * situation each iMCU row provides only one row group so the buffering logic
  170230. * must be different (eg, we must read two iMCU rows before we can emit the
  170231. * first row group). For now, we simply do not support providing context
  170232. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170233. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170234. * want it quick and dirty, so a context-free upsampler is sufficient.
  170235. */
  170236. /* Private buffer controller object */
  170237. typedef struct {
  170238. struct jpeg_d_main_controller pub; /* public fields */
  170239. /* Pointer to allocated workspace (M or M+2 row groups). */
  170240. JSAMPARRAY buffer[MAX_COMPONENTS];
  170241. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170242. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170243. /* Remaining fields are only used in the context case. */
  170244. /* These are the master pointers to the funny-order pointer lists. */
  170245. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170246. int whichptr; /* indicates which pointer set is now in use */
  170247. int context_state; /* process_data state machine status */
  170248. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170249. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170250. } my_main_controller4;
  170251. typedef my_main_controller4 * my_main_ptr4;
  170252. /* context_state values: */
  170253. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170254. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170255. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170256. /* Forward declarations */
  170257. METHODDEF(void) process_data_simple_main2
  170258. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170259. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170260. METHODDEF(void) process_data_context_main
  170261. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170262. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170263. #ifdef QUANT_2PASS_SUPPORTED
  170264. METHODDEF(void) process_data_crank_post
  170265. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170266. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170267. #endif
  170268. LOCAL(void)
  170269. alloc_funny_pointers (j_decompress_ptr cinfo)
  170270. /* Allocate space for the funny pointer lists.
  170271. * This is done only once, not once per pass.
  170272. */
  170273. {
  170274. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170275. int ci, rgroup;
  170276. int M = cinfo->min_DCT_scaled_size;
  170277. jpeg_component_info *compptr;
  170278. JSAMPARRAY xbuf;
  170279. /* Get top-level space for component array pointers.
  170280. * We alloc both arrays with one call to save a few cycles.
  170281. */
  170282. main_->xbuffer[0] = (JSAMPIMAGE)
  170283. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170284. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170285. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170286. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170287. ci++, compptr++) {
  170288. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170289. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170290. /* Get space for pointer lists --- M+4 row groups in each list.
  170291. * We alloc both pointer lists with one call to save a few cycles.
  170292. */
  170293. xbuf = (JSAMPARRAY)
  170294. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170295. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170296. xbuf += rgroup; /* want one row group at negative offsets */
  170297. main_->xbuffer[0][ci] = xbuf;
  170298. xbuf += rgroup * (M + 4);
  170299. main_->xbuffer[1][ci] = xbuf;
  170300. }
  170301. }
  170302. LOCAL(void)
  170303. make_funny_pointers (j_decompress_ptr cinfo)
  170304. /* Create the funny pointer lists discussed in the comments above.
  170305. * The actual workspace is already allocated (in main->buffer),
  170306. * and the space for the pointer lists is allocated too.
  170307. * This routine just fills in the curiously ordered lists.
  170308. * This will be repeated at the beginning of each pass.
  170309. */
  170310. {
  170311. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170312. int ci, i, rgroup;
  170313. int M = cinfo->min_DCT_scaled_size;
  170314. jpeg_component_info *compptr;
  170315. JSAMPARRAY buf, xbuf0, xbuf1;
  170316. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170317. ci++, compptr++) {
  170318. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170319. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170320. xbuf0 = main_->xbuffer[0][ci];
  170321. xbuf1 = main_->xbuffer[1][ci];
  170322. /* First copy the workspace pointers as-is */
  170323. buf = main_->buffer[ci];
  170324. for (i = 0; i < rgroup * (M + 2); i++) {
  170325. xbuf0[i] = xbuf1[i] = buf[i];
  170326. }
  170327. /* In the second list, put the last four row groups in swapped order */
  170328. for (i = 0; i < rgroup * 2; i++) {
  170329. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170330. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170331. }
  170332. /* The wraparound pointers at top and bottom will be filled later
  170333. * (see set_wraparound_pointers, below). Initially we want the "above"
  170334. * pointers to duplicate the first actual data line. This only needs
  170335. * to happen in xbuffer[0].
  170336. */
  170337. for (i = 0; i < rgroup; i++) {
  170338. xbuf0[i - rgroup] = xbuf0[0];
  170339. }
  170340. }
  170341. }
  170342. LOCAL(void)
  170343. set_wraparound_pointers (j_decompress_ptr cinfo)
  170344. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170345. * This changes the pointer list state from top-of-image to the normal state.
  170346. */
  170347. {
  170348. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170349. int ci, i, rgroup;
  170350. int M = cinfo->min_DCT_scaled_size;
  170351. jpeg_component_info *compptr;
  170352. JSAMPARRAY xbuf0, xbuf1;
  170353. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170354. ci++, compptr++) {
  170355. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170356. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170357. xbuf0 = main_->xbuffer[0][ci];
  170358. xbuf1 = main_->xbuffer[1][ci];
  170359. for (i = 0; i < rgroup; i++) {
  170360. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170361. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170362. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170363. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170364. }
  170365. }
  170366. }
  170367. LOCAL(void)
  170368. set_bottom_pointers (j_decompress_ptr cinfo)
  170369. /* Change the pointer lists to duplicate the last sample row at the bottom
  170370. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170371. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170372. */
  170373. {
  170374. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170375. int ci, i, rgroup, iMCUheight, rows_left;
  170376. jpeg_component_info *compptr;
  170377. JSAMPARRAY xbuf;
  170378. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170379. ci++, compptr++) {
  170380. /* Count sample rows in one iMCU row and in one row group */
  170381. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170382. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170383. /* Count nondummy sample rows remaining for this component */
  170384. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170385. if (rows_left == 0) rows_left = iMCUheight;
  170386. /* Count nondummy row groups. Should get same answer for each component,
  170387. * so we need only do it once.
  170388. */
  170389. if (ci == 0) {
  170390. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170391. }
  170392. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170393. * last partial rowgroup and ensures at least one full rowgroup of context.
  170394. */
  170395. xbuf = main_->xbuffer[main_->whichptr][ci];
  170396. for (i = 0; i < rgroup * 2; i++) {
  170397. xbuf[rows_left + i] = xbuf[rows_left-1];
  170398. }
  170399. }
  170400. }
  170401. /*
  170402. * Initialize for a processing pass.
  170403. */
  170404. METHODDEF(void)
  170405. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170406. {
  170407. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170408. switch (pass_mode) {
  170409. case JBUF_PASS_THRU:
  170410. if (cinfo->upsample->need_context_rows) {
  170411. main_->pub.process_data = process_data_context_main;
  170412. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170413. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170414. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170415. main_->iMCU_row_ctr = 0;
  170416. } else {
  170417. /* Simple case with no context needed */
  170418. main_->pub.process_data = process_data_simple_main2;
  170419. }
  170420. main_->buffer_full = FALSE; /* Mark buffer empty */
  170421. main_->rowgroup_ctr = 0;
  170422. break;
  170423. #ifdef QUANT_2PASS_SUPPORTED
  170424. case JBUF_CRANK_DEST:
  170425. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170426. main_->pub.process_data = process_data_crank_post;
  170427. break;
  170428. #endif
  170429. default:
  170430. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170431. break;
  170432. }
  170433. }
  170434. /*
  170435. * Process some data.
  170436. * This handles the simple case where no context is required.
  170437. */
  170438. METHODDEF(void)
  170439. process_data_simple_main2 (j_decompress_ptr cinfo,
  170440. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170441. JDIMENSION out_rows_avail)
  170442. {
  170443. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170444. JDIMENSION rowgroups_avail;
  170445. /* Read input data if we haven't filled the main buffer yet */
  170446. if (! main_->buffer_full) {
  170447. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170448. return; /* suspension forced, can do nothing more */
  170449. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170450. }
  170451. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170452. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170453. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170454. * to the postprocessor. The postprocessor has to check for bottom
  170455. * of image anyway (at row resolution), so no point in us doing it too.
  170456. */
  170457. /* Feed the postprocessor */
  170458. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170459. &main_->rowgroup_ctr, rowgroups_avail,
  170460. output_buf, out_row_ctr, out_rows_avail);
  170461. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170462. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170463. main_->buffer_full = FALSE;
  170464. main_->rowgroup_ctr = 0;
  170465. }
  170466. }
  170467. /*
  170468. * Process some data.
  170469. * This handles the case where context rows must be provided.
  170470. */
  170471. METHODDEF(void)
  170472. process_data_context_main (j_decompress_ptr cinfo,
  170473. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170474. JDIMENSION out_rows_avail)
  170475. {
  170476. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170477. /* Read input data if we haven't filled the main buffer yet */
  170478. if (! main_->buffer_full) {
  170479. if (! (*cinfo->coef->decompress_data) (cinfo,
  170480. main_->xbuffer[main_->whichptr]))
  170481. return; /* suspension forced, can do nothing more */
  170482. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170483. main_->iMCU_row_ctr++; /* count rows received */
  170484. }
  170485. /* Postprocessor typically will not swallow all the input data it is handed
  170486. * in one call (due to filling the output buffer first). Must be prepared
  170487. * to exit and restart. This switch lets us keep track of how far we got.
  170488. * Note that each case falls through to the next on successful completion.
  170489. */
  170490. switch (main_->context_state) {
  170491. case CTX_POSTPONED_ROW:
  170492. /* Call postprocessor using previously set pointers for postponed row */
  170493. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170494. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170495. output_buf, out_row_ctr, out_rows_avail);
  170496. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170497. return; /* Need to suspend */
  170498. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170499. if (*out_row_ctr >= out_rows_avail)
  170500. return; /* Postprocessor exactly filled output buf */
  170501. /*FALLTHROUGH*/
  170502. case CTX_PREPARE_FOR_IMCU:
  170503. /* Prepare to process first M-1 row groups of this iMCU row */
  170504. main_->rowgroup_ctr = 0;
  170505. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170506. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170507. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170508. */
  170509. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170510. set_bottom_pointers(cinfo);
  170511. main_->context_state = CTX_PROCESS_IMCU;
  170512. /*FALLTHROUGH*/
  170513. case CTX_PROCESS_IMCU:
  170514. /* Call postprocessor using previously set pointers */
  170515. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170516. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170517. output_buf, out_row_ctr, out_rows_avail);
  170518. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170519. return; /* Need to suspend */
  170520. /* After the first iMCU, change wraparound pointers to normal state */
  170521. if (main_->iMCU_row_ctr == 1)
  170522. set_wraparound_pointers(cinfo);
  170523. /* Prepare to load new iMCU row using other xbuffer list */
  170524. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170525. main_->buffer_full = FALSE;
  170526. /* Still need to process last row group of this iMCU row, */
  170527. /* which is saved at index M+1 of the other xbuffer */
  170528. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170529. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170530. main_->context_state = CTX_POSTPONED_ROW;
  170531. }
  170532. }
  170533. /*
  170534. * Process some data.
  170535. * Final pass of two-pass quantization: just call the postprocessor.
  170536. * Source data will be the postprocessor controller's internal buffer.
  170537. */
  170538. #ifdef QUANT_2PASS_SUPPORTED
  170539. METHODDEF(void)
  170540. process_data_crank_post (j_decompress_ptr cinfo,
  170541. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170542. JDIMENSION out_rows_avail)
  170543. {
  170544. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170545. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170546. output_buf, out_row_ctr, out_rows_avail);
  170547. }
  170548. #endif /* QUANT_2PASS_SUPPORTED */
  170549. /*
  170550. * Initialize main buffer controller.
  170551. */
  170552. GLOBAL(void)
  170553. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170554. {
  170555. my_main_ptr4 main_;
  170556. int ci, rgroup, ngroups;
  170557. jpeg_component_info *compptr;
  170558. main_ = (my_main_ptr4)
  170559. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170560. SIZEOF(my_main_controller4));
  170561. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170562. main_->pub.start_pass = start_pass_main2;
  170563. if (need_full_buffer) /* shouldn't happen */
  170564. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170565. /* Allocate the workspace.
  170566. * ngroups is the number of row groups we need.
  170567. */
  170568. if (cinfo->upsample->need_context_rows) {
  170569. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170570. ERREXIT(cinfo, JERR_NOTIMPL);
  170571. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170572. ngroups = cinfo->min_DCT_scaled_size + 2;
  170573. } else {
  170574. ngroups = cinfo->min_DCT_scaled_size;
  170575. }
  170576. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170577. ci++, compptr++) {
  170578. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170579. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170580. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170581. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170582. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170583. (JDIMENSION) (rgroup * ngroups));
  170584. }
  170585. }
  170586. /*** End of inlined file: jdmainct.c ***/
  170587. /*** Start of inlined file: jdmarker.c ***/
  170588. #define JPEG_INTERNALS
  170589. /* Private state */
  170590. typedef struct {
  170591. struct jpeg_marker_reader pub; /* public fields */
  170592. /* Application-overridable marker processing methods */
  170593. jpeg_marker_parser_method process_COM;
  170594. jpeg_marker_parser_method process_APPn[16];
  170595. /* Limit on marker data length to save for each marker type */
  170596. unsigned int length_limit_COM;
  170597. unsigned int length_limit_APPn[16];
  170598. /* Status of COM/APPn marker saving */
  170599. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170600. unsigned int bytes_read; /* data bytes read so far in marker */
  170601. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170602. } my_marker_reader;
  170603. typedef my_marker_reader * my_marker_ptr2;
  170604. /*
  170605. * Macros for fetching data from the data source module.
  170606. *
  170607. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170608. * the current restart point; we update them only when we have reached a
  170609. * suitable place to restart if a suspension occurs.
  170610. */
  170611. /* Declare and initialize local copies of input pointer/count */
  170612. #define INPUT_VARS(cinfo) \
  170613. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170614. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170615. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170616. /* Unload the local copies --- do this only at a restart boundary */
  170617. #define INPUT_SYNC(cinfo) \
  170618. ( datasrc->next_input_byte = next_input_byte, \
  170619. datasrc->bytes_in_buffer = bytes_in_buffer )
  170620. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170621. #define INPUT_RELOAD(cinfo) \
  170622. ( next_input_byte = datasrc->next_input_byte, \
  170623. bytes_in_buffer = datasrc->bytes_in_buffer )
  170624. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170625. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170626. * but we must reload the local copies after a successful fill.
  170627. */
  170628. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170629. if (bytes_in_buffer == 0) { \
  170630. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170631. { action; } \
  170632. INPUT_RELOAD(cinfo); \
  170633. }
  170634. /* Read a byte into variable V.
  170635. * If must suspend, take the specified action (typically "return FALSE").
  170636. */
  170637. #define INPUT_BYTE(cinfo,V,action) \
  170638. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170639. bytes_in_buffer--; \
  170640. V = GETJOCTET(*next_input_byte++); )
  170641. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170642. * V should be declared unsigned int or perhaps INT32.
  170643. */
  170644. #define INPUT_2BYTES(cinfo,V,action) \
  170645. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170646. bytes_in_buffer--; \
  170647. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170648. MAKE_BYTE_AVAIL(cinfo,action); \
  170649. bytes_in_buffer--; \
  170650. V += GETJOCTET(*next_input_byte++); )
  170651. /*
  170652. * Routines to process JPEG markers.
  170653. *
  170654. * Entry condition: JPEG marker itself has been read and its code saved
  170655. * in cinfo->unread_marker; input restart point is just after the marker.
  170656. *
  170657. * Exit: if return TRUE, have read and processed any parameters, and have
  170658. * updated the restart point to point after the parameters.
  170659. * If return FALSE, was forced to suspend before reaching end of
  170660. * marker parameters; restart point has not been moved. Same routine
  170661. * will be called again after application supplies more input data.
  170662. *
  170663. * This approach to suspension assumes that all of a marker's parameters
  170664. * can fit into a single input bufferload. This should hold for "normal"
  170665. * markers. Some COM/APPn markers might have large parameter segments
  170666. * that might not fit. If we are simply dropping such a marker, we use
  170667. * skip_input_data to get past it, and thereby put the problem on the
  170668. * source manager's shoulders. If we are saving the marker's contents
  170669. * into memory, we use a slightly different convention: when forced to
  170670. * suspend, the marker processor updates the restart point to the end of
  170671. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170672. * On resumption, cinfo->unread_marker still contains the marker code,
  170673. * but the data source will point to the next chunk of marker data.
  170674. * The marker processor must retain internal state to deal with this.
  170675. *
  170676. * Note that we don't bother to avoid duplicate trace messages if a
  170677. * suspension occurs within marker parameters. Other side effects
  170678. * require more care.
  170679. */
  170680. LOCAL(boolean)
  170681. get_soi (j_decompress_ptr cinfo)
  170682. /* Process an SOI marker */
  170683. {
  170684. int i;
  170685. TRACEMS(cinfo, 1, JTRC_SOI);
  170686. if (cinfo->marker->saw_SOI)
  170687. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170688. /* Reset all parameters that are defined to be reset by SOI */
  170689. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170690. cinfo->arith_dc_L[i] = 0;
  170691. cinfo->arith_dc_U[i] = 1;
  170692. cinfo->arith_ac_K[i] = 5;
  170693. }
  170694. cinfo->restart_interval = 0;
  170695. /* Set initial assumptions for colorspace etc */
  170696. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170697. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170698. cinfo->saw_JFIF_marker = FALSE;
  170699. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170700. cinfo->JFIF_minor_version = 1;
  170701. cinfo->density_unit = 0;
  170702. cinfo->X_density = 1;
  170703. cinfo->Y_density = 1;
  170704. cinfo->saw_Adobe_marker = FALSE;
  170705. cinfo->Adobe_transform = 0;
  170706. cinfo->marker->saw_SOI = TRUE;
  170707. return TRUE;
  170708. }
  170709. LOCAL(boolean)
  170710. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170711. /* Process a SOFn marker */
  170712. {
  170713. INT32 length;
  170714. int c, ci;
  170715. jpeg_component_info * compptr;
  170716. INPUT_VARS(cinfo);
  170717. cinfo->progressive_mode = is_prog;
  170718. cinfo->arith_code = is_arith;
  170719. INPUT_2BYTES(cinfo, length, return FALSE);
  170720. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170721. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170722. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170723. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170724. length -= 8;
  170725. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170726. (int) cinfo->image_width, (int) cinfo->image_height,
  170727. cinfo->num_components);
  170728. if (cinfo->marker->saw_SOF)
  170729. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170730. /* We don't support files in which the image height is initially specified */
  170731. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170732. /* might as well have a general sanity check. */
  170733. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170734. || cinfo->num_components <= 0)
  170735. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170736. if (length != (cinfo->num_components * 3))
  170737. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170738. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170739. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170740. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170741. cinfo->num_components * SIZEOF(jpeg_component_info));
  170742. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170743. ci++, compptr++) {
  170744. compptr->component_index = ci;
  170745. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170746. INPUT_BYTE(cinfo, c, return FALSE);
  170747. compptr->h_samp_factor = (c >> 4) & 15;
  170748. compptr->v_samp_factor = (c ) & 15;
  170749. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170750. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170751. compptr->component_id, compptr->h_samp_factor,
  170752. compptr->v_samp_factor, compptr->quant_tbl_no);
  170753. }
  170754. cinfo->marker->saw_SOF = TRUE;
  170755. INPUT_SYNC(cinfo);
  170756. return TRUE;
  170757. }
  170758. LOCAL(boolean)
  170759. get_sos (j_decompress_ptr cinfo)
  170760. /* Process a SOS marker */
  170761. {
  170762. INT32 length;
  170763. int i, ci, n, c, cc;
  170764. jpeg_component_info * compptr;
  170765. INPUT_VARS(cinfo);
  170766. if (! cinfo->marker->saw_SOF)
  170767. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170768. INPUT_2BYTES(cinfo, length, return FALSE);
  170769. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170770. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170771. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170772. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170773. cinfo->comps_in_scan = n;
  170774. /* Collect the component-spec parameters */
  170775. for (i = 0; i < n; i++) {
  170776. INPUT_BYTE(cinfo, cc, return FALSE);
  170777. INPUT_BYTE(cinfo, c, return FALSE);
  170778. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170779. ci++, compptr++) {
  170780. if (cc == compptr->component_id)
  170781. goto id_found;
  170782. }
  170783. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170784. id_found:
  170785. cinfo->cur_comp_info[i] = compptr;
  170786. compptr->dc_tbl_no = (c >> 4) & 15;
  170787. compptr->ac_tbl_no = (c ) & 15;
  170788. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170789. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170790. }
  170791. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170792. INPUT_BYTE(cinfo, c, return FALSE);
  170793. cinfo->Ss = c;
  170794. INPUT_BYTE(cinfo, c, return FALSE);
  170795. cinfo->Se = c;
  170796. INPUT_BYTE(cinfo, c, return FALSE);
  170797. cinfo->Ah = (c >> 4) & 15;
  170798. cinfo->Al = (c ) & 15;
  170799. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170800. cinfo->Ah, cinfo->Al);
  170801. /* Prepare to scan data & restart markers */
  170802. cinfo->marker->next_restart_num = 0;
  170803. /* Count another SOS marker */
  170804. cinfo->input_scan_number++;
  170805. INPUT_SYNC(cinfo);
  170806. return TRUE;
  170807. }
  170808. #ifdef D_ARITH_CODING_SUPPORTED
  170809. LOCAL(boolean)
  170810. get_dac (j_decompress_ptr cinfo)
  170811. /* Process a DAC marker */
  170812. {
  170813. INT32 length;
  170814. int index, val;
  170815. INPUT_VARS(cinfo);
  170816. INPUT_2BYTES(cinfo, length, return FALSE);
  170817. length -= 2;
  170818. while (length > 0) {
  170819. INPUT_BYTE(cinfo, index, return FALSE);
  170820. INPUT_BYTE(cinfo, val, return FALSE);
  170821. length -= 2;
  170822. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170823. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170824. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170825. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170826. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170827. } else { /* define DC table */
  170828. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170829. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170830. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170831. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170832. }
  170833. }
  170834. if (length != 0)
  170835. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170836. INPUT_SYNC(cinfo);
  170837. return TRUE;
  170838. }
  170839. #else /* ! D_ARITH_CODING_SUPPORTED */
  170840. #define get_dac(cinfo) skip_variable(cinfo)
  170841. #endif /* D_ARITH_CODING_SUPPORTED */
  170842. LOCAL(boolean)
  170843. get_dht (j_decompress_ptr cinfo)
  170844. /* Process a DHT marker */
  170845. {
  170846. INT32 length;
  170847. UINT8 bits[17];
  170848. UINT8 huffval[256];
  170849. int i, index, count;
  170850. JHUFF_TBL **htblptr;
  170851. INPUT_VARS(cinfo);
  170852. INPUT_2BYTES(cinfo, length, return FALSE);
  170853. length -= 2;
  170854. while (length > 16) {
  170855. INPUT_BYTE(cinfo, index, return FALSE);
  170856. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170857. bits[0] = 0;
  170858. count = 0;
  170859. for (i = 1; i <= 16; i++) {
  170860. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170861. count += bits[i];
  170862. }
  170863. length -= 1 + 16;
  170864. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170865. bits[1], bits[2], bits[3], bits[4],
  170866. bits[5], bits[6], bits[7], bits[8]);
  170867. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170868. bits[9], bits[10], bits[11], bits[12],
  170869. bits[13], bits[14], bits[15], bits[16]);
  170870. /* Here we just do minimal validation of the counts to avoid walking
  170871. * off the end of our table space. jdhuff.c will check more carefully.
  170872. */
  170873. if (count > 256 || ((INT32) count) > length)
  170874. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170875. for (i = 0; i < count; i++)
  170876. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170877. length -= count;
  170878. if (index & 0x10) { /* AC table definition */
  170879. index -= 0x10;
  170880. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170881. } else { /* DC table definition */
  170882. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170883. }
  170884. if (index < 0 || index >= NUM_HUFF_TBLS)
  170885. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170886. if (*htblptr == NULL)
  170887. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170888. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170889. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170890. }
  170891. if (length != 0)
  170892. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170893. INPUT_SYNC(cinfo);
  170894. return TRUE;
  170895. }
  170896. LOCAL(boolean)
  170897. get_dqt (j_decompress_ptr cinfo)
  170898. /* Process a DQT marker */
  170899. {
  170900. INT32 length;
  170901. int n, i, prec;
  170902. unsigned int tmp;
  170903. JQUANT_TBL *quant_ptr;
  170904. INPUT_VARS(cinfo);
  170905. INPUT_2BYTES(cinfo, length, return FALSE);
  170906. length -= 2;
  170907. while (length > 0) {
  170908. INPUT_BYTE(cinfo, n, return FALSE);
  170909. prec = n >> 4;
  170910. n &= 0x0F;
  170911. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170912. if (n >= NUM_QUANT_TBLS)
  170913. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170914. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170915. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170916. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170917. for (i = 0; i < DCTSIZE2; i++) {
  170918. if (prec)
  170919. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170920. else
  170921. INPUT_BYTE(cinfo, tmp, return FALSE);
  170922. /* We convert the zigzag-order table to natural array order. */
  170923. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170924. }
  170925. if (cinfo->err->trace_level >= 2) {
  170926. for (i = 0; i < DCTSIZE2; i += 8) {
  170927. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170928. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170929. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170930. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170931. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170932. }
  170933. }
  170934. length -= DCTSIZE2+1;
  170935. if (prec) length -= DCTSIZE2;
  170936. }
  170937. if (length != 0)
  170938. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170939. INPUT_SYNC(cinfo);
  170940. return TRUE;
  170941. }
  170942. LOCAL(boolean)
  170943. get_dri (j_decompress_ptr cinfo)
  170944. /* Process a DRI marker */
  170945. {
  170946. INT32 length;
  170947. unsigned int tmp;
  170948. INPUT_VARS(cinfo);
  170949. INPUT_2BYTES(cinfo, length, return FALSE);
  170950. if (length != 4)
  170951. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170952. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170953. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170954. cinfo->restart_interval = tmp;
  170955. INPUT_SYNC(cinfo);
  170956. return TRUE;
  170957. }
  170958. /*
  170959. * Routines for processing APPn and COM markers.
  170960. * These are either saved in memory or discarded, per application request.
  170961. * APP0 and APP14 are specially checked to see if they are
  170962. * JFIF and Adobe markers, respectively.
  170963. */
  170964. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170965. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170966. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170967. LOCAL(void)
  170968. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170969. unsigned int datalen, INT32 remaining)
  170970. /* Examine first few bytes from an APP0.
  170971. * Take appropriate action if it is a JFIF marker.
  170972. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170973. */
  170974. {
  170975. INT32 totallen = (INT32) datalen + remaining;
  170976. if (datalen >= APP0_DATA_LEN &&
  170977. GETJOCTET(data[0]) == 0x4A &&
  170978. GETJOCTET(data[1]) == 0x46 &&
  170979. GETJOCTET(data[2]) == 0x49 &&
  170980. GETJOCTET(data[3]) == 0x46 &&
  170981. GETJOCTET(data[4]) == 0) {
  170982. /* Found JFIF APP0 marker: save info */
  170983. cinfo->saw_JFIF_marker = TRUE;
  170984. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170985. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170986. cinfo->density_unit = GETJOCTET(data[7]);
  170987. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170988. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170989. /* Check version.
  170990. * Major version must be 1, anything else signals an incompatible change.
  170991. * (We used to treat this as an error, but now it's a nonfatal warning,
  170992. * because some bozo at Hijaak couldn't read the spec.)
  170993. * Minor version should be 0..2, but process anyway if newer.
  170994. */
  170995. if (cinfo->JFIF_major_version != 1)
  170996. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170997. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170998. /* Generate trace messages */
  170999. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171000. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171001. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171002. /* Validate thumbnail dimensions and issue appropriate messages */
  171003. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171004. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171005. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171006. totallen -= APP0_DATA_LEN;
  171007. if (totallen !=
  171008. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171009. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171010. } else if (datalen >= 6 &&
  171011. GETJOCTET(data[0]) == 0x4A &&
  171012. GETJOCTET(data[1]) == 0x46 &&
  171013. GETJOCTET(data[2]) == 0x58 &&
  171014. GETJOCTET(data[3]) == 0x58 &&
  171015. GETJOCTET(data[4]) == 0) {
  171016. /* Found JFIF "JFXX" extension APP0 marker */
  171017. /* The library doesn't actually do anything with these,
  171018. * but we try to produce a helpful trace message.
  171019. */
  171020. switch (GETJOCTET(data[5])) {
  171021. case 0x10:
  171022. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171023. break;
  171024. case 0x11:
  171025. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171026. break;
  171027. case 0x13:
  171028. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171029. break;
  171030. default:
  171031. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171032. GETJOCTET(data[5]), (int) totallen);
  171033. break;
  171034. }
  171035. } else {
  171036. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171037. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171038. }
  171039. }
  171040. LOCAL(void)
  171041. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171042. unsigned int datalen, INT32 remaining)
  171043. /* Examine first few bytes from an APP14.
  171044. * Take appropriate action if it is an Adobe marker.
  171045. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171046. */
  171047. {
  171048. unsigned int version, flags0, flags1, transform;
  171049. if (datalen >= APP14_DATA_LEN &&
  171050. GETJOCTET(data[0]) == 0x41 &&
  171051. GETJOCTET(data[1]) == 0x64 &&
  171052. GETJOCTET(data[2]) == 0x6F &&
  171053. GETJOCTET(data[3]) == 0x62 &&
  171054. GETJOCTET(data[4]) == 0x65) {
  171055. /* Found Adobe APP14 marker */
  171056. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171057. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171058. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171059. transform = GETJOCTET(data[11]);
  171060. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171061. cinfo->saw_Adobe_marker = TRUE;
  171062. cinfo->Adobe_transform = (UINT8) transform;
  171063. } else {
  171064. /* Start of APP14 does not match "Adobe", or too short */
  171065. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171066. }
  171067. }
  171068. METHODDEF(boolean)
  171069. get_interesting_appn (j_decompress_ptr cinfo)
  171070. /* Process an APP0 or APP14 marker without saving it */
  171071. {
  171072. INT32 length;
  171073. JOCTET b[APPN_DATA_LEN];
  171074. unsigned int i, numtoread;
  171075. INPUT_VARS(cinfo);
  171076. INPUT_2BYTES(cinfo, length, return FALSE);
  171077. length -= 2;
  171078. /* get the interesting part of the marker data */
  171079. if (length >= APPN_DATA_LEN)
  171080. numtoread = APPN_DATA_LEN;
  171081. else if (length > 0)
  171082. numtoread = (unsigned int) length;
  171083. else
  171084. numtoread = 0;
  171085. for (i = 0; i < numtoread; i++)
  171086. INPUT_BYTE(cinfo, b[i], return FALSE);
  171087. length -= numtoread;
  171088. /* process it */
  171089. switch (cinfo->unread_marker) {
  171090. case M_APP0:
  171091. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171092. break;
  171093. case M_APP14:
  171094. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171095. break;
  171096. default:
  171097. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171098. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171099. break;
  171100. }
  171101. /* skip any remaining data -- could be lots */
  171102. INPUT_SYNC(cinfo);
  171103. if (length > 0)
  171104. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171105. return TRUE;
  171106. }
  171107. #ifdef SAVE_MARKERS_SUPPORTED
  171108. METHODDEF(boolean)
  171109. save_marker (j_decompress_ptr cinfo)
  171110. /* Save an APPn or COM marker into the marker list */
  171111. {
  171112. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171113. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171114. unsigned int bytes_read, data_length;
  171115. JOCTET FAR * data;
  171116. INT32 length = 0;
  171117. INPUT_VARS(cinfo);
  171118. if (cur_marker == NULL) {
  171119. /* begin reading a marker */
  171120. INPUT_2BYTES(cinfo, length, return FALSE);
  171121. length -= 2;
  171122. if (length >= 0) { /* watch out for bogus length word */
  171123. /* figure out how much we want to save */
  171124. unsigned int limit;
  171125. if (cinfo->unread_marker == (int) M_COM)
  171126. limit = marker->length_limit_COM;
  171127. else
  171128. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171129. if ((unsigned int) length < limit)
  171130. limit = (unsigned int) length;
  171131. /* allocate and initialize the marker item */
  171132. cur_marker = (jpeg_saved_marker_ptr)
  171133. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171134. SIZEOF(struct jpeg_marker_struct) + limit);
  171135. cur_marker->next = NULL;
  171136. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171137. cur_marker->original_length = (unsigned int) length;
  171138. cur_marker->data_length = limit;
  171139. /* data area is just beyond the jpeg_marker_struct */
  171140. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171141. marker->cur_marker = cur_marker;
  171142. marker->bytes_read = 0;
  171143. bytes_read = 0;
  171144. data_length = limit;
  171145. } else {
  171146. /* deal with bogus length word */
  171147. bytes_read = data_length = 0;
  171148. data = NULL;
  171149. }
  171150. } else {
  171151. /* resume reading a marker */
  171152. bytes_read = marker->bytes_read;
  171153. data_length = cur_marker->data_length;
  171154. data = cur_marker->data + bytes_read;
  171155. }
  171156. while (bytes_read < data_length) {
  171157. INPUT_SYNC(cinfo); /* move the restart point to here */
  171158. marker->bytes_read = bytes_read;
  171159. /* If there's not at least one byte in buffer, suspend */
  171160. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171161. /* Copy bytes with reasonable rapidity */
  171162. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171163. *data++ = *next_input_byte++;
  171164. bytes_in_buffer--;
  171165. bytes_read++;
  171166. }
  171167. }
  171168. /* Done reading what we want to read */
  171169. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171170. /* Add new marker to end of list */
  171171. if (cinfo->marker_list == NULL) {
  171172. cinfo->marker_list = cur_marker;
  171173. } else {
  171174. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171175. while (prev->next != NULL)
  171176. prev = prev->next;
  171177. prev->next = cur_marker;
  171178. }
  171179. /* Reset pointer & calc remaining data length */
  171180. data = cur_marker->data;
  171181. length = cur_marker->original_length - data_length;
  171182. }
  171183. /* Reset to initial state for next marker */
  171184. marker->cur_marker = NULL;
  171185. /* Process the marker if interesting; else just make a generic trace msg */
  171186. switch (cinfo->unread_marker) {
  171187. case M_APP0:
  171188. examine_app0(cinfo, data, data_length, length);
  171189. break;
  171190. case M_APP14:
  171191. examine_app14(cinfo, data, data_length, length);
  171192. break;
  171193. default:
  171194. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171195. (int) (data_length + length));
  171196. break;
  171197. }
  171198. /* skip any remaining data -- could be lots */
  171199. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171200. if (length > 0)
  171201. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171202. return TRUE;
  171203. }
  171204. #endif /* SAVE_MARKERS_SUPPORTED */
  171205. METHODDEF(boolean)
  171206. skip_variable (j_decompress_ptr cinfo)
  171207. /* Skip over an unknown or uninteresting variable-length marker */
  171208. {
  171209. INT32 length;
  171210. INPUT_VARS(cinfo);
  171211. INPUT_2BYTES(cinfo, length, return FALSE);
  171212. length -= 2;
  171213. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171214. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171215. if (length > 0)
  171216. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171217. return TRUE;
  171218. }
  171219. /*
  171220. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171221. * Returns FALSE if had to suspend before reaching a marker;
  171222. * in that case cinfo->unread_marker is unchanged.
  171223. *
  171224. * Note that the result might not be a valid marker code,
  171225. * but it will never be 0 or FF.
  171226. */
  171227. LOCAL(boolean)
  171228. next_marker (j_decompress_ptr cinfo)
  171229. {
  171230. int c;
  171231. INPUT_VARS(cinfo);
  171232. for (;;) {
  171233. INPUT_BYTE(cinfo, c, return FALSE);
  171234. /* Skip any non-FF bytes.
  171235. * This may look a bit inefficient, but it will not occur in a valid file.
  171236. * We sync after each discarded byte so that a suspending data source
  171237. * can discard the byte from its buffer.
  171238. */
  171239. while (c != 0xFF) {
  171240. cinfo->marker->discarded_bytes++;
  171241. INPUT_SYNC(cinfo);
  171242. INPUT_BYTE(cinfo, c, return FALSE);
  171243. }
  171244. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171245. * pad bytes, so don't count them in discarded_bytes. We assume there
  171246. * will not be so many consecutive FF bytes as to overflow a suspending
  171247. * data source's input buffer.
  171248. */
  171249. do {
  171250. INPUT_BYTE(cinfo, c, return FALSE);
  171251. } while (c == 0xFF);
  171252. if (c != 0)
  171253. break; /* found a valid marker, exit loop */
  171254. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171255. * Discard it and loop back to try again.
  171256. */
  171257. cinfo->marker->discarded_bytes += 2;
  171258. INPUT_SYNC(cinfo);
  171259. }
  171260. if (cinfo->marker->discarded_bytes != 0) {
  171261. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171262. cinfo->marker->discarded_bytes = 0;
  171263. }
  171264. cinfo->unread_marker = c;
  171265. INPUT_SYNC(cinfo);
  171266. return TRUE;
  171267. }
  171268. LOCAL(boolean)
  171269. first_marker (j_decompress_ptr cinfo)
  171270. /* Like next_marker, but used to obtain the initial SOI marker. */
  171271. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171272. * we might well scan an entire input file before realizing it ain't JPEG.
  171273. * If an application wants to process non-JFIF files, it must seek to the
  171274. * SOI before calling the JPEG library.
  171275. */
  171276. {
  171277. int c, c2;
  171278. INPUT_VARS(cinfo);
  171279. INPUT_BYTE(cinfo, c, return FALSE);
  171280. INPUT_BYTE(cinfo, c2, return FALSE);
  171281. if (c != 0xFF || c2 != (int) M_SOI)
  171282. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171283. cinfo->unread_marker = c2;
  171284. INPUT_SYNC(cinfo);
  171285. return TRUE;
  171286. }
  171287. /*
  171288. * Read markers until SOS or EOI.
  171289. *
  171290. * Returns same codes as are defined for jpeg_consume_input:
  171291. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171292. */
  171293. METHODDEF(int)
  171294. read_markers (j_decompress_ptr cinfo)
  171295. {
  171296. /* Outer loop repeats once for each marker. */
  171297. for (;;) {
  171298. /* Collect the marker proper, unless we already did. */
  171299. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171300. if (cinfo->unread_marker == 0) {
  171301. if (! cinfo->marker->saw_SOI) {
  171302. if (! first_marker(cinfo))
  171303. return JPEG_SUSPENDED;
  171304. } else {
  171305. if (! next_marker(cinfo))
  171306. return JPEG_SUSPENDED;
  171307. }
  171308. }
  171309. /* At this point cinfo->unread_marker contains the marker code and the
  171310. * input point is just past the marker proper, but before any parameters.
  171311. * A suspension will cause us to return with this state still true.
  171312. */
  171313. switch (cinfo->unread_marker) {
  171314. case M_SOI:
  171315. if (! get_soi(cinfo))
  171316. return JPEG_SUSPENDED;
  171317. break;
  171318. case M_SOF0: /* Baseline */
  171319. case M_SOF1: /* Extended sequential, Huffman */
  171320. if (! get_sof(cinfo, FALSE, FALSE))
  171321. return JPEG_SUSPENDED;
  171322. break;
  171323. case M_SOF2: /* Progressive, Huffman */
  171324. if (! get_sof(cinfo, TRUE, FALSE))
  171325. return JPEG_SUSPENDED;
  171326. break;
  171327. case M_SOF9: /* Extended sequential, arithmetic */
  171328. if (! get_sof(cinfo, FALSE, TRUE))
  171329. return JPEG_SUSPENDED;
  171330. break;
  171331. case M_SOF10: /* Progressive, arithmetic */
  171332. if (! get_sof(cinfo, TRUE, TRUE))
  171333. return JPEG_SUSPENDED;
  171334. break;
  171335. /* Currently unsupported SOFn types */
  171336. case M_SOF3: /* Lossless, Huffman */
  171337. case M_SOF5: /* Differential sequential, Huffman */
  171338. case M_SOF6: /* Differential progressive, Huffman */
  171339. case M_SOF7: /* Differential lossless, Huffman */
  171340. case M_JPG: /* Reserved for JPEG extensions */
  171341. case M_SOF11: /* Lossless, arithmetic */
  171342. case M_SOF13: /* Differential sequential, arithmetic */
  171343. case M_SOF14: /* Differential progressive, arithmetic */
  171344. case M_SOF15: /* Differential lossless, arithmetic */
  171345. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171346. break;
  171347. case M_SOS:
  171348. if (! get_sos(cinfo))
  171349. return JPEG_SUSPENDED;
  171350. cinfo->unread_marker = 0; /* processed the marker */
  171351. return JPEG_REACHED_SOS;
  171352. case M_EOI:
  171353. TRACEMS(cinfo, 1, JTRC_EOI);
  171354. cinfo->unread_marker = 0; /* processed the marker */
  171355. return JPEG_REACHED_EOI;
  171356. case M_DAC:
  171357. if (! get_dac(cinfo))
  171358. return JPEG_SUSPENDED;
  171359. break;
  171360. case M_DHT:
  171361. if (! get_dht(cinfo))
  171362. return JPEG_SUSPENDED;
  171363. break;
  171364. case M_DQT:
  171365. if (! get_dqt(cinfo))
  171366. return JPEG_SUSPENDED;
  171367. break;
  171368. case M_DRI:
  171369. if (! get_dri(cinfo))
  171370. return JPEG_SUSPENDED;
  171371. break;
  171372. case M_APP0:
  171373. case M_APP1:
  171374. case M_APP2:
  171375. case M_APP3:
  171376. case M_APP4:
  171377. case M_APP5:
  171378. case M_APP6:
  171379. case M_APP7:
  171380. case M_APP8:
  171381. case M_APP9:
  171382. case M_APP10:
  171383. case M_APP11:
  171384. case M_APP12:
  171385. case M_APP13:
  171386. case M_APP14:
  171387. case M_APP15:
  171388. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171389. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171390. return JPEG_SUSPENDED;
  171391. break;
  171392. case M_COM:
  171393. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171394. return JPEG_SUSPENDED;
  171395. break;
  171396. case M_RST0: /* these are all parameterless */
  171397. case M_RST1:
  171398. case M_RST2:
  171399. case M_RST3:
  171400. case M_RST4:
  171401. case M_RST5:
  171402. case M_RST6:
  171403. case M_RST7:
  171404. case M_TEM:
  171405. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171406. break;
  171407. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171408. if (! skip_variable(cinfo))
  171409. return JPEG_SUSPENDED;
  171410. break;
  171411. default: /* must be DHP, EXP, JPGn, or RESn */
  171412. /* For now, we treat the reserved markers as fatal errors since they are
  171413. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171414. * Once the JPEG 3 version-number marker is well defined, this code
  171415. * ought to change!
  171416. */
  171417. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171418. break;
  171419. }
  171420. /* Successfully processed marker, so reset state variable */
  171421. cinfo->unread_marker = 0;
  171422. } /* end loop */
  171423. }
  171424. /*
  171425. * Read a restart marker, which is expected to appear next in the datastream;
  171426. * if the marker is not there, take appropriate recovery action.
  171427. * Returns FALSE if suspension is required.
  171428. *
  171429. * This is called by the entropy decoder after it has read an appropriate
  171430. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171431. * has already read a marker from the data source. Under normal conditions
  171432. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171433. * it holds a marker which the decoder will be unable to read past.
  171434. */
  171435. METHODDEF(boolean)
  171436. read_restart_marker (j_decompress_ptr cinfo)
  171437. {
  171438. /* Obtain a marker unless we already did. */
  171439. /* Note that next_marker will complain if it skips any data. */
  171440. if (cinfo->unread_marker == 0) {
  171441. if (! next_marker(cinfo))
  171442. return FALSE;
  171443. }
  171444. if (cinfo->unread_marker ==
  171445. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171446. /* Normal case --- swallow the marker and let entropy decoder continue */
  171447. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171448. cinfo->unread_marker = 0;
  171449. } else {
  171450. /* Uh-oh, the restart markers have been messed up. */
  171451. /* Let the data source manager determine how to resync. */
  171452. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171453. cinfo->marker->next_restart_num))
  171454. return FALSE;
  171455. }
  171456. /* Update next-restart state */
  171457. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171458. return TRUE;
  171459. }
  171460. /*
  171461. * This is the default resync_to_restart method for data source managers
  171462. * to use if they don't have any better approach. Some data source managers
  171463. * may be able to back up, or may have additional knowledge about the data
  171464. * which permits a more intelligent recovery strategy; such managers would
  171465. * presumably supply their own resync method.
  171466. *
  171467. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171468. * the restart marker it was expecting. (This code is *not* used unless
  171469. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171470. * the marker code actually found (might be anything, except 0 or FF).
  171471. * The desired restart marker number (0..7) is passed as a parameter.
  171472. * This routine is supposed to apply whatever error recovery strategy seems
  171473. * appropriate in order to position the input stream to the next data segment.
  171474. * Note that cinfo->unread_marker is treated as a marker appearing before
  171475. * the current data-source input point; usually it should be reset to zero
  171476. * before returning.
  171477. * Returns FALSE if suspension is required.
  171478. *
  171479. * This implementation is substantially constrained by wanting to treat the
  171480. * input as a data stream; this means we can't back up. Therefore, we have
  171481. * only the following actions to work with:
  171482. * 1. Simply discard the marker and let the entropy decoder resume at next
  171483. * byte of file.
  171484. * 2. Read forward until we find another marker, discarding intervening
  171485. * data. (In theory we could look ahead within the current bufferload,
  171486. * without having to discard data if we don't find the desired marker.
  171487. * This idea is not implemented here, in part because it makes behavior
  171488. * dependent on buffer size and chance buffer-boundary positions.)
  171489. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171490. * This will cause the entropy decoder to process an empty data segment,
  171491. * inserting dummy zeroes, and then we will reprocess the marker.
  171492. *
  171493. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171494. * appropriate if the found marker is a future restart marker (indicating
  171495. * that we have missed the desired restart marker, probably because it got
  171496. * corrupted).
  171497. * We apply #2 or #3 if the found marker is a restart marker no more than
  171498. * two counts behind or ahead of the expected one. We also apply #2 if the
  171499. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171500. * If the found marker is a restart marker more than 2 counts away, we do #1
  171501. * (too much risk that the marker is erroneous; with luck we will be able to
  171502. * resync at some future point).
  171503. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171504. * overrunning the end of a scan. An implementation limited to single-scan
  171505. * files might find it better to apply #2 for markers other than EOI, since
  171506. * any other marker would have to be bogus data in that case.
  171507. */
  171508. GLOBAL(boolean)
  171509. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171510. {
  171511. int marker = cinfo->unread_marker;
  171512. int action = 1;
  171513. /* Always put up a warning. */
  171514. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171515. /* Outer loop handles repeated decision after scanning forward. */
  171516. for (;;) {
  171517. if (marker < (int) M_SOF0)
  171518. action = 2; /* invalid marker */
  171519. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171520. action = 3; /* valid non-restart marker */
  171521. else {
  171522. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171523. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171524. action = 3; /* one of the next two expected restarts */
  171525. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171526. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171527. action = 2; /* a prior restart, so advance */
  171528. else
  171529. action = 1; /* desired restart or too far away */
  171530. }
  171531. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171532. switch (action) {
  171533. case 1:
  171534. /* Discard marker and let entropy decoder resume processing. */
  171535. cinfo->unread_marker = 0;
  171536. return TRUE;
  171537. case 2:
  171538. /* Scan to the next marker, and repeat the decision loop. */
  171539. if (! next_marker(cinfo))
  171540. return FALSE;
  171541. marker = cinfo->unread_marker;
  171542. break;
  171543. case 3:
  171544. /* Return without advancing past this marker. */
  171545. /* Entropy decoder will be forced to process an empty segment. */
  171546. return TRUE;
  171547. }
  171548. } /* end loop */
  171549. }
  171550. /*
  171551. * Reset marker processing state to begin a fresh datastream.
  171552. */
  171553. METHODDEF(void)
  171554. reset_marker_reader (j_decompress_ptr cinfo)
  171555. {
  171556. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171557. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171558. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171559. cinfo->unread_marker = 0; /* no pending marker */
  171560. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171561. marker->pub.saw_SOF = FALSE;
  171562. marker->pub.discarded_bytes = 0;
  171563. marker->cur_marker = NULL;
  171564. }
  171565. /*
  171566. * Initialize the marker reader module.
  171567. * This is called only once, when the decompression object is created.
  171568. */
  171569. GLOBAL(void)
  171570. jinit_marker_reader (j_decompress_ptr cinfo)
  171571. {
  171572. my_marker_ptr2 marker;
  171573. int i;
  171574. /* Create subobject in permanent pool */
  171575. marker = (my_marker_ptr2)
  171576. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171577. SIZEOF(my_marker_reader));
  171578. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171579. /* Initialize public method pointers */
  171580. marker->pub.reset_marker_reader = reset_marker_reader;
  171581. marker->pub.read_markers = read_markers;
  171582. marker->pub.read_restart_marker = read_restart_marker;
  171583. /* Initialize COM/APPn processing.
  171584. * By default, we examine and then discard APP0 and APP14,
  171585. * but simply discard COM and all other APPn.
  171586. */
  171587. marker->process_COM = skip_variable;
  171588. marker->length_limit_COM = 0;
  171589. for (i = 0; i < 16; i++) {
  171590. marker->process_APPn[i] = skip_variable;
  171591. marker->length_limit_APPn[i] = 0;
  171592. }
  171593. marker->process_APPn[0] = get_interesting_appn;
  171594. marker->process_APPn[14] = get_interesting_appn;
  171595. /* Reset marker processing state */
  171596. reset_marker_reader(cinfo);
  171597. }
  171598. /*
  171599. * Control saving of COM and APPn markers into marker_list.
  171600. */
  171601. #ifdef SAVE_MARKERS_SUPPORTED
  171602. GLOBAL(void)
  171603. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171604. unsigned int length_limit)
  171605. {
  171606. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171607. long maxlength;
  171608. jpeg_marker_parser_method processor;
  171609. /* Length limit mustn't be larger than what we can allocate
  171610. * (should only be a concern in a 16-bit environment).
  171611. */
  171612. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171613. if (((long) length_limit) > maxlength)
  171614. length_limit = (unsigned int) maxlength;
  171615. /* Choose processor routine to use.
  171616. * APP0/APP14 have special requirements.
  171617. */
  171618. if (length_limit) {
  171619. processor = save_marker;
  171620. /* If saving APP0/APP14, save at least enough for our internal use. */
  171621. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171622. length_limit = APP0_DATA_LEN;
  171623. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171624. length_limit = APP14_DATA_LEN;
  171625. } else {
  171626. processor = skip_variable;
  171627. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171628. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171629. processor = get_interesting_appn;
  171630. }
  171631. if (marker_code == (int) M_COM) {
  171632. marker->process_COM = processor;
  171633. marker->length_limit_COM = length_limit;
  171634. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171635. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171636. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171637. } else
  171638. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171639. }
  171640. #endif /* SAVE_MARKERS_SUPPORTED */
  171641. /*
  171642. * Install a special processing method for COM or APPn markers.
  171643. */
  171644. GLOBAL(void)
  171645. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171646. jpeg_marker_parser_method routine)
  171647. {
  171648. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171649. if (marker_code == (int) M_COM)
  171650. marker->process_COM = routine;
  171651. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171652. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171653. else
  171654. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171655. }
  171656. /*** End of inlined file: jdmarker.c ***/
  171657. /*** Start of inlined file: jdmaster.c ***/
  171658. #define JPEG_INTERNALS
  171659. /* Private state */
  171660. typedef struct {
  171661. struct jpeg_decomp_master pub; /* public fields */
  171662. int pass_number; /* # of passes completed */
  171663. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171664. /* Saved references to initialized quantizer modules,
  171665. * in case we need to switch modes.
  171666. */
  171667. struct jpeg_color_quantizer * quantizer_1pass;
  171668. struct jpeg_color_quantizer * quantizer_2pass;
  171669. } my_decomp_master;
  171670. typedef my_decomp_master * my_master_ptr6;
  171671. /*
  171672. * Determine whether merged upsample/color conversion should be used.
  171673. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171674. */
  171675. LOCAL(boolean)
  171676. use_merged_upsample (j_decompress_ptr cinfo)
  171677. {
  171678. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171679. /* Merging is the equivalent of plain box-filter upsampling */
  171680. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171681. return FALSE;
  171682. /* jdmerge.c only supports YCC=>RGB color conversion */
  171683. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171684. cinfo->out_color_space != JCS_RGB ||
  171685. cinfo->out_color_components != RGB_PIXELSIZE)
  171686. return FALSE;
  171687. /* and it only handles 2h1v or 2h2v sampling ratios */
  171688. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171689. cinfo->comp_info[1].h_samp_factor != 1 ||
  171690. cinfo->comp_info[2].h_samp_factor != 1 ||
  171691. cinfo->comp_info[0].v_samp_factor > 2 ||
  171692. cinfo->comp_info[1].v_samp_factor != 1 ||
  171693. cinfo->comp_info[2].v_samp_factor != 1)
  171694. return FALSE;
  171695. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171696. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171697. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171698. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171699. return FALSE;
  171700. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171701. return TRUE; /* by golly, it'll work... */
  171702. #else
  171703. return FALSE;
  171704. #endif
  171705. }
  171706. /*
  171707. * Compute output image dimensions and related values.
  171708. * NOTE: this is exported for possible use by application.
  171709. * Hence it mustn't do anything that can't be done twice.
  171710. * Also note that it may be called before the master module is initialized!
  171711. */
  171712. GLOBAL(void)
  171713. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171714. /* Do computations that are needed before master selection phase */
  171715. {
  171716. #ifdef IDCT_SCALING_SUPPORTED
  171717. int ci;
  171718. jpeg_component_info *compptr;
  171719. #endif
  171720. /* Prevent application from calling me at wrong times */
  171721. if (cinfo->global_state != DSTATE_READY)
  171722. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171723. #ifdef IDCT_SCALING_SUPPORTED
  171724. /* Compute actual output image dimensions and DCT scaling choices. */
  171725. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171726. /* Provide 1/8 scaling */
  171727. cinfo->output_width = (JDIMENSION)
  171728. jdiv_round_up((long) cinfo->image_width, 8L);
  171729. cinfo->output_height = (JDIMENSION)
  171730. jdiv_round_up((long) cinfo->image_height, 8L);
  171731. cinfo->min_DCT_scaled_size = 1;
  171732. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171733. /* Provide 1/4 scaling */
  171734. cinfo->output_width = (JDIMENSION)
  171735. jdiv_round_up((long) cinfo->image_width, 4L);
  171736. cinfo->output_height = (JDIMENSION)
  171737. jdiv_round_up((long) cinfo->image_height, 4L);
  171738. cinfo->min_DCT_scaled_size = 2;
  171739. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171740. /* Provide 1/2 scaling */
  171741. cinfo->output_width = (JDIMENSION)
  171742. jdiv_round_up((long) cinfo->image_width, 2L);
  171743. cinfo->output_height = (JDIMENSION)
  171744. jdiv_round_up((long) cinfo->image_height, 2L);
  171745. cinfo->min_DCT_scaled_size = 4;
  171746. } else {
  171747. /* Provide 1/1 scaling */
  171748. cinfo->output_width = cinfo->image_width;
  171749. cinfo->output_height = cinfo->image_height;
  171750. cinfo->min_DCT_scaled_size = DCTSIZE;
  171751. }
  171752. /* In selecting the actual DCT scaling for each component, we try to
  171753. * scale up the chroma components via IDCT scaling rather than upsampling.
  171754. * This saves time if the upsampler gets to use 1:1 scaling.
  171755. * Note this code assumes that the supported DCT scalings are powers of 2.
  171756. */
  171757. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171758. ci++, compptr++) {
  171759. int ssize = cinfo->min_DCT_scaled_size;
  171760. while (ssize < DCTSIZE &&
  171761. (compptr->h_samp_factor * ssize * 2 <=
  171762. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171763. (compptr->v_samp_factor * ssize * 2 <=
  171764. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171765. ssize = ssize * 2;
  171766. }
  171767. compptr->DCT_scaled_size = ssize;
  171768. }
  171769. /* Recompute downsampled dimensions of components;
  171770. * application needs to know these if using raw downsampled data.
  171771. */
  171772. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171773. ci++, compptr++) {
  171774. /* Size in samples, after IDCT scaling */
  171775. compptr->downsampled_width = (JDIMENSION)
  171776. jdiv_round_up((long) cinfo->image_width *
  171777. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171778. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171779. compptr->downsampled_height = (JDIMENSION)
  171780. jdiv_round_up((long) cinfo->image_height *
  171781. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171782. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171783. }
  171784. #else /* !IDCT_SCALING_SUPPORTED */
  171785. /* Hardwire it to "no scaling" */
  171786. cinfo->output_width = cinfo->image_width;
  171787. cinfo->output_height = cinfo->image_height;
  171788. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171789. * and has computed unscaled downsampled_width and downsampled_height.
  171790. */
  171791. #endif /* IDCT_SCALING_SUPPORTED */
  171792. /* Report number of components in selected colorspace. */
  171793. /* Probably this should be in the color conversion module... */
  171794. switch (cinfo->out_color_space) {
  171795. case JCS_GRAYSCALE:
  171796. cinfo->out_color_components = 1;
  171797. break;
  171798. case JCS_RGB:
  171799. #if RGB_PIXELSIZE != 3
  171800. cinfo->out_color_components = RGB_PIXELSIZE;
  171801. break;
  171802. #endif /* else share code with YCbCr */
  171803. case JCS_YCbCr:
  171804. cinfo->out_color_components = 3;
  171805. break;
  171806. case JCS_CMYK:
  171807. case JCS_YCCK:
  171808. cinfo->out_color_components = 4;
  171809. break;
  171810. default: /* else must be same colorspace as in file */
  171811. cinfo->out_color_components = cinfo->num_components;
  171812. break;
  171813. }
  171814. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171815. cinfo->out_color_components);
  171816. /* See if upsampler will want to emit more than one row at a time */
  171817. if (use_merged_upsample(cinfo))
  171818. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171819. else
  171820. cinfo->rec_outbuf_height = 1;
  171821. }
  171822. /*
  171823. * Several decompression processes need to range-limit values to the range
  171824. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171825. * due to noise introduced by quantization, roundoff error, etc. These
  171826. * processes are inner loops and need to be as fast as possible. On most
  171827. * machines, particularly CPUs with pipelines or instruction prefetch,
  171828. * a (subscript-check-less) C table lookup
  171829. * x = sample_range_limit[x];
  171830. * is faster than explicit tests
  171831. * if (x < 0) x = 0;
  171832. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171833. * These processes all use a common table prepared by the routine below.
  171834. *
  171835. * For most steps we can mathematically guarantee that the initial value
  171836. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171837. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171838. * limiting step (just after the IDCT), a wildly out-of-range value is
  171839. * possible if the input data is corrupt. To avoid any chance of indexing
  171840. * off the end of memory and getting a bad-pointer trap, we perform the
  171841. * post-IDCT limiting thus:
  171842. * x = range_limit[x & MASK];
  171843. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171844. * samples. Under normal circumstances this is more than enough range and
  171845. * a correct output will be generated; with bogus input data the mask will
  171846. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171847. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171848. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171849. * So the post-IDCT limiting table ends up looking like this:
  171850. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171851. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171852. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171853. * 0,1,...,CENTERJSAMPLE-1
  171854. * Negative inputs select values from the upper half of the table after
  171855. * masking.
  171856. *
  171857. * We can save some space by overlapping the start of the post-IDCT table
  171858. * with the simpler range limiting table. The post-IDCT table begins at
  171859. * sample_range_limit + CENTERJSAMPLE.
  171860. *
  171861. * Note that the table is allocated in near data space on PCs; it's small
  171862. * enough and used often enough to justify this.
  171863. */
  171864. LOCAL(void)
  171865. prepare_range_limit_table (j_decompress_ptr cinfo)
  171866. /* Allocate and fill in the sample_range_limit table */
  171867. {
  171868. JSAMPLE * table;
  171869. int i;
  171870. table = (JSAMPLE *)
  171871. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171872. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171873. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171874. cinfo->sample_range_limit = table;
  171875. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171876. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171877. /* Main part of "simple" table: limit[x] = x */
  171878. for (i = 0; i <= MAXJSAMPLE; i++)
  171879. table[i] = (JSAMPLE) i;
  171880. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171881. /* End of simple table, rest of first half of post-IDCT table */
  171882. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171883. table[i] = MAXJSAMPLE;
  171884. /* Second half of post-IDCT table */
  171885. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171886. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171887. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171888. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171889. }
  171890. /*
  171891. * Master selection of decompression modules.
  171892. * This is done once at jpeg_start_decompress time. We determine
  171893. * which modules will be used and give them appropriate initialization calls.
  171894. * We also initialize the decompressor input side to begin consuming data.
  171895. *
  171896. * Since jpeg_read_header has finished, we know what is in the SOF
  171897. * and (first) SOS markers. We also have all the application parameter
  171898. * settings.
  171899. */
  171900. LOCAL(void)
  171901. master_selection (j_decompress_ptr cinfo)
  171902. {
  171903. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171904. boolean use_c_buffer;
  171905. long samplesperrow;
  171906. JDIMENSION jd_samplesperrow;
  171907. /* Initialize dimensions and other stuff */
  171908. jpeg_calc_output_dimensions(cinfo);
  171909. prepare_range_limit_table(cinfo);
  171910. /* Width of an output scanline must be representable as JDIMENSION. */
  171911. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171912. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171913. if ((long) jd_samplesperrow != samplesperrow)
  171914. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171915. /* Initialize my private state */
  171916. master->pass_number = 0;
  171917. master->using_merged_upsample = use_merged_upsample(cinfo);
  171918. /* Color quantizer selection */
  171919. master->quantizer_1pass = NULL;
  171920. master->quantizer_2pass = NULL;
  171921. /* No mode changes if not using buffered-image mode. */
  171922. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171923. cinfo->enable_1pass_quant = FALSE;
  171924. cinfo->enable_external_quant = FALSE;
  171925. cinfo->enable_2pass_quant = FALSE;
  171926. }
  171927. if (cinfo->quantize_colors) {
  171928. if (cinfo->raw_data_out)
  171929. ERREXIT(cinfo, JERR_NOTIMPL);
  171930. /* 2-pass quantizer only works in 3-component color space. */
  171931. if (cinfo->out_color_components != 3) {
  171932. cinfo->enable_1pass_quant = TRUE;
  171933. cinfo->enable_external_quant = FALSE;
  171934. cinfo->enable_2pass_quant = FALSE;
  171935. cinfo->colormap = NULL;
  171936. } else if (cinfo->colormap != NULL) {
  171937. cinfo->enable_external_quant = TRUE;
  171938. } else if (cinfo->two_pass_quantize) {
  171939. cinfo->enable_2pass_quant = TRUE;
  171940. } else {
  171941. cinfo->enable_1pass_quant = TRUE;
  171942. }
  171943. if (cinfo->enable_1pass_quant) {
  171944. #ifdef QUANT_1PASS_SUPPORTED
  171945. jinit_1pass_quantizer(cinfo);
  171946. master->quantizer_1pass = cinfo->cquantize;
  171947. #else
  171948. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171949. #endif
  171950. }
  171951. /* We use the 2-pass code to map to external colormaps. */
  171952. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171953. #ifdef QUANT_2PASS_SUPPORTED
  171954. jinit_2pass_quantizer(cinfo);
  171955. master->quantizer_2pass = cinfo->cquantize;
  171956. #else
  171957. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171958. #endif
  171959. }
  171960. /* If both quantizers are initialized, the 2-pass one is left active;
  171961. * this is necessary for starting with quantization to an external map.
  171962. */
  171963. }
  171964. /* Post-processing: in particular, color conversion first */
  171965. if (! cinfo->raw_data_out) {
  171966. if (master->using_merged_upsample) {
  171967. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171968. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171969. #else
  171970. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171971. #endif
  171972. } else {
  171973. jinit_color_deconverter(cinfo);
  171974. jinit_upsampler(cinfo);
  171975. }
  171976. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171977. }
  171978. /* Inverse DCT */
  171979. jinit_inverse_dct(cinfo);
  171980. /* Entropy decoding: either Huffman or arithmetic coding. */
  171981. if (cinfo->arith_code) {
  171982. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171983. } else {
  171984. if (cinfo->progressive_mode) {
  171985. #ifdef D_PROGRESSIVE_SUPPORTED
  171986. jinit_phuff_decoder(cinfo);
  171987. #else
  171988. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171989. #endif
  171990. } else
  171991. jinit_huff_decoder(cinfo);
  171992. }
  171993. /* Initialize principal buffer controllers. */
  171994. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171995. jinit_d_coef_controller(cinfo, use_c_buffer);
  171996. if (! cinfo->raw_data_out)
  171997. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171998. /* We can now tell the memory manager to allocate virtual arrays. */
  171999. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172000. /* Initialize input side of decompressor to consume first scan. */
  172001. (*cinfo->inputctl->start_input_pass) (cinfo);
  172002. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172003. /* If jpeg_start_decompress will read the whole file, initialize
  172004. * progress monitoring appropriately. The input step is counted
  172005. * as one pass.
  172006. */
  172007. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172008. cinfo->inputctl->has_multiple_scans) {
  172009. int nscans;
  172010. /* Estimate number of scans to set pass_limit. */
  172011. if (cinfo->progressive_mode) {
  172012. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172013. nscans = 2 + 3 * cinfo->num_components;
  172014. } else {
  172015. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172016. nscans = cinfo->num_components;
  172017. }
  172018. cinfo->progress->pass_counter = 0L;
  172019. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172020. cinfo->progress->completed_passes = 0;
  172021. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172022. /* Count the input pass as done */
  172023. master->pass_number++;
  172024. }
  172025. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172026. }
  172027. /*
  172028. * Per-pass setup.
  172029. * This is called at the beginning of each output pass. We determine which
  172030. * modules will be active during this pass and give them appropriate
  172031. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172032. * is a "real" output pass or a dummy pass for color quantization.
  172033. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172034. */
  172035. METHODDEF(void)
  172036. prepare_for_output_pass (j_decompress_ptr cinfo)
  172037. {
  172038. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172039. if (master->pub.is_dummy_pass) {
  172040. #ifdef QUANT_2PASS_SUPPORTED
  172041. /* Final pass of 2-pass quantization */
  172042. master->pub.is_dummy_pass = FALSE;
  172043. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172044. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172045. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172046. #else
  172047. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172048. #endif /* QUANT_2PASS_SUPPORTED */
  172049. } else {
  172050. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172051. /* Select new quantization method */
  172052. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172053. cinfo->cquantize = master->quantizer_2pass;
  172054. master->pub.is_dummy_pass = TRUE;
  172055. } else if (cinfo->enable_1pass_quant) {
  172056. cinfo->cquantize = master->quantizer_1pass;
  172057. } else {
  172058. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172059. }
  172060. }
  172061. (*cinfo->idct->start_pass) (cinfo);
  172062. (*cinfo->coef->start_output_pass) (cinfo);
  172063. if (! cinfo->raw_data_out) {
  172064. if (! master->using_merged_upsample)
  172065. (*cinfo->cconvert->start_pass) (cinfo);
  172066. (*cinfo->upsample->start_pass) (cinfo);
  172067. if (cinfo->quantize_colors)
  172068. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172069. (*cinfo->post->start_pass) (cinfo,
  172070. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172071. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172072. }
  172073. }
  172074. /* Set up progress monitor's pass info if present */
  172075. if (cinfo->progress != NULL) {
  172076. cinfo->progress->completed_passes = master->pass_number;
  172077. cinfo->progress->total_passes = master->pass_number +
  172078. (master->pub.is_dummy_pass ? 2 : 1);
  172079. /* In buffered-image mode, we assume one more output pass if EOI not
  172080. * yet reached, but no more passes if EOI has been reached.
  172081. */
  172082. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172083. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172084. }
  172085. }
  172086. }
  172087. /*
  172088. * Finish up at end of an output pass.
  172089. */
  172090. METHODDEF(void)
  172091. finish_output_pass (j_decompress_ptr cinfo)
  172092. {
  172093. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172094. if (cinfo->quantize_colors)
  172095. (*cinfo->cquantize->finish_pass) (cinfo);
  172096. master->pass_number++;
  172097. }
  172098. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172099. /*
  172100. * Switch to a new external colormap between output passes.
  172101. */
  172102. GLOBAL(void)
  172103. jpeg_new_colormap (j_decompress_ptr cinfo)
  172104. {
  172105. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172106. /* Prevent application from calling me at wrong times */
  172107. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172108. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172109. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172110. cinfo->colormap != NULL) {
  172111. /* Select 2-pass quantizer for external colormap use */
  172112. cinfo->cquantize = master->quantizer_2pass;
  172113. /* Notify quantizer of colormap change */
  172114. (*cinfo->cquantize->new_color_map) (cinfo);
  172115. master->pub.is_dummy_pass = FALSE; /* just in case */
  172116. } else
  172117. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172118. }
  172119. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172120. /*
  172121. * Initialize master decompression control and select active modules.
  172122. * This is performed at the start of jpeg_start_decompress.
  172123. */
  172124. GLOBAL(void)
  172125. jinit_master_decompress (j_decompress_ptr cinfo)
  172126. {
  172127. my_master_ptr6 master;
  172128. master = (my_master_ptr6)
  172129. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172130. SIZEOF(my_decomp_master));
  172131. cinfo->master = (struct jpeg_decomp_master *) master;
  172132. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172133. master->pub.finish_output_pass = finish_output_pass;
  172134. master->pub.is_dummy_pass = FALSE;
  172135. master_selection(cinfo);
  172136. }
  172137. /*** End of inlined file: jdmaster.c ***/
  172138. #undef FIX
  172139. /*** Start of inlined file: jdmerge.c ***/
  172140. #define JPEG_INTERNALS
  172141. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172142. /* Private subobject */
  172143. typedef struct {
  172144. struct jpeg_upsampler pub; /* public fields */
  172145. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172146. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172147. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172148. JSAMPARRAY output_buf));
  172149. /* Private state for YCC->RGB conversion */
  172150. int * Cr_r_tab; /* => table for Cr to R conversion */
  172151. int * Cb_b_tab; /* => table for Cb to B conversion */
  172152. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172153. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172154. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172155. * We need a "spare" row buffer to hold the second output row if the
  172156. * application provides just a one-row buffer; we also use the spare
  172157. * to discard the dummy last row if the image height is odd.
  172158. */
  172159. JSAMPROW spare_row;
  172160. boolean spare_full; /* T if spare buffer is occupied */
  172161. JDIMENSION out_row_width; /* samples per output row */
  172162. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172163. } my_upsampler;
  172164. typedef my_upsampler * my_upsample_ptr;
  172165. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172166. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172167. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172168. /*
  172169. * Initialize tables for YCC->RGB colorspace conversion.
  172170. * This is taken directly from jdcolor.c; see that file for more info.
  172171. */
  172172. LOCAL(void)
  172173. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172174. {
  172175. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172176. int i;
  172177. INT32 x;
  172178. SHIFT_TEMPS
  172179. upsample->Cr_r_tab = (int *)
  172180. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172181. (MAXJSAMPLE+1) * SIZEOF(int));
  172182. upsample->Cb_b_tab = (int *)
  172183. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172184. (MAXJSAMPLE+1) * SIZEOF(int));
  172185. upsample->Cr_g_tab = (INT32 *)
  172186. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172187. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172188. upsample->Cb_g_tab = (INT32 *)
  172189. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172190. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172191. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172192. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172193. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172194. /* Cr=>R value is nearest int to 1.40200 * x */
  172195. upsample->Cr_r_tab[i] = (int)
  172196. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172197. /* Cb=>B value is nearest int to 1.77200 * x */
  172198. upsample->Cb_b_tab[i] = (int)
  172199. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172200. /* Cr=>G value is scaled-up -0.71414 * x */
  172201. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172202. /* Cb=>G value is scaled-up -0.34414 * x */
  172203. /* We also add in ONE_HALF so that need not do it in inner loop */
  172204. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172205. }
  172206. }
  172207. /*
  172208. * Initialize for an upsampling pass.
  172209. */
  172210. METHODDEF(void)
  172211. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172212. {
  172213. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172214. /* Mark the spare buffer empty */
  172215. upsample->spare_full = FALSE;
  172216. /* Initialize total-height counter for detecting bottom of image */
  172217. upsample->rows_to_go = cinfo->output_height;
  172218. }
  172219. /*
  172220. * Control routine to do upsampling (and color conversion).
  172221. *
  172222. * The control routine just handles the row buffering considerations.
  172223. */
  172224. METHODDEF(void)
  172225. merged_2v_upsample (j_decompress_ptr cinfo,
  172226. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172227. JDIMENSION,
  172228. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172229. JDIMENSION out_rows_avail)
  172230. /* 2:1 vertical sampling case: may need a spare row. */
  172231. {
  172232. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172233. JSAMPROW work_ptrs[2];
  172234. JDIMENSION num_rows; /* number of rows returned to caller */
  172235. if (upsample->spare_full) {
  172236. /* If we have a spare row saved from a previous cycle, just return it. */
  172237. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172238. 1, upsample->out_row_width);
  172239. num_rows = 1;
  172240. upsample->spare_full = FALSE;
  172241. } else {
  172242. /* Figure number of rows to return to caller. */
  172243. num_rows = 2;
  172244. /* Not more than the distance to the end of the image. */
  172245. if (num_rows > upsample->rows_to_go)
  172246. num_rows = upsample->rows_to_go;
  172247. /* And not more than what the client can accept: */
  172248. out_rows_avail -= *out_row_ctr;
  172249. if (num_rows > out_rows_avail)
  172250. num_rows = out_rows_avail;
  172251. /* Create output pointer array for upsampler. */
  172252. work_ptrs[0] = output_buf[*out_row_ctr];
  172253. if (num_rows > 1) {
  172254. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172255. } else {
  172256. work_ptrs[1] = upsample->spare_row;
  172257. upsample->spare_full = TRUE;
  172258. }
  172259. /* Now do the upsampling. */
  172260. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172261. }
  172262. /* Adjust counts */
  172263. *out_row_ctr += num_rows;
  172264. upsample->rows_to_go -= num_rows;
  172265. /* When the buffer is emptied, declare this input row group consumed */
  172266. if (! upsample->spare_full)
  172267. (*in_row_group_ctr)++;
  172268. }
  172269. METHODDEF(void)
  172270. merged_1v_upsample (j_decompress_ptr cinfo,
  172271. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172272. JDIMENSION,
  172273. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172274. JDIMENSION)
  172275. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172276. {
  172277. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172278. /* Just do the upsampling. */
  172279. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172280. output_buf + *out_row_ctr);
  172281. /* Adjust counts */
  172282. (*out_row_ctr)++;
  172283. (*in_row_group_ctr)++;
  172284. }
  172285. /*
  172286. * These are the routines invoked by the control routines to do
  172287. * the actual upsampling/conversion. One row group is processed per call.
  172288. *
  172289. * Note: since we may be writing directly into application-supplied buffers,
  172290. * we have to be honest about the output width; we can't assume the buffer
  172291. * has been rounded up to an even width.
  172292. */
  172293. /*
  172294. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172295. */
  172296. METHODDEF(void)
  172297. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172298. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172299. JSAMPARRAY output_buf)
  172300. {
  172301. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172302. register int y, cred, cgreen, cblue;
  172303. int cb, cr;
  172304. register JSAMPROW outptr;
  172305. JSAMPROW inptr0, inptr1, inptr2;
  172306. JDIMENSION col;
  172307. /* copy these pointers into registers if possible */
  172308. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172309. int * Crrtab = upsample->Cr_r_tab;
  172310. int * Cbbtab = upsample->Cb_b_tab;
  172311. INT32 * Crgtab = upsample->Cr_g_tab;
  172312. INT32 * Cbgtab = upsample->Cb_g_tab;
  172313. SHIFT_TEMPS
  172314. inptr0 = input_buf[0][in_row_group_ctr];
  172315. inptr1 = input_buf[1][in_row_group_ctr];
  172316. inptr2 = input_buf[2][in_row_group_ctr];
  172317. outptr = output_buf[0];
  172318. /* Loop for each pair of output pixels */
  172319. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172320. /* Do the chroma part of the calculation */
  172321. cb = GETJSAMPLE(*inptr1++);
  172322. cr = GETJSAMPLE(*inptr2++);
  172323. cred = Crrtab[cr];
  172324. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172325. cblue = Cbbtab[cb];
  172326. /* Fetch 2 Y values and emit 2 pixels */
  172327. y = GETJSAMPLE(*inptr0++);
  172328. outptr[RGB_RED] = range_limit[y + cred];
  172329. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172330. outptr[RGB_BLUE] = range_limit[y + cblue];
  172331. outptr += RGB_PIXELSIZE;
  172332. y = GETJSAMPLE(*inptr0++);
  172333. outptr[RGB_RED] = range_limit[y + cred];
  172334. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172335. outptr[RGB_BLUE] = range_limit[y + cblue];
  172336. outptr += RGB_PIXELSIZE;
  172337. }
  172338. /* If image width is odd, do the last output column separately */
  172339. if (cinfo->output_width & 1) {
  172340. cb = GETJSAMPLE(*inptr1);
  172341. cr = GETJSAMPLE(*inptr2);
  172342. cred = Crrtab[cr];
  172343. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172344. cblue = Cbbtab[cb];
  172345. y = GETJSAMPLE(*inptr0);
  172346. outptr[RGB_RED] = range_limit[y + cred];
  172347. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172348. outptr[RGB_BLUE] = range_limit[y + cblue];
  172349. }
  172350. }
  172351. /*
  172352. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172353. */
  172354. METHODDEF(void)
  172355. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172356. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172357. JSAMPARRAY output_buf)
  172358. {
  172359. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172360. register int y, cred, cgreen, cblue;
  172361. int cb, cr;
  172362. register JSAMPROW outptr0, outptr1;
  172363. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172364. JDIMENSION col;
  172365. /* copy these pointers into registers if possible */
  172366. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172367. int * Crrtab = upsample->Cr_r_tab;
  172368. int * Cbbtab = upsample->Cb_b_tab;
  172369. INT32 * Crgtab = upsample->Cr_g_tab;
  172370. INT32 * Cbgtab = upsample->Cb_g_tab;
  172371. SHIFT_TEMPS
  172372. inptr00 = input_buf[0][in_row_group_ctr*2];
  172373. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172374. inptr1 = input_buf[1][in_row_group_ctr];
  172375. inptr2 = input_buf[2][in_row_group_ctr];
  172376. outptr0 = output_buf[0];
  172377. outptr1 = output_buf[1];
  172378. /* Loop for each group of output pixels */
  172379. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172380. /* Do the chroma part of the calculation */
  172381. cb = GETJSAMPLE(*inptr1++);
  172382. cr = GETJSAMPLE(*inptr2++);
  172383. cred = Crrtab[cr];
  172384. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172385. cblue = Cbbtab[cb];
  172386. /* Fetch 4 Y values and emit 4 pixels */
  172387. y = GETJSAMPLE(*inptr00++);
  172388. outptr0[RGB_RED] = range_limit[y + cred];
  172389. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172390. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172391. outptr0 += RGB_PIXELSIZE;
  172392. y = GETJSAMPLE(*inptr00++);
  172393. outptr0[RGB_RED] = range_limit[y + cred];
  172394. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172395. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172396. outptr0 += RGB_PIXELSIZE;
  172397. y = GETJSAMPLE(*inptr01++);
  172398. outptr1[RGB_RED] = range_limit[y + cred];
  172399. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172400. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172401. outptr1 += RGB_PIXELSIZE;
  172402. y = GETJSAMPLE(*inptr01++);
  172403. outptr1[RGB_RED] = range_limit[y + cred];
  172404. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172405. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172406. outptr1 += RGB_PIXELSIZE;
  172407. }
  172408. /* If image width is odd, do the last output column separately */
  172409. if (cinfo->output_width & 1) {
  172410. cb = GETJSAMPLE(*inptr1);
  172411. cr = GETJSAMPLE(*inptr2);
  172412. cred = Crrtab[cr];
  172413. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172414. cblue = Cbbtab[cb];
  172415. y = GETJSAMPLE(*inptr00);
  172416. outptr0[RGB_RED] = range_limit[y + cred];
  172417. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172418. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172419. y = GETJSAMPLE(*inptr01);
  172420. outptr1[RGB_RED] = range_limit[y + cred];
  172421. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172422. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172423. }
  172424. }
  172425. /*
  172426. * Module initialization routine for merged upsampling/color conversion.
  172427. *
  172428. * NB: this is called under the conditions determined by use_merged_upsample()
  172429. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172430. * of this module; no safety checks are made here.
  172431. */
  172432. GLOBAL(void)
  172433. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172434. {
  172435. my_upsample_ptr upsample;
  172436. upsample = (my_upsample_ptr)
  172437. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172438. SIZEOF(my_upsampler));
  172439. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172440. upsample->pub.start_pass = start_pass_merged_upsample;
  172441. upsample->pub.need_context_rows = FALSE;
  172442. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172443. if (cinfo->max_v_samp_factor == 2) {
  172444. upsample->pub.upsample = merged_2v_upsample;
  172445. upsample->upmethod = h2v2_merged_upsample;
  172446. /* Allocate a spare row buffer */
  172447. upsample->spare_row = (JSAMPROW)
  172448. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172449. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172450. } else {
  172451. upsample->pub.upsample = merged_1v_upsample;
  172452. upsample->upmethod = h2v1_merged_upsample;
  172453. /* No spare row needed */
  172454. upsample->spare_row = NULL;
  172455. }
  172456. build_ycc_rgb_table2(cinfo);
  172457. }
  172458. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172459. /*** End of inlined file: jdmerge.c ***/
  172460. #undef ASSIGN_STATE
  172461. /*** Start of inlined file: jdphuff.c ***/
  172462. #define JPEG_INTERNALS
  172463. #ifdef D_PROGRESSIVE_SUPPORTED
  172464. /*
  172465. * Expanded entropy decoder object for progressive Huffman decoding.
  172466. *
  172467. * The savable_state subrecord contains fields that change within an MCU,
  172468. * but must not be updated permanently until we complete the MCU.
  172469. */
  172470. typedef struct {
  172471. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172472. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172473. } savable_state3;
  172474. /* This macro is to work around compilers with missing or broken
  172475. * structure assignment. You'll need to fix this code if you have
  172476. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172477. */
  172478. #ifndef NO_STRUCT_ASSIGN
  172479. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172480. #else
  172481. #if MAX_COMPS_IN_SCAN == 4
  172482. #define ASSIGN_STATE(dest,src) \
  172483. ((dest).EOBRUN = (src).EOBRUN, \
  172484. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172485. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172486. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172487. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172488. #endif
  172489. #endif
  172490. typedef struct {
  172491. struct jpeg_entropy_decoder pub; /* public fields */
  172492. /* These fields are loaded into local variables at start of each MCU.
  172493. * In case of suspension, we exit WITHOUT updating them.
  172494. */
  172495. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172496. savable_state3 saved; /* Other state at start of MCU */
  172497. /* These fields are NOT loaded into local working state. */
  172498. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172499. /* Pointers to derived tables (these workspaces have image lifespan) */
  172500. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172501. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172502. } phuff_entropy_decoder;
  172503. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172504. /* Forward declarations */
  172505. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172506. JBLOCKROW *MCU_data));
  172507. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172508. JBLOCKROW *MCU_data));
  172509. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172510. JBLOCKROW *MCU_data));
  172511. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172512. JBLOCKROW *MCU_data));
  172513. /*
  172514. * Initialize for a Huffman-compressed scan.
  172515. */
  172516. METHODDEF(void)
  172517. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172518. {
  172519. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172520. boolean is_DC_band, bad;
  172521. int ci, coefi, tbl;
  172522. int *coef_bit_ptr;
  172523. jpeg_component_info * compptr;
  172524. is_DC_band = (cinfo->Ss == 0);
  172525. /* Validate scan parameters */
  172526. bad = FALSE;
  172527. if (is_DC_band) {
  172528. if (cinfo->Se != 0)
  172529. bad = TRUE;
  172530. } else {
  172531. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172532. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172533. bad = TRUE;
  172534. /* AC scans may have only one component */
  172535. if (cinfo->comps_in_scan != 1)
  172536. bad = TRUE;
  172537. }
  172538. if (cinfo->Ah != 0) {
  172539. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172540. if (cinfo->Al != cinfo->Ah-1)
  172541. bad = TRUE;
  172542. }
  172543. if (cinfo->Al > 13) /* need not check for < 0 */
  172544. bad = TRUE;
  172545. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172546. * but the spec doesn't say so, and we try to be liberal about what we
  172547. * accept. Note: large Al values could result in out-of-range DC
  172548. * coefficients during early scans, leading to bizarre displays due to
  172549. * overflows in the IDCT math. But we won't crash.
  172550. */
  172551. if (bad)
  172552. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172553. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172554. /* Update progression status, and verify that scan order is legal.
  172555. * Note that inter-scan inconsistencies are treated as warnings
  172556. * not fatal errors ... not clear if this is right way to behave.
  172557. */
  172558. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172559. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172560. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172561. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172562. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172563. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172564. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172565. if (cinfo->Ah != expected)
  172566. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172567. coef_bit_ptr[coefi] = cinfo->Al;
  172568. }
  172569. }
  172570. /* Select MCU decoding routine */
  172571. if (cinfo->Ah == 0) {
  172572. if (is_DC_band)
  172573. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172574. else
  172575. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172576. } else {
  172577. if (is_DC_band)
  172578. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172579. else
  172580. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172581. }
  172582. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172583. compptr = cinfo->cur_comp_info[ci];
  172584. /* Make sure requested tables are present, and compute derived tables.
  172585. * We may build same derived table more than once, but it's not expensive.
  172586. */
  172587. if (is_DC_band) {
  172588. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172589. tbl = compptr->dc_tbl_no;
  172590. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172591. & entropy->derived_tbls[tbl]);
  172592. }
  172593. } else {
  172594. tbl = compptr->ac_tbl_no;
  172595. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172596. & entropy->derived_tbls[tbl]);
  172597. /* remember the single active table */
  172598. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172599. }
  172600. /* Initialize DC predictions to 0 */
  172601. entropy->saved.last_dc_val[ci] = 0;
  172602. }
  172603. /* Initialize bitread state variables */
  172604. entropy->bitstate.bits_left = 0;
  172605. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172606. entropy->pub.insufficient_data = FALSE;
  172607. /* Initialize private state variables */
  172608. entropy->saved.EOBRUN = 0;
  172609. /* Initialize restart counter */
  172610. entropy->restarts_to_go = cinfo->restart_interval;
  172611. }
  172612. /*
  172613. * Check for a restart marker & resynchronize decoder.
  172614. * Returns FALSE if must suspend.
  172615. */
  172616. LOCAL(boolean)
  172617. process_restartp (j_decompress_ptr cinfo)
  172618. {
  172619. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172620. int ci;
  172621. /* Throw away any unused bits remaining in bit buffer; */
  172622. /* include any full bytes in next_marker's count of discarded bytes */
  172623. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172624. entropy->bitstate.bits_left = 0;
  172625. /* Advance past the RSTn marker */
  172626. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172627. return FALSE;
  172628. /* Re-initialize DC predictions to 0 */
  172629. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172630. entropy->saved.last_dc_val[ci] = 0;
  172631. /* Re-init EOB run count, too */
  172632. entropy->saved.EOBRUN = 0;
  172633. /* Reset restart counter */
  172634. entropy->restarts_to_go = cinfo->restart_interval;
  172635. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172636. * against a marker. In that case we will end up treating the next data
  172637. * segment as empty, and we can avoid producing bogus output pixels by
  172638. * leaving the flag set.
  172639. */
  172640. if (cinfo->unread_marker == 0)
  172641. entropy->pub.insufficient_data = FALSE;
  172642. return TRUE;
  172643. }
  172644. /*
  172645. * Huffman MCU decoding.
  172646. * Each of these routines decodes and returns one MCU's worth of
  172647. * Huffman-compressed coefficients.
  172648. * The coefficients are reordered from zigzag order into natural array order,
  172649. * but are not dequantized.
  172650. *
  172651. * The i'th block of the MCU is stored into the block pointed to by
  172652. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172653. *
  172654. * We return FALSE if data source requested suspension. In that case no
  172655. * changes have been made to permanent state. (Exception: some output
  172656. * coefficients may already have been assigned. This is harmless for
  172657. * spectral selection, since we'll just re-assign them on the next call.
  172658. * Successive approximation AC refinement has to be more careful, however.)
  172659. */
  172660. /*
  172661. * MCU decoding for DC initial scan (either spectral selection,
  172662. * or first pass of successive approximation).
  172663. */
  172664. METHODDEF(boolean)
  172665. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172666. {
  172667. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172668. int Al = cinfo->Al;
  172669. register int s, r;
  172670. int blkn, ci;
  172671. JBLOCKROW block;
  172672. BITREAD_STATE_VARS;
  172673. savable_state3 state;
  172674. d_derived_tbl * tbl;
  172675. jpeg_component_info * compptr;
  172676. /* Process restart marker if needed; may have to suspend */
  172677. if (cinfo->restart_interval) {
  172678. if (entropy->restarts_to_go == 0)
  172679. if (! process_restartp(cinfo))
  172680. return FALSE;
  172681. }
  172682. /* If we've run out of data, just leave the MCU set to zeroes.
  172683. * This way, we return uniform gray for the remainder of the segment.
  172684. */
  172685. if (! entropy->pub.insufficient_data) {
  172686. /* Load up working state */
  172687. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172688. ASSIGN_STATE(state, entropy->saved);
  172689. /* Outer loop handles each block in the MCU */
  172690. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172691. block = MCU_data[blkn];
  172692. ci = cinfo->MCU_membership[blkn];
  172693. compptr = cinfo->cur_comp_info[ci];
  172694. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172695. /* Decode a single block's worth of coefficients */
  172696. /* Section F.2.2.1: decode the DC coefficient difference */
  172697. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172698. if (s) {
  172699. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172700. r = GET_BITS(s);
  172701. s = HUFF_EXTEND(r, s);
  172702. }
  172703. /* Convert DC difference to actual value, update last_dc_val */
  172704. s += state.last_dc_val[ci];
  172705. state.last_dc_val[ci] = s;
  172706. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172707. (*block)[0] = (JCOEF) (s << Al);
  172708. }
  172709. /* Completed MCU, so update state */
  172710. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172711. ASSIGN_STATE(entropy->saved, state);
  172712. }
  172713. /* Account for restart interval (no-op if not using restarts) */
  172714. entropy->restarts_to_go--;
  172715. return TRUE;
  172716. }
  172717. /*
  172718. * MCU decoding for AC initial scan (either spectral selection,
  172719. * or first pass of successive approximation).
  172720. */
  172721. METHODDEF(boolean)
  172722. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172723. {
  172724. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172725. int Se = cinfo->Se;
  172726. int Al = cinfo->Al;
  172727. register int s, k, r;
  172728. unsigned int EOBRUN;
  172729. JBLOCKROW block;
  172730. BITREAD_STATE_VARS;
  172731. d_derived_tbl * tbl;
  172732. /* Process restart marker if needed; may have to suspend */
  172733. if (cinfo->restart_interval) {
  172734. if (entropy->restarts_to_go == 0)
  172735. if (! process_restartp(cinfo))
  172736. return FALSE;
  172737. }
  172738. /* If we've run out of data, just leave the MCU set to zeroes.
  172739. * This way, we return uniform gray for the remainder of the segment.
  172740. */
  172741. if (! entropy->pub.insufficient_data) {
  172742. /* Load up working state.
  172743. * We can avoid loading/saving bitread state if in an EOB run.
  172744. */
  172745. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172746. /* There is always only one block per MCU */
  172747. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172748. EOBRUN--; /* ...process it now (we do nothing) */
  172749. else {
  172750. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172751. block = MCU_data[0];
  172752. tbl = entropy->ac_derived_tbl;
  172753. for (k = cinfo->Ss; k <= Se; k++) {
  172754. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172755. r = s >> 4;
  172756. s &= 15;
  172757. if (s) {
  172758. k += r;
  172759. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172760. r = GET_BITS(s);
  172761. s = HUFF_EXTEND(r, s);
  172762. /* Scale and output coefficient in natural (dezigzagged) order */
  172763. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172764. } else {
  172765. if (r == 15) { /* ZRL */
  172766. k += 15; /* skip 15 zeroes in band */
  172767. } else { /* EOBr, run length is 2^r + appended bits */
  172768. EOBRUN = 1 << r;
  172769. if (r) { /* EOBr, r > 0 */
  172770. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172771. r = GET_BITS(r);
  172772. EOBRUN += r;
  172773. }
  172774. EOBRUN--; /* this band is processed at this moment */
  172775. break; /* force end-of-band */
  172776. }
  172777. }
  172778. }
  172779. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172780. }
  172781. /* Completed MCU, so update state */
  172782. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172783. }
  172784. /* Account for restart interval (no-op if not using restarts) */
  172785. entropy->restarts_to_go--;
  172786. return TRUE;
  172787. }
  172788. /*
  172789. * MCU decoding for DC successive approximation refinement scan.
  172790. * Note: we assume such scans can be multi-component, although the spec
  172791. * is not very clear on the point.
  172792. */
  172793. METHODDEF(boolean)
  172794. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172795. {
  172796. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172797. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172798. int blkn;
  172799. JBLOCKROW block;
  172800. BITREAD_STATE_VARS;
  172801. /* Process restart marker if needed; may have to suspend */
  172802. if (cinfo->restart_interval) {
  172803. if (entropy->restarts_to_go == 0)
  172804. if (! process_restartp(cinfo))
  172805. return FALSE;
  172806. }
  172807. /* Not worth the cycles to check insufficient_data here,
  172808. * since we will not change the data anyway if we read zeroes.
  172809. */
  172810. /* Load up working state */
  172811. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172812. /* Outer loop handles each block in the MCU */
  172813. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172814. block = MCU_data[blkn];
  172815. /* Encoded data is simply the next bit of the two's-complement DC value */
  172816. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172817. if (GET_BITS(1))
  172818. (*block)[0] |= p1;
  172819. /* Note: since we use |=, repeating the assignment later is safe */
  172820. }
  172821. /* Completed MCU, so update state */
  172822. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172823. /* Account for restart interval (no-op if not using restarts) */
  172824. entropy->restarts_to_go--;
  172825. return TRUE;
  172826. }
  172827. /*
  172828. * MCU decoding for AC successive approximation refinement scan.
  172829. */
  172830. METHODDEF(boolean)
  172831. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172832. {
  172833. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172834. int Se = cinfo->Se;
  172835. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172836. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172837. register int s, k, r;
  172838. unsigned int EOBRUN;
  172839. JBLOCKROW block;
  172840. JCOEFPTR thiscoef;
  172841. BITREAD_STATE_VARS;
  172842. d_derived_tbl * tbl;
  172843. int num_newnz;
  172844. int newnz_pos[DCTSIZE2];
  172845. /* Process restart marker if needed; may have to suspend */
  172846. if (cinfo->restart_interval) {
  172847. if (entropy->restarts_to_go == 0)
  172848. if (! process_restartp(cinfo))
  172849. return FALSE;
  172850. }
  172851. /* If we've run out of data, don't modify the MCU.
  172852. */
  172853. if (! entropy->pub.insufficient_data) {
  172854. /* Load up working state */
  172855. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172856. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172857. /* There is always only one block per MCU */
  172858. block = MCU_data[0];
  172859. tbl = entropy->ac_derived_tbl;
  172860. /* If we are forced to suspend, we must undo the assignments to any newly
  172861. * nonzero coefficients in the block, because otherwise we'd get confused
  172862. * next time about which coefficients were already nonzero.
  172863. * But we need not undo addition of bits to already-nonzero coefficients;
  172864. * instead, we can test the current bit to see if we already did it.
  172865. */
  172866. num_newnz = 0;
  172867. /* initialize coefficient loop counter to start of band */
  172868. k = cinfo->Ss;
  172869. if (EOBRUN == 0) {
  172870. for (; k <= Se; k++) {
  172871. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172872. r = s >> 4;
  172873. s &= 15;
  172874. if (s) {
  172875. if (s != 1) /* size of new coef should always be 1 */
  172876. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172877. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172878. if (GET_BITS(1))
  172879. s = p1; /* newly nonzero coef is positive */
  172880. else
  172881. s = m1; /* newly nonzero coef is negative */
  172882. } else {
  172883. if (r != 15) {
  172884. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172885. if (r) {
  172886. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172887. r = GET_BITS(r);
  172888. EOBRUN += r;
  172889. }
  172890. break; /* rest of block is handled by EOB logic */
  172891. }
  172892. /* note s = 0 for processing ZRL */
  172893. }
  172894. /* Advance over already-nonzero coefs and r still-zero coefs,
  172895. * appending correction bits to the nonzeroes. A correction bit is 1
  172896. * if the absolute value of the coefficient must be increased.
  172897. */
  172898. do {
  172899. thiscoef = *block + jpeg_natural_order[k];
  172900. if (*thiscoef != 0) {
  172901. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172902. if (GET_BITS(1)) {
  172903. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172904. if (*thiscoef >= 0)
  172905. *thiscoef += p1;
  172906. else
  172907. *thiscoef += m1;
  172908. }
  172909. }
  172910. } else {
  172911. if (--r < 0)
  172912. break; /* reached target zero coefficient */
  172913. }
  172914. k++;
  172915. } while (k <= Se);
  172916. if (s) {
  172917. int pos = jpeg_natural_order[k];
  172918. /* Output newly nonzero coefficient */
  172919. (*block)[pos] = (JCOEF) s;
  172920. /* Remember its position in case we have to suspend */
  172921. newnz_pos[num_newnz++] = pos;
  172922. }
  172923. }
  172924. }
  172925. if (EOBRUN > 0) {
  172926. /* Scan any remaining coefficient positions after the end-of-band
  172927. * (the last newly nonzero coefficient, if any). Append a correction
  172928. * bit to each already-nonzero coefficient. A correction bit is 1
  172929. * if the absolute value of the coefficient must be increased.
  172930. */
  172931. for (; k <= Se; k++) {
  172932. thiscoef = *block + jpeg_natural_order[k];
  172933. if (*thiscoef != 0) {
  172934. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172935. if (GET_BITS(1)) {
  172936. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172937. if (*thiscoef >= 0)
  172938. *thiscoef += p1;
  172939. else
  172940. *thiscoef += m1;
  172941. }
  172942. }
  172943. }
  172944. }
  172945. /* Count one block completed in EOB run */
  172946. EOBRUN--;
  172947. }
  172948. /* Completed MCU, so update state */
  172949. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172950. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172951. }
  172952. /* Account for restart interval (no-op if not using restarts) */
  172953. entropy->restarts_to_go--;
  172954. return TRUE;
  172955. undoit:
  172956. /* Re-zero any output coefficients that we made newly nonzero */
  172957. while (num_newnz > 0)
  172958. (*block)[newnz_pos[--num_newnz]] = 0;
  172959. return FALSE;
  172960. }
  172961. /*
  172962. * Module initialization routine for progressive Huffman entropy decoding.
  172963. */
  172964. GLOBAL(void)
  172965. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172966. {
  172967. phuff_entropy_ptr2 entropy;
  172968. int *coef_bit_ptr;
  172969. int ci, i;
  172970. entropy = (phuff_entropy_ptr2)
  172971. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172972. SIZEOF(phuff_entropy_decoder));
  172973. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172974. entropy->pub.start_pass = start_pass_phuff_decoder;
  172975. /* Mark derived tables unallocated */
  172976. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172977. entropy->derived_tbls[i] = NULL;
  172978. }
  172979. /* Create progression status table */
  172980. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172981. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172982. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172983. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172984. for (ci = 0; ci < cinfo->num_components; ci++)
  172985. for (i = 0; i < DCTSIZE2; i++)
  172986. *coef_bit_ptr++ = -1;
  172987. }
  172988. #endif /* D_PROGRESSIVE_SUPPORTED */
  172989. /*** End of inlined file: jdphuff.c ***/
  172990. /*** Start of inlined file: jdpostct.c ***/
  172991. #define JPEG_INTERNALS
  172992. /* Private buffer controller object */
  172993. typedef struct {
  172994. struct jpeg_d_post_controller pub; /* public fields */
  172995. /* Color quantization source buffer: this holds output data from
  172996. * the upsample/color conversion step to be passed to the quantizer.
  172997. * For two-pass color quantization, we need a full-image buffer;
  172998. * for one-pass operation, a strip buffer is sufficient.
  172999. */
  173000. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173001. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173002. JDIMENSION strip_height; /* buffer size in rows */
  173003. /* for two-pass mode only: */
  173004. JDIMENSION starting_row; /* row # of first row in current strip */
  173005. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173006. } my_post_controller;
  173007. typedef my_post_controller * my_post_ptr;
  173008. /* Forward declarations */
  173009. METHODDEF(void) post_process_1pass
  173010. JPP((j_decompress_ptr cinfo,
  173011. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173012. JDIMENSION in_row_groups_avail,
  173013. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173014. JDIMENSION out_rows_avail));
  173015. #ifdef QUANT_2PASS_SUPPORTED
  173016. METHODDEF(void) post_process_prepass
  173017. JPP((j_decompress_ptr cinfo,
  173018. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173019. JDIMENSION in_row_groups_avail,
  173020. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173021. JDIMENSION out_rows_avail));
  173022. METHODDEF(void) post_process_2pass
  173023. JPP((j_decompress_ptr cinfo,
  173024. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173025. JDIMENSION in_row_groups_avail,
  173026. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173027. JDIMENSION out_rows_avail));
  173028. #endif
  173029. /*
  173030. * Initialize for a processing pass.
  173031. */
  173032. METHODDEF(void)
  173033. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173034. {
  173035. my_post_ptr post = (my_post_ptr) cinfo->post;
  173036. switch (pass_mode) {
  173037. case JBUF_PASS_THRU:
  173038. if (cinfo->quantize_colors) {
  173039. /* Single-pass processing with color quantization. */
  173040. post->pub.post_process_data = post_process_1pass;
  173041. /* We could be doing buffered-image output before starting a 2-pass
  173042. * color quantization; in that case, jinit_d_post_controller did not
  173043. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173044. */
  173045. if (post->buffer == NULL) {
  173046. post->buffer = (*cinfo->mem->access_virt_sarray)
  173047. ((j_common_ptr) cinfo, post->whole_image,
  173048. (JDIMENSION) 0, post->strip_height, TRUE);
  173049. }
  173050. } else {
  173051. /* For single-pass processing without color quantization,
  173052. * I have no work to do; just call the upsampler directly.
  173053. */
  173054. post->pub.post_process_data = cinfo->upsample->upsample;
  173055. }
  173056. break;
  173057. #ifdef QUANT_2PASS_SUPPORTED
  173058. case JBUF_SAVE_AND_PASS:
  173059. /* First pass of 2-pass quantization */
  173060. if (post->whole_image == NULL)
  173061. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173062. post->pub.post_process_data = post_process_prepass;
  173063. break;
  173064. case JBUF_CRANK_DEST:
  173065. /* Second pass of 2-pass quantization */
  173066. if (post->whole_image == NULL)
  173067. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173068. post->pub.post_process_data = post_process_2pass;
  173069. break;
  173070. #endif /* QUANT_2PASS_SUPPORTED */
  173071. default:
  173072. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173073. break;
  173074. }
  173075. post->starting_row = post->next_row = 0;
  173076. }
  173077. /*
  173078. * Process some data in the one-pass (strip buffer) case.
  173079. * This is used for color precision reduction as well as one-pass quantization.
  173080. */
  173081. METHODDEF(void)
  173082. post_process_1pass (j_decompress_ptr cinfo,
  173083. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173084. JDIMENSION in_row_groups_avail,
  173085. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173086. JDIMENSION out_rows_avail)
  173087. {
  173088. my_post_ptr post = (my_post_ptr) cinfo->post;
  173089. JDIMENSION num_rows, max_rows;
  173090. /* Fill the buffer, but not more than what we can dump out in one go. */
  173091. /* Note we rely on the upsampler to detect bottom of image. */
  173092. max_rows = out_rows_avail - *out_row_ctr;
  173093. if (max_rows > post->strip_height)
  173094. max_rows = post->strip_height;
  173095. num_rows = 0;
  173096. (*cinfo->upsample->upsample) (cinfo,
  173097. input_buf, in_row_group_ctr, in_row_groups_avail,
  173098. post->buffer, &num_rows, max_rows);
  173099. /* Quantize and emit data. */
  173100. (*cinfo->cquantize->color_quantize) (cinfo,
  173101. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173102. *out_row_ctr += num_rows;
  173103. }
  173104. #ifdef QUANT_2PASS_SUPPORTED
  173105. /*
  173106. * Process some data in the first pass of 2-pass quantization.
  173107. */
  173108. METHODDEF(void)
  173109. post_process_prepass (j_decompress_ptr cinfo,
  173110. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173111. JDIMENSION in_row_groups_avail,
  173112. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173113. JDIMENSION)
  173114. {
  173115. my_post_ptr post = (my_post_ptr) cinfo->post;
  173116. JDIMENSION old_next_row, num_rows;
  173117. /* Reposition virtual buffer if at start of strip. */
  173118. if (post->next_row == 0) {
  173119. post->buffer = (*cinfo->mem->access_virt_sarray)
  173120. ((j_common_ptr) cinfo, post->whole_image,
  173121. post->starting_row, post->strip_height, TRUE);
  173122. }
  173123. /* Upsample some data (up to a strip height's worth). */
  173124. old_next_row = post->next_row;
  173125. (*cinfo->upsample->upsample) (cinfo,
  173126. input_buf, in_row_group_ctr, in_row_groups_avail,
  173127. post->buffer, &post->next_row, post->strip_height);
  173128. /* Allow quantizer to scan new data. No data is emitted, */
  173129. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173130. if (post->next_row > old_next_row) {
  173131. num_rows = post->next_row - old_next_row;
  173132. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173133. (JSAMPARRAY) NULL, (int) num_rows);
  173134. *out_row_ctr += num_rows;
  173135. }
  173136. /* Advance if we filled the strip. */
  173137. if (post->next_row >= post->strip_height) {
  173138. post->starting_row += post->strip_height;
  173139. post->next_row = 0;
  173140. }
  173141. }
  173142. /*
  173143. * Process some data in the second pass of 2-pass quantization.
  173144. */
  173145. METHODDEF(void)
  173146. post_process_2pass (j_decompress_ptr cinfo,
  173147. JSAMPIMAGE, JDIMENSION *,
  173148. JDIMENSION,
  173149. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173150. JDIMENSION out_rows_avail)
  173151. {
  173152. my_post_ptr post = (my_post_ptr) cinfo->post;
  173153. JDIMENSION num_rows, max_rows;
  173154. /* Reposition virtual buffer if at start of strip. */
  173155. if (post->next_row == 0) {
  173156. post->buffer = (*cinfo->mem->access_virt_sarray)
  173157. ((j_common_ptr) cinfo, post->whole_image,
  173158. post->starting_row, post->strip_height, FALSE);
  173159. }
  173160. /* Determine number of rows to emit. */
  173161. num_rows = post->strip_height - post->next_row; /* available in strip */
  173162. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173163. if (num_rows > max_rows)
  173164. num_rows = max_rows;
  173165. /* We have to check bottom of image here, can't depend on upsampler. */
  173166. max_rows = cinfo->output_height - post->starting_row;
  173167. if (num_rows > max_rows)
  173168. num_rows = max_rows;
  173169. /* Quantize and emit data. */
  173170. (*cinfo->cquantize->color_quantize) (cinfo,
  173171. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173172. (int) num_rows);
  173173. *out_row_ctr += num_rows;
  173174. /* Advance if we filled the strip. */
  173175. post->next_row += num_rows;
  173176. if (post->next_row >= post->strip_height) {
  173177. post->starting_row += post->strip_height;
  173178. post->next_row = 0;
  173179. }
  173180. }
  173181. #endif /* QUANT_2PASS_SUPPORTED */
  173182. /*
  173183. * Initialize postprocessing controller.
  173184. */
  173185. GLOBAL(void)
  173186. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173187. {
  173188. my_post_ptr post;
  173189. post = (my_post_ptr)
  173190. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173191. SIZEOF(my_post_controller));
  173192. cinfo->post = (struct jpeg_d_post_controller *) post;
  173193. post->pub.start_pass = start_pass_dpost;
  173194. post->whole_image = NULL; /* flag for no virtual arrays */
  173195. post->buffer = NULL; /* flag for no strip buffer */
  173196. /* Create the quantization buffer, if needed */
  173197. if (cinfo->quantize_colors) {
  173198. /* The buffer strip height is max_v_samp_factor, which is typically
  173199. * an efficient number of rows for upsampling to return.
  173200. * (In the presence of output rescaling, we might want to be smarter?)
  173201. */
  173202. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173203. if (need_full_buffer) {
  173204. /* Two-pass color quantization: need full-image storage. */
  173205. /* We round up the number of rows to a multiple of the strip height. */
  173206. #ifdef QUANT_2PASS_SUPPORTED
  173207. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173208. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173209. cinfo->output_width * cinfo->out_color_components,
  173210. (JDIMENSION) jround_up((long) cinfo->output_height,
  173211. (long) post->strip_height),
  173212. post->strip_height);
  173213. #else
  173214. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173215. #endif /* QUANT_2PASS_SUPPORTED */
  173216. } else {
  173217. /* One-pass color quantization: just make a strip buffer. */
  173218. post->buffer = (*cinfo->mem->alloc_sarray)
  173219. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173220. cinfo->output_width * cinfo->out_color_components,
  173221. post->strip_height);
  173222. }
  173223. }
  173224. }
  173225. /*** End of inlined file: jdpostct.c ***/
  173226. #undef FIX
  173227. /*** Start of inlined file: jdsample.c ***/
  173228. #define JPEG_INTERNALS
  173229. /* Pointer to routine to upsample a single component */
  173230. typedef JMETHOD(void, upsample1_ptr,
  173231. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173232. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173233. /* Private subobject */
  173234. typedef struct {
  173235. struct jpeg_upsampler pub; /* public fields */
  173236. /* Color conversion buffer. When using separate upsampling and color
  173237. * conversion steps, this buffer holds one upsampled row group until it
  173238. * has been color converted and output.
  173239. * Note: we do not allocate any storage for component(s) which are full-size,
  173240. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173241. * simply set to point to the input data array, thereby avoiding copying.
  173242. */
  173243. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173244. /* Per-component upsampling method pointers */
  173245. upsample1_ptr methods[MAX_COMPONENTS];
  173246. int next_row_out; /* counts rows emitted from color_buf */
  173247. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173248. /* Height of an input row group for each component. */
  173249. int rowgroup_height[MAX_COMPONENTS];
  173250. /* These arrays save pixel expansion factors so that int_expand need not
  173251. * recompute them each time. They are unused for other upsampling methods.
  173252. */
  173253. UINT8 h_expand[MAX_COMPONENTS];
  173254. UINT8 v_expand[MAX_COMPONENTS];
  173255. } my_upsampler2;
  173256. typedef my_upsampler2 * my_upsample_ptr2;
  173257. /*
  173258. * Initialize for an upsampling pass.
  173259. */
  173260. METHODDEF(void)
  173261. start_pass_upsample (j_decompress_ptr cinfo)
  173262. {
  173263. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173264. /* Mark the conversion buffer empty */
  173265. upsample->next_row_out = cinfo->max_v_samp_factor;
  173266. /* Initialize total-height counter for detecting bottom of image */
  173267. upsample->rows_to_go = cinfo->output_height;
  173268. }
  173269. /*
  173270. * Control routine to do upsampling (and color conversion).
  173271. *
  173272. * In this version we upsample each component independently.
  173273. * We upsample one row group into the conversion buffer, then apply
  173274. * color conversion a row at a time.
  173275. */
  173276. METHODDEF(void)
  173277. sep_upsample (j_decompress_ptr cinfo,
  173278. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173279. JDIMENSION,
  173280. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173281. JDIMENSION out_rows_avail)
  173282. {
  173283. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173284. int ci;
  173285. jpeg_component_info * compptr;
  173286. JDIMENSION num_rows;
  173287. /* Fill the conversion buffer, if it's empty */
  173288. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173289. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173290. ci++, compptr++) {
  173291. /* Invoke per-component upsample method. Notice we pass a POINTER
  173292. * to color_buf[ci], so that fullsize_upsample can change it.
  173293. */
  173294. (*upsample->methods[ci]) (cinfo, compptr,
  173295. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173296. upsample->color_buf + ci);
  173297. }
  173298. upsample->next_row_out = 0;
  173299. }
  173300. /* Color-convert and emit rows */
  173301. /* How many we have in the buffer: */
  173302. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173303. /* Not more than the distance to the end of the image. Need this test
  173304. * in case the image height is not a multiple of max_v_samp_factor:
  173305. */
  173306. if (num_rows > upsample->rows_to_go)
  173307. num_rows = upsample->rows_to_go;
  173308. /* And not more than what the client can accept: */
  173309. out_rows_avail -= *out_row_ctr;
  173310. if (num_rows > out_rows_avail)
  173311. num_rows = out_rows_avail;
  173312. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173313. (JDIMENSION) upsample->next_row_out,
  173314. output_buf + *out_row_ctr,
  173315. (int) num_rows);
  173316. /* Adjust counts */
  173317. *out_row_ctr += num_rows;
  173318. upsample->rows_to_go -= num_rows;
  173319. upsample->next_row_out += num_rows;
  173320. /* When the buffer is emptied, declare this input row group consumed */
  173321. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173322. (*in_row_group_ctr)++;
  173323. }
  173324. /*
  173325. * These are the routines invoked by sep_upsample to upsample pixel values
  173326. * of a single component. One row group is processed per call.
  173327. */
  173328. /*
  173329. * For full-size components, we just make color_buf[ci] point at the
  173330. * input buffer, and thus avoid copying any data. Note that this is
  173331. * safe only because sep_upsample doesn't declare the input row group
  173332. * "consumed" until we are done color converting and emitting it.
  173333. */
  173334. METHODDEF(void)
  173335. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173336. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173337. {
  173338. *output_data_ptr = input_data;
  173339. }
  173340. /*
  173341. * This is a no-op version used for "uninteresting" components.
  173342. * These components will not be referenced by color conversion.
  173343. */
  173344. METHODDEF(void)
  173345. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173346. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173347. {
  173348. *output_data_ptr = NULL; /* safety check */
  173349. }
  173350. /*
  173351. * This version handles any integral sampling ratios.
  173352. * This is not used for typical JPEG files, so it need not be fast.
  173353. * Nor, for that matter, is it particularly accurate: the algorithm is
  173354. * simple replication of the input pixel onto the corresponding output
  173355. * pixels. The hi-falutin sampling literature refers to this as a
  173356. * "box filter". A box filter tends to introduce visible artifacts,
  173357. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173358. * you would be well advised to improve this code.
  173359. */
  173360. METHODDEF(void)
  173361. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173362. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173363. {
  173364. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173365. JSAMPARRAY output_data = *output_data_ptr;
  173366. register JSAMPROW inptr, outptr;
  173367. register JSAMPLE invalue;
  173368. register int h;
  173369. JSAMPROW outend;
  173370. int h_expand, v_expand;
  173371. int inrow, outrow;
  173372. h_expand = upsample->h_expand[compptr->component_index];
  173373. v_expand = upsample->v_expand[compptr->component_index];
  173374. inrow = outrow = 0;
  173375. while (outrow < cinfo->max_v_samp_factor) {
  173376. /* Generate one output row with proper horizontal expansion */
  173377. inptr = input_data[inrow];
  173378. outptr = output_data[outrow];
  173379. outend = outptr + cinfo->output_width;
  173380. while (outptr < outend) {
  173381. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173382. for (h = h_expand; h > 0; h--) {
  173383. *outptr++ = invalue;
  173384. }
  173385. }
  173386. /* Generate any additional output rows by duplicating the first one */
  173387. if (v_expand > 1) {
  173388. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173389. v_expand-1, cinfo->output_width);
  173390. }
  173391. inrow++;
  173392. outrow += v_expand;
  173393. }
  173394. }
  173395. /*
  173396. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173397. * It's still a box filter.
  173398. */
  173399. METHODDEF(void)
  173400. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173401. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173402. {
  173403. JSAMPARRAY output_data = *output_data_ptr;
  173404. register JSAMPROW inptr, outptr;
  173405. register JSAMPLE invalue;
  173406. JSAMPROW outend;
  173407. int inrow;
  173408. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173409. inptr = input_data[inrow];
  173410. outptr = output_data[inrow];
  173411. outend = outptr + cinfo->output_width;
  173412. while (outptr < outend) {
  173413. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173414. *outptr++ = invalue;
  173415. *outptr++ = invalue;
  173416. }
  173417. }
  173418. }
  173419. /*
  173420. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173421. * It's still a box filter.
  173422. */
  173423. METHODDEF(void)
  173424. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173425. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173426. {
  173427. JSAMPARRAY output_data = *output_data_ptr;
  173428. register JSAMPROW inptr, outptr;
  173429. register JSAMPLE invalue;
  173430. JSAMPROW outend;
  173431. int inrow, outrow;
  173432. inrow = outrow = 0;
  173433. while (outrow < cinfo->max_v_samp_factor) {
  173434. inptr = input_data[inrow];
  173435. outptr = output_data[outrow];
  173436. outend = outptr + cinfo->output_width;
  173437. while (outptr < outend) {
  173438. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173439. *outptr++ = invalue;
  173440. *outptr++ = invalue;
  173441. }
  173442. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173443. 1, cinfo->output_width);
  173444. inrow++;
  173445. outrow += 2;
  173446. }
  173447. }
  173448. /*
  173449. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173450. *
  173451. * The upsampling algorithm is linear interpolation between pixel centers,
  173452. * also known as a "triangle filter". This is a good compromise between
  173453. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173454. * of the way between input pixel centers.
  173455. *
  173456. * A note about the "bias" calculations: when rounding fractional values to
  173457. * integer, we do not want to always round 0.5 up to the next integer.
  173458. * If we did that, we'd introduce a noticeable bias towards larger values.
  173459. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173460. * alternate pixel locations (a simple ordered dither pattern).
  173461. */
  173462. METHODDEF(void)
  173463. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173464. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173465. {
  173466. JSAMPARRAY output_data = *output_data_ptr;
  173467. register JSAMPROW inptr, outptr;
  173468. register int invalue;
  173469. register JDIMENSION colctr;
  173470. int inrow;
  173471. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173472. inptr = input_data[inrow];
  173473. outptr = output_data[inrow];
  173474. /* Special case for first column */
  173475. invalue = GETJSAMPLE(*inptr++);
  173476. *outptr++ = (JSAMPLE) invalue;
  173477. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173478. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173479. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173480. invalue = GETJSAMPLE(*inptr++) * 3;
  173481. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173482. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173483. }
  173484. /* Special case for last column */
  173485. invalue = GETJSAMPLE(*inptr);
  173486. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173487. *outptr++ = (JSAMPLE) invalue;
  173488. }
  173489. }
  173490. /*
  173491. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173492. * Again a triangle filter; see comments for h2v1 case, above.
  173493. *
  173494. * It is OK for us to reference the adjacent input rows because we demanded
  173495. * context from the main buffer controller (see initialization code).
  173496. */
  173497. METHODDEF(void)
  173498. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173499. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173500. {
  173501. JSAMPARRAY output_data = *output_data_ptr;
  173502. register JSAMPROW inptr0, inptr1, outptr;
  173503. #if BITS_IN_JSAMPLE == 8
  173504. register int thiscolsum, lastcolsum, nextcolsum;
  173505. #else
  173506. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173507. #endif
  173508. register JDIMENSION colctr;
  173509. int inrow, outrow, v;
  173510. inrow = outrow = 0;
  173511. while (outrow < cinfo->max_v_samp_factor) {
  173512. for (v = 0; v < 2; v++) {
  173513. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173514. inptr0 = input_data[inrow];
  173515. if (v == 0) /* next nearest is row above */
  173516. inptr1 = input_data[inrow-1];
  173517. else /* next nearest is row below */
  173518. inptr1 = input_data[inrow+1];
  173519. outptr = output_data[outrow++];
  173520. /* Special case for first column */
  173521. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173522. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173523. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173524. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173525. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173526. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173527. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173528. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173529. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173530. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173531. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173532. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173533. }
  173534. /* Special case for last column */
  173535. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173536. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173537. }
  173538. inrow++;
  173539. }
  173540. }
  173541. /*
  173542. * Module initialization routine for upsampling.
  173543. */
  173544. GLOBAL(void)
  173545. jinit_upsampler (j_decompress_ptr cinfo)
  173546. {
  173547. my_upsample_ptr2 upsample;
  173548. int ci;
  173549. jpeg_component_info * compptr;
  173550. boolean need_buffer, do_fancy;
  173551. int h_in_group, v_in_group, h_out_group, v_out_group;
  173552. upsample = (my_upsample_ptr2)
  173553. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173554. SIZEOF(my_upsampler2));
  173555. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173556. upsample->pub.start_pass = start_pass_upsample;
  173557. upsample->pub.upsample = sep_upsample;
  173558. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173559. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173560. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173561. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173562. * so don't ask for it.
  173563. */
  173564. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173565. /* Verify we can handle the sampling factors, select per-component methods,
  173566. * and create storage as needed.
  173567. */
  173568. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173569. ci++, compptr++) {
  173570. /* Compute size of an "input group" after IDCT scaling. This many samples
  173571. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173572. */
  173573. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173574. cinfo->min_DCT_scaled_size;
  173575. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173576. cinfo->min_DCT_scaled_size;
  173577. h_out_group = cinfo->max_h_samp_factor;
  173578. v_out_group = cinfo->max_v_samp_factor;
  173579. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173580. need_buffer = TRUE;
  173581. if (! compptr->component_needed) {
  173582. /* Don't bother to upsample an uninteresting component. */
  173583. upsample->methods[ci] = noop_upsample;
  173584. need_buffer = FALSE;
  173585. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173586. /* Fullsize components can be processed without any work. */
  173587. upsample->methods[ci] = fullsize_upsample;
  173588. need_buffer = FALSE;
  173589. } else if (h_in_group * 2 == h_out_group &&
  173590. v_in_group == v_out_group) {
  173591. /* Special cases for 2h1v upsampling */
  173592. if (do_fancy && compptr->downsampled_width > 2)
  173593. upsample->methods[ci] = h2v1_fancy_upsample;
  173594. else
  173595. upsample->methods[ci] = h2v1_upsample;
  173596. } else if (h_in_group * 2 == h_out_group &&
  173597. v_in_group * 2 == v_out_group) {
  173598. /* Special cases for 2h2v upsampling */
  173599. if (do_fancy && compptr->downsampled_width > 2) {
  173600. upsample->methods[ci] = h2v2_fancy_upsample;
  173601. upsample->pub.need_context_rows = TRUE;
  173602. } else
  173603. upsample->methods[ci] = h2v2_upsample;
  173604. } else if ((h_out_group % h_in_group) == 0 &&
  173605. (v_out_group % v_in_group) == 0) {
  173606. /* Generic integral-factors upsampling method */
  173607. upsample->methods[ci] = int_upsample;
  173608. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173609. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173610. } else
  173611. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173612. if (need_buffer) {
  173613. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173614. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173615. (JDIMENSION) jround_up((long) cinfo->output_width,
  173616. (long) cinfo->max_h_samp_factor),
  173617. (JDIMENSION) cinfo->max_v_samp_factor);
  173618. }
  173619. }
  173620. }
  173621. /*** End of inlined file: jdsample.c ***/
  173622. /*** Start of inlined file: jdtrans.c ***/
  173623. #define JPEG_INTERNALS
  173624. /* Forward declarations */
  173625. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173626. /*
  173627. * Read the coefficient arrays from a JPEG file.
  173628. * jpeg_read_header must be completed before calling this.
  173629. *
  173630. * The entire image is read into a set of virtual coefficient-block arrays,
  173631. * one per component. The return value is a pointer to the array of
  173632. * virtual-array descriptors. These can be manipulated directly via the
  173633. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173634. * To release the memory occupied by the virtual arrays, call
  173635. * jpeg_finish_decompress() when done with the data.
  173636. *
  173637. * An alternative usage is to simply obtain access to the coefficient arrays
  173638. * during a buffered-image-mode decompression operation. This is allowed
  173639. * after any jpeg_finish_output() call. The arrays can be accessed until
  173640. * jpeg_finish_decompress() is called. (Note that any call to the library
  173641. * may reposition the arrays, so don't rely on access_virt_barray() results
  173642. * to stay valid across library calls.)
  173643. *
  173644. * Returns NULL if suspended. This case need be checked only if
  173645. * a suspending data source is used.
  173646. */
  173647. GLOBAL(jvirt_barray_ptr *)
  173648. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173649. {
  173650. if (cinfo->global_state == DSTATE_READY) {
  173651. /* First call: initialize active modules */
  173652. transdecode_master_selection(cinfo);
  173653. cinfo->global_state = DSTATE_RDCOEFS;
  173654. }
  173655. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173656. /* Absorb whole file into the coef buffer */
  173657. for (;;) {
  173658. int retcode;
  173659. /* Call progress monitor hook if present */
  173660. if (cinfo->progress != NULL)
  173661. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173662. /* Absorb some more input */
  173663. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173664. if (retcode == JPEG_SUSPENDED)
  173665. return NULL;
  173666. if (retcode == JPEG_REACHED_EOI)
  173667. break;
  173668. /* Advance progress counter if appropriate */
  173669. if (cinfo->progress != NULL &&
  173670. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173671. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173672. /* startup underestimated number of scans; ratchet up one scan */
  173673. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173674. }
  173675. }
  173676. }
  173677. /* Set state so that jpeg_finish_decompress does the right thing */
  173678. cinfo->global_state = DSTATE_STOPPING;
  173679. }
  173680. /* At this point we should be in state DSTATE_STOPPING if being used
  173681. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173682. * to the coefficients during a full buffered-image-mode decompression.
  173683. */
  173684. if ((cinfo->global_state == DSTATE_STOPPING ||
  173685. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173686. return cinfo->coef->coef_arrays;
  173687. }
  173688. /* Oops, improper usage */
  173689. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173690. return NULL; /* keep compiler happy */
  173691. }
  173692. /*
  173693. * Master selection of decompression modules for transcoding.
  173694. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173695. */
  173696. LOCAL(void)
  173697. transdecode_master_selection (j_decompress_ptr cinfo)
  173698. {
  173699. /* This is effectively a buffered-image operation. */
  173700. cinfo->buffered_image = TRUE;
  173701. /* Entropy decoding: either Huffman or arithmetic coding. */
  173702. if (cinfo->arith_code) {
  173703. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173704. } else {
  173705. if (cinfo->progressive_mode) {
  173706. #ifdef D_PROGRESSIVE_SUPPORTED
  173707. jinit_phuff_decoder(cinfo);
  173708. #else
  173709. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173710. #endif
  173711. } else
  173712. jinit_huff_decoder(cinfo);
  173713. }
  173714. /* Always get a full-image coefficient buffer. */
  173715. jinit_d_coef_controller(cinfo, TRUE);
  173716. /* We can now tell the memory manager to allocate virtual arrays. */
  173717. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173718. /* Initialize input side of decompressor to consume first scan. */
  173719. (*cinfo->inputctl->start_input_pass) (cinfo);
  173720. /* Initialize progress monitoring. */
  173721. if (cinfo->progress != NULL) {
  173722. int nscans;
  173723. /* Estimate number of scans to set pass_limit. */
  173724. if (cinfo->progressive_mode) {
  173725. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173726. nscans = 2 + 3 * cinfo->num_components;
  173727. } else if (cinfo->inputctl->has_multiple_scans) {
  173728. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173729. nscans = cinfo->num_components;
  173730. } else {
  173731. nscans = 1;
  173732. }
  173733. cinfo->progress->pass_counter = 0L;
  173734. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173735. cinfo->progress->completed_passes = 0;
  173736. cinfo->progress->total_passes = 1;
  173737. }
  173738. }
  173739. /*** End of inlined file: jdtrans.c ***/
  173740. /*** Start of inlined file: jfdctflt.c ***/
  173741. #define JPEG_INTERNALS
  173742. #ifdef DCT_FLOAT_SUPPORTED
  173743. /*
  173744. * This module is specialized to the case DCTSIZE = 8.
  173745. */
  173746. #if DCTSIZE != 8
  173747. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173748. #endif
  173749. /*
  173750. * Perform the forward DCT on one block of samples.
  173751. */
  173752. GLOBAL(void)
  173753. jpeg_fdct_float (FAST_FLOAT * data)
  173754. {
  173755. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173756. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173757. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173758. FAST_FLOAT *dataptr;
  173759. int ctr;
  173760. /* Pass 1: process rows. */
  173761. dataptr = data;
  173762. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173763. tmp0 = dataptr[0] + dataptr[7];
  173764. tmp7 = dataptr[0] - dataptr[7];
  173765. tmp1 = dataptr[1] + dataptr[6];
  173766. tmp6 = dataptr[1] - dataptr[6];
  173767. tmp2 = dataptr[2] + dataptr[5];
  173768. tmp5 = dataptr[2] - dataptr[5];
  173769. tmp3 = dataptr[3] + dataptr[4];
  173770. tmp4 = dataptr[3] - dataptr[4];
  173771. /* Even part */
  173772. tmp10 = tmp0 + tmp3; /* phase 2 */
  173773. tmp13 = tmp0 - tmp3;
  173774. tmp11 = tmp1 + tmp2;
  173775. tmp12 = tmp1 - tmp2;
  173776. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173777. dataptr[4] = tmp10 - tmp11;
  173778. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173779. dataptr[2] = tmp13 + z1; /* phase 5 */
  173780. dataptr[6] = tmp13 - z1;
  173781. /* Odd part */
  173782. tmp10 = tmp4 + tmp5; /* phase 2 */
  173783. tmp11 = tmp5 + tmp6;
  173784. tmp12 = tmp6 + tmp7;
  173785. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173786. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173787. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173788. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173789. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173790. z11 = tmp7 + z3; /* phase 5 */
  173791. z13 = tmp7 - z3;
  173792. dataptr[5] = z13 + z2; /* phase 6 */
  173793. dataptr[3] = z13 - z2;
  173794. dataptr[1] = z11 + z4;
  173795. dataptr[7] = z11 - z4;
  173796. dataptr += DCTSIZE; /* advance pointer to next row */
  173797. }
  173798. /* Pass 2: process columns. */
  173799. dataptr = data;
  173800. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173801. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173802. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173803. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173804. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173805. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173806. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173807. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173808. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173809. /* Even part */
  173810. tmp10 = tmp0 + tmp3; /* phase 2 */
  173811. tmp13 = tmp0 - tmp3;
  173812. tmp11 = tmp1 + tmp2;
  173813. tmp12 = tmp1 - tmp2;
  173814. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173815. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173816. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173817. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173818. dataptr[DCTSIZE*6] = tmp13 - z1;
  173819. /* Odd part */
  173820. tmp10 = tmp4 + tmp5; /* phase 2 */
  173821. tmp11 = tmp5 + tmp6;
  173822. tmp12 = tmp6 + tmp7;
  173823. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173824. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173825. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173826. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173827. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173828. z11 = tmp7 + z3; /* phase 5 */
  173829. z13 = tmp7 - z3;
  173830. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173831. dataptr[DCTSIZE*3] = z13 - z2;
  173832. dataptr[DCTSIZE*1] = z11 + z4;
  173833. dataptr[DCTSIZE*7] = z11 - z4;
  173834. dataptr++; /* advance pointer to next column */
  173835. }
  173836. }
  173837. #endif /* DCT_FLOAT_SUPPORTED */
  173838. /*** End of inlined file: jfdctflt.c ***/
  173839. /*** Start of inlined file: jfdctint.c ***/
  173840. #define JPEG_INTERNALS
  173841. #ifdef DCT_ISLOW_SUPPORTED
  173842. /*
  173843. * This module is specialized to the case DCTSIZE = 8.
  173844. */
  173845. #if DCTSIZE != 8
  173846. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173847. #endif
  173848. /*
  173849. * The poop on this scaling stuff is as follows:
  173850. *
  173851. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173852. * larger than the true DCT outputs. The final outputs are therefore
  173853. * a factor of N larger than desired; since N=8 this can be cured by
  173854. * a simple right shift at the end of the algorithm. The advantage of
  173855. * this arrangement is that we save two multiplications per 1-D DCT,
  173856. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173857. * In the IJG code, this factor of 8 is removed by the quantization step
  173858. * (in jcdctmgr.c), NOT in this module.
  173859. *
  173860. * We have to do addition and subtraction of the integer inputs, which
  173861. * is no problem, and multiplication by fractional constants, which is
  173862. * a problem to do in integer arithmetic. We multiply all the constants
  173863. * by CONST_SCALE and convert them to integer constants (thus retaining
  173864. * CONST_BITS bits of precision in the constants). After doing a
  173865. * multiplication we have to divide the product by CONST_SCALE, with proper
  173866. * rounding, to produce the correct output. This division can be done
  173867. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173868. * as long as possible so that partial sums can be added together with
  173869. * full fractional precision.
  173870. *
  173871. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173872. * they are represented to better-than-integral precision. These outputs
  173873. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173874. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173875. * array is INT32 anyway.)
  173876. *
  173877. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173878. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173879. * shows that the values given below are the most effective.
  173880. */
  173881. #if BITS_IN_JSAMPLE == 8
  173882. #define CONST_BITS 13
  173883. #define PASS1_BITS 2
  173884. #else
  173885. #define CONST_BITS 13
  173886. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173887. #endif
  173888. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173889. * causing a lot of useless floating-point operations at run time.
  173890. * To get around this we use the following pre-calculated constants.
  173891. * If you change CONST_BITS you may want to add appropriate values.
  173892. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173893. */
  173894. #if CONST_BITS == 13
  173895. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173896. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173897. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173898. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173899. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173900. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173901. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173902. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173903. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173904. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173905. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173906. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173907. #else
  173908. #define FIX_0_298631336 FIX(0.298631336)
  173909. #define FIX_0_390180644 FIX(0.390180644)
  173910. #define FIX_0_541196100 FIX(0.541196100)
  173911. #define FIX_0_765366865 FIX(0.765366865)
  173912. #define FIX_0_899976223 FIX(0.899976223)
  173913. #define FIX_1_175875602 FIX(1.175875602)
  173914. #define FIX_1_501321110 FIX(1.501321110)
  173915. #define FIX_1_847759065 FIX(1.847759065)
  173916. #define FIX_1_961570560 FIX(1.961570560)
  173917. #define FIX_2_053119869 FIX(2.053119869)
  173918. #define FIX_2_562915447 FIX(2.562915447)
  173919. #define FIX_3_072711026 FIX(3.072711026)
  173920. #endif
  173921. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173922. * For 8-bit samples with the recommended scaling, all the variable
  173923. * and constant values involved are no more than 16 bits wide, so a
  173924. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173925. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173926. */
  173927. #if BITS_IN_JSAMPLE == 8
  173928. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173929. #else
  173930. #define MULTIPLY(var,const) ((var) * (const))
  173931. #endif
  173932. /*
  173933. * Perform the forward DCT on one block of samples.
  173934. */
  173935. GLOBAL(void)
  173936. jpeg_fdct_islow (DCTELEM * data)
  173937. {
  173938. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173939. INT32 tmp10, tmp11, tmp12, tmp13;
  173940. INT32 z1, z2, z3, z4, z5;
  173941. DCTELEM *dataptr;
  173942. int ctr;
  173943. SHIFT_TEMPS
  173944. /* Pass 1: process rows. */
  173945. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173946. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173947. dataptr = data;
  173948. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173949. tmp0 = dataptr[0] + dataptr[7];
  173950. tmp7 = dataptr[0] - dataptr[7];
  173951. tmp1 = dataptr[1] + dataptr[6];
  173952. tmp6 = dataptr[1] - dataptr[6];
  173953. tmp2 = dataptr[2] + dataptr[5];
  173954. tmp5 = dataptr[2] - dataptr[5];
  173955. tmp3 = dataptr[3] + dataptr[4];
  173956. tmp4 = dataptr[3] - dataptr[4];
  173957. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173958. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173959. */
  173960. tmp10 = tmp0 + tmp3;
  173961. tmp13 = tmp0 - tmp3;
  173962. tmp11 = tmp1 + tmp2;
  173963. tmp12 = tmp1 - tmp2;
  173964. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173965. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173966. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173967. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173968. CONST_BITS-PASS1_BITS);
  173969. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173970. CONST_BITS-PASS1_BITS);
  173971. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173972. * cK represents cos(K*pi/16).
  173973. * i0..i3 in the paper are tmp4..tmp7 here.
  173974. */
  173975. z1 = tmp4 + tmp7;
  173976. z2 = tmp5 + tmp6;
  173977. z3 = tmp4 + tmp6;
  173978. z4 = tmp5 + tmp7;
  173979. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173980. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173981. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173982. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173983. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173984. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173985. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173986. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173987. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173988. z3 += z5;
  173989. z4 += z5;
  173990. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173991. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173992. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173993. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173994. dataptr += DCTSIZE; /* advance pointer to next row */
  173995. }
  173996. /* Pass 2: process columns.
  173997. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173998. * by an overall factor of 8.
  173999. */
  174000. dataptr = data;
  174001. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174002. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174003. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174004. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174005. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174006. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174007. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174008. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174009. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174010. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174011. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174012. */
  174013. tmp10 = tmp0 + tmp3;
  174014. tmp13 = tmp0 - tmp3;
  174015. tmp11 = tmp1 + tmp2;
  174016. tmp12 = tmp1 - tmp2;
  174017. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174018. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174019. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174020. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174021. CONST_BITS+PASS1_BITS);
  174022. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174023. CONST_BITS+PASS1_BITS);
  174024. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174025. * cK represents cos(K*pi/16).
  174026. * i0..i3 in the paper are tmp4..tmp7 here.
  174027. */
  174028. z1 = tmp4 + tmp7;
  174029. z2 = tmp5 + tmp6;
  174030. z3 = tmp4 + tmp6;
  174031. z4 = tmp5 + tmp7;
  174032. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174033. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174034. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174035. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174036. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174037. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174038. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174039. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174040. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174041. z3 += z5;
  174042. z4 += z5;
  174043. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174044. CONST_BITS+PASS1_BITS);
  174045. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174046. CONST_BITS+PASS1_BITS);
  174047. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174048. CONST_BITS+PASS1_BITS);
  174049. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174050. CONST_BITS+PASS1_BITS);
  174051. dataptr++; /* advance pointer to next column */
  174052. }
  174053. }
  174054. #endif /* DCT_ISLOW_SUPPORTED */
  174055. /*** End of inlined file: jfdctint.c ***/
  174056. #undef CONST_BITS
  174057. #undef MULTIPLY
  174058. #undef FIX_0_541196100
  174059. /*** Start of inlined file: jfdctfst.c ***/
  174060. #define JPEG_INTERNALS
  174061. #ifdef DCT_IFAST_SUPPORTED
  174062. /*
  174063. * This module is specialized to the case DCTSIZE = 8.
  174064. */
  174065. #if DCTSIZE != 8
  174066. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174067. #endif
  174068. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174069. * see jfdctint.c for more details. However, we choose to descale
  174070. * (right shift) multiplication products as soon as they are formed,
  174071. * rather than carrying additional fractional bits into subsequent additions.
  174072. * This compromises accuracy slightly, but it lets us save a few shifts.
  174073. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174074. * everywhere except in the multiplications proper; this saves a good deal
  174075. * of work on 16-bit-int machines.
  174076. *
  174077. * Again to save a few shifts, the intermediate results between pass 1 and
  174078. * pass 2 are not upscaled, but are represented only to integral precision.
  174079. *
  174080. * A final compromise is to represent the multiplicative constants to only
  174081. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174082. * machines, and may also reduce the cost of multiplication (since there
  174083. * are fewer one-bits in the constants).
  174084. */
  174085. #define CONST_BITS 8
  174086. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174087. * causing a lot of useless floating-point operations at run time.
  174088. * To get around this we use the following pre-calculated constants.
  174089. * If you change CONST_BITS you may want to add appropriate values.
  174090. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174091. */
  174092. #if CONST_BITS == 8
  174093. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174094. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174095. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174096. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174097. #else
  174098. #define FIX_0_382683433 FIX(0.382683433)
  174099. #define FIX_0_541196100 FIX(0.541196100)
  174100. #define FIX_0_707106781 FIX(0.707106781)
  174101. #define FIX_1_306562965 FIX(1.306562965)
  174102. #endif
  174103. /* We can gain a little more speed, with a further compromise in accuracy,
  174104. * by omitting the addition in a descaling shift. This yields an incorrectly
  174105. * rounded result half the time...
  174106. */
  174107. #ifndef USE_ACCURATE_ROUNDING
  174108. #undef DESCALE
  174109. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174110. #endif
  174111. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174112. * descale to yield a DCTELEM result.
  174113. */
  174114. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174115. /*
  174116. * Perform the forward DCT on one block of samples.
  174117. */
  174118. GLOBAL(void)
  174119. jpeg_fdct_ifast (DCTELEM * data)
  174120. {
  174121. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174122. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174123. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174124. DCTELEM *dataptr;
  174125. int ctr;
  174126. SHIFT_TEMPS
  174127. /* Pass 1: process rows. */
  174128. dataptr = data;
  174129. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174130. tmp0 = dataptr[0] + dataptr[7];
  174131. tmp7 = dataptr[0] - dataptr[7];
  174132. tmp1 = dataptr[1] + dataptr[6];
  174133. tmp6 = dataptr[1] - dataptr[6];
  174134. tmp2 = dataptr[2] + dataptr[5];
  174135. tmp5 = dataptr[2] - dataptr[5];
  174136. tmp3 = dataptr[3] + dataptr[4];
  174137. tmp4 = dataptr[3] - dataptr[4];
  174138. /* Even part */
  174139. tmp10 = tmp0 + tmp3; /* phase 2 */
  174140. tmp13 = tmp0 - tmp3;
  174141. tmp11 = tmp1 + tmp2;
  174142. tmp12 = tmp1 - tmp2;
  174143. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174144. dataptr[4] = tmp10 - tmp11;
  174145. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174146. dataptr[2] = tmp13 + z1; /* phase 5 */
  174147. dataptr[6] = tmp13 - z1;
  174148. /* Odd part */
  174149. tmp10 = tmp4 + tmp5; /* phase 2 */
  174150. tmp11 = tmp5 + tmp6;
  174151. tmp12 = tmp6 + tmp7;
  174152. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174153. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174154. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174155. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174156. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174157. z11 = tmp7 + z3; /* phase 5 */
  174158. z13 = tmp7 - z3;
  174159. dataptr[5] = z13 + z2; /* phase 6 */
  174160. dataptr[3] = z13 - z2;
  174161. dataptr[1] = z11 + z4;
  174162. dataptr[7] = z11 - z4;
  174163. dataptr += DCTSIZE; /* advance pointer to next row */
  174164. }
  174165. /* Pass 2: process columns. */
  174166. dataptr = data;
  174167. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174168. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174169. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174170. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174171. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174172. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174173. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174174. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174175. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174176. /* Even part */
  174177. tmp10 = tmp0 + tmp3; /* phase 2 */
  174178. tmp13 = tmp0 - tmp3;
  174179. tmp11 = tmp1 + tmp2;
  174180. tmp12 = tmp1 - tmp2;
  174181. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174182. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174183. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174184. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174185. dataptr[DCTSIZE*6] = tmp13 - z1;
  174186. /* Odd part */
  174187. tmp10 = tmp4 + tmp5; /* phase 2 */
  174188. tmp11 = tmp5 + tmp6;
  174189. tmp12 = tmp6 + tmp7;
  174190. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174191. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174192. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174193. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174194. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174195. z11 = tmp7 + z3; /* phase 5 */
  174196. z13 = tmp7 - z3;
  174197. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174198. dataptr[DCTSIZE*3] = z13 - z2;
  174199. dataptr[DCTSIZE*1] = z11 + z4;
  174200. dataptr[DCTSIZE*7] = z11 - z4;
  174201. dataptr++; /* advance pointer to next column */
  174202. }
  174203. }
  174204. #endif /* DCT_IFAST_SUPPORTED */
  174205. /*** End of inlined file: jfdctfst.c ***/
  174206. #undef FIX_0_541196100
  174207. /*** Start of inlined file: jidctflt.c ***/
  174208. #define JPEG_INTERNALS
  174209. #ifdef DCT_FLOAT_SUPPORTED
  174210. /*
  174211. * This module is specialized to the case DCTSIZE = 8.
  174212. */
  174213. #if DCTSIZE != 8
  174214. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174215. #endif
  174216. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174217. * entry; produce a float result.
  174218. */
  174219. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174220. /*
  174221. * Perform dequantization and inverse DCT on one block of coefficients.
  174222. */
  174223. GLOBAL(void)
  174224. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174225. JCOEFPTR coef_block,
  174226. JSAMPARRAY output_buf, JDIMENSION output_col)
  174227. {
  174228. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174229. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174230. FAST_FLOAT z5, z10, z11, z12, z13;
  174231. JCOEFPTR inptr;
  174232. FLOAT_MULT_TYPE * quantptr;
  174233. FAST_FLOAT * wsptr;
  174234. JSAMPROW outptr;
  174235. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174236. int ctr;
  174237. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174238. SHIFT_TEMPS
  174239. /* Pass 1: process columns from input, store into work array. */
  174240. inptr = coef_block;
  174241. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174242. wsptr = workspace;
  174243. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174244. /* Due to quantization, we will usually find that many of the input
  174245. * coefficients are zero, especially the AC terms. We can exploit this
  174246. * by short-circuiting the IDCT calculation for any column in which all
  174247. * the AC terms are zero. In that case each output is equal to the
  174248. * DC coefficient (with scale factor as needed).
  174249. * With typical images and quantization tables, half or more of the
  174250. * column DCT calculations can be simplified this way.
  174251. */
  174252. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174253. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174254. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174255. inptr[DCTSIZE*7] == 0) {
  174256. /* AC terms all zero */
  174257. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174258. wsptr[DCTSIZE*0] = dcval;
  174259. wsptr[DCTSIZE*1] = dcval;
  174260. wsptr[DCTSIZE*2] = dcval;
  174261. wsptr[DCTSIZE*3] = dcval;
  174262. wsptr[DCTSIZE*4] = dcval;
  174263. wsptr[DCTSIZE*5] = dcval;
  174264. wsptr[DCTSIZE*6] = dcval;
  174265. wsptr[DCTSIZE*7] = dcval;
  174266. inptr++; /* advance pointers to next column */
  174267. quantptr++;
  174268. wsptr++;
  174269. continue;
  174270. }
  174271. /* Even part */
  174272. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174273. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174274. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174275. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174276. tmp10 = tmp0 + tmp2; /* phase 3 */
  174277. tmp11 = tmp0 - tmp2;
  174278. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174279. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174280. tmp0 = tmp10 + tmp13; /* phase 2 */
  174281. tmp3 = tmp10 - tmp13;
  174282. tmp1 = tmp11 + tmp12;
  174283. tmp2 = tmp11 - tmp12;
  174284. /* Odd part */
  174285. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174286. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174287. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174288. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174289. z13 = tmp6 + tmp5; /* phase 6 */
  174290. z10 = tmp6 - tmp5;
  174291. z11 = tmp4 + tmp7;
  174292. z12 = tmp4 - tmp7;
  174293. tmp7 = z11 + z13; /* phase 5 */
  174294. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174295. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174296. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174297. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174298. tmp6 = tmp12 - tmp7; /* phase 2 */
  174299. tmp5 = tmp11 - tmp6;
  174300. tmp4 = tmp10 + tmp5;
  174301. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174302. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174303. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174304. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174305. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174306. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174307. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174308. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174309. inptr++; /* advance pointers to next column */
  174310. quantptr++;
  174311. wsptr++;
  174312. }
  174313. /* Pass 2: process rows from work array, store into output array. */
  174314. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174315. wsptr = workspace;
  174316. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174317. outptr = output_buf[ctr] + output_col;
  174318. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174319. * However, the column calculation has created many nonzero AC terms, so
  174320. * the simplification applies less often (typically 5% to 10% of the time).
  174321. * And testing floats for zero is relatively expensive, so we don't bother.
  174322. */
  174323. /* Even part */
  174324. tmp10 = wsptr[0] + wsptr[4];
  174325. tmp11 = wsptr[0] - wsptr[4];
  174326. tmp13 = wsptr[2] + wsptr[6];
  174327. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174328. tmp0 = tmp10 + tmp13;
  174329. tmp3 = tmp10 - tmp13;
  174330. tmp1 = tmp11 + tmp12;
  174331. tmp2 = tmp11 - tmp12;
  174332. /* Odd part */
  174333. z13 = wsptr[5] + wsptr[3];
  174334. z10 = wsptr[5] - wsptr[3];
  174335. z11 = wsptr[1] + wsptr[7];
  174336. z12 = wsptr[1] - wsptr[7];
  174337. tmp7 = z11 + z13;
  174338. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174339. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174340. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174341. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174342. tmp6 = tmp12 - tmp7;
  174343. tmp5 = tmp11 - tmp6;
  174344. tmp4 = tmp10 + tmp5;
  174345. /* Final output stage: scale down by a factor of 8 and range-limit */
  174346. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174347. & RANGE_MASK];
  174348. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174349. & RANGE_MASK];
  174350. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174351. & RANGE_MASK];
  174352. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174353. & RANGE_MASK];
  174354. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174355. & RANGE_MASK];
  174356. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174357. & RANGE_MASK];
  174358. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174359. & RANGE_MASK];
  174360. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174361. & RANGE_MASK];
  174362. wsptr += DCTSIZE; /* advance pointer to next row */
  174363. }
  174364. }
  174365. #endif /* DCT_FLOAT_SUPPORTED */
  174366. /*** End of inlined file: jidctflt.c ***/
  174367. #undef CONST_BITS
  174368. #undef FIX_1_847759065
  174369. #undef MULTIPLY
  174370. #undef DEQUANTIZE
  174371. #undef DESCALE
  174372. /*** Start of inlined file: jidctfst.c ***/
  174373. #define JPEG_INTERNALS
  174374. #ifdef DCT_IFAST_SUPPORTED
  174375. /*
  174376. * This module is specialized to the case DCTSIZE = 8.
  174377. */
  174378. #if DCTSIZE != 8
  174379. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174380. #endif
  174381. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174382. * see jidctint.c for more details. However, we choose to descale
  174383. * (right shift) multiplication products as soon as they are formed,
  174384. * rather than carrying additional fractional bits into subsequent additions.
  174385. * This compromises accuracy slightly, but it lets us save a few shifts.
  174386. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174387. * everywhere except in the multiplications proper; this saves a good deal
  174388. * of work on 16-bit-int machines.
  174389. *
  174390. * The dequantized coefficients are not integers because the AA&N scaling
  174391. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174392. * so that the first and second IDCT rounds have the same input scaling.
  174393. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174394. * avoid a descaling shift; this compromises accuracy rather drastically
  174395. * for small quantization table entries, but it saves a lot of shifts.
  174396. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174397. * so we use a much larger scaling factor to preserve accuracy.
  174398. *
  174399. * A final compromise is to represent the multiplicative constants to only
  174400. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174401. * machines, and may also reduce the cost of multiplication (since there
  174402. * are fewer one-bits in the constants).
  174403. */
  174404. #if BITS_IN_JSAMPLE == 8
  174405. #define CONST_BITS 8
  174406. #define PASS1_BITS 2
  174407. #else
  174408. #define CONST_BITS 8
  174409. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174410. #endif
  174411. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174412. * causing a lot of useless floating-point operations at run time.
  174413. * To get around this we use the following pre-calculated constants.
  174414. * If you change CONST_BITS you may want to add appropriate values.
  174415. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174416. */
  174417. #if CONST_BITS == 8
  174418. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174419. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174420. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174421. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174422. #else
  174423. #define FIX_1_082392200 FIX(1.082392200)
  174424. #define FIX_1_414213562 FIX(1.414213562)
  174425. #define FIX_1_847759065 FIX(1.847759065)
  174426. #define FIX_2_613125930 FIX(2.613125930)
  174427. #endif
  174428. /* We can gain a little more speed, with a further compromise in accuracy,
  174429. * by omitting the addition in a descaling shift. This yields an incorrectly
  174430. * rounded result half the time...
  174431. */
  174432. #ifndef USE_ACCURATE_ROUNDING
  174433. #undef DESCALE
  174434. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174435. #endif
  174436. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174437. * descale to yield a DCTELEM result.
  174438. */
  174439. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174440. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174441. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174442. * multiplication will do. For 12-bit data, the multiplier table is
  174443. * declared INT32, so a 32-bit multiply will be used.
  174444. */
  174445. #if BITS_IN_JSAMPLE == 8
  174446. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174447. #else
  174448. #define DEQUANTIZE(coef,quantval) \
  174449. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174450. #endif
  174451. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174452. * We assume that int right shift is unsigned if INT32 right shift is.
  174453. */
  174454. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174455. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174456. #if BITS_IN_JSAMPLE == 8
  174457. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174458. #else
  174459. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174460. #endif
  174461. #define IRIGHT_SHIFT(x,shft) \
  174462. ((ishift_temp = (x)) < 0 ? \
  174463. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174464. (ishift_temp >> (shft)))
  174465. #else
  174466. #define ISHIFT_TEMPS
  174467. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174468. #endif
  174469. #ifdef USE_ACCURATE_ROUNDING
  174470. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174471. #else
  174472. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174473. #endif
  174474. /*
  174475. * Perform dequantization and inverse DCT on one block of coefficients.
  174476. */
  174477. GLOBAL(void)
  174478. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174479. JCOEFPTR coef_block,
  174480. JSAMPARRAY output_buf, JDIMENSION output_col)
  174481. {
  174482. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174483. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174484. DCTELEM z5, z10, z11, z12, z13;
  174485. JCOEFPTR inptr;
  174486. IFAST_MULT_TYPE * quantptr;
  174487. int * wsptr;
  174488. JSAMPROW outptr;
  174489. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174490. int ctr;
  174491. int workspace[DCTSIZE2]; /* buffers data between passes */
  174492. SHIFT_TEMPS /* for DESCALE */
  174493. ISHIFT_TEMPS /* for IDESCALE */
  174494. /* Pass 1: process columns from input, store into work array. */
  174495. inptr = coef_block;
  174496. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174497. wsptr = workspace;
  174498. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174499. /* Due to quantization, we will usually find that many of the input
  174500. * coefficients are zero, especially the AC terms. We can exploit this
  174501. * by short-circuiting the IDCT calculation for any column in which all
  174502. * the AC terms are zero. In that case each output is equal to the
  174503. * DC coefficient (with scale factor as needed).
  174504. * With typical images and quantization tables, half or more of the
  174505. * column DCT calculations can be simplified this way.
  174506. */
  174507. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174508. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174509. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174510. inptr[DCTSIZE*7] == 0) {
  174511. /* AC terms all zero */
  174512. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174513. wsptr[DCTSIZE*0] = dcval;
  174514. wsptr[DCTSIZE*1] = dcval;
  174515. wsptr[DCTSIZE*2] = dcval;
  174516. wsptr[DCTSIZE*3] = dcval;
  174517. wsptr[DCTSIZE*4] = dcval;
  174518. wsptr[DCTSIZE*5] = dcval;
  174519. wsptr[DCTSIZE*6] = dcval;
  174520. wsptr[DCTSIZE*7] = dcval;
  174521. inptr++; /* advance pointers to next column */
  174522. quantptr++;
  174523. wsptr++;
  174524. continue;
  174525. }
  174526. /* Even part */
  174527. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174528. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174529. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174530. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174531. tmp10 = tmp0 + tmp2; /* phase 3 */
  174532. tmp11 = tmp0 - tmp2;
  174533. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174534. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174535. tmp0 = tmp10 + tmp13; /* phase 2 */
  174536. tmp3 = tmp10 - tmp13;
  174537. tmp1 = tmp11 + tmp12;
  174538. tmp2 = tmp11 - tmp12;
  174539. /* Odd part */
  174540. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174541. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174542. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174543. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174544. z13 = tmp6 + tmp5; /* phase 6 */
  174545. z10 = tmp6 - tmp5;
  174546. z11 = tmp4 + tmp7;
  174547. z12 = tmp4 - tmp7;
  174548. tmp7 = z11 + z13; /* phase 5 */
  174549. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174550. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174551. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174552. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174553. tmp6 = tmp12 - tmp7; /* phase 2 */
  174554. tmp5 = tmp11 - tmp6;
  174555. tmp4 = tmp10 + tmp5;
  174556. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174557. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174558. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174559. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174560. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174561. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174562. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174563. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174564. inptr++; /* advance pointers to next column */
  174565. quantptr++;
  174566. wsptr++;
  174567. }
  174568. /* Pass 2: process rows from work array, store into output array. */
  174569. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174570. /* and also undo the PASS1_BITS scaling. */
  174571. wsptr = workspace;
  174572. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174573. outptr = output_buf[ctr] + output_col;
  174574. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174575. * However, the column calculation has created many nonzero AC terms, so
  174576. * the simplification applies less often (typically 5% to 10% of the time).
  174577. * On machines with very fast multiplication, it's possible that the
  174578. * test takes more time than it's worth. In that case this section
  174579. * may be commented out.
  174580. */
  174581. #ifndef NO_ZERO_ROW_TEST
  174582. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174583. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174584. /* AC terms all zero */
  174585. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174586. & RANGE_MASK];
  174587. outptr[0] = dcval;
  174588. outptr[1] = dcval;
  174589. outptr[2] = dcval;
  174590. outptr[3] = dcval;
  174591. outptr[4] = dcval;
  174592. outptr[5] = dcval;
  174593. outptr[6] = dcval;
  174594. outptr[7] = dcval;
  174595. wsptr += DCTSIZE; /* advance pointer to next row */
  174596. continue;
  174597. }
  174598. #endif
  174599. /* Even part */
  174600. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174601. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174602. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174603. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174604. - tmp13;
  174605. tmp0 = tmp10 + tmp13;
  174606. tmp3 = tmp10 - tmp13;
  174607. tmp1 = tmp11 + tmp12;
  174608. tmp2 = tmp11 - tmp12;
  174609. /* Odd part */
  174610. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174611. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174612. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174613. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174614. tmp7 = z11 + z13; /* phase 5 */
  174615. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174616. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174617. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174618. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174619. tmp6 = tmp12 - tmp7; /* phase 2 */
  174620. tmp5 = tmp11 - tmp6;
  174621. tmp4 = tmp10 + tmp5;
  174622. /* Final output stage: scale down by a factor of 8 and range-limit */
  174623. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174624. & RANGE_MASK];
  174625. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174626. & RANGE_MASK];
  174627. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174628. & RANGE_MASK];
  174629. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174630. & RANGE_MASK];
  174631. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174632. & RANGE_MASK];
  174633. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174634. & RANGE_MASK];
  174635. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174636. & RANGE_MASK];
  174637. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174638. & RANGE_MASK];
  174639. wsptr += DCTSIZE; /* advance pointer to next row */
  174640. }
  174641. }
  174642. #endif /* DCT_IFAST_SUPPORTED */
  174643. /*** End of inlined file: jidctfst.c ***/
  174644. #undef CONST_BITS
  174645. #undef FIX_1_847759065
  174646. #undef MULTIPLY
  174647. #undef DEQUANTIZE
  174648. /*** Start of inlined file: jidctint.c ***/
  174649. #define JPEG_INTERNALS
  174650. #ifdef DCT_ISLOW_SUPPORTED
  174651. /*
  174652. * This module is specialized to the case DCTSIZE = 8.
  174653. */
  174654. #if DCTSIZE != 8
  174655. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174656. #endif
  174657. /*
  174658. * The poop on this scaling stuff is as follows:
  174659. *
  174660. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174661. * larger than the true IDCT outputs. The final outputs are therefore
  174662. * a factor of N larger than desired; since N=8 this can be cured by
  174663. * a simple right shift at the end of the algorithm. The advantage of
  174664. * this arrangement is that we save two multiplications per 1-D IDCT,
  174665. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174666. *
  174667. * We have to do addition and subtraction of the integer inputs, which
  174668. * is no problem, and multiplication by fractional constants, which is
  174669. * a problem to do in integer arithmetic. We multiply all the constants
  174670. * by CONST_SCALE and convert them to integer constants (thus retaining
  174671. * CONST_BITS bits of precision in the constants). After doing a
  174672. * multiplication we have to divide the product by CONST_SCALE, with proper
  174673. * rounding, to produce the correct output. This division can be done
  174674. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174675. * as long as possible so that partial sums can be added together with
  174676. * full fractional precision.
  174677. *
  174678. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174679. * they are represented to better-than-integral precision. These outputs
  174680. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174681. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174682. * intermediate INT32 array would be needed.)
  174683. *
  174684. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174685. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174686. * shows that the values given below are the most effective.
  174687. */
  174688. #if BITS_IN_JSAMPLE == 8
  174689. #define CONST_BITS 13
  174690. #define PASS1_BITS 2
  174691. #else
  174692. #define CONST_BITS 13
  174693. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174694. #endif
  174695. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174696. * causing a lot of useless floating-point operations at run time.
  174697. * To get around this we use the following pre-calculated constants.
  174698. * If you change CONST_BITS you may want to add appropriate values.
  174699. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174700. */
  174701. #if CONST_BITS == 13
  174702. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174703. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174704. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174705. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174706. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174707. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174708. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174709. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174710. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174711. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174712. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174713. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174714. #else
  174715. #define FIX_0_298631336 FIX(0.298631336)
  174716. #define FIX_0_390180644 FIX(0.390180644)
  174717. #define FIX_0_541196100 FIX(0.541196100)
  174718. #define FIX_0_765366865 FIX(0.765366865)
  174719. #define FIX_0_899976223 FIX(0.899976223)
  174720. #define FIX_1_175875602 FIX(1.175875602)
  174721. #define FIX_1_501321110 FIX(1.501321110)
  174722. #define FIX_1_847759065 FIX(1.847759065)
  174723. #define FIX_1_961570560 FIX(1.961570560)
  174724. #define FIX_2_053119869 FIX(2.053119869)
  174725. #define FIX_2_562915447 FIX(2.562915447)
  174726. #define FIX_3_072711026 FIX(3.072711026)
  174727. #endif
  174728. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174729. * For 8-bit samples with the recommended scaling, all the variable
  174730. * and constant values involved are no more than 16 bits wide, so a
  174731. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174732. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174733. */
  174734. #if BITS_IN_JSAMPLE == 8
  174735. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174736. #else
  174737. #define MULTIPLY(var,const) ((var) * (const))
  174738. #endif
  174739. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174740. * entry; produce an int result. In this module, both inputs and result
  174741. * are 16 bits or less, so either int or short multiply will work.
  174742. */
  174743. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174744. /*
  174745. * Perform dequantization and inverse DCT on one block of coefficients.
  174746. */
  174747. GLOBAL(void)
  174748. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174749. JCOEFPTR coef_block,
  174750. JSAMPARRAY output_buf, JDIMENSION output_col)
  174751. {
  174752. INT32 tmp0, tmp1, tmp2, tmp3;
  174753. INT32 tmp10, tmp11, tmp12, tmp13;
  174754. INT32 z1, z2, z3, z4, z5;
  174755. JCOEFPTR inptr;
  174756. ISLOW_MULT_TYPE * quantptr;
  174757. int * wsptr;
  174758. JSAMPROW outptr;
  174759. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174760. int ctr;
  174761. int workspace[DCTSIZE2]; /* buffers data between passes */
  174762. SHIFT_TEMPS
  174763. /* Pass 1: process columns from input, store into work array. */
  174764. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174765. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174766. inptr = coef_block;
  174767. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174768. wsptr = workspace;
  174769. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174770. /* Due to quantization, we will usually find that many of the input
  174771. * coefficients are zero, especially the AC terms. We can exploit this
  174772. * by short-circuiting the IDCT calculation for any column in which all
  174773. * the AC terms are zero. In that case each output is equal to the
  174774. * DC coefficient (with scale factor as needed).
  174775. * With typical images and quantization tables, half or more of the
  174776. * column DCT calculations can be simplified this way.
  174777. */
  174778. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174779. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174780. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174781. inptr[DCTSIZE*7] == 0) {
  174782. /* AC terms all zero */
  174783. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174784. wsptr[DCTSIZE*0] = dcval;
  174785. wsptr[DCTSIZE*1] = dcval;
  174786. wsptr[DCTSIZE*2] = dcval;
  174787. wsptr[DCTSIZE*3] = dcval;
  174788. wsptr[DCTSIZE*4] = dcval;
  174789. wsptr[DCTSIZE*5] = dcval;
  174790. wsptr[DCTSIZE*6] = dcval;
  174791. wsptr[DCTSIZE*7] = dcval;
  174792. inptr++; /* advance pointers to next column */
  174793. quantptr++;
  174794. wsptr++;
  174795. continue;
  174796. }
  174797. /* Even part: reverse the even part of the forward DCT. */
  174798. /* The rotator is sqrt(2)*c(-6). */
  174799. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174800. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174801. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174802. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174803. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174804. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174805. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174806. tmp0 = (z2 + z3) << CONST_BITS;
  174807. tmp1 = (z2 - z3) << CONST_BITS;
  174808. tmp10 = tmp0 + tmp3;
  174809. tmp13 = tmp0 - tmp3;
  174810. tmp11 = tmp1 + tmp2;
  174811. tmp12 = tmp1 - tmp2;
  174812. /* Odd part per figure 8; the matrix is unitary and hence its
  174813. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174814. */
  174815. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174816. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174817. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174818. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174819. z1 = tmp0 + tmp3;
  174820. z2 = tmp1 + tmp2;
  174821. z3 = tmp0 + tmp2;
  174822. z4 = tmp1 + tmp3;
  174823. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174824. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174825. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174826. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174827. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174828. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174829. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174830. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174831. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174832. z3 += z5;
  174833. z4 += z5;
  174834. tmp0 += z1 + z3;
  174835. tmp1 += z2 + z4;
  174836. tmp2 += z2 + z3;
  174837. tmp3 += z1 + z4;
  174838. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174839. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174840. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174841. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174842. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174843. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174844. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174845. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174846. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174847. inptr++; /* advance pointers to next column */
  174848. quantptr++;
  174849. wsptr++;
  174850. }
  174851. /* Pass 2: process rows from work array, store into output array. */
  174852. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174853. /* and also undo the PASS1_BITS scaling. */
  174854. wsptr = workspace;
  174855. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174856. outptr = output_buf[ctr] + output_col;
  174857. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174858. * However, the column calculation has created many nonzero AC terms, so
  174859. * the simplification applies less often (typically 5% to 10% of the time).
  174860. * On machines with very fast multiplication, it's possible that the
  174861. * test takes more time than it's worth. In that case this section
  174862. * may be commented out.
  174863. */
  174864. #ifndef NO_ZERO_ROW_TEST
  174865. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174866. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174867. /* AC terms all zero */
  174868. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174869. & RANGE_MASK];
  174870. outptr[0] = dcval;
  174871. outptr[1] = dcval;
  174872. outptr[2] = dcval;
  174873. outptr[3] = dcval;
  174874. outptr[4] = dcval;
  174875. outptr[5] = dcval;
  174876. outptr[6] = dcval;
  174877. outptr[7] = dcval;
  174878. wsptr += DCTSIZE; /* advance pointer to next row */
  174879. continue;
  174880. }
  174881. #endif
  174882. /* Even part: reverse the even part of the forward DCT. */
  174883. /* The rotator is sqrt(2)*c(-6). */
  174884. z2 = (INT32) wsptr[2];
  174885. z3 = (INT32) wsptr[6];
  174886. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174887. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174888. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174889. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174890. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174891. tmp10 = tmp0 + tmp3;
  174892. tmp13 = tmp0 - tmp3;
  174893. tmp11 = tmp1 + tmp2;
  174894. tmp12 = tmp1 - tmp2;
  174895. /* Odd part per figure 8; the matrix is unitary and hence its
  174896. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174897. */
  174898. tmp0 = (INT32) wsptr[7];
  174899. tmp1 = (INT32) wsptr[5];
  174900. tmp2 = (INT32) wsptr[3];
  174901. tmp3 = (INT32) wsptr[1];
  174902. z1 = tmp0 + tmp3;
  174903. z2 = tmp1 + tmp2;
  174904. z3 = tmp0 + tmp2;
  174905. z4 = tmp1 + tmp3;
  174906. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174907. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174908. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174909. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174910. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174911. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174912. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174913. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174914. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174915. z3 += z5;
  174916. z4 += z5;
  174917. tmp0 += z1 + z3;
  174918. tmp1 += z2 + z4;
  174919. tmp2 += z2 + z3;
  174920. tmp3 += z1 + z4;
  174921. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174922. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174923. CONST_BITS+PASS1_BITS+3)
  174924. & RANGE_MASK];
  174925. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174926. CONST_BITS+PASS1_BITS+3)
  174927. & RANGE_MASK];
  174928. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174929. CONST_BITS+PASS1_BITS+3)
  174930. & RANGE_MASK];
  174931. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174932. CONST_BITS+PASS1_BITS+3)
  174933. & RANGE_MASK];
  174934. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174935. CONST_BITS+PASS1_BITS+3)
  174936. & RANGE_MASK];
  174937. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174938. CONST_BITS+PASS1_BITS+3)
  174939. & RANGE_MASK];
  174940. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174941. CONST_BITS+PASS1_BITS+3)
  174942. & RANGE_MASK];
  174943. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174944. CONST_BITS+PASS1_BITS+3)
  174945. & RANGE_MASK];
  174946. wsptr += DCTSIZE; /* advance pointer to next row */
  174947. }
  174948. }
  174949. #endif /* DCT_ISLOW_SUPPORTED */
  174950. /*** End of inlined file: jidctint.c ***/
  174951. /*** Start of inlined file: jidctred.c ***/
  174952. #define JPEG_INTERNALS
  174953. #ifdef IDCT_SCALING_SUPPORTED
  174954. /*
  174955. * This module is specialized to the case DCTSIZE = 8.
  174956. */
  174957. #if DCTSIZE != 8
  174958. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174959. #endif
  174960. /* Scaling is the same as in jidctint.c. */
  174961. #if BITS_IN_JSAMPLE == 8
  174962. #define CONST_BITS 13
  174963. #define PASS1_BITS 2
  174964. #else
  174965. #define CONST_BITS 13
  174966. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174967. #endif
  174968. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174969. * causing a lot of useless floating-point operations at run time.
  174970. * To get around this we use the following pre-calculated constants.
  174971. * If you change CONST_BITS you may want to add appropriate values.
  174972. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174973. */
  174974. #if CONST_BITS == 13
  174975. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174976. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174977. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174978. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174979. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174980. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174981. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174982. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174983. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174984. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174985. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174986. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174987. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174988. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174989. #else
  174990. #define FIX_0_211164243 FIX(0.211164243)
  174991. #define FIX_0_509795579 FIX(0.509795579)
  174992. #define FIX_0_601344887 FIX(0.601344887)
  174993. #define FIX_0_720959822 FIX(0.720959822)
  174994. #define FIX_0_765366865 FIX(0.765366865)
  174995. #define FIX_0_850430095 FIX(0.850430095)
  174996. #define FIX_0_899976223 FIX(0.899976223)
  174997. #define FIX_1_061594337 FIX(1.061594337)
  174998. #define FIX_1_272758580 FIX(1.272758580)
  174999. #define FIX_1_451774981 FIX(1.451774981)
  175000. #define FIX_1_847759065 FIX(1.847759065)
  175001. #define FIX_2_172734803 FIX(2.172734803)
  175002. #define FIX_2_562915447 FIX(2.562915447)
  175003. #define FIX_3_624509785 FIX(3.624509785)
  175004. #endif
  175005. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175006. * For 8-bit samples with the recommended scaling, all the variable
  175007. * and constant values involved are no more than 16 bits wide, so a
  175008. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175009. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175010. */
  175011. #if BITS_IN_JSAMPLE == 8
  175012. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175013. #else
  175014. #define MULTIPLY(var,const) ((var) * (const))
  175015. #endif
  175016. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175017. * entry; produce an int result. In this module, both inputs and result
  175018. * are 16 bits or less, so either int or short multiply will work.
  175019. */
  175020. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175021. /*
  175022. * Perform dequantization and inverse DCT on one block of coefficients,
  175023. * producing a reduced-size 4x4 output block.
  175024. */
  175025. GLOBAL(void)
  175026. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175027. JCOEFPTR coef_block,
  175028. JSAMPARRAY output_buf, JDIMENSION output_col)
  175029. {
  175030. INT32 tmp0, tmp2, tmp10, tmp12;
  175031. INT32 z1, z2, z3, z4;
  175032. JCOEFPTR inptr;
  175033. ISLOW_MULT_TYPE * quantptr;
  175034. int * wsptr;
  175035. JSAMPROW outptr;
  175036. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175037. int ctr;
  175038. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175039. SHIFT_TEMPS
  175040. /* Pass 1: process columns from input, store into work array. */
  175041. inptr = coef_block;
  175042. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175043. wsptr = workspace;
  175044. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175045. /* Don't bother to process column 4, because second pass won't use it */
  175046. if (ctr == DCTSIZE-4)
  175047. continue;
  175048. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175049. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175050. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175051. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175052. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175053. wsptr[DCTSIZE*0] = dcval;
  175054. wsptr[DCTSIZE*1] = dcval;
  175055. wsptr[DCTSIZE*2] = dcval;
  175056. wsptr[DCTSIZE*3] = dcval;
  175057. continue;
  175058. }
  175059. /* Even part */
  175060. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175061. tmp0 <<= (CONST_BITS+1);
  175062. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175063. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175064. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175065. tmp10 = tmp0 + tmp2;
  175066. tmp12 = tmp0 - tmp2;
  175067. /* Odd part */
  175068. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175069. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175070. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175071. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175072. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175073. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175074. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175075. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175076. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175077. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175078. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175079. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175080. /* Final output stage */
  175081. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175082. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175083. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175084. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175085. }
  175086. /* Pass 2: process 4 rows from work array, store into output array. */
  175087. wsptr = workspace;
  175088. for (ctr = 0; ctr < 4; ctr++) {
  175089. outptr = output_buf[ctr] + output_col;
  175090. /* It's not clear whether a zero row test is worthwhile here ... */
  175091. #ifndef NO_ZERO_ROW_TEST
  175092. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175093. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175094. /* AC terms all zero */
  175095. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175096. & RANGE_MASK];
  175097. outptr[0] = dcval;
  175098. outptr[1] = dcval;
  175099. outptr[2] = dcval;
  175100. outptr[3] = dcval;
  175101. wsptr += DCTSIZE; /* advance pointer to next row */
  175102. continue;
  175103. }
  175104. #endif
  175105. /* Even part */
  175106. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175107. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175108. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175109. tmp10 = tmp0 + tmp2;
  175110. tmp12 = tmp0 - tmp2;
  175111. /* Odd part */
  175112. z1 = (INT32) wsptr[7];
  175113. z2 = (INT32) wsptr[5];
  175114. z3 = (INT32) wsptr[3];
  175115. z4 = (INT32) wsptr[1];
  175116. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175117. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175118. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175119. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175120. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175121. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175122. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175123. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175124. /* Final output stage */
  175125. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175126. CONST_BITS+PASS1_BITS+3+1)
  175127. & RANGE_MASK];
  175128. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175129. CONST_BITS+PASS1_BITS+3+1)
  175130. & RANGE_MASK];
  175131. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175132. CONST_BITS+PASS1_BITS+3+1)
  175133. & RANGE_MASK];
  175134. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175135. CONST_BITS+PASS1_BITS+3+1)
  175136. & RANGE_MASK];
  175137. wsptr += DCTSIZE; /* advance pointer to next row */
  175138. }
  175139. }
  175140. /*
  175141. * Perform dequantization and inverse DCT on one block of coefficients,
  175142. * producing a reduced-size 2x2 output block.
  175143. */
  175144. GLOBAL(void)
  175145. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175146. JCOEFPTR coef_block,
  175147. JSAMPARRAY output_buf, JDIMENSION output_col)
  175148. {
  175149. INT32 tmp0, tmp10, z1;
  175150. JCOEFPTR inptr;
  175151. ISLOW_MULT_TYPE * quantptr;
  175152. int * wsptr;
  175153. JSAMPROW outptr;
  175154. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175155. int ctr;
  175156. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175157. SHIFT_TEMPS
  175158. /* Pass 1: process columns from input, store into work array. */
  175159. inptr = coef_block;
  175160. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175161. wsptr = workspace;
  175162. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175163. /* Don't bother to process columns 2,4,6 */
  175164. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175165. continue;
  175166. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175167. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175168. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175169. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175170. wsptr[DCTSIZE*0] = dcval;
  175171. wsptr[DCTSIZE*1] = dcval;
  175172. continue;
  175173. }
  175174. /* Even part */
  175175. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175176. tmp10 = z1 << (CONST_BITS+2);
  175177. /* Odd part */
  175178. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175179. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175180. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175181. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175182. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175183. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175184. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175185. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175186. /* Final output stage */
  175187. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175188. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175189. }
  175190. /* Pass 2: process 2 rows from work array, store into output array. */
  175191. wsptr = workspace;
  175192. for (ctr = 0; ctr < 2; ctr++) {
  175193. outptr = output_buf[ctr] + output_col;
  175194. /* It's not clear whether a zero row test is worthwhile here ... */
  175195. #ifndef NO_ZERO_ROW_TEST
  175196. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175197. /* AC terms all zero */
  175198. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175199. & RANGE_MASK];
  175200. outptr[0] = dcval;
  175201. outptr[1] = dcval;
  175202. wsptr += DCTSIZE; /* advance pointer to next row */
  175203. continue;
  175204. }
  175205. #endif
  175206. /* Even part */
  175207. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175208. /* Odd part */
  175209. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175210. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175211. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175212. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175213. /* Final output stage */
  175214. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175215. CONST_BITS+PASS1_BITS+3+2)
  175216. & RANGE_MASK];
  175217. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175218. CONST_BITS+PASS1_BITS+3+2)
  175219. & RANGE_MASK];
  175220. wsptr += DCTSIZE; /* advance pointer to next row */
  175221. }
  175222. }
  175223. /*
  175224. * Perform dequantization and inverse DCT on one block of coefficients,
  175225. * producing a reduced-size 1x1 output block.
  175226. */
  175227. GLOBAL(void)
  175228. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175229. JCOEFPTR coef_block,
  175230. JSAMPARRAY output_buf, JDIMENSION output_col)
  175231. {
  175232. int dcval;
  175233. ISLOW_MULT_TYPE * quantptr;
  175234. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175235. SHIFT_TEMPS
  175236. /* We hardly need an inverse DCT routine for this: just take the
  175237. * average pixel value, which is one-eighth of the DC coefficient.
  175238. */
  175239. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175240. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175241. dcval = (int) DESCALE((INT32) dcval, 3);
  175242. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175243. }
  175244. #endif /* IDCT_SCALING_SUPPORTED */
  175245. /*** End of inlined file: jidctred.c ***/
  175246. /*** Start of inlined file: jmemmgr.c ***/
  175247. #define JPEG_INTERNALS
  175248. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175249. /*** Start of inlined file: jmemsys.h ***/
  175250. #ifndef __jmemsys_h__
  175251. #define __jmemsys_h__
  175252. /* Short forms of external names for systems with brain-damaged linkers. */
  175253. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175254. #define jpeg_get_small jGetSmall
  175255. #define jpeg_free_small jFreeSmall
  175256. #define jpeg_get_large jGetLarge
  175257. #define jpeg_free_large jFreeLarge
  175258. #define jpeg_mem_available jMemAvail
  175259. #define jpeg_open_backing_store jOpenBackStore
  175260. #define jpeg_mem_init jMemInit
  175261. #define jpeg_mem_term jMemTerm
  175262. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175263. /*
  175264. * These two functions are used to allocate and release small chunks of
  175265. * memory. (Typically the total amount requested through jpeg_get_small is
  175266. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175267. * Behavior should be the same as for the standard library functions malloc
  175268. * and free; in particular, jpeg_get_small must return NULL on failure.
  175269. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175270. * size of the object being freed, just in case it's needed.
  175271. * On an 80x86 machine using small-data memory model, these manage near heap.
  175272. */
  175273. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175274. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175275. size_t sizeofobject));
  175276. /*
  175277. * These two functions are used to allocate and release large chunks of
  175278. * memory (up to the total free space designated by jpeg_mem_available).
  175279. * The interface is the same as above, except that on an 80x86 machine,
  175280. * far pointers are used. On most other machines these are identical to
  175281. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175282. * in case a different allocation strategy is desirable for large chunks.
  175283. */
  175284. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175285. size_t sizeofobject));
  175286. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175287. size_t sizeofobject));
  175288. /*
  175289. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175290. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175291. * matter, but that case should never come into play). This macro is needed
  175292. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175293. * On those machines, we expect that jconfig.h will provide a proper value.
  175294. * On machines with 32-bit flat address spaces, any large constant may be used.
  175295. *
  175296. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175297. * size_t and will be a multiple of sizeof(align_type).
  175298. */
  175299. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175300. #define MAX_ALLOC_CHUNK 1000000000L
  175301. #endif
  175302. /*
  175303. * This routine computes the total space still available for allocation by
  175304. * jpeg_get_large. If more space than this is needed, backing store will be
  175305. * used. NOTE: any memory already allocated must not be counted.
  175306. *
  175307. * There is a minimum space requirement, corresponding to the minimum
  175308. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175309. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175310. * all working storage in memory, is also passed in case it is useful.
  175311. * Finally, the total space already allocated is passed. If no better
  175312. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175313. * is often a suitable calculation.
  175314. *
  175315. * It is OK for jpeg_mem_available to underestimate the space available
  175316. * (that'll just lead to more backing-store access than is really necessary).
  175317. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175318. * a slop factor from the true available space. 5% should be enough.
  175319. *
  175320. * On machines with lots of virtual memory, any large constant may be returned.
  175321. * Conversely, zero may be returned to always use the minimum amount of memory.
  175322. */
  175323. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175324. long min_bytes_needed,
  175325. long max_bytes_needed,
  175326. long already_allocated));
  175327. /*
  175328. * This structure holds whatever state is needed to access a single
  175329. * backing-store object. The read/write/close method pointers are called
  175330. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175331. * are private to the system-dependent backing store routines.
  175332. */
  175333. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175334. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175335. typedef unsigned short XMSH; /* type of extended-memory handles */
  175336. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175337. typedef union {
  175338. short file_handle; /* DOS file handle if it's a temp file */
  175339. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175340. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175341. } handle_union;
  175342. #endif /* USE_MSDOS_MEMMGR */
  175343. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175344. #include <Files.h>
  175345. #endif /* USE_MAC_MEMMGR */
  175346. //typedef struct backing_store_struct * backing_store_ptr;
  175347. typedef struct backing_store_struct {
  175348. /* Methods for reading/writing/closing this backing-store object */
  175349. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175350. struct backing_store_struct *info,
  175351. void FAR * buffer_address,
  175352. long file_offset, long byte_count));
  175353. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175354. struct backing_store_struct *info,
  175355. void FAR * buffer_address,
  175356. long file_offset, long byte_count));
  175357. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175358. struct backing_store_struct *info));
  175359. /* Private fields for system-dependent backing-store management */
  175360. #ifdef USE_MSDOS_MEMMGR
  175361. /* For the MS-DOS manager (jmemdos.c), we need: */
  175362. handle_union handle; /* reference to backing-store storage object */
  175363. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175364. #else
  175365. #ifdef USE_MAC_MEMMGR
  175366. /* For the Mac manager (jmemmac.c), we need: */
  175367. short temp_file; /* file reference number to temp file */
  175368. FSSpec tempSpec; /* the FSSpec for the temp file */
  175369. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175370. #else
  175371. /* For a typical implementation with temp files, we need: */
  175372. FILE * temp_file; /* stdio reference to temp file */
  175373. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175374. #endif
  175375. #endif
  175376. } backing_store_info;
  175377. /*
  175378. * Initial opening of a backing-store object. This must fill in the
  175379. * read/write/close pointers in the object. The read/write routines
  175380. * may take an error exit if the specified maximum file size is exceeded.
  175381. * (If jpeg_mem_available always returns a large value, this routine can
  175382. * just take an error exit.)
  175383. */
  175384. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175385. struct backing_store_struct *info,
  175386. long total_bytes_needed));
  175387. /*
  175388. * These routines take care of any system-dependent initialization and
  175389. * cleanup required. jpeg_mem_init will be called before anything is
  175390. * allocated (and, therefore, nothing in cinfo is of use except the error
  175391. * manager pointer). It should return a suitable default value for
  175392. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175393. * application. (Note that max_memory_to_use is only important if
  175394. * jpeg_mem_available chooses to consult it ... no one else will.)
  175395. * jpeg_mem_term may assume that all requested memory has been freed and that
  175396. * all opened backing-store objects have been closed.
  175397. */
  175398. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175399. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175400. #endif
  175401. /*** End of inlined file: jmemsys.h ***/
  175402. /* import the system-dependent declarations */
  175403. #ifndef NO_GETENV
  175404. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175405. extern char * getenv JPP((const char * name));
  175406. #endif
  175407. #endif
  175408. /*
  175409. * Some important notes:
  175410. * The allocation routines provided here must never return NULL.
  175411. * They should exit to error_exit if unsuccessful.
  175412. *
  175413. * It's not a good idea to try to merge the sarray and barray routines,
  175414. * even though they are textually almost the same, because samples are
  175415. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175416. * in machines where byte pointers have a different representation from
  175417. * word pointers, the resulting machine code could not be the same.
  175418. */
  175419. /*
  175420. * Many machines require storage alignment: longs must start on 4-byte
  175421. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175422. * always returns pointers that are multiples of the worst-case alignment
  175423. * requirement, and we had better do so too.
  175424. * There isn't any really portable way to determine the worst-case alignment
  175425. * requirement. This module assumes that the alignment requirement is
  175426. * multiples of sizeof(ALIGN_TYPE).
  175427. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175428. * workstations (where doubles really do need 8-byte alignment) and will work
  175429. * fine on nearly everything. If your machine has lesser alignment needs,
  175430. * you can save a few bytes by making ALIGN_TYPE smaller.
  175431. * The only place I know of where this will NOT work is certain Macintosh
  175432. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175433. * Doing 10-byte alignment is counterproductive because longwords won't be
  175434. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175435. * such a compiler.
  175436. */
  175437. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175438. #define ALIGN_TYPE double
  175439. #endif
  175440. /*
  175441. * We allocate objects from "pools", where each pool is gotten with a single
  175442. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175443. * overhead within a pool, except for alignment padding. Each pool has a
  175444. * header with a link to the next pool of the same class.
  175445. * Small and large pool headers are identical except that the latter's
  175446. * link pointer must be FAR on 80x86 machines.
  175447. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175448. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175449. * of the alignment requirement of ALIGN_TYPE.
  175450. */
  175451. typedef union small_pool_struct * small_pool_ptr;
  175452. typedef union small_pool_struct {
  175453. struct {
  175454. small_pool_ptr next; /* next in list of pools */
  175455. size_t bytes_used; /* how many bytes already used within pool */
  175456. size_t bytes_left; /* bytes still available in this pool */
  175457. } hdr;
  175458. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175459. } small_pool_hdr;
  175460. typedef union large_pool_struct FAR * large_pool_ptr;
  175461. typedef union large_pool_struct {
  175462. struct {
  175463. large_pool_ptr next; /* next in list of pools */
  175464. size_t bytes_used; /* how many bytes already used within pool */
  175465. size_t bytes_left; /* bytes still available in this pool */
  175466. } hdr;
  175467. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175468. } large_pool_hdr;
  175469. /*
  175470. * Here is the full definition of a memory manager object.
  175471. */
  175472. typedef struct {
  175473. struct jpeg_memory_mgr pub; /* public fields */
  175474. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175475. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175476. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175477. /* Since we only have one lifetime class of virtual arrays, only one
  175478. * linked list is necessary (for each datatype). Note that the virtual
  175479. * array control blocks being linked together are actually stored somewhere
  175480. * in the small-pool list.
  175481. */
  175482. jvirt_sarray_ptr virt_sarray_list;
  175483. jvirt_barray_ptr virt_barray_list;
  175484. /* This counts total space obtained from jpeg_get_small/large */
  175485. long total_space_allocated;
  175486. /* alloc_sarray and alloc_barray set this value for use by virtual
  175487. * array routines.
  175488. */
  175489. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175490. } my_memory_mgr;
  175491. typedef my_memory_mgr * my_mem_ptr;
  175492. /*
  175493. * The control blocks for virtual arrays.
  175494. * Note that these blocks are allocated in the "small" pool area.
  175495. * System-dependent info for the associated backing store (if any) is hidden
  175496. * inside the backing_store_info struct.
  175497. */
  175498. struct jvirt_sarray_control {
  175499. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175500. JDIMENSION rows_in_array; /* total virtual array height */
  175501. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175502. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175503. JDIMENSION rows_in_mem; /* height of memory buffer */
  175504. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175505. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175506. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175507. boolean pre_zero; /* pre-zero mode requested? */
  175508. boolean dirty; /* do current buffer contents need written? */
  175509. boolean b_s_open; /* is backing-store data valid? */
  175510. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175511. backing_store_info b_s_info; /* System-dependent control info */
  175512. };
  175513. struct jvirt_barray_control {
  175514. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175515. JDIMENSION rows_in_array; /* total virtual array height */
  175516. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175517. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175518. JDIMENSION rows_in_mem; /* height of memory buffer */
  175519. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175520. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175521. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175522. boolean pre_zero; /* pre-zero mode requested? */
  175523. boolean dirty; /* do current buffer contents need written? */
  175524. boolean b_s_open; /* is backing-store data valid? */
  175525. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175526. backing_store_info b_s_info; /* System-dependent control info */
  175527. };
  175528. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175529. LOCAL(void)
  175530. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175531. {
  175532. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175533. small_pool_ptr shdr_ptr;
  175534. large_pool_ptr lhdr_ptr;
  175535. /* Since this is only a debugging stub, we can cheat a little by using
  175536. * fprintf directly rather than going through the trace message code.
  175537. * This is helpful because message parm array can't handle longs.
  175538. */
  175539. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175540. pool_id, mem->total_space_allocated);
  175541. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175542. lhdr_ptr = lhdr_ptr->hdr.next) {
  175543. fprintf(stderr, " Large chunk used %ld\n",
  175544. (long) lhdr_ptr->hdr.bytes_used);
  175545. }
  175546. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175547. shdr_ptr = shdr_ptr->hdr.next) {
  175548. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175549. (long) shdr_ptr->hdr.bytes_used,
  175550. (long) shdr_ptr->hdr.bytes_left);
  175551. }
  175552. }
  175553. #endif /* MEM_STATS */
  175554. LOCAL(void)
  175555. out_of_memory (j_common_ptr cinfo, int which)
  175556. /* Report an out-of-memory error and stop execution */
  175557. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175558. {
  175559. #ifdef MEM_STATS
  175560. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175561. #endif
  175562. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175563. }
  175564. /*
  175565. * Allocation of "small" objects.
  175566. *
  175567. * For these, we use pooled storage. When a new pool must be created,
  175568. * we try to get enough space for the current request plus a "slop" factor,
  175569. * where the slop will be the amount of leftover space in the new pool.
  175570. * The speed vs. space tradeoff is largely determined by the slop values.
  175571. * A different slop value is provided for each pool class (lifetime),
  175572. * and we also distinguish the first pool of a class from later ones.
  175573. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175574. * machines, but may be too small if longs are 64 bits or more.
  175575. */
  175576. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175577. {
  175578. 1600, /* first PERMANENT pool */
  175579. 16000 /* first IMAGE pool */
  175580. };
  175581. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175582. {
  175583. 0, /* additional PERMANENT pools */
  175584. 5000 /* additional IMAGE pools */
  175585. };
  175586. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175587. METHODDEF(void *)
  175588. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175589. /* Allocate a "small" object */
  175590. {
  175591. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175592. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175593. char * data_ptr;
  175594. size_t odd_bytes, min_request, slop;
  175595. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175596. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175597. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175598. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175599. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175600. if (odd_bytes > 0)
  175601. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175602. /* See if space is available in any existing pool */
  175603. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175604. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175605. prev_hdr_ptr = NULL;
  175606. hdr_ptr = mem->small_list[pool_id];
  175607. while (hdr_ptr != NULL) {
  175608. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175609. break; /* found pool with enough space */
  175610. prev_hdr_ptr = hdr_ptr;
  175611. hdr_ptr = hdr_ptr->hdr.next;
  175612. }
  175613. /* Time to make a new pool? */
  175614. if (hdr_ptr == NULL) {
  175615. /* min_request is what we need now, slop is what will be leftover */
  175616. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175617. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175618. slop = first_pool_slop[pool_id];
  175619. else
  175620. slop = extra_pool_slop[pool_id];
  175621. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175622. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175623. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175624. /* Try to get space, if fail reduce slop and try again */
  175625. for (;;) {
  175626. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175627. if (hdr_ptr != NULL)
  175628. break;
  175629. slop /= 2;
  175630. if (slop < MIN_SLOP) /* give up when it gets real small */
  175631. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175632. }
  175633. mem->total_space_allocated += min_request + slop;
  175634. /* Success, initialize the new pool header and add to end of list */
  175635. hdr_ptr->hdr.next = NULL;
  175636. hdr_ptr->hdr.bytes_used = 0;
  175637. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175638. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175639. mem->small_list[pool_id] = hdr_ptr;
  175640. else
  175641. prev_hdr_ptr->hdr.next = hdr_ptr;
  175642. }
  175643. /* OK, allocate the object from the current pool */
  175644. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175645. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175646. hdr_ptr->hdr.bytes_used += sizeofobject;
  175647. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175648. return (void *) data_ptr;
  175649. }
  175650. /*
  175651. * Allocation of "large" objects.
  175652. *
  175653. * The external semantics of these are the same as "small" objects,
  175654. * except that FAR pointers are used on 80x86. However the pool
  175655. * management heuristics are quite different. We assume that each
  175656. * request is large enough that it may as well be passed directly to
  175657. * jpeg_get_large; the pool management just links everything together
  175658. * so that we can free it all on demand.
  175659. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175660. * structures. The routines that create these structures (see below)
  175661. * deliberately bunch rows together to ensure a large request size.
  175662. */
  175663. METHODDEF(void FAR *)
  175664. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175665. /* Allocate a "large" object */
  175666. {
  175667. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175668. large_pool_ptr hdr_ptr;
  175669. size_t odd_bytes;
  175670. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175671. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175672. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175673. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175674. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175675. if (odd_bytes > 0)
  175676. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175677. /* Always make a new pool */
  175678. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175679. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175680. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175681. SIZEOF(large_pool_hdr));
  175682. if (hdr_ptr == NULL)
  175683. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175684. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175685. /* Success, initialize the new pool header and add to list */
  175686. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175687. /* We maintain space counts in each pool header for statistical purposes,
  175688. * even though they are not needed for allocation.
  175689. */
  175690. hdr_ptr->hdr.bytes_used = sizeofobject;
  175691. hdr_ptr->hdr.bytes_left = 0;
  175692. mem->large_list[pool_id] = hdr_ptr;
  175693. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175694. }
  175695. /*
  175696. * Creation of 2-D sample arrays.
  175697. * The pointers are in near heap, the samples themselves in FAR heap.
  175698. *
  175699. * To minimize allocation overhead and to allow I/O of large contiguous
  175700. * blocks, we allocate the sample rows in groups of as many rows as possible
  175701. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175702. * NB: the virtual array control routines, later in this file, know about
  175703. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175704. * object so that it can be saved away if this sarray is the workspace for
  175705. * a virtual array.
  175706. */
  175707. METHODDEF(JSAMPARRAY)
  175708. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175709. JDIMENSION samplesperrow, JDIMENSION numrows)
  175710. /* Allocate a 2-D sample array */
  175711. {
  175712. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175713. JSAMPARRAY result;
  175714. JSAMPROW workspace;
  175715. JDIMENSION rowsperchunk, currow, i;
  175716. long ltemp;
  175717. /* Calculate max # of rows allowed in one allocation chunk */
  175718. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175719. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175720. if (ltemp <= 0)
  175721. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175722. if (ltemp < (long) numrows)
  175723. rowsperchunk = (JDIMENSION) ltemp;
  175724. else
  175725. rowsperchunk = numrows;
  175726. mem->last_rowsperchunk = rowsperchunk;
  175727. /* Get space for row pointers (small object) */
  175728. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175729. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175730. /* Get the rows themselves (large objects) */
  175731. currow = 0;
  175732. while (currow < numrows) {
  175733. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175734. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175735. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175736. * SIZEOF(JSAMPLE)));
  175737. for (i = rowsperchunk; i > 0; i--) {
  175738. result[currow++] = workspace;
  175739. workspace += samplesperrow;
  175740. }
  175741. }
  175742. return result;
  175743. }
  175744. /*
  175745. * Creation of 2-D coefficient-block arrays.
  175746. * This is essentially the same as the code for sample arrays, above.
  175747. */
  175748. METHODDEF(JBLOCKARRAY)
  175749. alloc_barray (j_common_ptr cinfo, int pool_id,
  175750. JDIMENSION blocksperrow, JDIMENSION numrows)
  175751. /* Allocate a 2-D coefficient-block array */
  175752. {
  175753. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175754. JBLOCKARRAY result;
  175755. JBLOCKROW workspace;
  175756. JDIMENSION rowsperchunk, currow, i;
  175757. long ltemp;
  175758. /* Calculate max # of rows allowed in one allocation chunk */
  175759. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175760. ((long) blocksperrow * SIZEOF(JBLOCK));
  175761. if (ltemp <= 0)
  175762. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175763. if (ltemp < (long) numrows)
  175764. rowsperchunk = (JDIMENSION) ltemp;
  175765. else
  175766. rowsperchunk = numrows;
  175767. mem->last_rowsperchunk = rowsperchunk;
  175768. /* Get space for row pointers (small object) */
  175769. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175770. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175771. /* Get the rows themselves (large objects) */
  175772. currow = 0;
  175773. while (currow < numrows) {
  175774. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175775. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175776. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175777. * SIZEOF(JBLOCK)));
  175778. for (i = rowsperchunk; i > 0; i--) {
  175779. result[currow++] = workspace;
  175780. workspace += blocksperrow;
  175781. }
  175782. }
  175783. return result;
  175784. }
  175785. /*
  175786. * About virtual array management:
  175787. *
  175788. * The above "normal" array routines are only used to allocate strip buffers
  175789. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175790. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175791. * time, but the memory manager must save the whole array for repeated
  175792. * accesses. The intended implementation is that there is a strip buffer in
  175793. * memory (as high as is possible given the desired memory limit), plus a
  175794. * backing file that holds the rest of the array.
  175795. *
  175796. * The request_virt_array routines are told the total size of the image and
  175797. * the maximum number of rows that will be accessed at once. The in-memory
  175798. * buffer must be at least as large as the maxaccess value.
  175799. *
  175800. * The request routines create control blocks but not the in-memory buffers.
  175801. * That is postponed until realize_virt_arrays is called. At that time the
  175802. * total amount of space needed is known (approximately, anyway), so free
  175803. * memory can be divided up fairly.
  175804. *
  175805. * The access_virt_array routines are responsible for making a specific strip
  175806. * area accessible (after reading or writing the backing file, if necessary).
  175807. * Note that the access routines are told whether the caller intends to modify
  175808. * the accessed strip; during a read-only pass this saves having to rewrite
  175809. * data to disk. The access routines are also responsible for pre-zeroing
  175810. * any newly accessed rows, if pre-zeroing was requested.
  175811. *
  175812. * In current usage, the access requests are usually for nonoverlapping
  175813. * strips; that is, successive access start_row numbers differ by exactly
  175814. * num_rows = maxaccess. This means we can get good performance with simple
  175815. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175816. * of the access height; then there will never be accesses across bufferload
  175817. * boundaries. The code will still work with overlapping access requests,
  175818. * but it doesn't handle bufferload overlaps very efficiently.
  175819. */
  175820. METHODDEF(jvirt_sarray_ptr)
  175821. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175822. JDIMENSION samplesperrow, JDIMENSION numrows,
  175823. JDIMENSION maxaccess)
  175824. /* Request a virtual 2-D sample array */
  175825. {
  175826. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175827. jvirt_sarray_ptr result;
  175828. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175829. if (pool_id != JPOOL_IMAGE)
  175830. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175831. /* get control block */
  175832. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175833. SIZEOF(struct jvirt_sarray_control));
  175834. result->mem_buffer = NULL; /* marks array not yet realized */
  175835. result->rows_in_array = numrows;
  175836. result->samplesperrow = samplesperrow;
  175837. result->maxaccess = maxaccess;
  175838. result->pre_zero = pre_zero;
  175839. result->b_s_open = FALSE; /* no associated backing-store object */
  175840. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175841. mem->virt_sarray_list = result;
  175842. return result;
  175843. }
  175844. METHODDEF(jvirt_barray_ptr)
  175845. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175846. JDIMENSION blocksperrow, JDIMENSION numrows,
  175847. JDIMENSION maxaccess)
  175848. /* Request a virtual 2-D coefficient-block array */
  175849. {
  175850. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175851. jvirt_barray_ptr result;
  175852. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175853. if (pool_id != JPOOL_IMAGE)
  175854. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175855. /* get control block */
  175856. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175857. SIZEOF(struct jvirt_barray_control));
  175858. result->mem_buffer = NULL; /* marks array not yet realized */
  175859. result->rows_in_array = numrows;
  175860. result->blocksperrow = blocksperrow;
  175861. result->maxaccess = maxaccess;
  175862. result->pre_zero = pre_zero;
  175863. result->b_s_open = FALSE; /* no associated backing-store object */
  175864. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175865. mem->virt_barray_list = result;
  175866. return result;
  175867. }
  175868. METHODDEF(void)
  175869. realize_virt_arrays (j_common_ptr cinfo)
  175870. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175871. {
  175872. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175873. long space_per_minheight, maximum_space, avail_mem;
  175874. long minheights, max_minheights;
  175875. jvirt_sarray_ptr sptr;
  175876. jvirt_barray_ptr bptr;
  175877. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175878. * and the maximum space needed (full image height in each buffer).
  175879. * These may be of use to the system-dependent jpeg_mem_available routine.
  175880. */
  175881. space_per_minheight = 0;
  175882. maximum_space = 0;
  175883. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175884. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175885. space_per_minheight += (long) sptr->maxaccess *
  175886. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175887. maximum_space += (long) sptr->rows_in_array *
  175888. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175889. }
  175890. }
  175891. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175892. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175893. space_per_minheight += (long) bptr->maxaccess *
  175894. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175895. maximum_space += (long) bptr->rows_in_array *
  175896. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175897. }
  175898. }
  175899. if (space_per_minheight <= 0)
  175900. return; /* no unrealized arrays, no work */
  175901. /* Determine amount of memory to actually use; this is system-dependent. */
  175902. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175903. mem->total_space_allocated);
  175904. /* If the maximum space needed is available, make all the buffers full
  175905. * height; otherwise parcel it out with the same number of minheights
  175906. * in each buffer.
  175907. */
  175908. if (avail_mem >= maximum_space)
  175909. max_minheights = 1000000000L;
  175910. else {
  175911. max_minheights = avail_mem / space_per_minheight;
  175912. /* If there doesn't seem to be enough space, try to get the minimum
  175913. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175914. */
  175915. if (max_minheights <= 0)
  175916. max_minheights = 1;
  175917. }
  175918. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175919. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175920. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175921. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175922. if (minheights <= max_minheights) {
  175923. /* This buffer fits in memory */
  175924. sptr->rows_in_mem = sptr->rows_in_array;
  175925. } else {
  175926. /* It doesn't fit in memory, create backing store. */
  175927. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175928. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175929. (long) sptr->rows_in_array *
  175930. (long) sptr->samplesperrow *
  175931. (long) SIZEOF(JSAMPLE));
  175932. sptr->b_s_open = TRUE;
  175933. }
  175934. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175935. sptr->samplesperrow, sptr->rows_in_mem);
  175936. sptr->rowsperchunk = mem->last_rowsperchunk;
  175937. sptr->cur_start_row = 0;
  175938. sptr->first_undef_row = 0;
  175939. sptr->dirty = FALSE;
  175940. }
  175941. }
  175942. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175943. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175944. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175945. if (minheights <= max_minheights) {
  175946. /* This buffer fits in memory */
  175947. bptr->rows_in_mem = bptr->rows_in_array;
  175948. } else {
  175949. /* It doesn't fit in memory, create backing store. */
  175950. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175951. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175952. (long) bptr->rows_in_array *
  175953. (long) bptr->blocksperrow *
  175954. (long) SIZEOF(JBLOCK));
  175955. bptr->b_s_open = TRUE;
  175956. }
  175957. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175958. bptr->blocksperrow, bptr->rows_in_mem);
  175959. bptr->rowsperchunk = mem->last_rowsperchunk;
  175960. bptr->cur_start_row = 0;
  175961. bptr->first_undef_row = 0;
  175962. bptr->dirty = FALSE;
  175963. }
  175964. }
  175965. }
  175966. LOCAL(void)
  175967. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175968. /* Do backing store read or write of a virtual sample array */
  175969. {
  175970. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175971. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175972. file_offset = ptr->cur_start_row * bytesperrow;
  175973. /* Loop to read or write each allocation chunk in mem_buffer */
  175974. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175975. /* One chunk, but check for short chunk at end of buffer */
  175976. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175977. /* Transfer no more than is currently defined */
  175978. thisrow = (long) ptr->cur_start_row + i;
  175979. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175980. /* Transfer no more than fits in file */
  175981. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175982. if (rows <= 0) /* this chunk might be past end of file! */
  175983. break;
  175984. byte_count = rows * bytesperrow;
  175985. if (writing)
  175986. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175987. (void FAR *) ptr->mem_buffer[i],
  175988. file_offset, byte_count);
  175989. else
  175990. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175991. (void FAR *) ptr->mem_buffer[i],
  175992. file_offset, byte_count);
  175993. file_offset += byte_count;
  175994. }
  175995. }
  175996. LOCAL(void)
  175997. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175998. /* Do backing store read or write of a virtual coefficient-block array */
  175999. {
  176000. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176001. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176002. file_offset = ptr->cur_start_row * bytesperrow;
  176003. /* Loop to read or write each allocation chunk in mem_buffer */
  176004. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176005. /* One chunk, but check for short chunk at end of buffer */
  176006. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176007. /* Transfer no more than is currently defined */
  176008. thisrow = (long) ptr->cur_start_row + i;
  176009. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176010. /* Transfer no more than fits in file */
  176011. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176012. if (rows <= 0) /* this chunk might be past end of file! */
  176013. break;
  176014. byte_count = rows * bytesperrow;
  176015. if (writing)
  176016. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176017. (void FAR *) ptr->mem_buffer[i],
  176018. file_offset, byte_count);
  176019. else
  176020. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176021. (void FAR *) ptr->mem_buffer[i],
  176022. file_offset, byte_count);
  176023. file_offset += byte_count;
  176024. }
  176025. }
  176026. METHODDEF(JSAMPARRAY)
  176027. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176028. JDIMENSION start_row, JDIMENSION num_rows,
  176029. boolean writable)
  176030. /* Access the part of a virtual sample array starting at start_row */
  176031. /* and extending for num_rows rows. writable is true if */
  176032. /* caller intends to modify the accessed area. */
  176033. {
  176034. JDIMENSION end_row = start_row + num_rows;
  176035. JDIMENSION undef_row;
  176036. /* debugging check */
  176037. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176038. ptr->mem_buffer == NULL)
  176039. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176040. /* Make the desired part of the virtual array accessible */
  176041. if (start_row < ptr->cur_start_row ||
  176042. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176043. if (! ptr->b_s_open)
  176044. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176045. /* Flush old buffer contents if necessary */
  176046. if (ptr->dirty) {
  176047. do_sarray_io(cinfo, ptr, TRUE);
  176048. ptr->dirty = FALSE;
  176049. }
  176050. /* Decide what part of virtual array to access.
  176051. * Algorithm: if target address > current window, assume forward scan,
  176052. * load starting at target address. If target address < current window,
  176053. * assume backward scan, load so that target area is top of window.
  176054. * Note that when switching from forward write to forward read, will have
  176055. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176056. */
  176057. if (start_row > ptr->cur_start_row) {
  176058. ptr->cur_start_row = start_row;
  176059. } else {
  176060. /* use long arithmetic here to avoid overflow & unsigned problems */
  176061. long ltemp;
  176062. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176063. if (ltemp < 0)
  176064. ltemp = 0; /* don't fall off front end of file */
  176065. ptr->cur_start_row = (JDIMENSION) ltemp;
  176066. }
  176067. /* Read in the selected part of the array.
  176068. * During the initial write pass, we will do no actual read
  176069. * because the selected part is all undefined.
  176070. */
  176071. do_sarray_io(cinfo, ptr, FALSE);
  176072. }
  176073. /* Ensure the accessed part of the array is defined; prezero if needed.
  176074. * To improve locality of access, we only prezero the part of the array
  176075. * that the caller is about to access, not the entire in-memory array.
  176076. */
  176077. if (ptr->first_undef_row < end_row) {
  176078. if (ptr->first_undef_row < start_row) {
  176079. if (writable) /* writer skipped over a section of array */
  176080. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176081. undef_row = start_row; /* but reader is allowed to read ahead */
  176082. } else {
  176083. undef_row = ptr->first_undef_row;
  176084. }
  176085. if (writable)
  176086. ptr->first_undef_row = end_row;
  176087. if (ptr->pre_zero) {
  176088. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176089. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176090. end_row -= ptr->cur_start_row;
  176091. while (undef_row < end_row) {
  176092. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176093. undef_row++;
  176094. }
  176095. } else {
  176096. if (! writable) /* reader looking at undefined data */
  176097. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176098. }
  176099. }
  176100. /* Flag the buffer dirty if caller will write in it */
  176101. if (writable)
  176102. ptr->dirty = TRUE;
  176103. /* Return address of proper part of the buffer */
  176104. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176105. }
  176106. METHODDEF(JBLOCKARRAY)
  176107. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176108. JDIMENSION start_row, JDIMENSION num_rows,
  176109. boolean writable)
  176110. /* Access the part of a virtual block array starting at start_row */
  176111. /* and extending for num_rows rows. writable is true if */
  176112. /* caller intends to modify the accessed area. */
  176113. {
  176114. JDIMENSION end_row = start_row + num_rows;
  176115. JDIMENSION undef_row;
  176116. /* debugging check */
  176117. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176118. ptr->mem_buffer == NULL)
  176119. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176120. /* Make the desired part of the virtual array accessible */
  176121. if (start_row < ptr->cur_start_row ||
  176122. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176123. if (! ptr->b_s_open)
  176124. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176125. /* Flush old buffer contents if necessary */
  176126. if (ptr->dirty) {
  176127. do_barray_io(cinfo, ptr, TRUE);
  176128. ptr->dirty = FALSE;
  176129. }
  176130. /* Decide what part of virtual array to access.
  176131. * Algorithm: if target address > current window, assume forward scan,
  176132. * load starting at target address. If target address < current window,
  176133. * assume backward scan, load so that target area is top of window.
  176134. * Note that when switching from forward write to forward read, will have
  176135. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176136. */
  176137. if (start_row > ptr->cur_start_row) {
  176138. ptr->cur_start_row = start_row;
  176139. } else {
  176140. /* use long arithmetic here to avoid overflow & unsigned problems */
  176141. long ltemp;
  176142. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176143. if (ltemp < 0)
  176144. ltemp = 0; /* don't fall off front end of file */
  176145. ptr->cur_start_row = (JDIMENSION) ltemp;
  176146. }
  176147. /* Read in the selected part of the array.
  176148. * During the initial write pass, we will do no actual read
  176149. * because the selected part is all undefined.
  176150. */
  176151. do_barray_io(cinfo, ptr, FALSE);
  176152. }
  176153. /* Ensure the accessed part of the array is defined; prezero if needed.
  176154. * To improve locality of access, we only prezero the part of the array
  176155. * that the caller is about to access, not the entire in-memory array.
  176156. */
  176157. if (ptr->first_undef_row < end_row) {
  176158. if (ptr->first_undef_row < start_row) {
  176159. if (writable) /* writer skipped over a section of array */
  176160. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176161. undef_row = start_row; /* but reader is allowed to read ahead */
  176162. } else {
  176163. undef_row = ptr->first_undef_row;
  176164. }
  176165. if (writable)
  176166. ptr->first_undef_row = end_row;
  176167. if (ptr->pre_zero) {
  176168. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176169. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176170. end_row -= ptr->cur_start_row;
  176171. while (undef_row < end_row) {
  176172. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176173. undef_row++;
  176174. }
  176175. } else {
  176176. if (! writable) /* reader looking at undefined data */
  176177. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176178. }
  176179. }
  176180. /* Flag the buffer dirty if caller will write in it */
  176181. if (writable)
  176182. ptr->dirty = TRUE;
  176183. /* Return address of proper part of the buffer */
  176184. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176185. }
  176186. /*
  176187. * Release all objects belonging to a specified pool.
  176188. */
  176189. METHODDEF(void)
  176190. free_pool (j_common_ptr cinfo, int pool_id)
  176191. {
  176192. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176193. small_pool_ptr shdr_ptr;
  176194. large_pool_ptr lhdr_ptr;
  176195. size_t space_freed;
  176196. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176197. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176198. #ifdef MEM_STATS
  176199. if (cinfo->err->trace_level > 1)
  176200. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176201. #endif
  176202. /* If freeing IMAGE pool, close any virtual arrays first */
  176203. if (pool_id == JPOOL_IMAGE) {
  176204. jvirt_sarray_ptr sptr;
  176205. jvirt_barray_ptr bptr;
  176206. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176207. if (sptr->b_s_open) { /* there may be no backing store */
  176208. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176209. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176210. }
  176211. }
  176212. mem->virt_sarray_list = NULL;
  176213. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176214. if (bptr->b_s_open) { /* there may be no backing store */
  176215. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176216. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176217. }
  176218. }
  176219. mem->virt_barray_list = NULL;
  176220. }
  176221. /* Release large objects */
  176222. lhdr_ptr = mem->large_list[pool_id];
  176223. mem->large_list[pool_id] = NULL;
  176224. while (lhdr_ptr != NULL) {
  176225. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176226. space_freed = lhdr_ptr->hdr.bytes_used +
  176227. lhdr_ptr->hdr.bytes_left +
  176228. SIZEOF(large_pool_hdr);
  176229. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176230. mem->total_space_allocated -= space_freed;
  176231. lhdr_ptr = next_lhdr_ptr;
  176232. }
  176233. /* Release small objects */
  176234. shdr_ptr = mem->small_list[pool_id];
  176235. mem->small_list[pool_id] = NULL;
  176236. while (shdr_ptr != NULL) {
  176237. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176238. space_freed = shdr_ptr->hdr.bytes_used +
  176239. shdr_ptr->hdr.bytes_left +
  176240. SIZEOF(small_pool_hdr);
  176241. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176242. mem->total_space_allocated -= space_freed;
  176243. shdr_ptr = next_shdr_ptr;
  176244. }
  176245. }
  176246. /*
  176247. * Close up shop entirely.
  176248. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176249. */
  176250. METHODDEF(void)
  176251. self_destruct (j_common_ptr cinfo)
  176252. {
  176253. int pool;
  176254. /* Close all backing store, release all memory.
  176255. * Releasing pools in reverse order might help avoid fragmentation
  176256. * with some (brain-damaged) malloc libraries.
  176257. */
  176258. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176259. free_pool(cinfo, pool);
  176260. }
  176261. /* Release the memory manager control block too. */
  176262. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176263. cinfo->mem = NULL; /* ensures I will be called only once */
  176264. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176265. }
  176266. /*
  176267. * Memory manager initialization.
  176268. * When this is called, only the error manager pointer is valid in cinfo!
  176269. */
  176270. GLOBAL(void)
  176271. jinit_memory_mgr (j_common_ptr cinfo)
  176272. {
  176273. my_mem_ptr mem;
  176274. long max_to_use;
  176275. int pool;
  176276. size_t test_mac;
  176277. cinfo->mem = NULL; /* for safety if init fails */
  176278. /* Check for configuration errors.
  176279. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176280. * doesn't reflect any real hardware alignment requirement.
  176281. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176282. * in common if and only if X is a power of 2, ie has only one one-bit.
  176283. * Some compilers may give an "unreachable code" warning here; ignore it.
  176284. */
  176285. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176286. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176287. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176288. * a multiple of SIZEOF(ALIGN_TYPE).
  176289. * Again, an "unreachable code" warning may be ignored here.
  176290. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176291. */
  176292. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176293. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176294. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176295. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176296. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176297. /* Attempt to allocate memory manager's control block */
  176298. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176299. if (mem == NULL) {
  176300. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176301. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176302. }
  176303. /* OK, fill in the method pointers */
  176304. mem->pub.alloc_small = alloc_small;
  176305. mem->pub.alloc_large = alloc_large;
  176306. mem->pub.alloc_sarray = alloc_sarray;
  176307. mem->pub.alloc_barray = alloc_barray;
  176308. mem->pub.request_virt_sarray = request_virt_sarray;
  176309. mem->pub.request_virt_barray = request_virt_barray;
  176310. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176311. mem->pub.access_virt_sarray = access_virt_sarray;
  176312. mem->pub.access_virt_barray = access_virt_barray;
  176313. mem->pub.free_pool = free_pool;
  176314. mem->pub.self_destruct = self_destruct;
  176315. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176316. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176317. /* Initialize working state */
  176318. mem->pub.max_memory_to_use = max_to_use;
  176319. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176320. mem->small_list[pool] = NULL;
  176321. mem->large_list[pool] = NULL;
  176322. }
  176323. mem->virt_sarray_list = NULL;
  176324. mem->virt_barray_list = NULL;
  176325. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176326. /* Declare ourselves open for business */
  176327. cinfo->mem = & mem->pub;
  176328. /* Check for an environment variable JPEGMEM; if found, override the
  176329. * default max_memory setting from jpeg_mem_init. Note that the
  176330. * surrounding application may again override this value.
  176331. * If your system doesn't support getenv(), define NO_GETENV to disable
  176332. * this feature.
  176333. */
  176334. #ifndef NO_GETENV
  176335. { char * memenv;
  176336. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176337. char ch = 'x';
  176338. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176339. if (ch == 'm' || ch == 'M')
  176340. max_to_use *= 1000L;
  176341. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176342. }
  176343. }
  176344. }
  176345. #endif
  176346. }
  176347. /*** End of inlined file: jmemmgr.c ***/
  176348. /*** Start of inlined file: jmemnobs.c ***/
  176349. #define JPEG_INTERNALS
  176350. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176351. extern void * malloc JPP((size_t size));
  176352. extern void free JPP((void *ptr));
  176353. #endif
  176354. /*
  176355. * Memory allocation and freeing are controlled by the regular library
  176356. * routines malloc() and free().
  176357. */
  176358. GLOBAL(void *)
  176359. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176360. {
  176361. return (void *) malloc(sizeofobject);
  176362. }
  176363. GLOBAL(void)
  176364. jpeg_free_small (j_common_ptr , void * object, size_t)
  176365. {
  176366. free(object);
  176367. }
  176368. /*
  176369. * "Large" objects are treated the same as "small" ones.
  176370. * NB: although we include FAR keywords in the routine declarations,
  176371. * this file won't actually work in 80x86 small/medium model; at least,
  176372. * you probably won't be able to process useful-size images in only 64KB.
  176373. */
  176374. GLOBAL(void FAR *)
  176375. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176376. {
  176377. return (void FAR *) malloc(sizeofobject);
  176378. }
  176379. GLOBAL(void)
  176380. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176381. {
  176382. free(object);
  176383. }
  176384. /*
  176385. * This routine computes the total memory space available for allocation.
  176386. * Here we always say, "we got all you want bud!"
  176387. */
  176388. GLOBAL(long)
  176389. jpeg_mem_available (j_common_ptr, long,
  176390. long max_bytes_needed, long)
  176391. {
  176392. return max_bytes_needed;
  176393. }
  176394. /*
  176395. * Backing store (temporary file) management.
  176396. * Since jpeg_mem_available always promised the moon,
  176397. * this should never be called and we can just error out.
  176398. */
  176399. GLOBAL(void)
  176400. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176401. long )
  176402. {
  176403. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176404. }
  176405. /*
  176406. * These routines take care of any system-dependent initialization and
  176407. * cleanup required. Here, there isn't any.
  176408. */
  176409. GLOBAL(long)
  176410. jpeg_mem_init (j_common_ptr)
  176411. {
  176412. return 0; /* just set max_memory_to_use to 0 */
  176413. }
  176414. GLOBAL(void)
  176415. jpeg_mem_term (j_common_ptr)
  176416. {
  176417. /* no work */
  176418. }
  176419. /*** End of inlined file: jmemnobs.c ***/
  176420. /*** Start of inlined file: jquant1.c ***/
  176421. #define JPEG_INTERNALS
  176422. #ifdef QUANT_1PASS_SUPPORTED
  176423. /*
  176424. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176425. * high quality, colormapped output capability. A 2-pass quantizer usually
  176426. * gives better visual quality; however, for quantized grayscale output this
  176427. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176428. * quantizer, though you can turn it off if you really want to.
  176429. *
  176430. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176431. * image. We use a map consisting of all combinations of Ncolors[i] color
  176432. * values for the i'th component. The Ncolors[] values are chosen so that
  176433. * their product, the total number of colors, is no more than that requested.
  176434. * (In most cases, the product will be somewhat less.)
  176435. *
  176436. * Since the colormap is orthogonal, the representative value for each color
  176437. * component can be determined without considering the other components;
  176438. * then these indexes can be combined into a colormap index by a standard
  176439. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176440. * can be precalculated and stored in the lookup table colorindex[].
  176441. * colorindex[i][j] maps pixel value j in component i to the nearest
  176442. * representative value (grid plane) for that component; this index is
  176443. * multiplied by the array stride for component i, so that the
  176444. * index of the colormap entry closest to a given pixel value is just
  176445. * sum( colorindex[component-number][pixel-component-value] )
  176446. * Aside from being fast, this scheme allows for variable spacing between
  176447. * representative values with no additional lookup cost.
  176448. *
  176449. * If gamma correction has been applied in color conversion, it might be wise
  176450. * to adjust the color grid spacing so that the representative colors are
  176451. * equidistant in linear space. At this writing, gamma correction is not
  176452. * implemented by jdcolor, so nothing is done here.
  176453. */
  176454. /* Declarations for ordered dithering.
  176455. *
  176456. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176457. * dithering is described in many references, for instance Dale Schumacher's
  176458. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176459. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176460. * "dither" value to the input pixel and then round the result to the nearest
  176461. * output value. The dither value is equivalent to (0.5 - threshold) times
  176462. * the distance between output values. For ordered dithering, we assume that
  176463. * the output colors are equally spaced; if not, results will probably be
  176464. * worse, since the dither may be too much or too little at a given point.
  176465. *
  176466. * The normal calculation would be to form pixel value + dither, range-limit
  176467. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176468. * We can skip the separate range-limiting step by extending the colorindex
  176469. * table in both directions.
  176470. */
  176471. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176472. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176473. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176474. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176475. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176476. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176477. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176478. /* Bayer's order-4 dither array. Generated by the code given in
  176479. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176480. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176481. */
  176482. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176483. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176484. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176485. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176486. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176487. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176488. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176489. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176490. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176491. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176492. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176493. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176494. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176495. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176496. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176497. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176498. };
  176499. /* Declarations for Floyd-Steinberg dithering.
  176500. *
  176501. * Errors are accumulated into the array fserrors[], at a resolution of
  176502. * 1/16th of a pixel count. The error at a given pixel is propagated
  176503. * to its not-yet-processed neighbors using the standard F-S fractions,
  176504. * ... (here) 7/16
  176505. * 3/16 5/16 1/16
  176506. * We work left-to-right on even rows, right-to-left on odd rows.
  176507. *
  176508. * We can get away with a single array (holding one row's worth of errors)
  176509. * by using it to store the current row's errors at pixel columns not yet
  176510. * processed, but the next row's errors at columns already processed. We
  176511. * need only a few extra variables to hold the errors immediately around the
  176512. * current column. (If we are lucky, those variables are in registers, but
  176513. * even if not, they're probably cheaper to access than array elements are.)
  176514. *
  176515. * The fserrors[] array is indexed [component#][position].
  176516. * We provide (#columns + 2) entries per component; the extra entry at each
  176517. * end saves us from special-casing the first and last pixels.
  176518. *
  176519. * Note: on a wide image, we might not have enough room in a PC's near data
  176520. * segment to hold the error array; so it is allocated with alloc_large.
  176521. */
  176522. #if BITS_IN_JSAMPLE == 8
  176523. typedef INT16 FSERROR; /* 16 bits should be enough */
  176524. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176525. #else
  176526. typedef INT32 FSERROR; /* may need more than 16 bits */
  176527. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176528. #endif
  176529. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176530. /* Private subobject */
  176531. #define MAX_Q_COMPS 4 /* max components I can handle */
  176532. typedef struct {
  176533. struct jpeg_color_quantizer pub; /* public fields */
  176534. /* Initially allocated colormap is saved here */
  176535. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176536. int sv_actual; /* number of entries in use */
  176537. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176538. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176539. * premultiplied as described above. Since colormap indexes must fit into
  176540. * JSAMPLEs, the entries of this array will too.
  176541. */
  176542. boolean is_padded; /* is the colorindex padded for odither? */
  176543. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176544. /* Variables for ordered dithering */
  176545. int row_index; /* cur row's vertical index in dither matrix */
  176546. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176547. /* Variables for Floyd-Steinberg dithering */
  176548. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176549. boolean on_odd_row; /* flag to remember which row we are on */
  176550. } my_cquantizer;
  176551. typedef my_cquantizer * my_cquantize_ptr;
  176552. /*
  176553. * Policy-making subroutines for create_colormap and create_colorindex.
  176554. * These routines determine the colormap to be used. The rest of the module
  176555. * only assumes that the colormap is orthogonal.
  176556. *
  176557. * * select_ncolors decides how to divvy up the available colors
  176558. * among the components.
  176559. * * output_value defines the set of representative values for a component.
  176560. * * largest_input_value defines the mapping from input values to
  176561. * representative values for a component.
  176562. * Note that the latter two routines may impose different policies for
  176563. * different components, though this is not currently done.
  176564. */
  176565. LOCAL(int)
  176566. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176567. /* Determine allocation of desired colors to components, */
  176568. /* and fill in Ncolors[] array to indicate choice. */
  176569. /* Return value is total number of colors (product of Ncolors[] values). */
  176570. {
  176571. int nc = cinfo->out_color_components; /* number of color components */
  176572. int max_colors = cinfo->desired_number_of_colors;
  176573. int total_colors, iroot, i, j;
  176574. boolean changed;
  176575. long temp;
  176576. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176577. /* We can allocate at least the nc'th root of max_colors per component. */
  176578. /* Compute floor(nc'th root of max_colors). */
  176579. iroot = 1;
  176580. do {
  176581. iroot++;
  176582. temp = iroot; /* set temp = iroot ** nc */
  176583. for (i = 1; i < nc; i++)
  176584. temp *= iroot;
  176585. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176586. iroot--; /* now iroot = floor(root) */
  176587. /* Must have at least 2 color values per component */
  176588. if (iroot < 2)
  176589. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176590. /* Initialize to iroot color values for each component */
  176591. total_colors = 1;
  176592. for (i = 0; i < nc; i++) {
  176593. Ncolors[i] = iroot;
  176594. total_colors *= iroot;
  176595. }
  176596. /* We may be able to increment the count for one or more components without
  176597. * exceeding max_colors, though we know not all can be incremented.
  176598. * Sometimes, the first component can be incremented more than once!
  176599. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176600. * In RGB colorspace, try to increment G first, then R, then B.
  176601. */
  176602. do {
  176603. changed = FALSE;
  176604. for (i = 0; i < nc; i++) {
  176605. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176606. /* calculate new total_colors if Ncolors[j] is incremented */
  176607. temp = total_colors / Ncolors[j];
  176608. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176609. if (temp > (long) max_colors)
  176610. break; /* won't fit, done with this pass */
  176611. Ncolors[j]++; /* OK, apply the increment */
  176612. total_colors = (int) temp;
  176613. changed = TRUE;
  176614. }
  176615. } while (changed);
  176616. return total_colors;
  176617. }
  176618. LOCAL(int)
  176619. output_value (j_decompress_ptr, int, int j, int maxj)
  176620. /* Return j'th output value, where j will range from 0 to maxj */
  176621. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176622. {
  176623. /* We always provide values 0 and MAXJSAMPLE for each component;
  176624. * any additional values are equally spaced between these limits.
  176625. * (Forcing the upper and lower values to the limits ensures that
  176626. * dithering can't produce a color outside the selected gamut.)
  176627. */
  176628. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176629. }
  176630. LOCAL(int)
  176631. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176632. /* Return largest input value that should map to j'th output value */
  176633. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176634. {
  176635. /* Breakpoints are halfway between values returned by output_value */
  176636. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176637. }
  176638. /*
  176639. * Create the colormap.
  176640. */
  176641. LOCAL(void)
  176642. create_colormap (j_decompress_ptr cinfo)
  176643. {
  176644. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176645. JSAMPARRAY colormap; /* Created colormap */
  176646. int total_colors; /* Number of distinct output colors */
  176647. int i,j,k, nci, blksize, blkdist, ptr, val;
  176648. /* Select number of colors for each component */
  176649. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176650. /* Report selected color counts */
  176651. if (cinfo->out_color_components == 3)
  176652. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176653. total_colors, cquantize->Ncolors[0],
  176654. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176655. else
  176656. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176657. /* Allocate and fill in the colormap. */
  176658. /* The colors are ordered in the map in standard row-major order, */
  176659. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176660. colormap = (*cinfo->mem->alloc_sarray)
  176661. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176662. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176663. /* blksize is number of adjacent repeated entries for a component */
  176664. /* blkdist is distance between groups of identical entries for a component */
  176665. blkdist = total_colors;
  176666. for (i = 0; i < cinfo->out_color_components; i++) {
  176667. /* fill in colormap entries for i'th color component */
  176668. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176669. blksize = blkdist / nci;
  176670. for (j = 0; j < nci; j++) {
  176671. /* Compute j'th output value (out of nci) for component */
  176672. val = output_value(cinfo, i, j, nci-1);
  176673. /* Fill in all colormap entries that have this value of this component */
  176674. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176675. /* fill in blksize entries beginning at ptr */
  176676. for (k = 0; k < blksize; k++)
  176677. colormap[i][ptr+k] = (JSAMPLE) val;
  176678. }
  176679. }
  176680. blkdist = blksize; /* blksize of this color is blkdist of next */
  176681. }
  176682. /* Save the colormap in private storage,
  176683. * where it will survive color quantization mode changes.
  176684. */
  176685. cquantize->sv_colormap = colormap;
  176686. cquantize->sv_actual = total_colors;
  176687. }
  176688. /*
  176689. * Create the color index table.
  176690. */
  176691. LOCAL(void)
  176692. create_colorindex (j_decompress_ptr cinfo)
  176693. {
  176694. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176695. JSAMPROW indexptr;
  176696. int i,j,k, nci, blksize, val, pad;
  176697. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176698. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176699. * This is not necessary in the other dithering modes. However, we
  176700. * flag whether it was done in case user changes dithering mode.
  176701. */
  176702. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176703. pad = MAXJSAMPLE*2;
  176704. cquantize->is_padded = TRUE;
  176705. } else {
  176706. pad = 0;
  176707. cquantize->is_padded = FALSE;
  176708. }
  176709. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176710. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176711. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176712. (JDIMENSION) cinfo->out_color_components);
  176713. /* blksize is number of adjacent repeated entries for a component */
  176714. blksize = cquantize->sv_actual;
  176715. for (i = 0; i < cinfo->out_color_components; i++) {
  176716. /* fill in colorindex entries for i'th color component */
  176717. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176718. blksize = blksize / nci;
  176719. /* adjust colorindex pointers to provide padding at negative indexes. */
  176720. if (pad)
  176721. cquantize->colorindex[i] += MAXJSAMPLE;
  176722. /* in loop, val = index of current output value, */
  176723. /* and k = largest j that maps to current val */
  176724. indexptr = cquantize->colorindex[i];
  176725. val = 0;
  176726. k = largest_input_value(cinfo, i, 0, nci-1);
  176727. for (j = 0; j <= MAXJSAMPLE; j++) {
  176728. while (j > k) /* advance val if past boundary */
  176729. k = largest_input_value(cinfo, i, ++val, nci-1);
  176730. /* premultiply so that no multiplication needed in main processing */
  176731. indexptr[j] = (JSAMPLE) (val * blksize);
  176732. }
  176733. /* Pad at both ends if necessary */
  176734. if (pad)
  176735. for (j = 1; j <= MAXJSAMPLE; j++) {
  176736. indexptr[-j] = indexptr[0];
  176737. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176738. }
  176739. }
  176740. }
  176741. /*
  176742. * Create an ordered-dither array for a component having ncolors
  176743. * distinct output values.
  176744. */
  176745. LOCAL(ODITHER_MATRIX_PTR)
  176746. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176747. {
  176748. ODITHER_MATRIX_PTR odither;
  176749. int j,k;
  176750. INT32 num,den;
  176751. odither = (ODITHER_MATRIX_PTR)
  176752. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176753. SIZEOF(ODITHER_MATRIX));
  176754. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176755. * Hence the dither value for the matrix cell with fill order f
  176756. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176757. * On 16-bit-int machine, be careful to avoid overflow.
  176758. */
  176759. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176760. for (j = 0; j < ODITHER_SIZE; j++) {
  176761. for (k = 0; k < ODITHER_SIZE; k++) {
  176762. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176763. * MAXJSAMPLE;
  176764. /* Ensure round towards zero despite C's lack of consistency
  176765. * about rounding negative values in integer division...
  176766. */
  176767. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176768. }
  176769. }
  176770. return odither;
  176771. }
  176772. /*
  176773. * Create the ordered-dither tables.
  176774. * Components having the same number of representative colors may
  176775. * share a dither table.
  176776. */
  176777. LOCAL(void)
  176778. create_odither_tables (j_decompress_ptr cinfo)
  176779. {
  176780. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176781. ODITHER_MATRIX_PTR odither;
  176782. int i, j, nci;
  176783. for (i = 0; i < cinfo->out_color_components; i++) {
  176784. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176785. odither = NULL; /* search for matching prior component */
  176786. for (j = 0; j < i; j++) {
  176787. if (nci == cquantize->Ncolors[j]) {
  176788. odither = cquantize->odither[j];
  176789. break;
  176790. }
  176791. }
  176792. if (odither == NULL) /* need a new table? */
  176793. odither = make_odither_array(cinfo, nci);
  176794. cquantize->odither[i] = odither;
  176795. }
  176796. }
  176797. /*
  176798. * Map some rows of pixels to the output colormapped representation.
  176799. */
  176800. METHODDEF(void)
  176801. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176802. JSAMPARRAY output_buf, int num_rows)
  176803. /* General case, no dithering */
  176804. {
  176805. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176806. JSAMPARRAY colorindex = cquantize->colorindex;
  176807. register int pixcode, ci;
  176808. register JSAMPROW ptrin, ptrout;
  176809. int row;
  176810. JDIMENSION col;
  176811. JDIMENSION width = cinfo->output_width;
  176812. register int nc = cinfo->out_color_components;
  176813. for (row = 0; row < num_rows; row++) {
  176814. ptrin = input_buf[row];
  176815. ptrout = output_buf[row];
  176816. for (col = width; col > 0; col--) {
  176817. pixcode = 0;
  176818. for (ci = 0; ci < nc; ci++) {
  176819. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176820. }
  176821. *ptrout++ = (JSAMPLE) pixcode;
  176822. }
  176823. }
  176824. }
  176825. METHODDEF(void)
  176826. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176827. JSAMPARRAY output_buf, int num_rows)
  176828. /* Fast path for out_color_components==3, no dithering */
  176829. {
  176830. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176831. register int pixcode;
  176832. register JSAMPROW ptrin, ptrout;
  176833. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176834. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176835. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176836. int row;
  176837. JDIMENSION col;
  176838. JDIMENSION width = cinfo->output_width;
  176839. for (row = 0; row < num_rows; row++) {
  176840. ptrin = input_buf[row];
  176841. ptrout = output_buf[row];
  176842. for (col = width; col > 0; col--) {
  176843. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176844. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176845. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176846. *ptrout++ = (JSAMPLE) pixcode;
  176847. }
  176848. }
  176849. }
  176850. METHODDEF(void)
  176851. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176852. JSAMPARRAY output_buf, int num_rows)
  176853. /* General case, with ordered dithering */
  176854. {
  176855. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176856. register JSAMPROW input_ptr;
  176857. register JSAMPROW output_ptr;
  176858. JSAMPROW colorindex_ci;
  176859. int * dither; /* points to active row of dither matrix */
  176860. int row_index, col_index; /* current indexes into dither matrix */
  176861. int nc = cinfo->out_color_components;
  176862. int ci;
  176863. int row;
  176864. JDIMENSION col;
  176865. JDIMENSION width = cinfo->output_width;
  176866. for (row = 0; row < num_rows; row++) {
  176867. /* Initialize output values to 0 so can process components separately */
  176868. jzero_far((void FAR *) output_buf[row],
  176869. (size_t) (width * SIZEOF(JSAMPLE)));
  176870. row_index = cquantize->row_index;
  176871. for (ci = 0; ci < nc; ci++) {
  176872. input_ptr = input_buf[row] + ci;
  176873. output_ptr = output_buf[row];
  176874. colorindex_ci = cquantize->colorindex[ci];
  176875. dither = cquantize->odither[ci][row_index];
  176876. col_index = 0;
  176877. for (col = width; col > 0; col--) {
  176878. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176879. * select output value, accumulate into output code for this pixel.
  176880. * Range-limiting need not be done explicitly, as we have extended
  176881. * the colorindex table to produce the right answers for out-of-range
  176882. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176883. * required amount of padding.
  176884. */
  176885. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176886. input_ptr += nc;
  176887. output_ptr++;
  176888. col_index = (col_index + 1) & ODITHER_MASK;
  176889. }
  176890. }
  176891. /* Advance row index for next row */
  176892. row_index = (row_index + 1) & ODITHER_MASK;
  176893. cquantize->row_index = row_index;
  176894. }
  176895. }
  176896. METHODDEF(void)
  176897. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176898. JSAMPARRAY output_buf, int num_rows)
  176899. /* Fast path for out_color_components==3, with ordered dithering */
  176900. {
  176901. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176902. register int pixcode;
  176903. register JSAMPROW input_ptr;
  176904. register JSAMPROW output_ptr;
  176905. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176906. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176907. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176908. int * dither0; /* points to active row of dither matrix */
  176909. int * dither1;
  176910. int * dither2;
  176911. int row_index, col_index; /* current indexes into dither matrix */
  176912. int row;
  176913. JDIMENSION col;
  176914. JDIMENSION width = cinfo->output_width;
  176915. for (row = 0; row < num_rows; row++) {
  176916. row_index = cquantize->row_index;
  176917. input_ptr = input_buf[row];
  176918. output_ptr = output_buf[row];
  176919. dither0 = cquantize->odither[0][row_index];
  176920. dither1 = cquantize->odither[1][row_index];
  176921. dither2 = cquantize->odither[2][row_index];
  176922. col_index = 0;
  176923. for (col = width; col > 0; col--) {
  176924. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176925. dither0[col_index]]);
  176926. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176927. dither1[col_index]]);
  176928. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176929. dither2[col_index]]);
  176930. *output_ptr++ = (JSAMPLE) pixcode;
  176931. col_index = (col_index + 1) & ODITHER_MASK;
  176932. }
  176933. row_index = (row_index + 1) & ODITHER_MASK;
  176934. cquantize->row_index = row_index;
  176935. }
  176936. }
  176937. METHODDEF(void)
  176938. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176939. JSAMPARRAY output_buf, int num_rows)
  176940. /* General case, with Floyd-Steinberg dithering */
  176941. {
  176942. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176943. register LOCFSERROR cur; /* current error or pixel value */
  176944. LOCFSERROR belowerr; /* error for pixel below cur */
  176945. LOCFSERROR bpreverr; /* error for below/prev col */
  176946. LOCFSERROR bnexterr; /* error for below/next col */
  176947. LOCFSERROR delta;
  176948. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176949. register JSAMPROW input_ptr;
  176950. register JSAMPROW output_ptr;
  176951. JSAMPROW colorindex_ci;
  176952. JSAMPROW colormap_ci;
  176953. int pixcode;
  176954. int nc = cinfo->out_color_components;
  176955. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176956. int dirnc; /* dir * nc */
  176957. int ci;
  176958. int row;
  176959. JDIMENSION col;
  176960. JDIMENSION width = cinfo->output_width;
  176961. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176962. SHIFT_TEMPS
  176963. for (row = 0; row < num_rows; row++) {
  176964. /* Initialize output values to 0 so can process components separately */
  176965. jzero_far((void FAR *) output_buf[row],
  176966. (size_t) (width * SIZEOF(JSAMPLE)));
  176967. for (ci = 0; ci < nc; ci++) {
  176968. input_ptr = input_buf[row] + ci;
  176969. output_ptr = output_buf[row];
  176970. if (cquantize->on_odd_row) {
  176971. /* work right to left in this row */
  176972. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176973. output_ptr += width-1;
  176974. dir = -1;
  176975. dirnc = -nc;
  176976. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176977. } else {
  176978. /* work left to right in this row */
  176979. dir = 1;
  176980. dirnc = nc;
  176981. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176982. }
  176983. colorindex_ci = cquantize->colorindex[ci];
  176984. colormap_ci = cquantize->sv_colormap[ci];
  176985. /* Preset error values: no error propagated to first pixel from left */
  176986. cur = 0;
  176987. /* and no error propagated to row below yet */
  176988. belowerr = bpreverr = 0;
  176989. for (col = width; col > 0; col--) {
  176990. /* cur holds the error propagated from the previous pixel on the
  176991. * current line. Add the error propagated from the previous line
  176992. * to form the complete error correction term for this pixel, and
  176993. * round the error term (which is expressed * 16) to an integer.
  176994. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176995. * for either sign of the error value.
  176996. * Note: errorptr points to *previous* column's array entry.
  176997. */
  176998. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176999. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177000. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177001. * of the range_limit array.
  177002. */
  177003. cur += GETJSAMPLE(*input_ptr);
  177004. cur = GETJSAMPLE(range_limit[cur]);
  177005. /* Select output value, accumulate into output code for this pixel */
  177006. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177007. *output_ptr += (JSAMPLE) pixcode;
  177008. /* Compute actual representation error at this pixel */
  177009. /* Note: we can do this even though we don't have the final */
  177010. /* pixel code, because the colormap is orthogonal. */
  177011. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177012. /* Compute error fractions to be propagated to adjacent pixels.
  177013. * Add these into the running sums, and simultaneously shift the
  177014. * next-line error sums left by 1 column.
  177015. */
  177016. bnexterr = cur;
  177017. delta = cur * 2;
  177018. cur += delta; /* form error * 3 */
  177019. errorptr[0] = (FSERROR) (bpreverr + cur);
  177020. cur += delta; /* form error * 5 */
  177021. bpreverr = belowerr + cur;
  177022. belowerr = bnexterr;
  177023. cur += delta; /* form error * 7 */
  177024. /* At this point cur contains the 7/16 error value to be propagated
  177025. * to the next pixel on the current line, and all the errors for the
  177026. * next line have been shifted over. We are therefore ready to move on.
  177027. */
  177028. input_ptr += dirnc; /* advance input ptr to next column */
  177029. output_ptr += dir; /* advance output ptr to next column */
  177030. errorptr += dir; /* advance errorptr to current column */
  177031. }
  177032. /* Post-loop cleanup: we must unload the final error value into the
  177033. * final fserrors[] entry. Note we need not unload belowerr because
  177034. * it is for the dummy column before or after the actual array.
  177035. */
  177036. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177037. }
  177038. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177039. }
  177040. }
  177041. /*
  177042. * Allocate workspace for Floyd-Steinberg errors.
  177043. */
  177044. LOCAL(void)
  177045. alloc_fs_workspace (j_decompress_ptr cinfo)
  177046. {
  177047. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177048. size_t arraysize;
  177049. int i;
  177050. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177051. for (i = 0; i < cinfo->out_color_components; i++) {
  177052. cquantize->fserrors[i] = (FSERRPTR)
  177053. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177054. }
  177055. }
  177056. /*
  177057. * Initialize for one-pass color quantization.
  177058. */
  177059. METHODDEF(void)
  177060. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177061. {
  177062. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177063. size_t arraysize;
  177064. int i;
  177065. /* Install my colormap. */
  177066. cinfo->colormap = cquantize->sv_colormap;
  177067. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177068. /* Initialize for desired dithering mode. */
  177069. switch (cinfo->dither_mode) {
  177070. case JDITHER_NONE:
  177071. if (cinfo->out_color_components == 3)
  177072. cquantize->pub.color_quantize = color_quantize3;
  177073. else
  177074. cquantize->pub.color_quantize = color_quantize;
  177075. break;
  177076. case JDITHER_ORDERED:
  177077. if (cinfo->out_color_components == 3)
  177078. cquantize->pub.color_quantize = quantize3_ord_dither;
  177079. else
  177080. cquantize->pub.color_quantize = quantize_ord_dither;
  177081. cquantize->row_index = 0; /* initialize state for ordered dither */
  177082. /* If user changed to ordered dither from another mode,
  177083. * we must recreate the color index table with padding.
  177084. * This will cost extra space, but probably isn't very likely.
  177085. */
  177086. if (! cquantize->is_padded)
  177087. create_colorindex(cinfo);
  177088. /* Create ordered-dither tables if we didn't already. */
  177089. if (cquantize->odither[0] == NULL)
  177090. create_odither_tables(cinfo);
  177091. break;
  177092. case JDITHER_FS:
  177093. cquantize->pub.color_quantize = quantize_fs_dither;
  177094. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177095. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177096. if (cquantize->fserrors[0] == NULL)
  177097. alloc_fs_workspace(cinfo);
  177098. /* Initialize the propagated errors to zero. */
  177099. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177100. for (i = 0; i < cinfo->out_color_components; i++)
  177101. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177102. break;
  177103. default:
  177104. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177105. break;
  177106. }
  177107. }
  177108. /*
  177109. * Finish up at the end of the pass.
  177110. */
  177111. METHODDEF(void)
  177112. finish_pass_1_quant (j_decompress_ptr)
  177113. {
  177114. /* no work in 1-pass case */
  177115. }
  177116. /*
  177117. * Switch to a new external colormap between output passes.
  177118. * Shouldn't get to this module!
  177119. */
  177120. METHODDEF(void)
  177121. new_color_map_1_quant (j_decompress_ptr cinfo)
  177122. {
  177123. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177124. }
  177125. /*
  177126. * Module initialization routine for 1-pass color quantization.
  177127. */
  177128. GLOBAL(void)
  177129. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177130. {
  177131. my_cquantize_ptr cquantize;
  177132. cquantize = (my_cquantize_ptr)
  177133. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177134. SIZEOF(my_cquantizer));
  177135. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177136. cquantize->pub.start_pass = start_pass_1_quant;
  177137. cquantize->pub.finish_pass = finish_pass_1_quant;
  177138. cquantize->pub.new_color_map = new_color_map_1_quant;
  177139. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177140. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177141. /* Make sure my internal arrays won't overflow */
  177142. if (cinfo->out_color_components > MAX_Q_COMPS)
  177143. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177144. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177145. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177146. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177147. /* Create the colormap and color index table. */
  177148. create_colormap(cinfo);
  177149. create_colorindex(cinfo);
  177150. /* Allocate Floyd-Steinberg workspace now if requested.
  177151. * We do this now since it is FAR storage and may affect the memory
  177152. * manager's space calculations. If the user changes to FS dither
  177153. * mode in a later pass, we will allocate the space then, and will
  177154. * possibly overrun the max_memory_to_use setting.
  177155. */
  177156. if (cinfo->dither_mode == JDITHER_FS)
  177157. alloc_fs_workspace(cinfo);
  177158. }
  177159. #endif /* QUANT_1PASS_SUPPORTED */
  177160. /*** End of inlined file: jquant1.c ***/
  177161. /*** Start of inlined file: jquant2.c ***/
  177162. #define JPEG_INTERNALS
  177163. #ifdef QUANT_2PASS_SUPPORTED
  177164. /*
  177165. * This module implements the well-known Heckbert paradigm for color
  177166. * quantization. Most of the ideas used here can be traced back to
  177167. * Heckbert's seminal paper
  177168. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177169. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177170. *
  177171. * In the first pass over the image, we accumulate a histogram showing the
  177172. * usage count of each possible color. To keep the histogram to a reasonable
  177173. * size, we reduce the precision of the input; typical practice is to retain
  177174. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177175. * in the same histogram cell.
  177176. *
  177177. * Next, the color-selection step begins with a box representing the whole
  177178. * color space, and repeatedly splits the "largest" remaining box until we
  177179. * have as many boxes as desired colors. Then the mean color in each
  177180. * remaining box becomes one of the possible output colors.
  177181. *
  177182. * The second pass over the image maps each input pixel to the closest output
  177183. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177184. * This mapping is logically trivial, but making it go fast enough requires
  177185. * considerable care.
  177186. *
  177187. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177188. * the "largest" box and deciding where to cut it. The particular policies
  177189. * used here have proved out well in experimental comparisons, but better ones
  177190. * may yet be found.
  177191. *
  177192. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177193. * space, processing the raw upsampled data without a color conversion step.
  177194. * This allowed the color conversion math to be done only once per colormap
  177195. * entry, not once per pixel. However, that optimization precluded other
  177196. * useful optimizations (such as merging color conversion with upsampling)
  177197. * and it also interfered with desired capabilities such as quantizing to an
  177198. * externally-supplied colormap. We have therefore abandoned that approach.
  177199. * The present code works in the post-conversion color space, typically RGB.
  177200. *
  177201. * To improve the visual quality of the results, we actually work in scaled
  177202. * RGB space, giving G distances more weight than R, and R in turn more than
  177203. * B. To do everything in integer math, we must use integer scale factors.
  177204. * The 2/3/1 scale factors used here correspond loosely to the relative
  177205. * weights of the colors in the NTSC grayscale equation.
  177206. * If you want to use this code to quantize a non-RGB color space, you'll
  177207. * probably need to change these scale factors.
  177208. */
  177209. #define R_SCALE 2 /* scale R distances by this much */
  177210. #define G_SCALE 3 /* scale G distances by this much */
  177211. #define B_SCALE 1 /* and B by this much */
  177212. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177213. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177214. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177215. * you'll get compile errors until you extend this logic. In that case
  177216. * you'll probably want to tweak the histogram sizes too.
  177217. */
  177218. #if RGB_RED == 0
  177219. #define C0_SCALE R_SCALE
  177220. #endif
  177221. #if RGB_BLUE == 0
  177222. #define C0_SCALE B_SCALE
  177223. #endif
  177224. #if RGB_GREEN == 1
  177225. #define C1_SCALE G_SCALE
  177226. #endif
  177227. #if RGB_RED == 2
  177228. #define C2_SCALE R_SCALE
  177229. #endif
  177230. #if RGB_BLUE == 2
  177231. #define C2_SCALE B_SCALE
  177232. #endif
  177233. /*
  177234. * First we have the histogram data structure and routines for creating it.
  177235. *
  177236. * The number of bits of precision can be adjusted by changing these symbols.
  177237. * We recommend keeping 6 bits for G and 5 each for R and B.
  177238. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177239. * better results; if you are short of memory, 5 bits all around will save
  177240. * some space but degrade the results.
  177241. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177242. * (preferably unsigned long) for each cell. In practice this is overkill;
  177243. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177244. * and clamping those that do overflow to the maximum value will give close-
  177245. * enough results. This reduces the recommended histogram size from 256Kb
  177246. * to 128Kb, which is a useful savings on PC-class machines.
  177247. * (In the second pass the histogram space is re-used for pixel mapping data;
  177248. * in that capacity, each cell must be able to store zero to the number of
  177249. * desired colors. 16 bits/cell is plenty for that too.)
  177250. * Since the JPEG code is intended to run in small memory model on 80x86
  177251. * machines, we can't just allocate the histogram in one chunk. Instead
  177252. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177253. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177254. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177255. * on 80x86 machines, the pointer row is in near memory but the actual
  177256. * arrays are in far memory (same arrangement as we use for image arrays).
  177257. */
  177258. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177259. /* These will do the right thing for either R,G,B or B,G,R color order,
  177260. * but you may not like the results for other color orders.
  177261. */
  177262. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177263. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177264. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177265. /* Number of elements along histogram axes. */
  177266. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177267. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177268. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177269. /* These are the amounts to shift an input value to get a histogram index. */
  177270. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177271. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177272. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177273. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177274. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177275. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177276. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177277. typedef hist2d * hist3d; /* type for top-level pointer */
  177278. /* Declarations for Floyd-Steinberg dithering.
  177279. *
  177280. * Errors are accumulated into the array fserrors[], at a resolution of
  177281. * 1/16th of a pixel count. The error at a given pixel is propagated
  177282. * to its not-yet-processed neighbors using the standard F-S fractions,
  177283. * ... (here) 7/16
  177284. * 3/16 5/16 1/16
  177285. * We work left-to-right on even rows, right-to-left on odd rows.
  177286. *
  177287. * We can get away with a single array (holding one row's worth of errors)
  177288. * by using it to store the current row's errors at pixel columns not yet
  177289. * processed, but the next row's errors at columns already processed. We
  177290. * need only a few extra variables to hold the errors immediately around the
  177291. * current column. (If we are lucky, those variables are in registers, but
  177292. * even if not, they're probably cheaper to access than array elements are.)
  177293. *
  177294. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177295. * each end saves us from special-casing the first and last pixels.
  177296. * Each entry is three values long, one value for each color component.
  177297. *
  177298. * Note: on a wide image, we might not have enough room in a PC's near data
  177299. * segment to hold the error array; so it is allocated with alloc_large.
  177300. */
  177301. #if BITS_IN_JSAMPLE == 8
  177302. typedef INT16 FSERROR; /* 16 bits should be enough */
  177303. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177304. #else
  177305. typedef INT32 FSERROR; /* may need more than 16 bits */
  177306. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177307. #endif
  177308. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177309. /* Private subobject */
  177310. typedef struct {
  177311. struct jpeg_color_quantizer pub; /* public fields */
  177312. /* Space for the eventually created colormap is stashed here */
  177313. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177314. int desired; /* desired # of colors = size of colormap */
  177315. /* Variables for accumulating image statistics */
  177316. hist3d histogram; /* pointer to the histogram */
  177317. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177318. /* Variables for Floyd-Steinberg dithering */
  177319. FSERRPTR fserrors; /* accumulated errors */
  177320. boolean on_odd_row; /* flag to remember which row we are on */
  177321. int * error_limiter; /* table for clamping the applied error */
  177322. } my_cquantizer2;
  177323. typedef my_cquantizer2 * my_cquantize_ptr2;
  177324. /*
  177325. * Prescan some rows of pixels.
  177326. * In this module the prescan simply updates the histogram, which has been
  177327. * initialized to zeroes by start_pass.
  177328. * An output_buf parameter is required by the method signature, but no data
  177329. * is actually output (in fact the buffer controller is probably passing a
  177330. * NULL pointer).
  177331. */
  177332. METHODDEF(void)
  177333. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177334. JSAMPARRAY, int num_rows)
  177335. {
  177336. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177337. register JSAMPROW ptr;
  177338. register histptr histp;
  177339. register hist3d histogram = cquantize->histogram;
  177340. int row;
  177341. JDIMENSION col;
  177342. JDIMENSION width = cinfo->output_width;
  177343. for (row = 0; row < num_rows; row++) {
  177344. ptr = input_buf[row];
  177345. for (col = width; col > 0; col--) {
  177346. /* get pixel value and index into the histogram */
  177347. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177348. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177349. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177350. /* increment, check for overflow and undo increment if so. */
  177351. if (++(*histp) <= 0)
  177352. (*histp)--;
  177353. ptr += 3;
  177354. }
  177355. }
  177356. }
  177357. /*
  177358. * Next we have the really interesting routines: selection of a colormap
  177359. * given the completed histogram.
  177360. * These routines work with a list of "boxes", each representing a rectangular
  177361. * subset of the input color space (to histogram precision).
  177362. */
  177363. typedef struct {
  177364. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177365. int c0min, c0max;
  177366. int c1min, c1max;
  177367. int c2min, c2max;
  177368. /* The volume (actually 2-norm) of the box */
  177369. INT32 volume;
  177370. /* The number of nonzero histogram cells within this box */
  177371. long colorcount;
  177372. } box;
  177373. typedef box * boxptr;
  177374. LOCAL(boxptr)
  177375. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177376. /* Find the splittable box with the largest color population */
  177377. /* Returns NULL if no splittable boxes remain */
  177378. {
  177379. register boxptr boxp;
  177380. register int i;
  177381. register long maxc = 0;
  177382. boxptr which = NULL;
  177383. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177384. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177385. which = boxp;
  177386. maxc = boxp->colorcount;
  177387. }
  177388. }
  177389. return which;
  177390. }
  177391. LOCAL(boxptr)
  177392. find_biggest_volume (boxptr boxlist, int numboxes)
  177393. /* Find the splittable box with the largest (scaled) volume */
  177394. /* Returns NULL if no splittable boxes remain */
  177395. {
  177396. register boxptr boxp;
  177397. register int i;
  177398. register INT32 maxv = 0;
  177399. boxptr which = NULL;
  177400. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177401. if (boxp->volume > maxv) {
  177402. which = boxp;
  177403. maxv = boxp->volume;
  177404. }
  177405. }
  177406. return which;
  177407. }
  177408. LOCAL(void)
  177409. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177410. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177411. /* and recompute its volume and population */
  177412. {
  177413. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177414. hist3d histogram = cquantize->histogram;
  177415. histptr histp;
  177416. int c0,c1,c2;
  177417. int c0min,c0max,c1min,c1max,c2min,c2max;
  177418. INT32 dist0,dist1,dist2;
  177419. long ccount;
  177420. c0min = boxp->c0min; c0max = boxp->c0max;
  177421. c1min = boxp->c1min; c1max = boxp->c1max;
  177422. c2min = boxp->c2min; c2max = boxp->c2max;
  177423. if (c0max > c0min)
  177424. for (c0 = c0min; c0 <= c0max; c0++)
  177425. for (c1 = c1min; c1 <= c1max; c1++) {
  177426. histp = & histogram[c0][c1][c2min];
  177427. for (c2 = c2min; c2 <= c2max; c2++)
  177428. if (*histp++ != 0) {
  177429. boxp->c0min = c0min = c0;
  177430. goto have_c0min;
  177431. }
  177432. }
  177433. have_c0min:
  177434. if (c0max > c0min)
  177435. for (c0 = c0max; c0 >= c0min; c0--)
  177436. for (c1 = c1min; c1 <= c1max; c1++) {
  177437. histp = & histogram[c0][c1][c2min];
  177438. for (c2 = c2min; c2 <= c2max; c2++)
  177439. if (*histp++ != 0) {
  177440. boxp->c0max = c0max = c0;
  177441. goto have_c0max;
  177442. }
  177443. }
  177444. have_c0max:
  177445. if (c1max > c1min)
  177446. for (c1 = c1min; c1 <= c1max; c1++)
  177447. for (c0 = c0min; c0 <= c0max; c0++) {
  177448. histp = & histogram[c0][c1][c2min];
  177449. for (c2 = c2min; c2 <= c2max; c2++)
  177450. if (*histp++ != 0) {
  177451. boxp->c1min = c1min = c1;
  177452. goto have_c1min;
  177453. }
  177454. }
  177455. have_c1min:
  177456. if (c1max > c1min)
  177457. for (c1 = c1max; c1 >= c1min; c1--)
  177458. for (c0 = c0min; c0 <= c0max; c0++) {
  177459. histp = & histogram[c0][c1][c2min];
  177460. for (c2 = c2min; c2 <= c2max; c2++)
  177461. if (*histp++ != 0) {
  177462. boxp->c1max = c1max = c1;
  177463. goto have_c1max;
  177464. }
  177465. }
  177466. have_c1max:
  177467. if (c2max > c2min)
  177468. for (c2 = c2min; c2 <= c2max; c2++)
  177469. for (c0 = c0min; c0 <= c0max; c0++) {
  177470. histp = & histogram[c0][c1min][c2];
  177471. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177472. if (*histp != 0) {
  177473. boxp->c2min = c2min = c2;
  177474. goto have_c2min;
  177475. }
  177476. }
  177477. have_c2min:
  177478. if (c2max > c2min)
  177479. for (c2 = c2max; c2 >= c2min; c2--)
  177480. for (c0 = c0min; c0 <= c0max; c0++) {
  177481. histp = & histogram[c0][c1min][c2];
  177482. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177483. if (*histp != 0) {
  177484. boxp->c2max = c2max = c2;
  177485. goto have_c2max;
  177486. }
  177487. }
  177488. have_c2max:
  177489. /* Update box volume.
  177490. * We use 2-norm rather than real volume here; this biases the method
  177491. * against making long narrow boxes, and it has the side benefit that
  177492. * a box is splittable iff norm > 0.
  177493. * Since the differences are expressed in histogram-cell units,
  177494. * we have to shift back to JSAMPLE units to get consistent distances;
  177495. * after which, we scale according to the selected distance scale factors.
  177496. */
  177497. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177498. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177499. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177500. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177501. /* Now scan remaining volume of box and compute population */
  177502. ccount = 0;
  177503. for (c0 = c0min; c0 <= c0max; c0++)
  177504. for (c1 = c1min; c1 <= c1max; c1++) {
  177505. histp = & histogram[c0][c1][c2min];
  177506. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177507. if (*histp != 0) {
  177508. ccount++;
  177509. }
  177510. }
  177511. boxp->colorcount = ccount;
  177512. }
  177513. LOCAL(int)
  177514. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177515. int desired_colors)
  177516. /* Repeatedly select and split the largest box until we have enough boxes */
  177517. {
  177518. int n,lb;
  177519. int c0,c1,c2,cmax;
  177520. register boxptr b1,b2;
  177521. while (numboxes < desired_colors) {
  177522. /* Select box to split.
  177523. * Current algorithm: by population for first half, then by volume.
  177524. */
  177525. if (numboxes*2 <= desired_colors) {
  177526. b1 = find_biggest_color_pop(boxlist, numboxes);
  177527. } else {
  177528. b1 = find_biggest_volume(boxlist, numboxes);
  177529. }
  177530. if (b1 == NULL) /* no splittable boxes left! */
  177531. break;
  177532. b2 = &boxlist[numboxes]; /* where new box will go */
  177533. /* Copy the color bounds to the new box. */
  177534. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177535. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177536. /* Choose which axis to split the box on.
  177537. * Current algorithm: longest scaled axis.
  177538. * See notes in update_box about scaling distances.
  177539. */
  177540. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177541. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177542. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177543. /* We want to break any ties in favor of green, then red, blue last.
  177544. * This code does the right thing for R,G,B or B,G,R color orders only.
  177545. */
  177546. #if RGB_RED == 0
  177547. cmax = c1; n = 1;
  177548. if (c0 > cmax) { cmax = c0; n = 0; }
  177549. if (c2 > cmax) { n = 2; }
  177550. #else
  177551. cmax = c1; n = 1;
  177552. if (c2 > cmax) { cmax = c2; n = 2; }
  177553. if (c0 > cmax) { n = 0; }
  177554. #endif
  177555. /* Choose split point along selected axis, and update box bounds.
  177556. * Current algorithm: split at halfway point.
  177557. * (Since the box has been shrunk to minimum volume,
  177558. * any split will produce two nonempty subboxes.)
  177559. * Note that lb value is max for lower box, so must be < old max.
  177560. */
  177561. switch (n) {
  177562. case 0:
  177563. lb = (b1->c0max + b1->c0min) / 2;
  177564. b1->c0max = lb;
  177565. b2->c0min = lb+1;
  177566. break;
  177567. case 1:
  177568. lb = (b1->c1max + b1->c1min) / 2;
  177569. b1->c1max = lb;
  177570. b2->c1min = lb+1;
  177571. break;
  177572. case 2:
  177573. lb = (b1->c2max + b1->c2min) / 2;
  177574. b1->c2max = lb;
  177575. b2->c2min = lb+1;
  177576. break;
  177577. }
  177578. /* Update stats for boxes */
  177579. update_box(cinfo, b1);
  177580. update_box(cinfo, b2);
  177581. numboxes++;
  177582. }
  177583. return numboxes;
  177584. }
  177585. LOCAL(void)
  177586. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177587. /* Compute representative color for a box, put it in colormap[icolor] */
  177588. {
  177589. /* Current algorithm: mean weighted by pixels (not colors) */
  177590. /* Note it is important to get the rounding correct! */
  177591. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177592. hist3d histogram = cquantize->histogram;
  177593. histptr histp;
  177594. int c0,c1,c2;
  177595. int c0min,c0max,c1min,c1max,c2min,c2max;
  177596. long count;
  177597. long total = 0;
  177598. long c0total = 0;
  177599. long c1total = 0;
  177600. long c2total = 0;
  177601. c0min = boxp->c0min; c0max = boxp->c0max;
  177602. c1min = boxp->c1min; c1max = boxp->c1max;
  177603. c2min = boxp->c2min; c2max = boxp->c2max;
  177604. for (c0 = c0min; c0 <= c0max; c0++)
  177605. for (c1 = c1min; c1 <= c1max; c1++) {
  177606. histp = & histogram[c0][c1][c2min];
  177607. for (c2 = c2min; c2 <= c2max; c2++) {
  177608. if ((count = *histp++) != 0) {
  177609. total += count;
  177610. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177611. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177612. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177613. }
  177614. }
  177615. }
  177616. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177617. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177618. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177619. }
  177620. LOCAL(void)
  177621. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177622. /* Master routine for color selection */
  177623. {
  177624. boxptr boxlist;
  177625. int numboxes;
  177626. int i;
  177627. /* Allocate workspace for box list */
  177628. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177629. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177630. /* Initialize one box containing whole space */
  177631. numboxes = 1;
  177632. boxlist[0].c0min = 0;
  177633. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177634. boxlist[0].c1min = 0;
  177635. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177636. boxlist[0].c2min = 0;
  177637. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177638. /* Shrink it to actually-used volume and set its statistics */
  177639. update_box(cinfo, & boxlist[0]);
  177640. /* Perform median-cut to produce final box list */
  177641. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177642. /* Compute the representative color for each box, fill colormap */
  177643. for (i = 0; i < numboxes; i++)
  177644. compute_color(cinfo, & boxlist[i], i);
  177645. cinfo->actual_number_of_colors = numboxes;
  177646. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177647. }
  177648. /*
  177649. * These routines are concerned with the time-critical task of mapping input
  177650. * colors to the nearest color in the selected colormap.
  177651. *
  177652. * We re-use the histogram space as an "inverse color map", essentially a
  177653. * cache for the results of nearest-color searches. All colors within a
  177654. * histogram cell will be mapped to the same colormap entry, namely the one
  177655. * closest to the cell's center. This may not be quite the closest entry to
  177656. * the actual input color, but it's almost as good. A zero in the cache
  177657. * indicates we haven't found the nearest color for that cell yet; the array
  177658. * is cleared to zeroes before starting the mapping pass. When we find the
  177659. * nearest color for a cell, its colormap index plus one is recorded in the
  177660. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177661. * when they need to use an unfilled entry in the cache.
  177662. *
  177663. * Our method of efficiently finding nearest colors is based on the "locally
  177664. * sorted search" idea described by Heckbert and on the incremental distance
  177665. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177666. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177667. * the distances from a given colormap entry to each cell of the histogram can
  177668. * be computed quickly using an incremental method: the differences between
  177669. * distances to adjacent cells themselves differ by a constant. This allows a
  177670. * fairly fast implementation of the "brute force" approach of computing the
  177671. * distance from every colormap entry to every histogram cell. Unfortunately,
  177672. * it needs a work array to hold the best-distance-so-far for each histogram
  177673. * cell (because the inner loop has to be over cells, not colormap entries).
  177674. * The work array elements have to be INT32s, so the work array would need
  177675. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177676. *
  177677. * To get around these problems, we apply Thomas' method to compute the
  177678. * nearest colors for only the cells within a small subbox of the histogram.
  177679. * The work array need be only as big as the subbox, so the memory usage
  177680. * problem is solved. Furthermore, we need not fill subboxes that are never
  177681. * referenced in pass2; many images use only part of the color gamut, so a
  177682. * fair amount of work is saved. An additional advantage of this
  177683. * approach is that we can apply Heckbert's locality criterion to quickly
  177684. * eliminate colormap entries that are far away from the subbox; typically
  177685. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177686. * and we need not compute their distances to individual cells in the subbox.
  177687. * The speed of this approach is heavily influenced by the subbox size: too
  177688. * small means too much overhead, too big loses because Heckbert's criterion
  177689. * can't eliminate as many colormap entries. Empirically the best subbox
  177690. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177691. *
  177692. * Thomas' article also describes a refined method which is asymptotically
  177693. * faster than the brute-force method, but it is also far more complex and
  177694. * cannot efficiently be applied to small subboxes. It is therefore not
  177695. * useful for programs intended to be portable to DOS machines. On machines
  177696. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177697. * refined method might be faster than the present code --- but then again,
  177698. * it might not be any faster, and it's certainly more complicated.
  177699. */
  177700. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177701. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177702. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177703. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177704. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177705. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177706. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177707. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177708. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177709. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177710. /*
  177711. * The next three routines implement inverse colormap filling. They could
  177712. * all be folded into one big routine, but splitting them up this way saves
  177713. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177714. * and may allow some compilers to produce better code by registerizing more
  177715. * inner-loop variables.
  177716. */
  177717. LOCAL(int)
  177718. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177719. JSAMPLE colorlist[])
  177720. /* Locate the colormap entries close enough to an update box to be candidates
  177721. * for the nearest entry to some cell(s) in the update box. The update box
  177722. * is specified by the center coordinates of its first cell. The number of
  177723. * candidate colormap entries is returned, and their colormap indexes are
  177724. * placed in colorlist[].
  177725. * This routine uses Heckbert's "locally sorted search" criterion to select
  177726. * the colors that need further consideration.
  177727. */
  177728. {
  177729. int numcolors = cinfo->actual_number_of_colors;
  177730. int maxc0, maxc1, maxc2;
  177731. int centerc0, centerc1, centerc2;
  177732. int i, x, ncolors;
  177733. INT32 minmaxdist, min_dist, max_dist, tdist;
  177734. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177735. /* Compute true coordinates of update box's upper corner and center.
  177736. * Actually we compute the coordinates of the center of the upper-corner
  177737. * histogram cell, which are the upper bounds of the volume we care about.
  177738. * Note that since ">>" rounds down, the "center" values may be closer to
  177739. * min than to max; hence comparisons to them must be "<=", not "<".
  177740. */
  177741. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177742. centerc0 = (minc0 + maxc0) >> 1;
  177743. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177744. centerc1 = (minc1 + maxc1) >> 1;
  177745. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177746. centerc2 = (minc2 + maxc2) >> 1;
  177747. /* For each color in colormap, find:
  177748. * 1. its minimum squared-distance to any point in the update box
  177749. * (zero if color is within update box);
  177750. * 2. its maximum squared-distance to any point in the update box.
  177751. * Both of these can be found by considering only the corners of the box.
  177752. * We save the minimum distance for each color in mindist[];
  177753. * only the smallest maximum distance is of interest.
  177754. */
  177755. minmaxdist = 0x7FFFFFFFL;
  177756. for (i = 0; i < numcolors; i++) {
  177757. /* We compute the squared-c0-distance term, then add in the other two. */
  177758. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177759. if (x < minc0) {
  177760. tdist = (x - minc0) * C0_SCALE;
  177761. min_dist = tdist*tdist;
  177762. tdist = (x - maxc0) * C0_SCALE;
  177763. max_dist = tdist*tdist;
  177764. } else if (x > maxc0) {
  177765. tdist = (x - maxc0) * C0_SCALE;
  177766. min_dist = tdist*tdist;
  177767. tdist = (x - minc0) * C0_SCALE;
  177768. max_dist = tdist*tdist;
  177769. } else {
  177770. /* within cell range so no contribution to min_dist */
  177771. min_dist = 0;
  177772. if (x <= centerc0) {
  177773. tdist = (x - maxc0) * C0_SCALE;
  177774. max_dist = tdist*tdist;
  177775. } else {
  177776. tdist = (x - minc0) * C0_SCALE;
  177777. max_dist = tdist*tdist;
  177778. }
  177779. }
  177780. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177781. if (x < minc1) {
  177782. tdist = (x - minc1) * C1_SCALE;
  177783. min_dist += tdist*tdist;
  177784. tdist = (x - maxc1) * C1_SCALE;
  177785. max_dist += tdist*tdist;
  177786. } else if (x > maxc1) {
  177787. tdist = (x - maxc1) * C1_SCALE;
  177788. min_dist += tdist*tdist;
  177789. tdist = (x - minc1) * C1_SCALE;
  177790. max_dist += tdist*tdist;
  177791. } else {
  177792. /* within cell range so no contribution to min_dist */
  177793. if (x <= centerc1) {
  177794. tdist = (x - maxc1) * C1_SCALE;
  177795. max_dist += tdist*tdist;
  177796. } else {
  177797. tdist = (x - minc1) * C1_SCALE;
  177798. max_dist += tdist*tdist;
  177799. }
  177800. }
  177801. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177802. if (x < minc2) {
  177803. tdist = (x - minc2) * C2_SCALE;
  177804. min_dist += tdist*tdist;
  177805. tdist = (x - maxc2) * C2_SCALE;
  177806. max_dist += tdist*tdist;
  177807. } else if (x > maxc2) {
  177808. tdist = (x - maxc2) * C2_SCALE;
  177809. min_dist += tdist*tdist;
  177810. tdist = (x - minc2) * C2_SCALE;
  177811. max_dist += tdist*tdist;
  177812. } else {
  177813. /* within cell range so no contribution to min_dist */
  177814. if (x <= centerc2) {
  177815. tdist = (x - maxc2) * C2_SCALE;
  177816. max_dist += tdist*tdist;
  177817. } else {
  177818. tdist = (x - minc2) * C2_SCALE;
  177819. max_dist += tdist*tdist;
  177820. }
  177821. }
  177822. mindist[i] = min_dist; /* save away the results */
  177823. if (max_dist < minmaxdist)
  177824. minmaxdist = max_dist;
  177825. }
  177826. /* Now we know that no cell in the update box is more than minmaxdist
  177827. * away from some colormap entry. Therefore, only colors that are
  177828. * within minmaxdist of some part of the box need be considered.
  177829. */
  177830. ncolors = 0;
  177831. for (i = 0; i < numcolors; i++) {
  177832. if (mindist[i] <= minmaxdist)
  177833. colorlist[ncolors++] = (JSAMPLE) i;
  177834. }
  177835. return ncolors;
  177836. }
  177837. LOCAL(void)
  177838. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177839. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177840. /* Find the closest colormap entry for each cell in the update box,
  177841. * given the list of candidate colors prepared by find_nearby_colors.
  177842. * Return the indexes of the closest entries in the bestcolor[] array.
  177843. * This routine uses Thomas' incremental distance calculation method to
  177844. * find the distance from a colormap entry to successive cells in the box.
  177845. */
  177846. {
  177847. int ic0, ic1, ic2;
  177848. int i, icolor;
  177849. register INT32 * bptr; /* pointer into bestdist[] array */
  177850. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177851. INT32 dist0, dist1; /* initial distance values */
  177852. register INT32 dist2; /* current distance in inner loop */
  177853. INT32 xx0, xx1; /* distance increments */
  177854. register INT32 xx2;
  177855. INT32 inc0, inc1, inc2; /* initial values for increments */
  177856. /* This array holds the distance to the nearest-so-far color for each cell */
  177857. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177858. /* Initialize best-distance for each cell of the update box */
  177859. bptr = bestdist;
  177860. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177861. *bptr++ = 0x7FFFFFFFL;
  177862. /* For each color selected by find_nearby_colors,
  177863. * compute its distance to the center of each cell in the box.
  177864. * If that's less than best-so-far, update best distance and color number.
  177865. */
  177866. /* Nominal steps between cell centers ("x" in Thomas article) */
  177867. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177868. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177869. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177870. for (i = 0; i < numcolors; i++) {
  177871. icolor = GETJSAMPLE(colorlist[i]);
  177872. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177873. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177874. dist0 = inc0*inc0;
  177875. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177876. dist0 += inc1*inc1;
  177877. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177878. dist0 += inc2*inc2;
  177879. /* Form the initial difference increments */
  177880. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177881. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177882. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177883. /* Now loop over all cells in box, updating distance per Thomas method */
  177884. bptr = bestdist;
  177885. cptr = bestcolor;
  177886. xx0 = inc0;
  177887. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177888. dist1 = dist0;
  177889. xx1 = inc1;
  177890. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177891. dist2 = dist1;
  177892. xx2 = inc2;
  177893. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177894. if (dist2 < *bptr) {
  177895. *bptr = dist2;
  177896. *cptr = (JSAMPLE) icolor;
  177897. }
  177898. dist2 += xx2;
  177899. xx2 += 2 * STEP_C2 * STEP_C2;
  177900. bptr++;
  177901. cptr++;
  177902. }
  177903. dist1 += xx1;
  177904. xx1 += 2 * STEP_C1 * STEP_C1;
  177905. }
  177906. dist0 += xx0;
  177907. xx0 += 2 * STEP_C0 * STEP_C0;
  177908. }
  177909. }
  177910. }
  177911. LOCAL(void)
  177912. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177913. /* Fill the inverse-colormap entries in the update box that contains */
  177914. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177915. /* we can fill as many others as we wish.) */
  177916. {
  177917. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177918. hist3d histogram = cquantize->histogram;
  177919. int minc0, minc1, minc2; /* lower left corner of update box */
  177920. int ic0, ic1, ic2;
  177921. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177922. register histptr cachep; /* pointer into main cache array */
  177923. /* This array lists the candidate colormap indexes. */
  177924. JSAMPLE colorlist[MAXNUMCOLORS];
  177925. int numcolors; /* number of candidate colors */
  177926. /* This array holds the actually closest colormap index for each cell. */
  177927. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177928. /* Convert cell coordinates to update box ID */
  177929. c0 >>= BOX_C0_LOG;
  177930. c1 >>= BOX_C1_LOG;
  177931. c2 >>= BOX_C2_LOG;
  177932. /* Compute true coordinates of update box's origin corner.
  177933. * Actually we compute the coordinates of the center of the corner
  177934. * histogram cell, which are the lower bounds of the volume we care about.
  177935. */
  177936. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177937. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177938. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177939. /* Determine which colormap entries are close enough to be candidates
  177940. * for the nearest entry to some cell in the update box.
  177941. */
  177942. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177943. /* Determine the actually nearest colors. */
  177944. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177945. bestcolor);
  177946. /* Save the best color numbers (plus 1) in the main cache array */
  177947. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177948. c1 <<= BOX_C1_LOG;
  177949. c2 <<= BOX_C2_LOG;
  177950. cptr = bestcolor;
  177951. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177952. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177953. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177954. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177955. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177956. }
  177957. }
  177958. }
  177959. }
  177960. /*
  177961. * Map some rows of pixels to the output colormapped representation.
  177962. */
  177963. METHODDEF(void)
  177964. pass2_no_dither (j_decompress_ptr cinfo,
  177965. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177966. /* This version performs no dithering */
  177967. {
  177968. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177969. hist3d histogram = cquantize->histogram;
  177970. register JSAMPROW inptr, outptr;
  177971. register histptr cachep;
  177972. register int c0, c1, c2;
  177973. int row;
  177974. JDIMENSION col;
  177975. JDIMENSION width = cinfo->output_width;
  177976. for (row = 0; row < num_rows; row++) {
  177977. inptr = input_buf[row];
  177978. outptr = output_buf[row];
  177979. for (col = width; col > 0; col--) {
  177980. /* get pixel value and index into the cache */
  177981. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177982. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177983. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177984. cachep = & histogram[c0][c1][c2];
  177985. /* If we have not seen this color before, find nearest colormap entry */
  177986. /* and update the cache */
  177987. if (*cachep == 0)
  177988. fill_inverse_cmap(cinfo, c0,c1,c2);
  177989. /* Now emit the colormap index for this cell */
  177990. *outptr++ = (JSAMPLE) (*cachep - 1);
  177991. }
  177992. }
  177993. }
  177994. METHODDEF(void)
  177995. pass2_fs_dither (j_decompress_ptr cinfo,
  177996. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177997. /* This version performs Floyd-Steinberg dithering */
  177998. {
  177999. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178000. hist3d histogram = cquantize->histogram;
  178001. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178002. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178003. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178004. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178005. JSAMPROW inptr; /* => current input pixel */
  178006. JSAMPROW outptr; /* => current output pixel */
  178007. histptr cachep;
  178008. int dir; /* +1 or -1 depending on direction */
  178009. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178010. int row;
  178011. JDIMENSION col;
  178012. JDIMENSION width = cinfo->output_width;
  178013. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178014. int *error_limit = cquantize->error_limiter;
  178015. JSAMPROW colormap0 = cinfo->colormap[0];
  178016. JSAMPROW colormap1 = cinfo->colormap[1];
  178017. JSAMPROW colormap2 = cinfo->colormap[2];
  178018. SHIFT_TEMPS
  178019. for (row = 0; row < num_rows; row++) {
  178020. inptr = input_buf[row];
  178021. outptr = output_buf[row];
  178022. if (cquantize->on_odd_row) {
  178023. /* work right to left in this row */
  178024. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178025. outptr += width-1;
  178026. dir = -1;
  178027. dir3 = -3;
  178028. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178029. cquantize->on_odd_row = FALSE; /* flip for next time */
  178030. } else {
  178031. /* work left to right in this row */
  178032. dir = 1;
  178033. dir3 = 3;
  178034. errorptr = cquantize->fserrors; /* => entry before first real column */
  178035. cquantize->on_odd_row = TRUE; /* flip for next time */
  178036. }
  178037. /* Preset error values: no error propagated to first pixel from left */
  178038. cur0 = cur1 = cur2 = 0;
  178039. /* and no error propagated to row below yet */
  178040. belowerr0 = belowerr1 = belowerr2 = 0;
  178041. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178042. for (col = width; col > 0; col--) {
  178043. /* curN holds the error propagated from the previous pixel on the
  178044. * current line. Add the error propagated from the previous line
  178045. * to form the complete error correction term for this pixel, and
  178046. * round the error term (which is expressed * 16) to an integer.
  178047. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178048. * for either sign of the error value.
  178049. * Note: errorptr points to *previous* column's array entry.
  178050. */
  178051. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178052. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178053. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178054. /* Limit the error using transfer function set by init_error_limit.
  178055. * See comments with init_error_limit for rationale.
  178056. */
  178057. cur0 = error_limit[cur0];
  178058. cur1 = error_limit[cur1];
  178059. cur2 = error_limit[cur2];
  178060. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178061. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178062. * this sets the required size of the range_limit array.
  178063. */
  178064. cur0 += GETJSAMPLE(inptr[0]);
  178065. cur1 += GETJSAMPLE(inptr[1]);
  178066. cur2 += GETJSAMPLE(inptr[2]);
  178067. cur0 = GETJSAMPLE(range_limit[cur0]);
  178068. cur1 = GETJSAMPLE(range_limit[cur1]);
  178069. cur2 = GETJSAMPLE(range_limit[cur2]);
  178070. /* Index into the cache with adjusted pixel value */
  178071. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178072. /* If we have not seen this color before, find nearest colormap */
  178073. /* entry and update the cache */
  178074. if (*cachep == 0)
  178075. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178076. /* Now emit the colormap index for this cell */
  178077. { register int pixcode = *cachep - 1;
  178078. *outptr = (JSAMPLE) pixcode;
  178079. /* Compute representation error for this pixel */
  178080. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178081. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178082. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178083. }
  178084. /* Compute error fractions to be propagated to adjacent pixels.
  178085. * Add these into the running sums, and simultaneously shift the
  178086. * next-line error sums left by 1 column.
  178087. */
  178088. { register LOCFSERROR bnexterr, delta;
  178089. bnexterr = cur0; /* Process component 0 */
  178090. delta = cur0 * 2;
  178091. cur0 += delta; /* form error * 3 */
  178092. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178093. cur0 += delta; /* form error * 5 */
  178094. bpreverr0 = belowerr0 + cur0;
  178095. belowerr0 = bnexterr;
  178096. cur0 += delta; /* form error * 7 */
  178097. bnexterr = cur1; /* Process component 1 */
  178098. delta = cur1 * 2;
  178099. cur1 += delta; /* form error * 3 */
  178100. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178101. cur1 += delta; /* form error * 5 */
  178102. bpreverr1 = belowerr1 + cur1;
  178103. belowerr1 = bnexterr;
  178104. cur1 += delta; /* form error * 7 */
  178105. bnexterr = cur2; /* Process component 2 */
  178106. delta = cur2 * 2;
  178107. cur2 += delta; /* form error * 3 */
  178108. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178109. cur2 += delta; /* form error * 5 */
  178110. bpreverr2 = belowerr2 + cur2;
  178111. belowerr2 = bnexterr;
  178112. cur2 += delta; /* form error * 7 */
  178113. }
  178114. /* At this point curN contains the 7/16 error value to be propagated
  178115. * to the next pixel on the current line, and all the errors for the
  178116. * next line have been shifted over. We are therefore ready to move on.
  178117. */
  178118. inptr += dir3; /* Advance pixel pointers to next column */
  178119. outptr += dir;
  178120. errorptr += dir3; /* advance errorptr to current column */
  178121. }
  178122. /* Post-loop cleanup: we must unload the final error values into the
  178123. * final fserrors[] entry. Note we need not unload belowerrN because
  178124. * it is for the dummy column before or after the actual array.
  178125. */
  178126. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178127. errorptr[1] = (FSERROR) bpreverr1;
  178128. errorptr[2] = (FSERROR) bpreverr2;
  178129. }
  178130. }
  178131. /*
  178132. * Initialize the error-limiting transfer function (lookup table).
  178133. * The raw F-S error computation can potentially compute error values of up to
  178134. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178135. * much less, otherwise obviously wrong pixels will be created. (Typical
  178136. * effects include weird fringes at color-area boundaries, isolated bright
  178137. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178138. * is to ensure that the "corners" of the color cube are allocated as output
  178139. * colors; then repeated errors in the same direction cannot cause cascading
  178140. * error buildup. However, that only prevents the error from getting
  178141. * completely out of hand; Aaron Giles reports that error limiting improves
  178142. * the results even with corner colors allocated.
  178143. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178144. * well, but the smoother transfer function used below is even better. Thanks
  178145. * to Aaron Giles for this idea.
  178146. */
  178147. LOCAL(void)
  178148. init_error_limit (j_decompress_ptr cinfo)
  178149. /* Allocate and fill in the error_limiter table */
  178150. {
  178151. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178152. int * table;
  178153. int in, out;
  178154. table = (int *) (*cinfo->mem->alloc_small)
  178155. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178156. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178157. cquantize->error_limiter = table;
  178158. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178159. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178160. out = 0;
  178161. for (in = 0; in < STEPSIZE; in++, out++) {
  178162. table[in] = out; table[-in] = -out;
  178163. }
  178164. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178165. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178166. table[in] = out; table[-in] = -out;
  178167. }
  178168. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178169. for (; in <= MAXJSAMPLE; in++) {
  178170. table[in] = out; table[-in] = -out;
  178171. }
  178172. #undef STEPSIZE
  178173. }
  178174. /*
  178175. * Finish up at the end of each pass.
  178176. */
  178177. METHODDEF(void)
  178178. finish_pass1 (j_decompress_ptr cinfo)
  178179. {
  178180. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178181. /* Select the representative colors and fill in cinfo->colormap */
  178182. cinfo->colormap = cquantize->sv_colormap;
  178183. select_colors(cinfo, cquantize->desired);
  178184. /* Force next pass to zero the color index table */
  178185. cquantize->needs_zeroed = TRUE;
  178186. }
  178187. METHODDEF(void)
  178188. finish_pass2 (j_decompress_ptr)
  178189. {
  178190. /* no work */
  178191. }
  178192. /*
  178193. * Initialize for each processing pass.
  178194. */
  178195. METHODDEF(void)
  178196. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178197. {
  178198. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178199. hist3d histogram = cquantize->histogram;
  178200. int i;
  178201. /* Only F-S dithering or no dithering is supported. */
  178202. /* If user asks for ordered dither, give him F-S. */
  178203. if (cinfo->dither_mode != JDITHER_NONE)
  178204. cinfo->dither_mode = JDITHER_FS;
  178205. if (is_pre_scan) {
  178206. /* Set up method pointers */
  178207. cquantize->pub.color_quantize = prescan_quantize;
  178208. cquantize->pub.finish_pass = finish_pass1;
  178209. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178210. } else {
  178211. /* Set up method pointers */
  178212. if (cinfo->dither_mode == JDITHER_FS)
  178213. cquantize->pub.color_quantize = pass2_fs_dither;
  178214. else
  178215. cquantize->pub.color_quantize = pass2_no_dither;
  178216. cquantize->pub.finish_pass = finish_pass2;
  178217. /* Make sure color count is acceptable */
  178218. i = cinfo->actual_number_of_colors;
  178219. if (i < 1)
  178220. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178221. if (i > MAXNUMCOLORS)
  178222. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178223. if (cinfo->dither_mode == JDITHER_FS) {
  178224. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178225. (3 * SIZEOF(FSERROR)));
  178226. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178227. if (cquantize->fserrors == NULL)
  178228. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178229. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178230. /* Initialize the propagated errors to zero. */
  178231. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178232. /* Make the error-limit table if we didn't already. */
  178233. if (cquantize->error_limiter == NULL)
  178234. init_error_limit(cinfo);
  178235. cquantize->on_odd_row = FALSE;
  178236. }
  178237. }
  178238. /* Zero the histogram or inverse color map, if necessary */
  178239. if (cquantize->needs_zeroed) {
  178240. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178241. jzero_far((void FAR *) histogram[i],
  178242. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178243. }
  178244. cquantize->needs_zeroed = FALSE;
  178245. }
  178246. }
  178247. /*
  178248. * Switch to a new external colormap between output passes.
  178249. */
  178250. METHODDEF(void)
  178251. new_color_map_2_quant (j_decompress_ptr cinfo)
  178252. {
  178253. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178254. /* Reset the inverse color map */
  178255. cquantize->needs_zeroed = TRUE;
  178256. }
  178257. /*
  178258. * Module initialization routine for 2-pass color quantization.
  178259. */
  178260. GLOBAL(void)
  178261. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178262. {
  178263. my_cquantize_ptr2 cquantize;
  178264. int i;
  178265. cquantize = (my_cquantize_ptr2)
  178266. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178267. SIZEOF(my_cquantizer2));
  178268. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178269. cquantize->pub.start_pass = start_pass_2_quant;
  178270. cquantize->pub.new_color_map = new_color_map_2_quant;
  178271. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178272. cquantize->error_limiter = NULL;
  178273. /* Make sure jdmaster didn't give me a case I can't handle */
  178274. if (cinfo->out_color_components != 3)
  178275. ERREXIT(cinfo, JERR_NOTIMPL);
  178276. /* Allocate the histogram/inverse colormap storage */
  178277. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178278. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178279. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178280. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178281. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178282. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178283. }
  178284. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178285. /* Allocate storage for the completed colormap, if required.
  178286. * We do this now since it is FAR storage and may affect
  178287. * the memory manager's space calculations.
  178288. */
  178289. if (cinfo->enable_2pass_quant) {
  178290. /* Make sure color count is acceptable */
  178291. int desired = cinfo->desired_number_of_colors;
  178292. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178293. if (desired < 8)
  178294. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178295. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178296. if (desired > MAXNUMCOLORS)
  178297. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178298. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178299. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178300. cquantize->desired = desired;
  178301. } else
  178302. cquantize->sv_colormap = NULL;
  178303. /* Only F-S dithering or no dithering is supported. */
  178304. /* If user asks for ordered dither, give him F-S. */
  178305. if (cinfo->dither_mode != JDITHER_NONE)
  178306. cinfo->dither_mode = JDITHER_FS;
  178307. /* Allocate Floyd-Steinberg workspace if necessary.
  178308. * This isn't really needed until pass 2, but again it is FAR storage.
  178309. * Although we will cope with a later change in dither_mode,
  178310. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178311. */
  178312. if (cinfo->dither_mode == JDITHER_FS) {
  178313. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178314. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178315. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178316. /* Might as well create the error-limiting table too. */
  178317. init_error_limit(cinfo);
  178318. }
  178319. }
  178320. #endif /* QUANT_2PASS_SUPPORTED */
  178321. /*** End of inlined file: jquant2.c ***/
  178322. /*** Start of inlined file: jutils.c ***/
  178323. #define JPEG_INTERNALS
  178324. /*
  178325. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178326. * of a DCT block read in natural order (left to right, top to bottom).
  178327. */
  178328. #if 0 /* This table is not actually needed in v6a */
  178329. const int jpeg_zigzag_order[DCTSIZE2] = {
  178330. 0, 1, 5, 6, 14, 15, 27, 28,
  178331. 2, 4, 7, 13, 16, 26, 29, 42,
  178332. 3, 8, 12, 17, 25, 30, 41, 43,
  178333. 9, 11, 18, 24, 31, 40, 44, 53,
  178334. 10, 19, 23, 32, 39, 45, 52, 54,
  178335. 20, 22, 33, 38, 46, 51, 55, 60,
  178336. 21, 34, 37, 47, 50, 56, 59, 61,
  178337. 35, 36, 48, 49, 57, 58, 62, 63
  178338. };
  178339. #endif
  178340. /*
  178341. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178342. * of zigzag order.
  178343. *
  178344. * When reading corrupted data, the Huffman decoders could attempt
  178345. * to reference an entry beyond the end of this array (if the decoded
  178346. * zero run length reaches past the end of the block). To prevent
  178347. * wild stores without adding an inner-loop test, we put some extra
  178348. * "63"s after the real entries. This will cause the extra coefficient
  178349. * to be stored in location 63 of the block, not somewhere random.
  178350. * The worst case would be a run-length of 15, which means we need 16
  178351. * fake entries.
  178352. */
  178353. const int jpeg_natural_order[DCTSIZE2+16] = {
  178354. 0, 1, 8, 16, 9, 2, 3, 10,
  178355. 17, 24, 32, 25, 18, 11, 4, 5,
  178356. 12, 19, 26, 33, 40, 48, 41, 34,
  178357. 27, 20, 13, 6, 7, 14, 21, 28,
  178358. 35, 42, 49, 56, 57, 50, 43, 36,
  178359. 29, 22, 15, 23, 30, 37, 44, 51,
  178360. 58, 59, 52, 45, 38, 31, 39, 46,
  178361. 53, 60, 61, 54, 47, 55, 62, 63,
  178362. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178363. 63, 63, 63, 63, 63, 63, 63, 63
  178364. };
  178365. /*
  178366. * Arithmetic utilities
  178367. */
  178368. GLOBAL(long)
  178369. jdiv_round_up (long a, long b)
  178370. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178371. /* Assumes a >= 0, b > 0 */
  178372. {
  178373. return (a + b - 1L) / b;
  178374. }
  178375. GLOBAL(long)
  178376. jround_up (long a, long b)
  178377. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178378. /* Assumes a >= 0, b > 0 */
  178379. {
  178380. a += b - 1L;
  178381. return a - (a % b);
  178382. }
  178383. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178384. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178385. * are FAR and we're assuming a small-pointer memory model. However, some
  178386. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178387. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178388. * Otherwise, the routines below do it the hard way. (The performance cost
  178389. * is not all that great, because these routines aren't very heavily used.)
  178390. */
  178391. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178392. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178393. #define FMEMZERO(target,size) MEMZERO(target,size)
  178394. #else /* 80x86 case, define if we can */
  178395. #ifdef USE_FMEM
  178396. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178397. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178398. #endif
  178399. #endif
  178400. GLOBAL(void)
  178401. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178402. JSAMPARRAY output_array, int dest_row,
  178403. int num_rows, JDIMENSION num_cols)
  178404. /* Copy some rows of samples from one place to another.
  178405. * num_rows rows are copied from input_array[source_row++]
  178406. * to output_array[dest_row++]; these areas may overlap for duplication.
  178407. * The source and destination arrays must be at least as wide as num_cols.
  178408. */
  178409. {
  178410. register JSAMPROW inptr, outptr;
  178411. #ifdef FMEMCOPY
  178412. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178413. #else
  178414. register JDIMENSION count;
  178415. #endif
  178416. register int row;
  178417. input_array += source_row;
  178418. output_array += dest_row;
  178419. for (row = num_rows; row > 0; row--) {
  178420. inptr = *input_array++;
  178421. outptr = *output_array++;
  178422. #ifdef FMEMCOPY
  178423. FMEMCOPY(outptr, inptr, count);
  178424. #else
  178425. for (count = num_cols; count > 0; count--)
  178426. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178427. #endif
  178428. }
  178429. }
  178430. GLOBAL(void)
  178431. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178432. JDIMENSION num_blocks)
  178433. /* Copy a row of coefficient blocks from one place to another. */
  178434. {
  178435. #ifdef FMEMCOPY
  178436. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178437. #else
  178438. register JCOEFPTR inptr, outptr;
  178439. register long count;
  178440. inptr = (JCOEFPTR) input_row;
  178441. outptr = (JCOEFPTR) output_row;
  178442. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178443. *outptr++ = *inptr++;
  178444. }
  178445. #endif
  178446. }
  178447. GLOBAL(void)
  178448. jzero_far (void FAR * target, size_t bytestozero)
  178449. /* Zero out a chunk of FAR memory. */
  178450. /* This might be sample-array data, block-array data, or alloc_large data. */
  178451. {
  178452. #ifdef FMEMZERO
  178453. FMEMZERO(target, bytestozero);
  178454. #else
  178455. register char FAR * ptr = (char FAR *) target;
  178456. register size_t count;
  178457. for (count = bytestozero; count > 0; count--) {
  178458. *ptr++ = 0;
  178459. }
  178460. #endif
  178461. }
  178462. /*** End of inlined file: jutils.c ***/
  178463. /*** Start of inlined file: transupp.c ***/
  178464. /* Although this file really shouldn't have access to the library internals,
  178465. * it's helpful to let it call jround_up() and jcopy_block_row().
  178466. */
  178467. #define JPEG_INTERNALS
  178468. /*** Start of inlined file: transupp.h ***/
  178469. /* If you happen not to want the image transform support, disable it here */
  178470. #ifndef TRANSFORMS_SUPPORTED
  178471. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178472. #endif
  178473. /* Short forms of external names for systems with brain-damaged linkers. */
  178474. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178475. #define jtransform_request_workspace jTrRequest
  178476. #define jtransform_adjust_parameters jTrAdjust
  178477. #define jtransform_execute_transformation jTrExec
  178478. #define jcopy_markers_setup jCMrkSetup
  178479. #define jcopy_markers_execute jCMrkExec
  178480. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178481. /*
  178482. * Codes for supported types of image transformations.
  178483. */
  178484. typedef enum {
  178485. JXFORM_NONE, /* no transformation */
  178486. JXFORM_FLIP_H, /* horizontal flip */
  178487. JXFORM_FLIP_V, /* vertical flip */
  178488. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178489. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178490. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178491. JXFORM_ROT_180, /* 180-degree rotation */
  178492. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178493. } JXFORM_CODE;
  178494. /*
  178495. * Although rotating and flipping data expressed as DCT coefficients is not
  178496. * hard, there is an asymmetry in the JPEG format specification for images
  178497. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178498. * image edges are padded out to the next iMCU boundary with junk data; but
  178499. * no padding is possible at the top and left edges. If we were to flip
  178500. * the whole image including the pad data, then pad garbage would become
  178501. * visible at the top and/or left, and real pixels would disappear into the
  178502. * pad margins --- perhaps permanently, since encoders & decoders may not
  178503. * bother to preserve DCT blocks that appear to be completely outside the
  178504. * nominal image area. So, we have to exclude any partial iMCUs from the
  178505. * basic transformation.
  178506. *
  178507. * Transpose is the only transformation that can handle partial iMCUs at the
  178508. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178509. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178510. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178511. * The other transforms are defined as combinations of these basic transforms
  178512. * and process edge blocks in a way that preserves the equivalence.
  178513. *
  178514. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178515. * this is not strictly lossless, but it usually gives the best-looking
  178516. * result for odd-size images. Note that when this option is active,
  178517. * the expected mathematical equivalences between the transforms may not hold.
  178518. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178519. * followed by -rot 180 -trim trims both edges.)
  178520. *
  178521. * We also offer a "force to grayscale" option, which simply discards the
  178522. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178523. * the luminance channel is preserved exactly. It's not the same kind of
  178524. * thing as the rotate/flip transformations, but it's convenient to handle it
  178525. * as part of this package, mainly because the transformation routines have to
  178526. * be aware of the option to know how many components to work on.
  178527. */
  178528. typedef struct {
  178529. /* Options: set by caller */
  178530. JXFORM_CODE transform; /* image transform operator */
  178531. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178532. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178533. /* Internal workspace: caller should not touch these */
  178534. int num_components; /* # of components in workspace */
  178535. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178536. } jpeg_transform_info;
  178537. #if TRANSFORMS_SUPPORTED
  178538. /* Request any required workspace */
  178539. EXTERN(void) jtransform_request_workspace
  178540. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178541. /* Adjust output image parameters */
  178542. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178543. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178544. jvirt_barray_ptr *src_coef_arrays,
  178545. jpeg_transform_info *info));
  178546. /* Execute the actual transformation, if any */
  178547. EXTERN(void) jtransform_execute_transformation
  178548. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178549. jvirt_barray_ptr *src_coef_arrays,
  178550. jpeg_transform_info *info));
  178551. #endif /* TRANSFORMS_SUPPORTED */
  178552. /*
  178553. * Support for copying optional markers from source to destination file.
  178554. */
  178555. typedef enum {
  178556. JCOPYOPT_NONE, /* copy no optional markers */
  178557. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178558. JCOPYOPT_ALL /* copy all optional markers */
  178559. } JCOPY_OPTION;
  178560. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178561. /* Setup decompression object to save desired markers in memory */
  178562. EXTERN(void) jcopy_markers_setup
  178563. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178564. /* Copy markers saved in the given source object to the destination object */
  178565. EXTERN(void) jcopy_markers_execute
  178566. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178567. JCOPY_OPTION option));
  178568. /*** End of inlined file: transupp.h ***/
  178569. /* My own external interface */
  178570. #if TRANSFORMS_SUPPORTED
  178571. /*
  178572. * Lossless image transformation routines. These routines work on DCT
  178573. * coefficient arrays and thus do not require any lossy decompression
  178574. * or recompression of the image.
  178575. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178576. *
  178577. * Horizontal flipping is done in-place, using a single top-to-bottom
  178578. * pass through the virtual source array. It will thus be much the
  178579. * fastest option for images larger than main memory.
  178580. *
  178581. * The other routines require a set of destination virtual arrays, so they
  178582. * need twice as much memory as jpegtran normally does. The destination
  178583. * arrays are always written in normal scan order (top to bottom) because
  178584. * the virtual array manager expects this. The source arrays will be scanned
  178585. * in the corresponding order, which means multiple passes through the source
  178586. * arrays for most of the transforms. That could result in much thrashing
  178587. * if the image is larger than main memory.
  178588. *
  178589. * Some notes about the operating environment of the individual transform
  178590. * routines:
  178591. * 1. Both the source and destination virtual arrays are allocated from the
  178592. * source JPEG object, and therefore should be manipulated by calling the
  178593. * source's memory manager.
  178594. * 2. The destination's component count should be used. It may be smaller
  178595. * than the source's when forcing to grayscale.
  178596. * 3. Likewise the destination's sampling factors should be used. When
  178597. * forcing to grayscale the destination's sampling factors will be all 1,
  178598. * and we may as well take that as the effective iMCU size.
  178599. * 4. When "trim" is in effect, the destination's dimensions will be the
  178600. * trimmed values but the source's will be untrimmed.
  178601. * 5. All the routines assume that the source and destination buffers are
  178602. * padded out to a full iMCU boundary. This is true, although for the
  178603. * source buffer it is an undocumented property of jdcoefct.c.
  178604. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178605. * dimensions and ignore the source's.
  178606. */
  178607. LOCAL(void)
  178608. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178609. jvirt_barray_ptr *src_coef_arrays)
  178610. /* Horizontal flip; done in-place, so no separate dest array is required */
  178611. {
  178612. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178613. int ci, k, offset_y;
  178614. JBLOCKARRAY buffer;
  178615. JCOEFPTR ptr1, ptr2;
  178616. JCOEF temp1, temp2;
  178617. jpeg_component_info *compptr;
  178618. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178619. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178620. * mirroring by changing the signs of odd-numbered columns.
  178621. * Partial iMCUs at the right edge are left untouched.
  178622. */
  178623. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178624. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178625. compptr = dstinfo->comp_info + ci;
  178626. comp_width = MCU_cols * compptr->h_samp_factor;
  178627. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178628. blk_y += compptr->v_samp_factor) {
  178629. buffer = (*srcinfo->mem->access_virt_barray)
  178630. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178631. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178632. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178633. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178634. ptr1 = buffer[offset_y][blk_x];
  178635. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178636. /* this unrolled loop doesn't need to know which row it's on... */
  178637. for (k = 0; k < DCTSIZE2; k += 2) {
  178638. temp1 = *ptr1; /* swap even column */
  178639. temp2 = *ptr2;
  178640. *ptr1++ = temp2;
  178641. *ptr2++ = temp1;
  178642. temp1 = *ptr1; /* swap odd column with sign change */
  178643. temp2 = *ptr2;
  178644. *ptr1++ = -temp2;
  178645. *ptr2++ = -temp1;
  178646. }
  178647. }
  178648. }
  178649. }
  178650. }
  178651. }
  178652. LOCAL(void)
  178653. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178654. jvirt_barray_ptr *src_coef_arrays,
  178655. jvirt_barray_ptr *dst_coef_arrays)
  178656. /* Vertical flip */
  178657. {
  178658. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178659. int ci, i, j, offset_y;
  178660. JBLOCKARRAY src_buffer, dst_buffer;
  178661. JBLOCKROW src_row_ptr, dst_row_ptr;
  178662. JCOEFPTR src_ptr, dst_ptr;
  178663. jpeg_component_info *compptr;
  178664. /* We output into a separate array because we can't touch different
  178665. * rows of the source virtual array simultaneously. Otherwise, this
  178666. * is a pretty straightforward analog of horizontal flip.
  178667. * Within a DCT block, vertical mirroring is done by changing the signs
  178668. * of odd-numbered rows.
  178669. * Partial iMCUs at the bottom edge are copied verbatim.
  178670. */
  178671. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178672. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178673. compptr = dstinfo->comp_info + ci;
  178674. comp_height = MCU_rows * compptr->v_samp_factor;
  178675. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178676. dst_blk_y += compptr->v_samp_factor) {
  178677. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178678. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178679. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178680. if (dst_blk_y < comp_height) {
  178681. /* Row is within the mirrorable area. */
  178682. src_buffer = (*srcinfo->mem->access_virt_barray)
  178683. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178684. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178685. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178686. } else {
  178687. /* Bottom-edge blocks will be copied verbatim. */
  178688. src_buffer = (*srcinfo->mem->access_virt_barray)
  178689. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178690. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178691. }
  178692. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178693. if (dst_blk_y < comp_height) {
  178694. /* Row is within the mirrorable area. */
  178695. dst_row_ptr = dst_buffer[offset_y];
  178696. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178697. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178698. dst_blk_x++) {
  178699. dst_ptr = dst_row_ptr[dst_blk_x];
  178700. src_ptr = src_row_ptr[dst_blk_x];
  178701. for (i = 0; i < DCTSIZE; i += 2) {
  178702. /* copy even row */
  178703. for (j = 0; j < DCTSIZE; j++)
  178704. *dst_ptr++ = *src_ptr++;
  178705. /* copy odd row with sign change */
  178706. for (j = 0; j < DCTSIZE; j++)
  178707. *dst_ptr++ = - *src_ptr++;
  178708. }
  178709. }
  178710. } else {
  178711. /* Just copy row verbatim. */
  178712. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178713. compptr->width_in_blocks);
  178714. }
  178715. }
  178716. }
  178717. }
  178718. }
  178719. LOCAL(void)
  178720. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178721. jvirt_barray_ptr *src_coef_arrays,
  178722. jvirt_barray_ptr *dst_coef_arrays)
  178723. /* Transpose source into destination */
  178724. {
  178725. JDIMENSION dst_blk_x, dst_blk_y;
  178726. int ci, i, j, offset_x, offset_y;
  178727. JBLOCKARRAY src_buffer, dst_buffer;
  178728. JCOEFPTR src_ptr, dst_ptr;
  178729. jpeg_component_info *compptr;
  178730. /* Transposing pixels within a block just requires transposing the
  178731. * DCT coefficients.
  178732. * Partial iMCUs at the edges require no special treatment; we simply
  178733. * process all the available DCT blocks for every component.
  178734. */
  178735. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178736. compptr = dstinfo->comp_info + ci;
  178737. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178738. dst_blk_y += compptr->v_samp_factor) {
  178739. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178740. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178741. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178742. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178743. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178744. dst_blk_x += compptr->h_samp_factor) {
  178745. src_buffer = (*srcinfo->mem->access_virt_barray)
  178746. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178747. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178748. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178749. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178750. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178751. for (i = 0; i < DCTSIZE; i++)
  178752. for (j = 0; j < DCTSIZE; j++)
  178753. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178754. }
  178755. }
  178756. }
  178757. }
  178758. }
  178759. }
  178760. LOCAL(void)
  178761. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178762. jvirt_barray_ptr *src_coef_arrays,
  178763. jvirt_barray_ptr *dst_coef_arrays)
  178764. /* 90 degree rotation is equivalent to
  178765. * 1. Transposing the image;
  178766. * 2. Horizontal mirroring.
  178767. * These two steps are merged into a single processing routine.
  178768. */
  178769. {
  178770. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178771. int ci, i, j, offset_x, offset_y;
  178772. JBLOCKARRAY src_buffer, dst_buffer;
  178773. JCOEFPTR src_ptr, dst_ptr;
  178774. jpeg_component_info *compptr;
  178775. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178776. * at the (output) right edge properly. They just get transposed and
  178777. * not mirrored.
  178778. */
  178779. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178780. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178781. compptr = dstinfo->comp_info + ci;
  178782. comp_width = MCU_cols * compptr->h_samp_factor;
  178783. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178784. dst_blk_y += compptr->v_samp_factor) {
  178785. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178786. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178787. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178788. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178789. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178790. dst_blk_x += compptr->h_samp_factor) {
  178791. src_buffer = (*srcinfo->mem->access_virt_barray)
  178792. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178793. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178794. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178795. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178796. if (dst_blk_x < comp_width) {
  178797. /* Block is within the mirrorable area. */
  178798. dst_ptr = dst_buffer[offset_y]
  178799. [comp_width - dst_blk_x - offset_x - 1];
  178800. for (i = 0; i < DCTSIZE; i++) {
  178801. for (j = 0; j < DCTSIZE; j++)
  178802. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178803. i++;
  178804. for (j = 0; j < DCTSIZE; j++)
  178805. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178806. }
  178807. } else {
  178808. /* Edge blocks are transposed but not mirrored. */
  178809. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178810. for (i = 0; i < DCTSIZE; i++)
  178811. for (j = 0; j < DCTSIZE; j++)
  178812. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178813. }
  178814. }
  178815. }
  178816. }
  178817. }
  178818. }
  178819. }
  178820. LOCAL(void)
  178821. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178822. jvirt_barray_ptr *src_coef_arrays,
  178823. jvirt_barray_ptr *dst_coef_arrays)
  178824. /* 270 degree rotation is equivalent to
  178825. * 1. Horizontal mirroring;
  178826. * 2. Transposing the image.
  178827. * These two steps are merged into a single processing routine.
  178828. */
  178829. {
  178830. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178831. int ci, i, j, offset_x, offset_y;
  178832. JBLOCKARRAY src_buffer, dst_buffer;
  178833. JCOEFPTR src_ptr, dst_ptr;
  178834. jpeg_component_info *compptr;
  178835. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178836. * at the (output) bottom edge properly. They just get transposed and
  178837. * not mirrored.
  178838. */
  178839. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178840. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178841. compptr = dstinfo->comp_info + ci;
  178842. comp_height = MCU_rows * compptr->v_samp_factor;
  178843. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178844. dst_blk_y += compptr->v_samp_factor) {
  178845. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178846. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178847. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178848. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178849. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178850. dst_blk_x += compptr->h_samp_factor) {
  178851. src_buffer = (*srcinfo->mem->access_virt_barray)
  178852. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178853. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178854. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178855. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178856. if (dst_blk_y < comp_height) {
  178857. /* Block is within the mirrorable area. */
  178858. src_ptr = src_buffer[offset_x]
  178859. [comp_height - dst_blk_y - offset_y - 1];
  178860. for (i = 0; i < DCTSIZE; i++) {
  178861. for (j = 0; j < DCTSIZE; j++) {
  178862. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178863. j++;
  178864. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178865. }
  178866. }
  178867. } else {
  178868. /* Edge blocks are transposed but not mirrored. */
  178869. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178870. for (i = 0; i < DCTSIZE; i++)
  178871. for (j = 0; j < DCTSIZE; j++)
  178872. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178873. }
  178874. }
  178875. }
  178876. }
  178877. }
  178878. }
  178879. }
  178880. LOCAL(void)
  178881. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178882. jvirt_barray_ptr *src_coef_arrays,
  178883. jvirt_barray_ptr *dst_coef_arrays)
  178884. /* 180 degree rotation is equivalent to
  178885. * 1. Vertical mirroring;
  178886. * 2. Horizontal mirroring.
  178887. * These two steps are merged into a single processing routine.
  178888. */
  178889. {
  178890. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178891. int ci, i, j, offset_y;
  178892. JBLOCKARRAY src_buffer, dst_buffer;
  178893. JBLOCKROW src_row_ptr, dst_row_ptr;
  178894. JCOEFPTR src_ptr, dst_ptr;
  178895. jpeg_component_info *compptr;
  178896. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178897. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178898. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178899. compptr = dstinfo->comp_info + ci;
  178900. comp_width = MCU_cols * compptr->h_samp_factor;
  178901. comp_height = MCU_rows * compptr->v_samp_factor;
  178902. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178903. dst_blk_y += compptr->v_samp_factor) {
  178904. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178905. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178906. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178907. if (dst_blk_y < comp_height) {
  178908. /* Row is within the vertically mirrorable area. */
  178909. src_buffer = (*srcinfo->mem->access_virt_barray)
  178910. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178911. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178912. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178913. } else {
  178914. /* Bottom-edge rows are only mirrored horizontally. */
  178915. src_buffer = (*srcinfo->mem->access_virt_barray)
  178916. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178917. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178918. }
  178919. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178920. if (dst_blk_y < comp_height) {
  178921. /* Row is within the mirrorable area. */
  178922. dst_row_ptr = dst_buffer[offset_y];
  178923. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178924. /* Process the blocks that can be mirrored both ways. */
  178925. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178926. dst_ptr = dst_row_ptr[dst_blk_x];
  178927. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178928. for (i = 0; i < DCTSIZE; i += 2) {
  178929. /* For even row, negate every odd column. */
  178930. for (j = 0; j < DCTSIZE; j += 2) {
  178931. *dst_ptr++ = *src_ptr++;
  178932. *dst_ptr++ = - *src_ptr++;
  178933. }
  178934. /* For odd row, negate every even column. */
  178935. for (j = 0; j < DCTSIZE; j += 2) {
  178936. *dst_ptr++ = - *src_ptr++;
  178937. *dst_ptr++ = *src_ptr++;
  178938. }
  178939. }
  178940. }
  178941. /* Any remaining right-edge blocks are only mirrored vertically. */
  178942. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178943. dst_ptr = dst_row_ptr[dst_blk_x];
  178944. src_ptr = src_row_ptr[dst_blk_x];
  178945. for (i = 0; i < DCTSIZE; i += 2) {
  178946. for (j = 0; j < DCTSIZE; j++)
  178947. *dst_ptr++ = *src_ptr++;
  178948. for (j = 0; j < DCTSIZE; j++)
  178949. *dst_ptr++ = - *src_ptr++;
  178950. }
  178951. }
  178952. } else {
  178953. /* Remaining rows are just mirrored horizontally. */
  178954. dst_row_ptr = dst_buffer[offset_y];
  178955. src_row_ptr = src_buffer[offset_y];
  178956. /* Process the blocks that can be mirrored. */
  178957. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178958. dst_ptr = dst_row_ptr[dst_blk_x];
  178959. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178960. for (i = 0; i < DCTSIZE2; i += 2) {
  178961. *dst_ptr++ = *src_ptr++;
  178962. *dst_ptr++ = - *src_ptr++;
  178963. }
  178964. }
  178965. /* Any remaining right-edge blocks are only copied. */
  178966. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178967. dst_ptr = dst_row_ptr[dst_blk_x];
  178968. src_ptr = src_row_ptr[dst_blk_x];
  178969. for (i = 0; i < DCTSIZE2; i++)
  178970. *dst_ptr++ = *src_ptr++;
  178971. }
  178972. }
  178973. }
  178974. }
  178975. }
  178976. }
  178977. LOCAL(void)
  178978. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178979. jvirt_barray_ptr *src_coef_arrays,
  178980. jvirt_barray_ptr *dst_coef_arrays)
  178981. /* Transverse transpose is equivalent to
  178982. * 1. 180 degree rotation;
  178983. * 2. Transposition;
  178984. * or
  178985. * 1. Horizontal mirroring;
  178986. * 2. Transposition;
  178987. * 3. Horizontal mirroring.
  178988. * These steps are merged into a single processing routine.
  178989. */
  178990. {
  178991. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178992. int ci, i, j, offset_x, offset_y;
  178993. JBLOCKARRAY src_buffer, dst_buffer;
  178994. JCOEFPTR src_ptr, dst_ptr;
  178995. jpeg_component_info *compptr;
  178996. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178997. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178998. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178999. compptr = dstinfo->comp_info + ci;
  179000. comp_width = MCU_cols * compptr->h_samp_factor;
  179001. comp_height = MCU_rows * compptr->v_samp_factor;
  179002. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179003. dst_blk_y += compptr->v_samp_factor) {
  179004. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179005. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179006. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179007. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179008. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179009. dst_blk_x += compptr->h_samp_factor) {
  179010. src_buffer = (*srcinfo->mem->access_virt_barray)
  179011. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179012. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179013. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179014. if (dst_blk_y < comp_height) {
  179015. src_ptr = src_buffer[offset_x]
  179016. [comp_height - dst_blk_y - offset_y - 1];
  179017. if (dst_blk_x < comp_width) {
  179018. /* Block is within the mirrorable area. */
  179019. dst_ptr = dst_buffer[offset_y]
  179020. [comp_width - dst_blk_x - offset_x - 1];
  179021. for (i = 0; i < DCTSIZE; i++) {
  179022. for (j = 0; j < DCTSIZE; j++) {
  179023. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179024. j++;
  179025. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179026. }
  179027. i++;
  179028. for (j = 0; j < DCTSIZE; j++) {
  179029. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179030. j++;
  179031. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179032. }
  179033. }
  179034. } else {
  179035. /* Right-edge blocks are mirrored in y only */
  179036. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179037. for (i = 0; i < DCTSIZE; i++) {
  179038. for (j = 0; j < DCTSIZE; j++) {
  179039. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179040. j++;
  179041. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179042. }
  179043. }
  179044. }
  179045. } else {
  179046. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179047. if (dst_blk_x < comp_width) {
  179048. /* Bottom-edge blocks are mirrored in x only */
  179049. dst_ptr = dst_buffer[offset_y]
  179050. [comp_width - dst_blk_x - offset_x - 1];
  179051. for (i = 0; i < DCTSIZE; i++) {
  179052. for (j = 0; j < DCTSIZE; j++)
  179053. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179054. i++;
  179055. for (j = 0; j < DCTSIZE; j++)
  179056. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179057. }
  179058. } else {
  179059. /* At lower right corner, just transpose, no mirroring */
  179060. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179061. for (i = 0; i < DCTSIZE; i++)
  179062. for (j = 0; j < DCTSIZE; j++)
  179063. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179064. }
  179065. }
  179066. }
  179067. }
  179068. }
  179069. }
  179070. }
  179071. }
  179072. /* Request any required workspace.
  179073. *
  179074. * We allocate the workspace virtual arrays from the source decompression
  179075. * object, so that all the arrays (both the original data and the workspace)
  179076. * will be taken into account while making memory management decisions.
  179077. * Hence, this routine must be called after jpeg_read_header (which reads
  179078. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179079. * the source's virtual arrays).
  179080. */
  179081. GLOBAL(void)
  179082. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179083. jpeg_transform_info *info)
  179084. {
  179085. jvirt_barray_ptr *coef_arrays = NULL;
  179086. jpeg_component_info *compptr;
  179087. int ci;
  179088. if (info->force_grayscale &&
  179089. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179090. srcinfo->num_components == 3) {
  179091. /* We'll only process the first component */
  179092. info->num_components = 1;
  179093. } else {
  179094. /* Process all the components */
  179095. info->num_components = srcinfo->num_components;
  179096. }
  179097. switch (info->transform) {
  179098. case JXFORM_NONE:
  179099. case JXFORM_FLIP_H:
  179100. /* Don't need a workspace array */
  179101. break;
  179102. case JXFORM_FLIP_V:
  179103. case JXFORM_ROT_180:
  179104. /* Need workspace arrays having same dimensions as source image.
  179105. * Note that we allocate arrays padded out to the next iMCU boundary,
  179106. * so that transform routines need not worry about missing edge blocks.
  179107. */
  179108. coef_arrays = (jvirt_barray_ptr *)
  179109. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179110. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179111. for (ci = 0; ci < info->num_components; ci++) {
  179112. compptr = srcinfo->comp_info + ci;
  179113. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179114. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179115. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179116. (long) compptr->h_samp_factor),
  179117. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179118. (long) compptr->v_samp_factor),
  179119. (JDIMENSION) compptr->v_samp_factor);
  179120. }
  179121. break;
  179122. case JXFORM_TRANSPOSE:
  179123. case JXFORM_TRANSVERSE:
  179124. case JXFORM_ROT_90:
  179125. case JXFORM_ROT_270:
  179126. /* Need workspace arrays having transposed dimensions.
  179127. * Note that we allocate arrays padded out to the next iMCU boundary,
  179128. * so that transform routines need not worry about missing edge blocks.
  179129. */
  179130. coef_arrays = (jvirt_barray_ptr *)
  179131. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179132. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179133. for (ci = 0; ci < info->num_components; ci++) {
  179134. compptr = srcinfo->comp_info + ci;
  179135. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179136. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179137. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179138. (long) compptr->v_samp_factor),
  179139. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179140. (long) compptr->h_samp_factor),
  179141. (JDIMENSION) compptr->h_samp_factor);
  179142. }
  179143. break;
  179144. }
  179145. info->workspace_coef_arrays = coef_arrays;
  179146. }
  179147. /* Transpose destination image parameters */
  179148. LOCAL(void)
  179149. transpose_critical_parameters (j_compress_ptr dstinfo)
  179150. {
  179151. int tblno, i, j, ci, itemp;
  179152. jpeg_component_info *compptr;
  179153. JQUANT_TBL *qtblptr;
  179154. JDIMENSION dtemp;
  179155. UINT16 qtemp;
  179156. /* Transpose basic image dimensions */
  179157. dtemp = dstinfo->image_width;
  179158. dstinfo->image_width = dstinfo->image_height;
  179159. dstinfo->image_height = dtemp;
  179160. /* Transpose sampling factors */
  179161. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179162. compptr = dstinfo->comp_info + ci;
  179163. itemp = compptr->h_samp_factor;
  179164. compptr->h_samp_factor = compptr->v_samp_factor;
  179165. compptr->v_samp_factor = itemp;
  179166. }
  179167. /* Transpose quantization tables */
  179168. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179169. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179170. if (qtblptr != NULL) {
  179171. for (i = 0; i < DCTSIZE; i++) {
  179172. for (j = 0; j < i; j++) {
  179173. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179174. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179175. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179176. }
  179177. }
  179178. }
  179179. }
  179180. }
  179181. /* Trim off any partial iMCUs on the indicated destination edge */
  179182. LOCAL(void)
  179183. trim_right_edge (j_compress_ptr dstinfo)
  179184. {
  179185. int ci, max_h_samp_factor;
  179186. JDIMENSION MCU_cols;
  179187. /* We have to compute max_h_samp_factor ourselves,
  179188. * because it hasn't been set yet in the destination
  179189. * (and we don't want to use the source's value).
  179190. */
  179191. max_h_samp_factor = 1;
  179192. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179193. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179194. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179195. }
  179196. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179197. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179198. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179199. }
  179200. LOCAL(void)
  179201. trim_bottom_edge (j_compress_ptr dstinfo)
  179202. {
  179203. int ci, max_v_samp_factor;
  179204. JDIMENSION MCU_rows;
  179205. /* We have to compute max_v_samp_factor ourselves,
  179206. * because it hasn't been set yet in the destination
  179207. * (and we don't want to use the source's value).
  179208. */
  179209. max_v_samp_factor = 1;
  179210. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179211. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179212. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179213. }
  179214. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179215. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179216. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179217. }
  179218. /* Adjust output image parameters as needed.
  179219. *
  179220. * This must be called after jpeg_copy_critical_parameters()
  179221. * and before jpeg_write_coefficients().
  179222. *
  179223. * The return value is the set of virtual coefficient arrays to be written
  179224. * (either the ones allocated by jtransform_request_workspace, or the
  179225. * original source data arrays). The caller will need to pass this value
  179226. * to jpeg_write_coefficients().
  179227. */
  179228. GLOBAL(jvirt_barray_ptr *)
  179229. jtransform_adjust_parameters (j_decompress_ptr,
  179230. j_compress_ptr dstinfo,
  179231. jvirt_barray_ptr *src_coef_arrays,
  179232. jpeg_transform_info *info)
  179233. {
  179234. /* If force-to-grayscale is requested, adjust destination parameters */
  179235. if (info->force_grayscale) {
  179236. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179237. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179238. * will get set to 1, which typically won't match the source.
  179239. * In fact we do this even if the source is already grayscale; that
  179240. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179241. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179242. */
  179243. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179244. dstinfo->num_components == 3) ||
  179245. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179246. dstinfo->num_components == 1)) {
  179247. /* We have to preserve the source's quantization table number. */
  179248. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179249. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179250. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179251. } else {
  179252. /* Sorry, can't do it */
  179253. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179254. }
  179255. }
  179256. /* Correct the destination's image dimensions etc if necessary */
  179257. switch (info->transform) {
  179258. case JXFORM_NONE:
  179259. /* Nothing to do */
  179260. break;
  179261. case JXFORM_FLIP_H:
  179262. if (info->trim)
  179263. trim_right_edge(dstinfo);
  179264. break;
  179265. case JXFORM_FLIP_V:
  179266. if (info->trim)
  179267. trim_bottom_edge(dstinfo);
  179268. break;
  179269. case JXFORM_TRANSPOSE:
  179270. transpose_critical_parameters(dstinfo);
  179271. /* transpose does NOT have to trim anything */
  179272. break;
  179273. case JXFORM_TRANSVERSE:
  179274. transpose_critical_parameters(dstinfo);
  179275. if (info->trim) {
  179276. trim_right_edge(dstinfo);
  179277. trim_bottom_edge(dstinfo);
  179278. }
  179279. break;
  179280. case JXFORM_ROT_90:
  179281. transpose_critical_parameters(dstinfo);
  179282. if (info->trim)
  179283. trim_right_edge(dstinfo);
  179284. break;
  179285. case JXFORM_ROT_180:
  179286. if (info->trim) {
  179287. trim_right_edge(dstinfo);
  179288. trim_bottom_edge(dstinfo);
  179289. }
  179290. break;
  179291. case JXFORM_ROT_270:
  179292. transpose_critical_parameters(dstinfo);
  179293. if (info->trim)
  179294. trim_bottom_edge(dstinfo);
  179295. break;
  179296. }
  179297. /* Return the appropriate output data set */
  179298. if (info->workspace_coef_arrays != NULL)
  179299. return info->workspace_coef_arrays;
  179300. return src_coef_arrays;
  179301. }
  179302. /* Execute the actual transformation, if any.
  179303. *
  179304. * This must be called *after* jpeg_write_coefficients, because it depends
  179305. * on jpeg_write_coefficients to have computed subsidiary values such as
  179306. * the per-component width and height fields in the destination object.
  179307. *
  179308. * Note that some transformations will modify the source data arrays!
  179309. */
  179310. GLOBAL(void)
  179311. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179312. j_compress_ptr dstinfo,
  179313. jvirt_barray_ptr *src_coef_arrays,
  179314. jpeg_transform_info *info)
  179315. {
  179316. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179317. switch (info->transform) {
  179318. case JXFORM_NONE:
  179319. break;
  179320. case JXFORM_FLIP_H:
  179321. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179322. break;
  179323. case JXFORM_FLIP_V:
  179324. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179325. break;
  179326. case JXFORM_TRANSPOSE:
  179327. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179328. break;
  179329. case JXFORM_TRANSVERSE:
  179330. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179331. break;
  179332. case JXFORM_ROT_90:
  179333. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179334. break;
  179335. case JXFORM_ROT_180:
  179336. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179337. break;
  179338. case JXFORM_ROT_270:
  179339. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179340. break;
  179341. }
  179342. }
  179343. #endif /* TRANSFORMS_SUPPORTED */
  179344. /* Setup decompression object to save desired markers in memory.
  179345. * This must be called before jpeg_read_header() to have the desired effect.
  179346. */
  179347. GLOBAL(void)
  179348. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179349. {
  179350. #ifdef SAVE_MARKERS_SUPPORTED
  179351. int m;
  179352. /* Save comments except under NONE option */
  179353. if (option != JCOPYOPT_NONE) {
  179354. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179355. }
  179356. /* Save all types of APPn markers iff ALL option */
  179357. if (option == JCOPYOPT_ALL) {
  179358. for (m = 0; m < 16; m++)
  179359. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179360. }
  179361. #endif /* SAVE_MARKERS_SUPPORTED */
  179362. }
  179363. /* Copy markers saved in the given source object to the destination object.
  179364. * This should be called just after jpeg_start_compress() or
  179365. * jpeg_write_coefficients().
  179366. * Note that those routines will have written the SOI, and also the
  179367. * JFIF APP0 or Adobe APP14 markers if selected.
  179368. */
  179369. GLOBAL(void)
  179370. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179371. JCOPY_OPTION)
  179372. {
  179373. jpeg_saved_marker_ptr marker;
  179374. /* In the current implementation, we don't actually need to examine the
  179375. * option flag here; we just copy everything that got saved.
  179376. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179377. * if the encoder library already wrote one.
  179378. */
  179379. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179380. if (dstinfo->write_JFIF_header &&
  179381. marker->marker == JPEG_APP0 &&
  179382. marker->data_length >= 5 &&
  179383. GETJOCTET(marker->data[0]) == 0x4A &&
  179384. GETJOCTET(marker->data[1]) == 0x46 &&
  179385. GETJOCTET(marker->data[2]) == 0x49 &&
  179386. GETJOCTET(marker->data[3]) == 0x46 &&
  179387. GETJOCTET(marker->data[4]) == 0)
  179388. continue; /* reject duplicate JFIF */
  179389. if (dstinfo->write_Adobe_marker &&
  179390. marker->marker == JPEG_APP0+14 &&
  179391. marker->data_length >= 5 &&
  179392. GETJOCTET(marker->data[0]) == 0x41 &&
  179393. GETJOCTET(marker->data[1]) == 0x64 &&
  179394. GETJOCTET(marker->data[2]) == 0x6F &&
  179395. GETJOCTET(marker->data[3]) == 0x62 &&
  179396. GETJOCTET(marker->data[4]) == 0x65)
  179397. continue; /* reject duplicate Adobe */
  179398. #ifdef NEED_FAR_POINTERS
  179399. /* We could use jpeg_write_marker if the data weren't FAR... */
  179400. {
  179401. unsigned int i;
  179402. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179403. for (i = 0; i < marker->data_length; i++)
  179404. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179405. }
  179406. #else
  179407. jpeg_write_marker(dstinfo, marker->marker,
  179408. marker->data, marker->data_length);
  179409. #endif
  179410. }
  179411. }
  179412. /*** End of inlined file: transupp.c ***/
  179413. }
  179414. #else
  179415. #define JPEG_INTERNALS
  179416. #undef FAR
  179417. #include <jpeglib.h>
  179418. #endif
  179419. }
  179420. #undef max
  179421. #undef min
  179422. #if JUCE_MSVC
  179423. #pragma warning (pop)
  179424. #endif
  179425. BEGIN_JUCE_NAMESPACE
  179426. namespace JPEGHelpers
  179427. {
  179428. using namespace jpeglibNamespace;
  179429. #if ! JUCE_MSVC
  179430. using jpeglibNamespace::boolean;
  179431. #endif
  179432. struct JPEGDecodingFailure {};
  179433. static void fatalErrorHandler (j_common_ptr)
  179434. {
  179435. throw JPEGDecodingFailure();
  179436. }
  179437. static void silentErrorCallback1 (j_common_ptr) {}
  179438. static void silentErrorCallback2 (j_common_ptr, int) {}
  179439. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179440. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179441. {
  179442. zerostruct (err);
  179443. err.error_exit = fatalErrorHandler;
  179444. err.emit_message = silentErrorCallback2;
  179445. err.output_message = silentErrorCallback1;
  179446. err.format_message = silentErrorCallback3;
  179447. err.reset_error_mgr = silentErrorCallback1;
  179448. }
  179449. static void dummyCallback1 (j_decompress_ptr)
  179450. {
  179451. }
  179452. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179453. {
  179454. decompStruct->src->next_input_byte += num;
  179455. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179456. decompStruct->src->bytes_in_buffer -= num;
  179457. }
  179458. static boolean jpegFill (j_decompress_ptr)
  179459. {
  179460. return 0;
  179461. }
  179462. static const int jpegBufferSize = 512;
  179463. struct JuceJpegDest : public jpeg_destination_mgr
  179464. {
  179465. OutputStream* output;
  179466. char* buffer;
  179467. };
  179468. static void jpegWriteInit (j_compress_ptr)
  179469. {
  179470. }
  179471. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179472. {
  179473. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179474. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179475. dest->output->write (dest->buffer, (int) numToWrite);
  179476. }
  179477. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179478. {
  179479. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179480. const int numToWrite = jpegBufferSize;
  179481. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179482. dest->free_in_buffer = jpegBufferSize;
  179483. return dest->output->write (dest->buffer, numToWrite);
  179484. }
  179485. }
  179486. JPEGImageFormat::JPEGImageFormat()
  179487. : quality (-1.0f)
  179488. {
  179489. }
  179490. JPEGImageFormat::~JPEGImageFormat() {}
  179491. void JPEGImageFormat::setQuality (const float newQuality)
  179492. {
  179493. quality = newQuality;
  179494. }
  179495. const String JPEGImageFormat::getFormatName()
  179496. {
  179497. return "JPEG";
  179498. }
  179499. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179500. {
  179501. const int bytesNeeded = 10;
  179502. uint8 header [bytesNeeded];
  179503. if (in.read (header, bytesNeeded) == bytesNeeded)
  179504. {
  179505. return header[0] == 0xff
  179506. && header[1] == 0xd8
  179507. && header[2] == 0xff
  179508. && (header[3] == 0xe0 || header[3] == 0xe1);
  179509. }
  179510. return false;
  179511. }
  179512. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179513. {
  179514. using namespace jpeglibNamespace;
  179515. using namespace JPEGHelpers;
  179516. MemoryOutputStream mb;
  179517. mb.writeFromInputStream (in, -1);
  179518. Image image;
  179519. if (mb.getDataSize() > 16)
  179520. {
  179521. struct jpeg_decompress_struct jpegDecompStruct;
  179522. struct jpeg_error_mgr jerr;
  179523. setupSilentErrorHandler (jerr);
  179524. jpegDecompStruct.err = &jerr;
  179525. jpeg_create_decompress (&jpegDecompStruct);
  179526. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179527. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179528. jpegDecompStruct.src->init_source = dummyCallback1;
  179529. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179530. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179531. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179532. jpegDecompStruct.src->term_source = dummyCallback1;
  179533. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179534. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179535. try
  179536. {
  179537. jpeg_read_header (&jpegDecompStruct, TRUE);
  179538. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179539. const int width = jpegDecompStruct.output_width;
  179540. const int height = jpegDecompStruct.output_height;
  179541. jpegDecompStruct.out_color_space = JCS_RGB;
  179542. JSAMPARRAY buffer
  179543. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179544. JPOOL_IMAGE,
  179545. width * 3, 1);
  179546. if (jpeg_start_decompress (&jpegDecompStruct))
  179547. {
  179548. image = Image (Image::RGB, width, height, false);
  179549. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179550. const Image::BitmapData destData (image, true);
  179551. for (int y = 0; y < height; ++y)
  179552. {
  179553. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179554. const uint8* src = *buffer;
  179555. uint8* dest = destData.getLinePointer (y);
  179556. if (hasAlphaChan)
  179557. {
  179558. for (int i = width; --i >= 0;)
  179559. {
  179560. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179561. ((PixelARGB*) dest)->premultiply();
  179562. dest += destData.pixelStride;
  179563. src += 3;
  179564. }
  179565. }
  179566. else
  179567. {
  179568. for (int i = width; --i >= 0;)
  179569. {
  179570. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179571. dest += destData.pixelStride;
  179572. src += 3;
  179573. }
  179574. }
  179575. }
  179576. jpeg_finish_decompress (&jpegDecompStruct);
  179577. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179578. }
  179579. jpeg_destroy_decompress (&jpegDecompStruct);
  179580. }
  179581. catch (...)
  179582. {}
  179583. }
  179584. return image;
  179585. }
  179586. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179587. {
  179588. using namespace jpeglibNamespace;
  179589. using namespace JPEGHelpers;
  179590. if (image.hasAlphaChannel())
  179591. {
  179592. // this method could fill the background in white and still save the image..
  179593. jassertfalse;
  179594. return true;
  179595. }
  179596. struct jpeg_compress_struct jpegCompStruct;
  179597. struct jpeg_error_mgr jerr;
  179598. setupSilentErrorHandler (jerr);
  179599. jpegCompStruct.err = &jerr;
  179600. jpeg_create_compress (&jpegCompStruct);
  179601. JuceJpegDest dest;
  179602. jpegCompStruct.dest = &dest;
  179603. dest.output = &out;
  179604. HeapBlock <char> tempBuffer (jpegBufferSize);
  179605. dest.buffer = tempBuffer;
  179606. dest.next_output_byte = (JOCTET*) dest.buffer;
  179607. dest.free_in_buffer = jpegBufferSize;
  179608. dest.init_destination = jpegWriteInit;
  179609. dest.empty_output_buffer = jpegWriteFlush;
  179610. dest.term_destination = jpegWriteTerminate;
  179611. jpegCompStruct.image_width = image.getWidth();
  179612. jpegCompStruct.image_height = image.getHeight();
  179613. jpegCompStruct.input_components = 3;
  179614. jpegCompStruct.in_color_space = JCS_RGB;
  179615. jpegCompStruct.write_JFIF_header = 1;
  179616. jpegCompStruct.X_density = 72;
  179617. jpegCompStruct.Y_density = 72;
  179618. jpeg_set_defaults (&jpegCompStruct);
  179619. jpegCompStruct.dct_method = JDCT_FLOAT;
  179620. jpegCompStruct.optimize_coding = 1;
  179621. //jpegCompStruct.smoothing_factor = 10;
  179622. if (quality < 0.0f)
  179623. quality = 0.85f;
  179624. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179625. jpeg_start_compress (&jpegCompStruct, TRUE);
  179626. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179627. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179628. JPOOL_IMAGE, strideBytes, 1);
  179629. const Image::BitmapData srcData (image, false);
  179630. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179631. {
  179632. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179633. uint8* dst = *buffer;
  179634. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179635. {
  179636. *dst++ = ((const PixelRGB*) src)->getRed();
  179637. *dst++ = ((const PixelRGB*) src)->getGreen();
  179638. *dst++ = ((const PixelRGB*) src)->getBlue();
  179639. src += srcData.pixelStride;
  179640. }
  179641. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179642. }
  179643. jpeg_finish_compress (&jpegCompStruct);
  179644. jpeg_destroy_compress (&jpegCompStruct);
  179645. out.flush();
  179646. return true;
  179647. }
  179648. END_JUCE_NAMESPACE
  179649. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179650. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179651. #if JUCE_MSVC
  179652. #pragma warning (push)
  179653. #pragma warning (disable: 4390 4611)
  179654. #endif
  179655. namespace zlibNamespace
  179656. {
  179657. #if JUCE_INCLUDE_ZLIB_CODE
  179658. #undef OS_CODE
  179659. #undef fdopen
  179660. #undef OS_CODE
  179661. #else
  179662. #include <zlib.h>
  179663. #endif
  179664. }
  179665. namespace pnglibNamespace
  179666. {
  179667. using namespace zlibNamespace;
  179668. #if JUCE_INCLUDE_PNGLIB_CODE
  179669. #if _MSC_VER != 1310
  179670. using ::calloc; // (causes conflict in VS.NET 2003)
  179671. using ::malloc;
  179672. using ::free;
  179673. #endif
  179674. using ::abs;
  179675. #define PNG_INTERNAL
  179676. #define NO_DUMMY_DECL
  179677. #define PNG_SETJMP_NOT_SUPPORTED
  179678. /*** Start of inlined file: png.h ***/
  179679. /* png.h - header file for PNG reference library
  179680. *
  179681. * libpng version 1.2.21 - October 4, 2007
  179682. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179683. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179684. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179685. *
  179686. * Authors and maintainers:
  179687. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179688. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179689. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179690. * See also "Contributing Authors", below.
  179691. *
  179692. * Note about libpng version numbers:
  179693. *
  179694. * Due to various miscommunications, unforeseen code incompatibilities
  179695. * and occasional factors outside the authors' control, version numbering
  179696. * on the library has not always been consistent and straightforward.
  179697. * The following table summarizes matters since version 0.89c, which was
  179698. * the first widely used release:
  179699. *
  179700. * source png.h png.h shared-lib
  179701. * version string int version
  179702. * ------- ------ ----- ----------
  179703. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179704. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179705. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179706. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179707. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179708. * 0.97c 0.97 97 2.0.97
  179709. * 0.98 0.98 98 2.0.98
  179710. * 0.99 0.99 98 2.0.99
  179711. * 0.99a-m 0.99 99 2.0.99
  179712. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179713. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179714. * 1.0.1 png.h string is 10001 2.1.0
  179715. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179716. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179717. * 1.0.2a-b 10003 version, except as noted.
  179718. * 1.0.3 10003
  179719. * 1.0.3a-d 10004
  179720. * 1.0.4 10004
  179721. * 1.0.4a-f 10005
  179722. * 1.0.5 (+ 2 patches) 10005
  179723. * 1.0.5a-d 10006
  179724. * 1.0.5e-r 10100 (not source compatible)
  179725. * 1.0.5s-v 10006 (not binary compatible)
  179726. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179727. * 1.0.6d-f 10007 (still binary incompatible)
  179728. * 1.0.6g 10007
  179729. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179730. * 1.0.6i 10007 10.6i
  179731. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179732. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179733. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179734. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179735. * 1.0.7 1 10007 (still compatible)
  179736. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179737. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179738. * 1.0.8 1 10008 2.1.0.8
  179739. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179740. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179741. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179742. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179743. * 1.0.9 1 10009 2.1.0.9
  179744. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179745. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179746. * 1.0.10 1 10010 2.1.0.10
  179747. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179748. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179749. * 1.0.11 1 10011 2.1.0.11
  179750. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179751. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179752. * 1.0.12 2 10012 2.1.0.12
  179753. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179754. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179755. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179756. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179757. * 1.2.0 3 10200 3.1.2.0
  179758. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179759. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179760. * 1.2.1 3 10201 3.1.2.1
  179761. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179762. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179763. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179764. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179765. * 1.0.13 10 10013 10.so.0.1.0.13
  179766. * 1.2.2 12 10202 12.so.0.1.2.2
  179767. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179768. * 1.2.3 12 10203 12.so.0.1.2.3
  179769. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179770. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179771. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179772. * 1.0.14 10 10014 10.so.0.1.0.14
  179773. * 1.2.4 13 10204 12.so.0.1.2.4
  179774. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179775. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179776. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179777. * 1.0.15 10 10015 10.so.0.1.0.15
  179778. * 1.2.5 13 10205 12.so.0.1.2.5
  179779. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179780. * 1.0.16 10 10016 10.so.0.1.0.16
  179781. * 1.2.6 13 10206 12.so.0.1.2.6
  179782. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179783. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179784. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179785. * 1.0.17 10 10017 10.so.0.1.0.17
  179786. * 1.2.7 13 10207 12.so.0.1.2.7
  179787. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179788. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179789. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179790. * 1.0.18 10 10018 10.so.0.1.0.18
  179791. * 1.2.8 13 10208 12.so.0.1.2.8
  179792. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179793. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179794. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179795. * 1.2.9 13 10209 12.so.0.9[.0]
  179796. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179797. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179798. * 1.2.10 13 10210 12.so.0.10[.0]
  179799. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179800. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179801. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179802. * 1.0.19 10 10019 10.so.0.19[.0]
  179803. * 1.2.11 13 10211 12.so.0.11[.0]
  179804. * 1.0.20 10 10020 10.so.0.20[.0]
  179805. * 1.2.12 13 10212 12.so.0.12[.0]
  179806. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179807. * 1.0.21 10 10021 10.so.0.21[.0]
  179808. * 1.2.13 13 10213 12.so.0.13[.0]
  179809. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179810. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179811. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179812. * 1.0.22 10 10022 10.so.0.22[.0]
  179813. * 1.2.14 13 10214 12.so.0.14[.0]
  179814. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179815. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179816. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179817. * 1.0.23 10 10023 10.so.0.23[.0]
  179818. * 1.2.15 13 10215 12.so.0.15[.0]
  179819. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179820. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179821. * 1.0.24 10 10024 10.so.0.24[.0]
  179822. * 1.2.16 13 10216 12.so.0.16[.0]
  179823. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179824. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179825. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179826. * 1.0.25 10 10025 10.so.0.25[.0]
  179827. * 1.2.17 13 10217 12.so.0.17[.0]
  179828. * 1.0.26 10 10026 10.so.0.26[.0]
  179829. * 1.2.18 13 10218 12.so.0.18[.0]
  179830. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179831. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179832. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179833. * 1.0.27 10 10027 10.so.0.27[.0]
  179834. * 1.2.19 13 10219 12.so.0.19[.0]
  179835. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179836. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179837. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179838. * 1.0.28 10 10028 10.so.0.28[.0]
  179839. * 1.2.20 13 10220 12.so.0.20[.0]
  179840. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179841. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179842. * 1.0.29 10 10029 10.so.0.29[.0]
  179843. * 1.2.21 13 10221 12.so.0.21[.0]
  179844. *
  179845. * Henceforth the source version will match the shared-library major
  179846. * and minor numbers; the shared-library major version number will be
  179847. * used for changes in backward compatibility, as it is intended. The
  179848. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179849. * for applications, is an unsigned integer of the form xyyzz corresponding
  179850. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179851. * were given the previous public release number plus a letter, until
  179852. * version 1.0.6j; from then on they were given the upcoming public
  179853. * release number plus "betaNN" or "rcN".
  179854. *
  179855. * Binary incompatibility exists only when applications make direct access
  179856. * to the info_ptr or png_ptr members through png.h, and the compiled
  179857. * application is loaded with a different version of the library.
  179858. *
  179859. * DLLNUM will change each time there are forward or backward changes
  179860. * in binary compatibility (e.g., when a new feature is added).
  179861. *
  179862. * See libpng.txt or libpng.3 for more information. The PNG specification
  179863. * is available as a W3C Recommendation and as an ISO Specification,
  179864. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179865. */
  179866. /*
  179867. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179868. *
  179869. * If you modify libpng you may insert additional notices immediately following
  179870. * this sentence.
  179871. *
  179872. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179873. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179874. * distributed according to the same disclaimer and license as libpng-1.2.5
  179875. * with the following individual added to the list of Contributing Authors:
  179876. *
  179877. * Cosmin Truta
  179878. *
  179879. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179880. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179881. * distributed according to the same disclaimer and license as libpng-1.0.6
  179882. * with the following individuals added to the list of Contributing Authors:
  179883. *
  179884. * Simon-Pierre Cadieux
  179885. * Eric S. Raymond
  179886. * Gilles Vollant
  179887. *
  179888. * and with the following additions to the disclaimer:
  179889. *
  179890. * There is no warranty against interference with your enjoyment of the
  179891. * library or against infringement. There is no warranty that our
  179892. * efforts or the library will fulfill any of your particular purposes
  179893. * or needs. This library is provided with all faults, and the entire
  179894. * risk of satisfactory quality, performance, accuracy, and effort is with
  179895. * the user.
  179896. *
  179897. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179898. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179899. * distributed according to the same disclaimer and license as libpng-0.96,
  179900. * with the following individuals added to the list of Contributing Authors:
  179901. *
  179902. * Tom Lane
  179903. * Glenn Randers-Pehrson
  179904. * Willem van Schaik
  179905. *
  179906. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179907. * Copyright (c) 1996, 1997 Andreas Dilger
  179908. * Distributed according to the same disclaimer and license as libpng-0.88,
  179909. * with the following individuals added to the list of Contributing Authors:
  179910. *
  179911. * John Bowler
  179912. * Kevin Bracey
  179913. * Sam Bushell
  179914. * Magnus Holmgren
  179915. * Greg Roelofs
  179916. * Tom Tanner
  179917. *
  179918. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179919. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179920. *
  179921. * For the purposes of this copyright and license, "Contributing Authors"
  179922. * is defined as the following set of individuals:
  179923. *
  179924. * Andreas Dilger
  179925. * Dave Martindale
  179926. * Guy Eric Schalnat
  179927. * Paul Schmidt
  179928. * Tim Wegner
  179929. *
  179930. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179931. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179932. * including, without limitation, the warranties of merchantability and of
  179933. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179934. * assume no liability for direct, indirect, incidental, special, exemplary,
  179935. * or consequential damages, which may result from the use of the PNG
  179936. * Reference Library, even if advised of the possibility of such damage.
  179937. *
  179938. * Permission is hereby granted to use, copy, modify, and distribute this
  179939. * source code, or portions hereof, for any purpose, without fee, subject
  179940. * to the following restrictions:
  179941. *
  179942. * 1. The origin of this source code must not be misrepresented.
  179943. *
  179944. * 2. Altered versions must be plainly marked as such and
  179945. * must not be misrepresented as being the original source.
  179946. *
  179947. * 3. This Copyright notice may not be removed or altered from
  179948. * any source or altered source distribution.
  179949. *
  179950. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179951. * fee, and encourage the use of this source code as a component to
  179952. * supporting the PNG file format in commercial products. If you use this
  179953. * source code in a product, acknowledgment is not required but would be
  179954. * appreciated.
  179955. */
  179956. /*
  179957. * A "png_get_copyright" function is available, for convenient use in "about"
  179958. * boxes and the like:
  179959. *
  179960. * printf("%s",png_get_copyright(NULL));
  179961. *
  179962. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179963. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179964. */
  179965. /*
  179966. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179967. * certification mark of the Open Source Initiative.
  179968. */
  179969. /*
  179970. * The contributing authors would like to thank all those who helped
  179971. * with testing, bug fixes, and patience. This wouldn't have been
  179972. * possible without all of you.
  179973. *
  179974. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179975. */
  179976. /*
  179977. * Y2K compliance in libpng:
  179978. * =========================
  179979. *
  179980. * October 4, 2007
  179981. *
  179982. * Since the PNG Development group is an ad-hoc body, we can't make
  179983. * an official declaration.
  179984. *
  179985. * This is your unofficial assurance that libpng from version 0.71 and
  179986. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179987. * versions were also Y2K compliant.
  179988. *
  179989. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179990. * that will hold years up to 65535. The other two hold the date in text
  179991. * format, and will hold years up to 9999.
  179992. *
  179993. * The integer is
  179994. * "png_uint_16 year" in png_time_struct.
  179995. *
  179996. * The strings are
  179997. * "png_charp time_buffer" in png_struct and
  179998. * "near_time_buffer", which is a local character string in png.c.
  179999. *
  180000. * There are seven time-related functions:
  180001. * png.c: png_convert_to_rfc_1123() in png.c
  180002. * (formerly png_convert_to_rfc_1152() in error)
  180003. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180004. * png_convert_from_time_t() in pngwrite.c
  180005. * png_get_tIME() in pngget.c
  180006. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180007. * png_set_tIME() in pngset.c
  180008. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180009. *
  180010. * All handle dates properly in a Y2K environment. The
  180011. * png_convert_from_time_t() function calls gmtime() to convert from system
  180012. * clock time, which returns (year - 1900), which we properly convert to
  180013. * the full 4-digit year. There is a possibility that applications using
  180014. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180015. * function, or that they are incorrectly passing only a 2-digit year
  180016. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180017. * but this is not under our control. The libpng documentation has always
  180018. * stated that it works with 4-digit years, and the APIs have been
  180019. * documented as such.
  180020. *
  180021. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180022. * integer to hold the year, and can hold years as large as 65535.
  180023. *
  180024. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180025. * no date-related code.
  180026. *
  180027. * Glenn Randers-Pehrson
  180028. * libpng maintainer
  180029. * PNG Development Group
  180030. */
  180031. #ifndef PNG_H
  180032. #define PNG_H
  180033. /* This is not the place to learn how to use libpng. The file libpng.txt
  180034. * describes how to use libpng, and the file example.c summarizes it
  180035. * with some code on which to build. This file is useful for looking
  180036. * at the actual function definitions and structure components.
  180037. */
  180038. /* Version information for png.h - this should match the version in png.c */
  180039. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180040. #define PNG_HEADER_VERSION_STRING \
  180041. " libpng version 1.2.21 - October 4, 2007\n"
  180042. #define PNG_LIBPNG_VER_SONUM 0
  180043. #define PNG_LIBPNG_VER_DLLNUM 13
  180044. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180045. #define PNG_LIBPNG_VER_MAJOR 1
  180046. #define PNG_LIBPNG_VER_MINOR 2
  180047. #define PNG_LIBPNG_VER_RELEASE 21
  180048. /* This should match the numeric part of the final component of
  180049. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180050. #define PNG_LIBPNG_VER_BUILD 0
  180051. /* Release Status */
  180052. #define PNG_LIBPNG_BUILD_ALPHA 1
  180053. #define PNG_LIBPNG_BUILD_BETA 2
  180054. #define PNG_LIBPNG_BUILD_RC 3
  180055. #define PNG_LIBPNG_BUILD_STABLE 4
  180056. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180057. /* Release-Specific Flags */
  180058. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180059. PNG_LIBPNG_BUILD_STABLE only */
  180060. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180061. PNG_LIBPNG_BUILD_SPECIAL */
  180062. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180063. PNG_LIBPNG_BUILD_PRIVATE */
  180064. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180065. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180066. * We must not include leading zeros.
  180067. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180068. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180069. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180070. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180071. #ifndef PNG_VERSION_INFO_ONLY
  180072. /* include the compression library's header */
  180073. #endif
  180074. /* include all user configurable info, including optional assembler routines */
  180075. /*** Start of inlined file: pngconf.h ***/
  180076. /* pngconf.h - machine configurable file for libpng
  180077. *
  180078. * libpng version 1.2.21 - October 4, 2007
  180079. * For conditions of distribution and use, see copyright notice in png.h
  180080. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180081. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180082. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180083. */
  180084. /* Any machine specific code is near the front of this file, so if you
  180085. * are configuring libpng for a machine, you may want to read the section
  180086. * starting here down to where it starts to typedef png_color, png_text,
  180087. * and png_info.
  180088. */
  180089. #ifndef PNGCONF_H
  180090. #define PNGCONF_H
  180091. #define PNG_1_2_X
  180092. // These are some Juce config settings that should remove any unnecessary code bloat..
  180093. #define PNG_NO_STDIO 1
  180094. #define PNG_DEBUG 0
  180095. #define PNG_NO_WARNINGS 1
  180096. #define PNG_NO_ERROR_TEXT 1
  180097. #define PNG_NO_ERROR_NUMBERS 1
  180098. #define PNG_NO_USER_MEM 1
  180099. #define PNG_NO_READ_iCCP 1
  180100. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180101. #define PNG_NO_READ_USER_CHUNKS 1
  180102. #define PNG_NO_READ_iTXt 1
  180103. #define PNG_NO_READ_sCAL 1
  180104. #define PNG_NO_READ_sPLT 1
  180105. #define png_error(a, b) png_err(a)
  180106. #define png_warning(a, b)
  180107. #define png_chunk_error(a, b) png_err(a)
  180108. #define png_chunk_warning(a, b)
  180109. /*
  180110. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180111. * includes the resource compiler for Windows DLL configurations.
  180112. */
  180113. #ifdef PNG_USER_CONFIG
  180114. # ifndef PNG_USER_PRIVATEBUILD
  180115. # define PNG_USER_PRIVATEBUILD
  180116. # endif
  180117. #include "pngusr.h"
  180118. #endif
  180119. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180120. #ifdef PNG_CONFIGURE_LIBPNG
  180121. #ifdef HAVE_CONFIG_H
  180122. #include "config.h"
  180123. #endif
  180124. #endif
  180125. /*
  180126. * Added at libpng-1.2.8
  180127. *
  180128. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180129. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180130. * the DLL was built>
  180131. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180132. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180133. * distinguish your DLL from those of the official release. These
  180134. * correspond to the trailing letters that come after the version
  180135. * number and must match your private DLL name>
  180136. * e.g. // private DLL "libpng13gx.dll"
  180137. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180138. *
  180139. * The following macros are also at your disposal if you want to complete the
  180140. * DLL VERSIONINFO structure.
  180141. * - PNG_USER_VERSIONINFO_COMMENTS
  180142. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180143. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180144. */
  180145. #ifdef __STDC__
  180146. #ifdef SPECIALBUILD
  180147. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180148. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180149. #endif
  180150. #ifdef PRIVATEBUILD
  180151. # pragma message("PRIVATEBUILD is deprecated.\
  180152. Use PNG_USER_PRIVATEBUILD instead.")
  180153. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180154. #endif
  180155. #endif /* __STDC__ */
  180156. #ifndef PNG_VERSION_INFO_ONLY
  180157. /* End of material added to libpng-1.2.8 */
  180158. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180159. Restored at libpng-1.2.21 */
  180160. # define PNG_WARN_UNINITIALIZED_ROW 1
  180161. /* End of material added at libpng-1.2.19/1.2.21 */
  180162. /* This is the size of the compression buffer, and thus the size of
  180163. * an IDAT chunk. Make this whatever size you feel is best for your
  180164. * machine. One of these will be allocated per png_struct. When this
  180165. * is full, it writes the data to the disk, and does some other
  180166. * calculations. Making this an extremely small size will slow
  180167. * the library down, but you may want to experiment to determine
  180168. * where it becomes significant, if you are concerned with memory
  180169. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180170. * this describes the size of the buffer available to read the data in.
  180171. * Unless this gets smaller than the size of a row (compressed),
  180172. * it should not make much difference how big this is.
  180173. */
  180174. #ifndef PNG_ZBUF_SIZE
  180175. # define PNG_ZBUF_SIZE 8192
  180176. #endif
  180177. /* Enable if you want a write-only libpng */
  180178. #ifndef PNG_NO_READ_SUPPORTED
  180179. # define PNG_READ_SUPPORTED
  180180. #endif
  180181. /* Enable if you want a read-only libpng */
  180182. #ifndef PNG_NO_WRITE_SUPPORTED
  180183. # define PNG_WRITE_SUPPORTED
  180184. #endif
  180185. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180186. support PNGs that are embedded in MNG datastreams */
  180187. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180188. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180189. # define PNG_MNG_FEATURES_SUPPORTED
  180190. # endif
  180191. #endif
  180192. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180193. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180194. # define PNG_FLOATING_POINT_SUPPORTED
  180195. # endif
  180196. #endif
  180197. /* If you are running on a machine where you cannot allocate more
  180198. * than 64K of memory at once, uncomment this. While libpng will not
  180199. * normally need that much memory in a chunk (unless you load up a very
  180200. * large file), zlib needs to know how big of a chunk it can use, and
  180201. * libpng thus makes sure to check any memory allocation to verify it
  180202. * will fit into memory.
  180203. #define PNG_MAX_MALLOC_64K
  180204. */
  180205. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180206. # define PNG_MAX_MALLOC_64K
  180207. #endif
  180208. /* Special munging to support doing things the 'cygwin' way:
  180209. * 'Normal' png-on-win32 defines/defaults:
  180210. * PNG_BUILD_DLL -- building dll
  180211. * PNG_USE_DLL -- building an application, linking to dll
  180212. * (no define) -- building static library, or building an
  180213. * application and linking to the static lib
  180214. * 'Cygwin' defines/defaults:
  180215. * PNG_BUILD_DLL -- (ignored) building the dll
  180216. * (no define) -- (ignored) building an application, linking to the dll
  180217. * PNG_STATIC -- (ignored) building the static lib, or building an
  180218. * application that links to the static lib.
  180219. * ALL_STATIC -- (ignored) building various static libs, or building an
  180220. * application that links to the static libs.
  180221. * Thus,
  180222. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180223. * this bit of #ifdefs will define the 'correct' config variables based on
  180224. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180225. * unnecessary.
  180226. *
  180227. * Also, the precedence order is:
  180228. * ALL_STATIC (since we can't #undef something outside our namespace)
  180229. * PNG_BUILD_DLL
  180230. * PNG_STATIC
  180231. * (nothing) == PNG_USE_DLL
  180232. *
  180233. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180234. * of auto-import in binutils, we no longer need to worry about
  180235. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180236. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180237. * to __declspec() stuff. However, we DO need to worry about
  180238. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180239. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180240. */
  180241. #if defined(__CYGWIN__)
  180242. # if defined(ALL_STATIC)
  180243. # if defined(PNG_BUILD_DLL)
  180244. # undef PNG_BUILD_DLL
  180245. # endif
  180246. # if defined(PNG_USE_DLL)
  180247. # undef PNG_USE_DLL
  180248. # endif
  180249. # if defined(PNG_DLL)
  180250. # undef PNG_DLL
  180251. # endif
  180252. # if !defined(PNG_STATIC)
  180253. # define PNG_STATIC
  180254. # endif
  180255. # else
  180256. # if defined (PNG_BUILD_DLL)
  180257. # if defined(PNG_STATIC)
  180258. # undef PNG_STATIC
  180259. # endif
  180260. # if defined(PNG_USE_DLL)
  180261. # undef PNG_USE_DLL
  180262. # endif
  180263. # if !defined(PNG_DLL)
  180264. # define PNG_DLL
  180265. # endif
  180266. # else
  180267. # if defined(PNG_STATIC)
  180268. # if defined(PNG_USE_DLL)
  180269. # undef PNG_USE_DLL
  180270. # endif
  180271. # if defined(PNG_DLL)
  180272. # undef PNG_DLL
  180273. # endif
  180274. # else
  180275. # if !defined(PNG_USE_DLL)
  180276. # define PNG_USE_DLL
  180277. # endif
  180278. # if !defined(PNG_DLL)
  180279. # define PNG_DLL
  180280. # endif
  180281. # endif
  180282. # endif
  180283. # endif
  180284. #endif
  180285. /* This protects us against compilers that run on a windowing system
  180286. * and thus don't have or would rather us not use the stdio types:
  180287. * stdin, stdout, and stderr. The only one currently used is stderr
  180288. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180289. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180290. * will also prevent these, plus will prevent the entire set of stdio
  180291. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180292. * unless (PNG_DEBUG > 0) has been #defined.
  180293. *
  180294. * #define PNG_NO_CONSOLE_IO
  180295. * #define PNG_NO_STDIO
  180296. */
  180297. #if defined(_WIN32_WCE)
  180298. # include <windows.h>
  180299. /* Console I/O functions are not supported on WindowsCE */
  180300. # define PNG_NO_CONSOLE_IO
  180301. # ifdef PNG_DEBUG
  180302. # undef PNG_DEBUG
  180303. # endif
  180304. #endif
  180305. #ifdef PNG_BUILD_DLL
  180306. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180307. # ifndef PNG_NO_CONSOLE_IO
  180308. # define PNG_NO_CONSOLE_IO
  180309. # endif
  180310. # endif
  180311. #endif
  180312. # ifdef PNG_NO_STDIO
  180313. # ifndef PNG_NO_CONSOLE_IO
  180314. # define PNG_NO_CONSOLE_IO
  180315. # endif
  180316. # ifdef PNG_DEBUG
  180317. # if (PNG_DEBUG > 0)
  180318. # include <stdio.h>
  180319. # endif
  180320. # endif
  180321. # else
  180322. # if !defined(_WIN32_WCE)
  180323. /* "stdio.h" functions are not supported on WindowsCE */
  180324. # include <stdio.h>
  180325. # endif
  180326. # endif
  180327. /* This macro protects us against machines that don't have function
  180328. * prototypes (ie K&R style headers). If your compiler does not handle
  180329. * function prototypes, define this macro and use the included ansi2knr.
  180330. * I've always been able to use _NO_PROTO as the indicator, but you may
  180331. * need to drag the empty declaration out in front of here, or change the
  180332. * ifdef to suit your own needs.
  180333. */
  180334. #ifndef PNGARG
  180335. #ifdef OF /* zlib prototype munger */
  180336. # define PNGARG(arglist) OF(arglist)
  180337. #else
  180338. #ifdef _NO_PROTO
  180339. # define PNGARG(arglist) ()
  180340. # ifndef PNG_TYPECAST_NULL
  180341. # define PNG_TYPECAST_NULL
  180342. # endif
  180343. #else
  180344. # define PNGARG(arglist) arglist
  180345. #endif /* _NO_PROTO */
  180346. #endif /* OF */
  180347. #endif /* PNGARG */
  180348. /* Try to determine if we are compiling on a Mac. Note that testing for
  180349. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180350. * on non-Mac platforms.
  180351. */
  180352. #ifndef MACOS
  180353. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180354. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180355. # define MACOS
  180356. # endif
  180357. #endif
  180358. /* enough people need this for various reasons to include it here */
  180359. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180360. # include <sys/types.h>
  180361. #endif
  180362. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180363. # define PNG_SETJMP_SUPPORTED
  180364. #endif
  180365. #ifdef PNG_SETJMP_SUPPORTED
  180366. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180367. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180368. */
  180369. # ifdef __linux__
  180370. # ifdef _BSD_SOURCE
  180371. # define PNG_SAVE_BSD_SOURCE
  180372. # undef _BSD_SOURCE
  180373. # endif
  180374. # ifdef _SETJMP_H
  180375. /* If you encounter a compiler error here, see the explanation
  180376. * near the end of INSTALL.
  180377. */
  180378. __png.h__ already includes setjmp.h;
  180379. __dont__ include it again.;
  180380. # endif
  180381. # endif /* __linux__ */
  180382. /* include setjmp.h for error handling */
  180383. # include <setjmp.h>
  180384. # ifdef __linux__
  180385. # ifdef PNG_SAVE_BSD_SOURCE
  180386. # define _BSD_SOURCE
  180387. # undef PNG_SAVE_BSD_SOURCE
  180388. # endif
  180389. # endif /* __linux__ */
  180390. #endif /* PNG_SETJMP_SUPPORTED */
  180391. #ifdef BSD
  180392. #if ! JUCE_MAC
  180393. # include <strings.h>
  180394. #endif
  180395. #else
  180396. # include <string.h>
  180397. #endif
  180398. /* Other defines for things like memory and the like can go here. */
  180399. #ifdef PNG_INTERNAL
  180400. #include <stdlib.h>
  180401. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180402. * aren't usually used outside the library (as far as I know), so it is
  180403. * debatable if they should be exported at all. In the future, when it is
  180404. * possible to have run-time registry of chunk-handling functions, some of
  180405. * these will be made available again.
  180406. #define PNG_EXTERN extern
  180407. */
  180408. #define PNG_EXTERN
  180409. /* Other defines specific to compilers can go here. Try to keep
  180410. * them inside an appropriate ifdef/endif pair for portability.
  180411. */
  180412. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180413. # if defined(MACOS)
  180414. /* We need to check that <math.h> hasn't already been included earlier
  180415. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180416. * <fp.h> if possible.
  180417. */
  180418. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180419. # include <fp.h>
  180420. # endif
  180421. # else
  180422. # include <math.h>
  180423. # endif
  180424. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180425. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180426. * MATH=68881
  180427. */
  180428. # include <m68881.h>
  180429. # endif
  180430. #endif
  180431. /* Codewarrior on NT has linking problems without this. */
  180432. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180433. # define PNG_ALWAYS_EXTERN
  180434. #endif
  180435. /* This provides the non-ANSI (far) memory allocation routines. */
  180436. #if defined(__TURBOC__) && defined(__MSDOS__)
  180437. # include <mem.h>
  180438. # include <alloc.h>
  180439. #endif
  180440. /* I have no idea why is this necessary... */
  180441. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180442. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180443. # include <malloc.h>
  180444. #endif
  180445. /* This controls how fine the dithering gets. As this allocates
  180446. * a largish chunk of memory (32K), those who are not as concerned
  180447. * with dithering quality can decrease some or all of these.
  180448. */
  180449. #ifndef PNG_DITHER_RED_BITS
  180450. # define PNG_DITHER_RED_BITS 5
  180451. #endif
  180452. #ifndef PNG_DITHER_GREEN_BITS
  180453. # define PNG_DITHER_GREEN_BITS 5
  180454. #endif
  180455. #ifndef PNG_DITHER_BLUE_BITS
  180456. # define PNG_DITHER_BLUE_BITS 5
  180457. #endif
  180458. /* This controls how fine the gamma correction becomes when you
  180459. * are only interested in 8 bits anyway. Increasing this value
  180460. * results in more memory being used, and more pow() functions
  180461. * being called to fill in the gamma tables. Don't set this value
  180462. * less then 8, and even that may not work (I haven't tested it).
  180463. */
  180464. #ifndef PNG_MAX_GAMMA_8
  180465. # define PNG_MAX_GAMMA_8 11
  180466. #endif
  180467. /* This controls how much a difference in gamma we can tolerate before
  180468. * we actually start doing gamma conversion.
  180469. */
  180470. #ifndef PNG_GAMMA_THRESHOLD
  180471. # define PNG_GAMMA_THRESHOLD 0.05
  180472. #endif
  180473. #endif /* PNG_INTERNAL */
  180474. /* The following uses const char * instead of char * for error
  180475. * and warning message functions, so some compilers won't complain.
  180476. * If you do not want to use const, define PNG_NO_CONST here.
  180477. */
  180478. #ifndef PNG_NO_CONST
  180479. # define PNG_CONST const
  180480. #else
  180481. # define PNG_CONST
  180482. #endif
  180483. /* The following defines give you the ability to remove code from the
  180484. * library that you will not be using. I wish I could figure out how to
  180485. * automate this, but I can't do that without making it seriously hard
  180486. * on the users. So if you are not using an ability, change the #define
  180487. * to and #undef, and that part of the library will not be compiled. If
  180488. * your linker can't find a function, you may want to make sure the
  180489. * ability is defined here. Some of these depend upon some others being
  180490. * defined. I haven't figured out all the interactions here, so you may
  180491. * have to experiment awhile to get everything to compile. If you are
  180492. * creating or using a shared library, you probably shouldn't touch this,
  180493. * as it will affect the size of the structures, and this will cause bad
  180494. * things to happen if the library and/or application ever change.
  180495. */
  180496. /* Any features you will not be using can be undef'ed here */
  180497. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180498. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180499. * on the compile line, then pick and choose which ones to define without
  180500. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180501. * if you only want to have a png-compliant reader/writer but don't need
  180502. * any of the extra transformations. This saves about 80 kbytes in a
  180503. * typical installation of the library. (PNG_NO_* form added in version
  180504. * 1.0.1c, for consistency)
  180505. */
  180506. /* The size of the png_text structure changed in libpng-1.0.6 when
  180507. * iTXt support was added. iTXt support was turned off by default through
  180508. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180509. * instead of calling png_set_text() and letting libpng malloc it. It
  180510. * was turned on by default in libpng-1.3.0.
  180511. */
  180512. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180513. # ifndef PNG_NO_iTXt_SUPPORTED
  180514. # define PNG_NO_iTXt_SUPPORTED
  180515. # endif
  180516. # ifndef PNG_NO_READ_iTXt
  180517. # define PNG_NO_READ_iTXt
  180518. # endif
  180519. # ifndef PNG_NO_WRITE_iTXt
  180520. # define PNG_NO_WRITE_iTXt
  180521. # endif
  180522. #endif
  180523. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180524. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180525. # define PNG_READ_iTXt
  180526. # endif
  180527. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180528. # define PNG_WRITE_iTXt
  180529. # endif
  180530. #endif
  180531. /* The following support, added after version 1.0.0, can be turned off here en
  180532. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180533. * with old applications that require the length of png_struct and png_info
  180534. * to remain unchanged.
  180535. */
  180536. #ifdef PNG_LEGACY_SUPPORTED
  180537. # define PNG_NO_FREE_ME
  180538. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180539. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180540. # define PNG_NO_READ_USER_CHUNKS
  180541. # define PNG_NO_READ_iCCP
  180542. # define PNG_NO_WRITE_iCCP
  180543. # define PNG_NO_READ_iTXt
  180544. # define PNG_NO_WRITE_iTXt
  180545. # define PNG_NO_READ_sCAL
  180546. # define PNG_NO_WRITE_sCAL
  180547. # define PNG_NO_READ_sPLT
  180548. # define PNG_NO_WRITE_sPLT
  180549. # define PNG_NO_INFO_IMAGE
  180550. # define PNG_NO_READ_RGB_TO_GRAY
  180551. # define PNG_NO_READ_USER_TRANSFORM
  180552. # define PNG_NO_WRITE_USER_TRANSFORM
  180553. # define PNG_NO_USER_MEM
  180554. # define PNG_NO_READ_EMPTY_PLTE
  180555. # define PNG_NO_MNG_FEATURES
  180556. # define PNG_NO_FIXED_POINT_SUPPORTED
  180557. #endif
  180558. /* Ignore attempt to turn off both floating and fixed point support */
  180559. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180560. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180561. # define PNG_FIXED_POINT_SUPPORTED
  180562. #endif
  180563. #ifndef PNG_NO_FREE_ME
  180564. # define PNG_FREE_ME_SUPPORTED
  180565. #endif
  180566. #if defined(PNG_READ_SUPPORTED)
  180567. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180568. !defined(PNG_NO_READ_TRANSFORMS)
  180569. # define PNG_READ_TRANSFORMS_SUPPORTED
  180570. #endif
  180571. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180572. # ifndef PNG_NO_READ_EXPAND
  180573. # define PNG_READ_EXPAND_SUPPORTED
  180574. # endif
  180575. # ifndef PNG_NO_READ_SHIFT
  180576. # define PNG_READ_SHIFT_SUPPORTED
  180577. # endif
  180578. # ifndef PNG_NO_READ_PACK
  180579. # define PNG_READ_PACK_SUPPORTED
  180580. # endif
  180581. # ifndef PNG_NO_READ_BGR
  180582. # define PNG_READ_BGR_SUPPORTED
  180583. # endif
  180584. # ifndef PNG_NO_READ_SWAP
  180585. # define PNG_READ_SWAP_SUPPORTED
  180586. # endif
  180587. # ifndef PNG_NO_READ_PACKSWAP
  180588. # define PNG_READ_PACKSWAP_SUPPORTED
  180589. # endif
  180590. # ifndef PNG_NO_READ_INVERT
  180591. # define PNG_READ_INVERT_SUPPORTED
  180592. # endif
  180593. # ifndef PNG_NO_READ_DITHER
  180594. # define PNG_READ_DITHER_SUPPORTED
  180595. # endif
  180596. # ifndef PNG_NO_READ_BACKGROUND
  180597. # define PNG_READ_BACKGROUND_SUPPORTED
  180598. # endif
  180599. # ifndef PNG_NO_READ_16_TO_8
  180600. # define PNG_READ_16_TO_8_SUPPORTED
  180601. # endif
  180602. # ifndef PNG_NO_READ_FILLER
  180603. # define PNG_READ_FILLER_SUPPORTED
  180604. # endif
  180605. # ifndef PNG_NO_READ_GAMMA
  180606. # define PNG_READ_GAMMA_SUPPORTED
  180607. # endif
  180608. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180609. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180610. # endif
  180611. # ifndef PNG_NO_READ_SWAP_ALPHA
  180612. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180613. # endif
  180614. # ifndef PNG_NO_READ_INVERT_ALPHA
  180615. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180616. # endif
  180617. # ifndef PNG_NO_READ_STRIP_ALPHA
  180618. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180619. # endif
  180620. # ifndef PNG_NO_READ_USER_TRANSFORM
  180621. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180622. # endif
  180623. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180624. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180625. # endif
  180626. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180627. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180628. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180629. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180630. #endif /* about interlacing capability! You'll */
  180631. /* still have interlacing unless you change the following line: */
  180632. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180633. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180634. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180635. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180636. # endif
  180637. #endif
  180638. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180639. /* Deprecated, will be removed from version 2.0.0.
  180640. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180641. #ifndef PNG_NO_READ_EMPTY_PLTE
  180642. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180643. #endif
  180644. #endif
  180645. #endif /* PNG_READ_SUPPORTED */
  180646. #if defined(PNG_WRITE_SUPPORTED)
  180647. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180648. !defined(PNG_NO_WRITE_TRANSFORMS)
  180649. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180650. #endif
  180651. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180652. # ifndef PNG_NO_WRITE_SHIFT
  180653. # define PNG_WRITE_SHIFT_SUPPORTED
  180654. # endif
  180655. # ifndef PNG_NO_WRITE_PACK
  180656. # define PNG_WRITE_PACK_SUPPORTED
  180657. # endif
  180658. # ifndef PNG_NO_WRITE_BGR
  180659. # define PNG_WRITE_BGR_SUPPORTED
  180660. # endif
  180661. # ifndef PNG_NO_WRITE_SWAP
  180662. # define PNG_WRITE_SWAP_SUPPORTED
  180663. # endif
  180664. # ifndef PNG_NO_WRITE_PACKSWAP
  180665. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180666. # endif
  180667. # ifndef PNG_NO_WRITE_INVERT
  180668. # define PNG_WRITE_INVERT_SUPPORTED
  180669. # endif
  180670. # ifndef PNG_NO_WRITE_FILLER
  180671. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180672. # endif
  180673. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180674. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180675. # endif
  180676. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180677. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180678. # endif
  180679. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180680. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180681. # endif
  180682. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180683. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180684. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180685. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180686. encoders, but can cause trouble
  180687. if left undefined */
  180688. #endif
  180689. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180690. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180691. defined(PNG_FLOATING_POINT_SUPPORTED)
  180692. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180693. #endif
  180694. #ifndef PNG_NO_WRITE_FLUSH
  180695. # define PNG_WRITE_FLUSH_SUPPORTED
  180696. #endif
  180697. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180698. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180699. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180700. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180701. #endif
  180702. #endif
  180703. #endif /* PNG_WRITE_SUPPORTED */
  180704. #ifndef PNG_1_0_X
  180705. # ifndef PNG_NO_ERROR_NUMBERS
  180706. # define PNG_ERROR_NUMBERS_SUPPORTED
  180707. # endif
  180708. #endif /* PNG_1_0_X */
  180709. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180710. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180711. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180712. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180713. # endif
  180714. #endif
  180715. #ifndef PNG_NO_STDIO
  180716. # define PNG_TIME_RFC1123_SUPPORTED
  180717. #endif
  180718. /* This adds extra functions in pngget.c for accessing data from the
  180719. * info pointer (added in version 0.99)
  180720. * png_get_image_width()
  180721. * png_get_image_height()
  180722. * png_get_bit_depth()
  180723. * png_get_color_type()
  180724. * png_get_compression_type()
  180725. * png_get_filter_type()
  180726. * png_get_interlace_type()
  180727. * png_get_pixel_aspect_ratio()
  180728. * png_get_pixels_per_meter()
  180729. * png_get_x_offset_pixels()
  180730. * png_get_y_offset_pixels()
  180731. * png_get_x_offset_microns()
  180732. * png_get_y_offset_microns()
  180733. */
  180734. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180735. # define PNG_EASY_ACCESS_SUPPORTED
  180736. #endif
  180737. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180738. * and removed from version 1.2.20. The following will be removed
  180739. * from libpng-1.4.0
  180740. */
  180741. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180742. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180743. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180744. # endif
  180745. #endif
  180746. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180747. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180748. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180749. # endif
  180750. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180751. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180752. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180753. # define PNG_NO_MMX_CODE
  180754. # endif
  180755. # endif
  180756. # if defined(__APPLE__)
  180757. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180758. # define PNG_NO_MMX_CODE
  180759. # endif
  180760. # endif
  180761. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180762. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180763. # define PNG_NO_MMX_CODE
  180764. # endif
  180765. # endif
  180766. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180767. # define PNG_MMX_CODE_SUPPORTED
  180768. # endif
  180769. #endif
  180770. /* end of obsolete code to be removed from libpng-1.4.0 */
  180771. #if !defined(PNG_1_0_X)
  180772. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180773. # define PNG_USER_MEM_SUPPORTED
  180774. #endif
  180775. #endif /* PNG_1_0_X */
  180776. /* Added at libpng-1.2.6 */
  180777. #if !defined(PNG_1_0_X)
  180778. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180779. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180780. # define PNG_SET_USER_LIMITS_SUPPORTED
  180781. #endif
  180782. #endif
  180783. #endif /* PNG_1_0_X */
  180784. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180785. * how large, set these limits to 0x7fffffffL
  180786. */
  180787. #ifndef PNG_USER_WIDTH_MAX
  180788. # define PNG_USER_WIDTH_MAX 1000000L
  180789. #endif
  180790. #ifndef PNG_USER_HEIGHT_MAX
  180791. # define PNG_USER_HEIGHT_MAX 1000000L
  180792. #endif
  180793. /* These are currently experimental features, define them if you want */
  180794. /* very little testing */
  180795. /*
  180796. #ifdef PNG_READ_SUPPORTED
  180797. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180798. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180799. # endif
  180800. #endif
  180801. */
  180802. /* This is only for PowerPC big-endian and 680x0 systems */
  180803. /* some testing */
  180804. /*
  180805. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180806. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180807. #endif
  180808. */
  180809. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180810. /*
  180811. #define PNG_NO_POINTER_INDEXING
  180812. */
  180813. /* These functions are turned off by default, as they will be phased out. */
  180814. /*
  180815. #define PNG_USELESS_TESTS_SUPPORTED
  180816. #define PNG_CORRECT_PALETTE_SUPPORTED
  180817. */
  180818. /* Any chunks you are not interested in, you can undef here. The
  180819. * ones that allocate memory may be expecially important (hIST,
  180820. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180821. * a bit smaller.
  180822. */
  180823. #if defined(PNG_READ_SUPPORTED) && \
  180824. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180825. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180826. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180827. #endif
  180828. #if defined(PNG_WRITE_SUPPORTED) && \
  180829. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180830. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180831. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180832. #endif
  180833. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180834. #ifdef PNG_NO_READ_TEXT
  180835. # define PNG_NO_READ_iTXt
  180836. # define PNG_NO_READ_tEXt
  180837. # define PNG_NO_READ_zTXt
  180838. #endif
  180839. #ifndef PNG_NO_READ_bKGD
  180840. # define PNG_READ_bKGD_SUPPORTED
  180841. # define PNG_bKGD_SUPPORTED
  180842. #endif
  180843. #ifndef PNG_NO_READ_cHRM
  180844. # define PNG_READ_cHRM_SUPPORTED
  180845. # define PNG_cHRM_SUPPORTED
  180846. #endif
  180847. #ifndef PNG_NO_READ_gAMA
  180848. # define PNG_READ_gAMA_SUPPORTED
  180849. # define PNG_gAMA_SUPPORTED
  180850. #endif
  180851. #ifndef PNG_NO_READ_hIST
  180852. # define PNG_READ_hIST_SUPPORTED
  180853. # define PNG_hIST_SUPPORTED
  180854. #endif
  180855. #ifndef PNG_NO_READ_iCCP
  180856. # define PNG_READ_iCCP_SUPPORTED
  180857. # define PNG_iCCP_SUPPORTED
  180858. #endif
  180859. #ifndef PNG_NO_READ_iTXt
  180860. # ifndef PNG_READ_iTXt_SUPPORTED
  180861. # define PNG_READ_iTXt_SUPPORTED
  180862. # endif
  180863. # ifndef PNG_iTXt_SUPPORTED
  180864. # define PNG_iTXt_SUPPORTED
  180865. # endif
  180866. #endif
  180867. #ifndef PNG_NO_READ_oFFs
  180868. # define PNG_READ_oFFs_SUPPORTED
  180869. # define PNG_oFFs_SUPPORTED
  180870. #endif
  180871. #ifndef PNG_NO_READ_pCAL
  180872. # define PNG_READ_pCAL_SUPPORTED
  180873. # define PNG_pCAL_SUPPORTED
  180874. #endif
  180875. #ifndef PNG_NO_READ_sCAL
  180876. # define PNG_READ_sCAL_SUPPORTED
  180877. # define PNG_sCAL_SUPPORTED
  180878. #endif
  180879. #ifndef PNG_NO_READ_pHYs
  180880. # define PNG_READ_pHYs_SUPPORTED
  180881. # define PNG_pHYs_SUPPORTED
  180882. #endif
  180883. #ifndef PNG_NO_READ_sBIT
  180884. # define PNG_READ_sBIT_SUPPORTED
  180885. # define PNG_sBIT_SUPPORTED
  180886. #endif
  180887. #ifndef PNG_NO_READ_sPLT
  180888. # define PNG_READ_sPLT_SUPPORTED
  180889. # define PNG_sPLT_SUPPORTED
  180890. #endif
  180891. #ifndef PNG_NO_READ_sRGB
  180892. # define PNG_READ_sRGB_SUPPORTED
  180893. # define PNG_sRGB_SUPPORTED
  180894. #endif
  180895. #ifndef PNG_NO_READ_tEXt
  180896. # define PNG_READ_tEXt_SUPPORTED
  180897. # define PNG_tEXt_SUPPORTED
  180898. #endif
  180899. #ifndef PNG_NO_READ_tIME
  180900. # define PNG_READ_tIME_SUPPORTED
  180901. # define PNG_tIME_SUPPORTED
  180902. #endif
  180903. #ifndef PNG_NO_READ_tRNS
  180904. # define PNG_READ_tRNS_SUPPORTED
  180905. # define PNG_tRNS_SUPPORTED
  180906. #endif
  180907. #ifndef PNG_NO_READ_zTXt
  180908. # define PNG_READ_zTXt_SUPPORTED
  180909. # define PNG_zTXt_SUPPORTED
  180910. #endif
  180911. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180912. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180913. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180914. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180915. # endif
  180916. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180917. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180918. # endif
  180919. #endif
  180920. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180921. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180922. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180923. # define PNG_USER_CHUNKS_SUPPORTED
  180924. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180925. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180926. # endif
  180927. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180928. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180929. # endif
  180930. #endif
  180931. #ifndef PNG_NO_READ_OPT_PLTE
  180932. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180933. #endif /* optional PLTE chunk in RGB and RGBA images */
  180934. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180935. defined(PNG_READ_zTXt_SUPPORTED)
  180936. # define PNG_READ_TEXT_SUPPORTED
  180937. # define PNG_TEXT_SUPPORTED
  180938. #endif
  180939. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180940. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180941. #ifdef PNG_NO_WRITE_TEXT
  180942. # define PNG_NO_WRITE_iTXt
  180943. # define PNG_NO_WRITE_tEXt
  180944. # define PNG_NO_WRITE_zTXt
  180945. #endif
  180946. #ifndef PNG_NO_WRITE_bKGD
  180947. # define PNG_WRITE_bKGD_SUPPORTED
  180948. # ifndef PNG_bKGD_SUPPORTED
  180949. # define PNG_bKGD_SUPPORTED
  180950. # endif
  180951. #endif
  180952. #ifndef PNG_NO_WRITE_cHRM
  180953. # define PNG_WRITE_cHRM_SUPPORTED
  180954. # ifndef PNG_cHRM_SUPPORTED
  180955. # define PNG_cHRM_SUPPORTED
  180956. # endif
  180957. #endif
  180958. #ifndef PNG_NO_WRITE_gAMA
  180959. # define PNG_WRITE_gAMA_SUPPORTED
  180960. # ifndef PNG_gAMA_SUPPORTED
  180961. # define PNG_gAMA_SUPPORTED
  180962. # endif
  180963. #endif
  180964. #ifndef PNG_NO_WRITE_hIST
  180965. # define PNG_WRITE_hIST_SUPPORTED
  180966. # ifndef PNG_hIST_SUPPORTED
  180967. # define PNG_hIST_SUPPORTED
  180968. # endif
  180969. #endif
  180970. #ifndef PNG_NO_WRITE_iCCP
  180971. # define PNG_WRITE_iCCP_SUPPORTED
  180972. # ifndef PNG_iCCP_SUPPORTED
  180973. # define PNG_iCCP_SUPPORTED
  180974. # endif
  180975. #endif
  180976. #ifndef PNG_NO_WRITE_iTXt
  180977. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180978. # define PNG_WRITE_iTXt_SUPPORTED
  180979. # endif
  180980. # ifndef PNG_iTXt_SUPPORTED
  180981. # define PNG_iTXt_SUPPORTED
  180982. # endif
  180983. #endif
  180984. #ifndef PNG_NO_WRITE_oFFs
  180985. # define PNG_WRITE_oFFs_SUPPORTED
  180986. # ifndef PNG_oFFs_SUPPORTED
  180987. # define PNG_oFFs_SUPPORTED
  180988. # endif
  180989. #endif
  180990. #ifndef PNG_NO_WRITE_pCAL
  180991. # define PNG_WRITE_pCAL_SUPPORTED
  180992. # ifndef PNG_pCAL_SUPPORTED
  180993. # define PNG_pCAL_SUPPORTED
  180994. # endif
  180995. #endif
  180996. #ifndef PNG_NO_WRITE_sCAL
  180997. # define PNG_WRITE_sCAL_SUPPORTED
  180998. # ifndef PNG_sCAL_SUPPORTED
  180999. # define PNG_sCAL_SUPPORTED
  181000. # endif
  181001. #endif
  181002. #ifndef PNG_NO_WRITE_pHYs
  181003. # define PNG_WRITE_pHYs_SUPPORTED
  181004. # ifndef PNG_pHYs_SUPPORTED
  181005. # define PNG_pHYs_SUPPORTED
  181006. # endif
  181007. #endif
  181008. #ifndef PNG_NO_WRITE_sBIT
  181009. # define PNG_WRITE_sBIT_SUPPORTED
  181010. # ifndef PNG_sBIT_SUPPORTED
  181011. # define PNG_sBIT_SUPPORTED
  181012. # endif
  181013. #endif
  181014. #ifndef PNG_NO_WRITE_sPLT
  181015. # define PNG_WRITE_sPLT_SUPPORTED
  181016. # ifndef PNG_sPLT_SUPPORTED
  181017. # define PNG_sPLT_SUPPORTED
  181018. # endif
  181019. #endif
  181020. #ifndef PNG_NO_WRITE_sRGB
  181021. # define PNG_WRITE_sRGB_SUPPORTED
  181022. # ifndef PNG_sRGB_SUPPORTED
  181023. # define PNG_sRGB_SUPPORTED
  181024. # endif
  181025. #endif
  181026. #ifndef PNG_NO_WRITE_tEXt
  181027. # define PNG_WRITE_tEXt_SUPPORTED
  181028. # ifndef PNG_tEXt_SUPPORTED
  181029. # define PNG_tEXt_SUPPORTED
  181030. # endif
  181031. #endif
  181032. #ifndef PNG_NO_WRITE_tIME
  181033. # define PNG_WRITE_tIME_SUPPORTED
  181034. # ifndef PNG_tIME_SUPPORTED
  181035. # define PNG_tIME_SUPPORTED
  181036. # endif
  181037. #endif
  181038. #ifndef PNG_NO_WRITE_tRNS
  181039. # define PNG_WRITE_tRNS_SUPPORTED
  181040. # ifndef PNG_tRNS_SUPPORTED
  181041. # define PNG_tRNS_SUPPORTED
  181042. # endif
  181043. #endif
  181044. #ifndef PNG_NO_WRITE_zTXt
  181045. # define PNG_WRITE_zTXt_SUPPORTED
  181046. # ifndef PNG_zTXt_SUPPORTED
  181047. # define PNG_zTXt_SUPPORTED
  181048. # endif
  181049. #endif
  181050. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181051. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181052. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181053. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181054. # endif
  181055. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181056. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181057. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181058. # endif
  181059. # endif
  181060. #endif
  181061. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181062. defined(PNG_WRITE_zTXt_SUPPORTED)
  181063. # define PNG_WRITE_TEXT_SUPPORTED
  181064. # ifndef PNG_TEXT_SUPPORTED
  181065. # define PNG_TEXT_SUPPORTED
  181066. # endif
  181067. #endif
  181068. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181069. /* Turn this off to disable png_read_png() and
  181070. * png_write_png() and leave the row_pointers member
  181071. * out of the info structure.
  181072. */
  181073. #ifndef PNG_NO_INFO_IMAGE
  181074. # define PNG_INFO_IMAGE_SUPPORTED
  181075. #endif
  181076. /* need the time information for reading tIME chunks */
  181077. #if defined(PNG_tIME_SUPPORTED)
  181078. # if !defined(_WIN32_WCE)
  181079. /* "time.h" functions are not supported on WindowsCE */
  181080. # include <time.h>
  181081. # endif
  181082. #endif
  181083. /* Some typedefs to get us started. These should be safe on most of the
  181084. * common platforms. The typedefs should be at least as large as the
  181085. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181086. * don't have to be exactly that size. Some compilers dislike passing
  181087. * unsigned shorts as function parameters, so you may be better off using
  181088. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181089. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181090. */
  181091. typedef unsigned long png_uint_32;
  181092. typedef long png_int_32;
  181093. typedef unsigned short png_uint_16;
  181094. typedef short png_int_16;
  181095. typedef unsigned char png_byte;
  181096. /* This is usually size_t. It is typedef'ed just in case you need it to
  181097. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181098. #ifdef PNG_SIZE_T
  181099. typedef PNG_SIZE_T png_size_t;
  181100. # define png_sizeof(x) png_convert_size(sizeof (x))
  181101. #else
  181102. typedef size_t png_size_t;
  181103. # define png_sizeof(x) sizeof (x)
  181104. #endif
  181105. /* The following is needed for medium model support. It cannot be in the
  181106. * PNG_INTERNAL section. Needs modification for other compilers besides
  181107. * MSC. Model independent support declares all arrays and pointers to be
  181108. * large using the far keyword. The zlib version used must also support
  181109. * model independent data. As of version zlib 1.0.4, the necessary changes
  181110. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181111. * changes that are needed. (Tim Wegner)
  181112. */
  181113. /* Separate compiler dependencies (problem here is that zlib.h always
  181114. defines FAR. (SJT) */
  181115. #ifdef __BORLANDC__
  181116. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181117. # define LDATA 1
  181118. # else
  181119. # define LDATA 0
  181120. # endif
  181121. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181122. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181123. # define PNG_MAX_MALLOC_64K
  181124. # if (LDATA != 1)
  181125. # ifndef FAR
  181126. # define FAR __far
  181127. # endif
  181128. # define USE_FAR_KEYWORD
  181129. # endif /* LDATA != 1 */
  181130. /* Possibly useful for moving data out of default segment.
  181131. * Uncomment it if you want. Could also define FARDATA as
  181132. * const if your compiler supports it. (SJT)
  181133. # define FARDATA FAR
  181134. */
  181135. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181136. #endif /* __BORLANDC__ */
  181137. /* Suggest testing for specific compiler first before testing for
  181138. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181139. * making reliance oncertain keywords suspect. (SJT)
  181140. */
  181141. /* MSC Medium model */
  181142. #if defined(FAR)
  181143. # if defined(M_I86MM)
  181144. # define USE_FAR_KEYWORD
  181145. # define FARDATA FAR
  181146. # include <dos.h>
  181147. # endif
  181148. #endif
  181149. /* SJT: default case */
  181150. #ifndef FAR
  181151. # define FAR
  181152. #endif
  181153. /* At this point FAR is always defined */
  181154. #ifndef FARDATA
  181155. # define FARDATA
  181156. #endif
  181157. /* Typedef for floating-point numbers that are converted
  181158. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181159. typedef png_int_32 png_fixed_point;
  181160. /* Add typedefs for pointers */
  181161. typedef void FAR * png_voidp;
  181162. typedef png_byte FAR * png_bytep;
  181163. typedef png_uint_32 FAR * png_uint_32p;
  181164. typedef png_int_32 FAR * png_int_32p;
  181165. typedef png_uint_16 FAR * png_uint_16p;
  181166. typedef png_int_16 FAR * png_int_16p;
  181167. typedef PNG_CONST char FAR * png_const_charp;
  181168. typedef char FAR * png_charp;
  181169. typedef png_fixed_point FAR * png_fixed_point_p;
  181170. #ifndef PNG_NO_STDIO
  181171. #if defined(_WIN32_WCE)
  181172. typedef HANDLE png_FILE_p;
  181173. #else
  181174. typedef FILE * png_FILE_p;
  181175. #endif
  181176. #endif
  181177. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181178. typedef double FAR * png_doublep;
  181179. #endif
  181180. /* Pointers to pointers; i.e. arrays */
  181181. typedef png_byte FAR * FAR * png_bytepp;
  181182. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181183. typedef png_int_32 FAR * FAR * png_int_32pp;
  181184. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181185. typedef png_int_16 FAR * FAR * png_int_16pp;
  181186. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181187. typedef char FAR * FAR * png_charpp;
  181188. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181189. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181190. typedef double FAR * FAR * png_doublepp;
  181191. #endif
  181192. /* Pointers to pointers to pointers; i.e., pointer to array */
  181193. typedef char FAR * FAR * FAR * png_charppp;
  181194. #if 0
  181195. /* SPC - Is this stuff deprecated? */
  181196. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181197. /* libpng typedefs for types in zlib. If zlib changes
  181198. * or another compression library is used, then change these.
  181199. * Eliminates need to change all the source files.
  181200. */
  181201. typedef charf * png_zcharp;
  181202. typedef charf * FAR * png_zcharpp;
  181203. typedef z_stream FAR * png_zstreamp;
  181204. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181205. /*
  181206. * Define PNG_BUILD_DLL if the module being built is a Windows
  181207. * LIBPNG DLL.
  181208. *
  181209. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181210. * It is equivalent to Microsoft predefined macro _DLL that is
  181211. * automatically defined when you compile using the share
  181212. * version of the CRT (C Run-Time library)
  181213. *
  181214. * The cygwin mods make this behavior a little different:
  181215. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181216. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181217. * -or- if you are building an application that you want to link to the
  181218. * static library.
  181219. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181220. * the other flags is defined.
  181221. */
  181222. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181223. # define PNG_DLL
  181224. #endif
  181225. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181226. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181227. * command-line override
  181228. */
  181229. #if defined(__CYGWIN__)
  181230. # if !defined(PNG_STATIC)
  181231. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181232. # undef PNG_USE_GLOBAL_ARRAYS
  181233. # endif
  181234. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181235. # define PNG_USE_LOCAL_ARRAYS
  181236. # endif
  181237. # else
  181238. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181239. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181240. # undef PNG_USE_GLOBAL_ARRAYS
  181241. # endif
  181242. # endif
  181243. # endif
  181244. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181245. # define PNG_USE_LOCAL_ARRAYS
  181246. # endif
  181247. #endif
  181248. /* Do not use global arrays (helps with building DLL's)
  181249. * They are no longer used in libpng itself, since version 1.0.5c,
  181250. * but might be required for some pre-1.0.5c applications.
  181251. */
  181252. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181253. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181254. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181255. # define PNG_USE_LOCAL_ARRAYS
  181256. # else
  181257. # define PNG_USE_GLOBAL_ARRAYS
  181258. # endif
  181259. #endif
  181260. #if defined(__CYGWIN__)
  181261. # undef PNGAPI
  181262. # define PNGAPI __cdecl
  181263. # undef PNG_IMPEXP
  181264. # define PNG_IMPEXP
  181265. #endif
  181266. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181267. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181268. * Don't ignore those warnings; you must also reset the default calling
  181269. * convention in your compiler to match your PNGAPI, and you must build
  181270. * zlib and your applications the same way you build libpng.
  181271. */
  181272. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181273. # ifndef PNG_NO_MODULEDEF
  181274. # define PNG_NO_MODULEDEF
  181275. # endif
  181276. #endif
  181277. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181278. # define PNG_IMPEXP
  181279. #endif
  181280. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181281. (( defined(_Windows) || defined(_WINDOWS) || \
  181282. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181283. # ifndef PNGAPI
  181284. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181285. # define PNGAPI __cdecl
  181286. # else
  181287. # define PNGAPI _cdecl
  181288. # endif
  181289. # endif
  181290. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181291. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181292. # define PNG_IMPEXP
  181293. # endif
  181294. # if !defined(PNG_IMPEXP)
  181295. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181296. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181297. /* Borland/Microsoft */
  181298. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181299. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181300. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181301. # else
  181302. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181303. # if defined(PNG_BUILD_DLL)
  181304. # define PNG_IMPEXP __export
  181305. # else
  181306. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181307. VC++ */
  181308. # endif /* Exists in Borland C++ for
  181309. C++ classes (== huge) */
  181310. # endif
  181311. # endif
  181312. # if !defined(PNG_IMPEXP)
  181313. # if defined(PNG_BUILD_DLL)
  181314. # define PNG_IMPEXP __declspec(dllexport)
  181315. # else
  181316. # define PNG_IMPEXP __declspec(dllimport)
  181317. # endif
  181318. # endif
  181319. # endif /* PNG_IMPEXP */
  181320. #else /* !(DLL || non-cygwin WINDOWS) */
  181321. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181322. # ifndef PNGAPI
  181323. # define PNGAPI _System
  181324. # endif
  181325. # else
  181326. # if 0 /* ... other platforms, with other meanings */
  181327. # endif
  181328. # endif
  181329. #endif
  181330. #ifndef PNGAPI
  181331. # define PNGAPI
  181332. #endif
  181333. #ifndef PNG_IMPEXP
  181334. # define PNG_IMPEXP
  181335. #endif
  181336. #ifdef PNG_BUILDSYMS
  181337. # ifndef PNG_EXPORT
  181338. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181339. # endif
  181340. # ifdef PNG_USE_GLOBAL_ARRAYS
  181341. # ifndef PNG_EXPORT_VAR
  181342. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181343. # endif
  181344. # endif
  181345. #endif
  181346. #ifndef PNG_EXPORT
  181347. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181348. #endif
  181349. #ifdef PNG_USE_GLOBAL_ARRAYS
  181350. # ifndef PNG_EXPORT_VAR
  181351. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181352. # endif
  181353. #endif
  181354. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181355. * functions that are passed far data must be model independent.
  181356. */
  181357. #ifndef PNG_ABORT
  181358. # define PNG_ABORT() abort()
  181359. #endif
  181360. #ifdef PNG_SETJMP_SUPPORTED
  181361. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181362. #else
  181363. # define png_jmpbuf(png_ptr) \
  181364. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181365. #endif
  181366. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181367. /* use this to make far-to-near assignments */
  181368. # define CHECK 1
  181369. # define NOCHECK 0
  181370. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181371. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181372. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181373. # define png_strcpy _fstrcpy
  181374. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181375. # define png_strlen _fstrlen
  181376. # define png_memcmp _fmemcmp /* SJT: added */
  181377. # define png_memcpy _fmemcpy
  181378. # define png_memset _fmemset
  181379. #else /* use the usual functions */
  181380. # define CVT_PTR(ptr) (ptr)
  181381. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181382. # ifndef PNG_NO_SNPRINTF
  181383. # ifdef _MSC_VER
  181384. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181385. # define png_snprintf2 _snprintf
  181386. # define png_snprintf6 _snprintf
  181387. # else
  181388. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181389. # define png_snprintf2 snprintf
  181390. # define png_snprintf6 snprintf
  181391. # endif
  181392. # else
  181393. /* You don't have or don't want to use snprintf(). Caution: Using
  181394. * sprintf instead of snprintf exposes your application to accidental
  181395. * or malevolent buffer overflows. If you don't have snprintf()
  181396. * as a general rule you should provide one (you can get one from
  181397. * Portable OpenSSH). */
  181398. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181399. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181400. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181401. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181402. # endif
  181403. # define png_strcpy strcpy
  181404. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181405. # define png_strlen strlen
  181406. # define png_memcmp memcmp /* SJT: added */
  181407. # define png_memcpy memcpy
  181408. # define png_memset memset
  181409. #endif
  181410. /* End of memory model independent support */
  181411. /* Just a little check that someone hasn't tried to define something
  181412. * contradictory.
  181413. */
  181414. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181415. # undef PNG_ZBUF_SIZE
  181416. # define PNG_ZBUF_SIZE 65536L
  181417. #endif
  181418. /* Added at libpng-1.2.8 */
  181419. #endif /* PNG_VERSION_INFO_ONLY */
  181420. #endif /* PNGCONF_H */
  181421. /*** End of inlined file: pngconf.h ***/
  181422. #ifdef _MSC_VER
  181423. #pragma warning (disable: 4996 4100)
  181424. #endif
  181425. /*
  181426. * Added at libpng-1.2.8 */
  181427. /* Ref MSDN: Private as priority over Special
  181428. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181429. * procedures. If this value is given, the StringFileInfo block must
  181430. * contain a PrivateBuild string.
  181431. *
  181432. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181433. * standard release procedures but is a variation of the standard
  181434. * file of the same version number. If this value is given, the
  181435. * StringFileInfo block must contain a SpecialBuild string.
  181436. */
  181437. #if defined(PNG_USER_PRIVATEBUILD)
  181438. # define PNG_LIBPNG_BUILD_TYPE \
  181439. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181440. #else
  181441. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181442. # define PNG_LIBPNG_BUILD_TYPE \
  181443. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181444. # else
  181445. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181446. # endif
  181447. #endif
  181448. #ifndef PNG_VERSION_INFO_ONLY
  181449. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181450. #ifdef __cplusplus
  181451. //extern "C" {
  181452. #endif /* __cplusplus */
  181453. /* This file is arranged in several sections. The first section contains
  181454. * structure and type definitions. The second section contains the external
  181455. * library functions, while the third has the internal library functions,
  181456. * which applications aren't expected to use directly.
  181457. */
  181458. #ifndef PNG_NO_TYPECAST_NULL
  181459. #define int_p_NULL (int *)NULL
  181460. #define png_bytep_NULL (png_bytep)NULL
  181461. #define png_bytepp_NULL (png_bytepp)NULL
  181462. #define png_doublep_NULL (png_doublep)NULL
  181463. #define png_error_ptr_NULL (png_error_ptr)NULL
  181464. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181465. #define png_free_ptr_NULL (png_free_ptr)NULL
  181466. #define png_infopp_NULL (png_infopp)NULL
  181467. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181468. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181469. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181470. #define png_structp_NULL (png_structp)NULL
  181471. #define png_uint_16p_NULL (png_uint_16p)NULL
  181472. #define png_voidp_NULL (png_voidp)NULL
  181473. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181474. #else
  181475. #define int_p_NULL NULL
  181476. #define png_bytep_NULL NULL
  181477. #define png_bytepp_NULL NULL
  181478. #define png_doublep_NULL NULL
  181479. #define png_error_ptr_NULL NULL
  181480. #define png_flush_ptr_NULL NULL
  181481. #define png_free_ptr_NULL NULL
  181482. #define png_infopp_NULL NULL
  181483. #define png_malloc_ptr_NULL NULL
  181484. #define png_read_status_ptr_NULL NULL
  181485. #define png_rw_ptr_NULL NULL
  181486. #define png_structp_NULL NULL
  181487. #define png_uint_16p_NULL NULL
  181488. #define png_voidp_NULL NULL
  181489. #define png_write_status_ptr_NULL NULL
  181490. #endif
  181491. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181492. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181493. /* Version information for C files, stored in png.c. This had better match
  181494. * the version above.
  181495. */
  181496. #ifdef PNG_USE_GLOBAL_ARRAYS
  181497. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181498. /* need room for 99.99.99beta99z */
  181499. #else
  181500. #define png_libpng_ver png_get_header_ver(NULL)
  181501. #endif
  181502. #ifdef PNG_USE_GLOBAL_ARRAYS
  181503. /* This was removed in version 1.0.5c */
  181504. /* Structures to facilitate easy interlacing. See png.c for more details */
  181505. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181506. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181507. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181508. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181509. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181510. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181511. /* This isn't currently used. If you need it, see png.c for more details.
  181512. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181513. */
  181514. #endif
  181515. #endif /* PNG_NO_EXTERN */
  181516. /* Three color definitions. The order of the red, green, and blue, (and the
  181517. * exact size) is not important, although the size of the fields need to
  181518. * be png_byte or png_uint_16 (as defined below).
  181519. */
  181520. typedef struct png_color_struct
  181521. {
  181522. png_byte red;
  181523. png_byte green;
  181524. png_byte blue;
  181525. } png_color;
  181526. typedef png_color FAR * png_colorp;
  181527. typedef png_color FAR * FAR * png_colorpp;
  181528. typedef struct png_color_16_struct
  181529. {
  181530. png_byte index; /* used for palette files */
  181531. png_uint_16 red; /* for use in red green blue files */
  181532. png_uint_16 green;
  181533. png_uint_16 blue;
  181534. png_uint_16 gray; /* for use in grayscale files */
  181535. } png_color_16;
  181536. typedef png_color_16 FAR * png_color_16p;
  181537. typedef png_color_16 FAR * FAR * png_color_16pp;
  181538. typedef struct png_color_8_struct
  181539. {
  181540. png_byte red; /* for use in red green blue files */
  181541. png_byte green;
  181542. png_byte blue;
  181543. png_byte gray; /* for use in grayscale files */
  181544. png_byte alpha; /* for alpha channel files */
  181545. } png_color_8;
  181546. typedef png_color_8 FAR * png_color_8p;
  181547. typedef png_color_8 FAR * FAR * png_color_8pp;
  181548. /*
  181549. * The following two structures are used for the in-core representation
  181550. * of sPLT chunks.
  181551. */
  181552. typedef struct png_sPLT_entry_struct
  181553. {
  181554. png_uint_16 red;
  181555. png_uint_16 green;
  181556. png_uint_16 blue;
  181557. png_uint_16 alpha;
  181558. png_uint_16 frequency;
  181559. } png_sPLT_entry;
  181560. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181561. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181562. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181563. * occupy the LSB of their respective members, and the MSB of each member
  181564. * is zero-filled. The frequency member always occupies the full 16 bits.
  181565. */
  181566. typedef struct png_sPLT_struct
  181567. {
  181568. png_charp name; /* palette name */
  181569. png_byte depth; /* depth of palette samples */
  181570. png_sPLT_entryp entries; /* palette entries */
  181571. png_int_32 nentries; /* number of palette entries */
  181572. } png_sPLT_t;
  181573. typedef png_sPLT_t FAR * png_sPLT_tp;
  181574. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181575. #ifdef PNG_TEXT_SUPPORTED
  181576. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181577. * and whether that contents is compressed or not. The "key" field
  181578. * points to a regular zero-terminated C string. The "text", "lang", and
  181579. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181580. * However, the * structure returned by png_get_text() will always contain
  181581. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181582. * so they can be safely used in printf() and other string-handling functions.
  181583. */
  181584. typedef struct png_text_struct
  181585. {
  181586. int compression; /* compression value:
  181587. -1: tEXt, none
  181588. 0: zTXt, deflate
  181589. 1: iTXt, none
  181590. 2: iTXt, deflate */
  181591. png_charp key; /* keyword, 1-79 character description of "text" */
  181592. png_charp text; /* comment, may be an empty string (ie "")
  181593. or a NULL pointer */
  181594. png_size_t text_length; /* length of the text string */
  181595. #ifdef PNG_iTXt_SUPPORTED
  181596. png_size_t itxt_length; /* length of the itxt string */
  181597. png_charp lang; /* language code, 0-79 characters
  181598. or a NULL pointer */
  181599. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181600. chars or a NULL pointer */
  181601. #endif
  181602. } png_text;
  181603. typedef png_text FAR * png_textp;
  181604. typedef png_text FAR * FAR * png_textpp;
  181605. #endif
  181606. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181607. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181608. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181609. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181610. #define PNG_TEXT_COMPRESSION_NONE -1
  181611. #define PNG_TEXT_COMPRESSION_zTXt 0
  181612. #define PNG_ITXT_COMPRESSION_NONE 1
  181613. #define PNG_ITXT_COMPRESSION_zTXt 2
  181614. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181615. /* png_time is a way to hold the time in an machine independent way.
  181616. * Two conversions are provided, both from time_t and struct tm. There
  181617. * is no portable way to convert to either of these structures, as far
  181618. * as I know. If you know of a portable way, send it to me. As a side
  181619. * note - PNG has always been Year 2000 compliant!
  181620. */
  181621. typedef struct png_time_struct
  181622. {
  181623. png_uint_16 year; /* full year, as in, 1995 */
  181624. png_byte month; /* month of year, 1 - 12 */
  181625. png_byte day; /* day of month, 1 - 31 */
  181626. png_byte hour; /* hour of day, 0 - 23 */
  181627. png_byte minute; /* minute of hour, 0 - 59 */
  181628. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181629. } png_time;
  181630. typedef png_time FAR * png_timep;
  181631. typedef png_time FAR * FAR * png_timepp;
  181632. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181633. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181634. * no specific support. The idea is that we can use this to queue
  181635. * up private chunks for output even though the library doesn't actually
  181636. * know about their semantics.
  181637. */
  181638. typedef struct png_unknown_chunk_t
  181639. {
  181640. png_byte name[5];
  181641. png_byte *data;
  181642. png_size_t size;
  181643. /* libpng-using applications should NOT directly modify this byte. */
  181644. png_byte location; /* mode of operation at read time */
  181645. }
  181646. png_unknown_chunk;
  181647. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181648. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181649. #endif
  181650. /* png_info is a structure that holds the information in a PNG file so
  181651. * that the application can find out the characteristics of the image.
  181652. * If you are reading the file, this structure will tell you what is
  181653. * in the PNG file. If you are writing the file, fill in the information
  181654. * you want to put into the PNG file, then call png_write_info().
  181655. * The names chosen should be very close to the PNG specification, so
  181656. * consult that document for information about the meaning of each field.
  181657. *
  181658. * With libpng < 0.95, it was only possible to directly set and read the
  181659. * the values in the png_info_struct, which meant that the contents and
  181660. * order of the values had to remain fixed. With libpng 0.95 and later,
  181661. * however, there are now functions that abstract the contents of
  181662. * png_info_struct from the application, so this makes it easier to use
  181663. * libpng with dynamic libraries, and even makes it possible to use
  181664. * libraries that don't have all of the libpng ancillary chunk-handing
  181665. * functionality.
  181666. *
  181667. * In any case, the order of the parameters in png_info_struct should NOT
  181668. * be changed for as long as possible to keep compatibility with applications
  181669. * that use the old direct-access method with png_info_struct.
  181670. *
  181671. * The following members may have allocated storage attached that should be
  181672. * cleaned up before the structure is discarded: palette, trans, text,
  181673. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181674. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181675. * are automatically freed when the info structure is deallocated, if they were
  181676. * allocated internally by libpng. This behavior can be changed by means
  181677. * of the png_data_freer() function.
  181678. *
  181679. * More allocation details: all the chunk-reading functions that
  181680. * change these members go through the corresponding png_set_*
  181681. * functions. A function to clear these members is available: see
  181682. * png_free_data(). The png_set_* functions do not depend on being
  181683. * able to point info structure members to any of the storage they are
  181684. * passed (they make their own copies), EXCEPT that the png_set_text
  181685. * functions use the same storage passed to them in the text_ptr or
  181686. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181687. * functions do not make their own copies.
  181688. */
  181689. typedef struct png_info_struct
  181690. {
  181691. /* the following are necessary for every PNG file */
  181692. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181693. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181694. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181695. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181696. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181697. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181698. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181699. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181700. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181701. /* The following three should have been named *_method not *_type */
  181702. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181703. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181704. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181705. /* The following is informational only on read, and not used on writes. */
  181706. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181707. png_byte pixel_depth; /* number of bits per pixel */
  181708. png_byte spare_byte; /* to align the data, and for future use */
  181709. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181710. /* The rest of the data is optional. If you are reading, check the
  181711. * valid field to see if the information in these are valid. If you
  181712. * are writing, set the valid field to those chunks you want written,
  181713. * and initialize the appropriate fields below.
  181714. */
  181715. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181716. /* The gAMA chunk describes the gamma characteristics of the system
  181717. * on which the image was created, normally in the range [1.0, 2.5].
  181718. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181719. */
  181720. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181721. #endif
  181722. #if defined(PNG_sRGB_SUPPORTED)
  181723. /* GR-P, 0.96a */
  181724. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181725. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181726. #endif
  181727. #if defined(PNG_TEXT_SUPPORTED)
  181728. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181729. * uncompressed, compressed, and optionally compressed forms, respectively.
  181730. * The data in "text" is an array of pointers to uncompressed,
  181731. * null-terminated C strings. Each chunk has a keyword that describes the
  181732. * textual data contained in that chunk. Keywords are not required to be
  181733. * unique, and the text string may be empty. Any number of text chunks may
  181734. * be in an image.
  181735. */
  181736. int num_text; /* number of comments read/to write */
  181737. int max_text; /* current size of text array */
  181738. png_textp text; /* array of comments read/to write */
  181739. #endif /* PNG_TEXT_SUPPORTED */
  181740. #if defined(PNG_tIME_SUPPORTED)
  181741. /* The tIME chunk holds the last time the displayed image data was
  181742. * modified. See the png_time struct for the contents of this struct.
  181743. */
  181744. png_time mod_time;
  181745. #endif
  181746. #if defined(PNG_sBIT_SUPPORTED)
  181747. /* The sBIT chunk specifies the number of significant high-order bits
  181748. * in the pixel data. Values are in the range [1, bit_depth], and are
  181749. * only specified for the channels in the pixel data. The contents of
  181750. * the low-order bits is not specified. Data is valid if
  181751. * (valid & PNG_INFO_sBIT) is non-zero.
  181752. */
  181753. png_color_8 sig_bit; /* significant bits in color channels */
  181754. #endif
  181755. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181756. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181757. /* The tRNS chunk supplies transparency data for paletted images and
  181758. * other image types that don't need a full alpha channel. There are
  181759. * "num_trans" transparency values for a paletted image, stored in the
  181760. * same order as the palette colors, starting from index 0. Values
  181761. * for the data are in the range [0, 255], ranging from fully transparent
  181762. * to fully opaque, respectively. For non-paletted images, there is a
  181763. * single color specified that should be treated as fully transparent.
  181764. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181765. */
  181766. png_bytep trans; /* transparent values for paletted image */
  181767. png_color_16 trans_values; /* transparent color for non-palette image */
  181768. #endif
  181769. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181770. /* The bKGD chunk gives the suggested image background color if the
  181771. * display program does not have its own background color and the image
  181772. * is needs to composited onto a background before display. The colors
  181773. * in "background" are normally in the same color space/depth as the
  181774. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181775. */
  181776. png_color_16 background;
  181777. #endif
  181778. #if defined(PNG_oFFs_SUPPORTED)
  181779. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181780. * and downwards from the top-left corner of the display, page, or other
  181781. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181782. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181783. */
  181784. png_int_32 x_offset; /* x offset on page */
  181785. png_int_32 y_offset; /* y offset on page */
  181786. png_byte offset_unit_type; /* offset units type */
  181787. #endif
  181788. #if defined(PNG_pHYs_SUPPORTED)
  181789. /* The pHYs chunk gives the physical pixel density of the image for
  181790. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181791. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181792. */
  181793. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181794. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181795. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181796. #endif
  181797. #if defined(PNG_hIST_SUPPORTED)
  181798. /* The hIST chunk contains the relative frequency or importance of the
  181799. * various palette entries, so that a viewer can intelligently select a
  181800. * reduced-color palette, if required. Data is an array of "num_palette"
  181801. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181802. * is non-zero.
  181803. */
  181804. png_uint_16p hist;
  181805. #endif
  181806. #ifdef PNG_cHRM_SUPPORTED
  181807. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181808. * on which the PNG was created. This data allows the viewer to do gamut
  181809. * mapping of the input image to ensure that the viewer sees the same
  181810. * colors in the image as the creator. Values are in the range
  181811. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181812. */
  181813. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181814. float x_white;
  181815. float y_white;
  181816. float x_red;
  181817. float y_red;
  181818. float x_green;
  181819. float y_green;
  181820. float x_blue;
  181821. float y_blue;
  181822. #endif
  181823. #endif
  181824. #if defined(PNG_pCAL_SUPPORTED)
  181825. /* The pCAL chunk describes a transformation between the stored pixel
  181826. * values and original physical data values used to create the image.
  181827. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181828. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181829. * (possibly non-linear) transformation function given by "pcal_type"
  181830. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181831. * defines below, and the PNG-Group's PNG extensions document for a
  181832. * complete description of the transformations and how they should be
  181833. * implemented, and for a description of the ASCII parameter strings.
  181834. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181835. */
  181836. png_charp pcal_purpose; /* pCAL chunk description string */
  181837. png_int_32 pcal_X0; /* minimum value */
  181838. png_int_32 pcal_X1; /* maximum value */
  181839. png_charp pcal_units; /* Latin-1 string giving physical units */
  181840. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181841. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181842. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181843. #endif
  181844. /* New members added in libpng-1.0.6 */
  181845. #ifdef PNG_FREE_ME_SUPPORTED
  181846. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181847. #endif
  181848. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181849. /* storage for unknown chunks that the library doesn't recognize. */
  181850. png_unknown_chunkp unknown_chunks;
  181851. png_size_t unknown_chunks_num;
  181852. #endif
  181853. #if defined(PNG_iCCP_SUPPORTED)
  181854. /* iCCP chunk data. */
  181855. png_charp iccp_name; /* profile name */
  181856. png_charp iccp_profile; /* International Color Consortium profile data */
  181857. /* Note to maintainer: should be png_bytep */
  181858. png_uint_32 iccp_proflen; /* ICC profile data length */
  181859. png_byte iccp_compression; /* Always zero */
  181860. #endif
  181861. #if defined(PNG_sPLT_SUPPORTED)
  181862. /* data on sPLT chunks (there may be more than one). */
  181863. png_sPLT_tp splt_palettes;
  181864. png_uint_32 splt_palettes_num;
  181865. #endif
  181866. #if defined(PNG_sCAL_SUPPORTED)
  181867. /* The sCAL chunk describes the actual physical dimensions of the
  181868. * subject matter of the graphic. The chunk contains a unit specification
  181869. * a byte value, and two ASCII strings representing floating-point
  181870. * values. The values are width and height corresponsing to one pixel
  181871. * in the image. This external representation is converted to double
  181872. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181873. */
  181874. png_byte scal_unit; /* unit of physical scale */
  181875. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181876. double scal_pixel_width; /* width of one pixel */
  181877. double scal_pixel_height; /* height of one pixel */
  181878. #endif
  181879. #ifdef PNG_FIXED_POINT_SUPPORTED
  181880. png_charp scal_s_width; /* string containing height */
  181881. png_charp scal_s_height; /* string containing width */
  181882. #endif
  181883. #endif
  181884. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181885. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181886. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181887. png_bytepp row_pointers; /* the image bits */
  181888. #endif
  181889. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181890. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181891. #endif
  181892. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181893. png_fixed_point int_x_white;
  181894. png_fixed_point int_y_white;
  181895. png_fixed_point int_x_red;
  181896. png_fixed_point int_y_red;
  181897. png_fixed_point int_x_green;
  181898. png_fixed_point int_y_green;
  181899. png_fixed_point int_x_blue;
  181900. png_fixed_point int_y_blue;
  181901. #endif
  181902. } png_info;
  181903. typedef png_info FAR * png_infop;
  181904. typedef png_info FAR * FAR * png_infopp;
  181905. /* Maximum positive integer used in PNG is (2^31)-1 */
  181906. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181907. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181908. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181909. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181910. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181911. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181912. #endif
  181913. /* These describe the color_type field in png_info. */
  181914. /* color type masks */
  181915. #define PNG_COLOR_MASK_PALETTE 1
  181916. #define PNG_COLOR_MASK_COLOR 2
  181917. #define PNG_COLOR_MASK_ALPHA 4
  181918. /* color types. Note that not all combinations are legal */
  181919. #define PNG_COLOR_TYPE_GRAY 0
  181920. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181921. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181922. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181923. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181924. /* aliases */
  181925. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181926. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181927. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181928. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181929. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181930. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181931. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181932. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181933. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181934. /* These are for the interlacing type. These values should NOT be changed. */
  181935. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181936. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181937. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181938. /* These are for the oFFs chunk. These values should NOT be changed. */
  181939. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181940. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181941. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181942. /* These are for the pCAL chunk. These values should NOT be changed. */
  181943. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181944. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181945. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181946. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181947. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181948. /* These are for the sCAL chunk. These values should NOT be changed. */
  181949. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181950. #define PNG_SCALE_METER 1 /* meters per pixel */
  181951. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181952. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181953. /* These are for the pHYs chunk. These values should NOT be changed. */
  181954. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181955. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181956. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181957. /* These are for the sRGB chunk. These values should NOT be changed. */
  181958. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181959. #define PNG_sRGB_INTENT_RELATIVE 1
  181960. #define PNG_sRGB_INTENT_SATURATION 2
  181961. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181962. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181963. /* This is for text chunks */
  181964. #define PNG_KEYWORD_MAX_LENGTH 79
  181965. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181966. #define PNG_MAX_PALETTE_LENGTH 256
  181967. /* These determine if an ancillary chunk's data has been successfully read
  181968. * from the PNG header, or if the application has filled in the corresponding
  181969. * data in the info_struct to be written into the output file. The values
  181970. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181971. */
  181972. #define PNG_INFO_gAMA 0x0001
  181973. #define PNG_INFO_sBIT 0x0002
  181974. #define PNG_INFO_cHRM 0x0004
  181975. #define PNG_INFO_PLTE 0x0008
  181976. #define PNG_INFO_tRNS 0x0010
  181977. #define PNG_INFO_bKGD 0x0020
  181978. #define PNG_INFO_hIST 0x0040
  181979. #define PNG_INFO_pHYs 0x0080
  181980. #define PNG_INFO_oFFs 0x0100
  181981. #define PNG_INFO_tIME 0x0200
  181982. #define PNG_INFO_pCAL 0x0400
  181983. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181984. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181985. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181986. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181987. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181988. /* This is used for the transformation routines, as some of them
  181989. * change these values for the row. It also should enable using
  181990. * the routines for other purposes.
  181991. */
  181992. typedef struct png_row_info_struct
  181993. {
  181994. png_uint_32 width; /* width of row */
  181995. png_uint_32 rowbytes; /* number of bytes in row */
  181996. png_byte color_type; /* color type of row */
  181997. png_byte bit_depth; /* bit depth of row */
  181998. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181999. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182000. } png_row_info;
  182001. typedef png_row_info FAR * png_row_infop;
  182002. typedef png_row_info FAR * FAR * png_row_infopp;
  182003. /* These are the function types for the I/O functions and for the functions
  182004. * that allow the user to override the default I/O functions with his or her
  182005. * own. The png_error_ptr type should match that of user-supplied warning
  182006. * and error functions, while the png_rw_ptr type should match that of the
  182007. * user read/write data functions.
  182008. */
  182009. typedef struct png_struct_def png_struct;
  182010. typedef png_struct FAR * png_structp;
  182011. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182012. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182013. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182014. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182015. int));
  182016. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182017. int));
  182018. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182019. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182020. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182021. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182022. png_uint_32, int));
  182023. #endif
  182024. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182025. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182026. defined(PNG_LEGACY_SUPPORTED)
  182027. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182028. png_row_infop, png_bytep));
  182029. #endif
  182030. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182031. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182032. #endif
  182033. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182034. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182035. #endif
  182036. /* Transform masks for the high-level interface */
  182037. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182038. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182039. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182040. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182041. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182042. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182043. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182044. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182045. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182046. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182047. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182048. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182049. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182050. /* Flags for MNG supported features */
  182051. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182052. #define PNG_FLAG_MNG_FILTER_64 0x04
  182053. #define PNG_ALL_MNG_FEATURES 0x05
  182054. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182055. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182056. /* The structure that holds the information to read and write PNG files.
  182057. * The only people who need to care about what is inside of this are the
  182058. * people who will be modifying the library for their own special needs.
  182059. * It should NOT be accessed directly by an application, except to store
  182060. * the jmp_buf.
  182061. */
  182062. struct png_struct_def
  182063. {
  182064. #ifdef PNG_SETJMP_SUPPORTED
  182065. jmp_buf jmpbuf; /* used in png_error */
  182066. #endif
  182067. png_error_ptr error_fn; /* function for printing errors and aborting */
  182068. png_error_ptr warning_fn; /* function for printing warnings */
  182069. png_voidp error_ptr; /* user supplied struct for error functions */
  182070. png_rw_ptr write_data_fn; /* function for writing output data */
  182071. png_rw_ptr read_data_fn; /* function for reading input data */
  182072. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182073. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182074. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182075. #endif
  182076. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182077. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182078. #endif
  182079. /* These were added in libpng-1.0.2 */
  182080. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182081. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182082. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182083. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182084. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182085. png_byte user_transform_channels; /* channels in user transformed pixels */
  182086. #endif
  182087. #endif
  182088. png_uint_32 mode; /* tells us where we are in the PNG file */
  182089. png_uint_32 flags; /* flags indicating various things to libpng */
  182090. png_uint_32 transformations; /* which transformations to perform */
  182091. z_stream zstream; /* pointer to decompression structure (below) */
  182092. png_bytep zbuf; /* buffer for zlib */
  182093. png_size_t zbuf_size; /* size of zbuf */
  182094. int zlib_level; /* holds zlib compression level */
  182095. int zlib_method; /* holds zlib compression method */
  182096. int zlib_window_bits; /* holds zlib compression window bits */
  182097. int zlib_mem_level; /* holds zlib compression memory level */
  182098. int zlib_strategy; /* holds zlib compression strategy */
  182099. png_uint_32 width; /* width of image in pixels */
  182100. png_uint_32 height; /* height of image in pixels */
  182101. png_uint_32 num_rows; /* number of rows in current pass */
  182102. png_uint_32 usr_width; /* width of row at start of write */
  182103. png_uint_32 rowbytes; /* size of row in bytes */
  182104. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182105. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182106. png_uint_32 row_number; /* current row in interlace pass */
  182107. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182108. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182109. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182110. png_bytep up_row; /* buffer to save "up" row when filtering */
  182111. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182112. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182113. png_row_info row_info; /* used for transformation routines */
  182114. png_uint_32 idat_size; /* current IDAT size for read */
  182115. png_uint_32 crc; /* current chunk CRC value */
  182116. png_colorp palette; /* palette from the input file */
  182117. png_uint_16 num_palette; /* number of color entries in palette */
  182118. png_uint_16 num_trans; /* number of transparency values */
  182119. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182120. png_byte compression; /* file compression type (always 0) */
  182121. png_byte filter; /* file filter type (always 0) */
  182122. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182123. png_byte pass; /* current interlace pass (0 - 6) */
  182124. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182125. png_byte color_type; /* color type of file */
  182126. png_byte bit_depth; /* bit depth of file */
  182127. png_byte usr_bit_depth; /* bit depth of users row */
  182128. png_byte pixel_depth; /* number of bits per pixel */
  182129. png_byte channels; /* number of channels in file */
  182130. png_byte usr_channels; /* channels at start of write */
  182131. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182132. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182133. #ifdef PNG_LEGACY_SUPPORTED
  182134. png_byte filler; /* filler byte for pixel expansion */
  182135. #else
  182136. png_uint_16 filler; /* filler bytes for pixel expansion */
  182137. #endif
  182138. #endif
  182139. #if defined(PNG_bKGD_SUPPORTED)
  182140. png_byte background_gamma_type;
  182141. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182142. float background_gamma;
  182143. # endif
  182144. png_color_16 background; /* background color in screen gamma space */
  182145. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182146. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182147. #endif
  182148. #endif /* PNG_bKGD_SUPPORTED */
  182149. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182150. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182151. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182152. png_uint_32 flush_rows; /* number of rows written since last flush */
  182153. #endif
  182154. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182155. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182156. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182157. float gamma; /* file gamma value */
  182158. float screen_gamma; /* screen gamma value (display_exponent) */
  182159. #endif
  182160. #endif
  182161. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182162. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182163. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182164. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182165. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182166. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182167. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182168. #endif
  182169. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182170. png_color_8 sig_bit; /* significant bits in each available channel */
  182171. #endif
  182172. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182173. png_color_8 shift; /* shift for significant bit tranformation */
  182174. #endif
  182175. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182176. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182177. png_bytep trans; /* transparency values for paletted files */
  182178. png_color_16 trans_values; /* transparency values for non-paletted files */
  182179. #endif
  182180. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182181. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182182. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182183. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182184. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182185. png_progressive_end_ptr end_fn; /* called after image is complete */
  182186. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182187. png_bytep save_buffer; /* buffer for previously read data */
  182188. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182189. png_bytep current_buffer; /* buffer for recently used data */
  182190. png_uint_32 push_length; /* size of current input chunk */
  182191. png_uint_32 skip_length; /* bytes to skip in input data */
  182192. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182193. png_size_t save_buffer_max; /* total size of save_buffer */
  182194. png_size_t buffer_size; /* total amount of available input data */
  182195. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182196. int process_mode; /* what push library is currently doing */
  182197. int cur_palette; /* current push library palette index */
  182198. # if defined(PNG_TEXT_SUPPORTED)
  182199. png_size_t current_text_size; /* current size of text input data */
  182200. png_size_t current_text_left; /* how much text left to read in input */
  182201. png_charp current_text; /* current text chunk buffer */
  182202. png_charp current_text_ptr; /* current location in current_text */
  182203. # endif /* PNG_TEXT_SUPPORTED */
  182204. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182205. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182206. /* for the Borland special 64K segment handler */
  182207. png_bytepp offset_table_ptr;
  182208. png_bytep offset_table;
  182209. png_uint_16 offset_table_number;
  182210. png_uint_16 offset_table_count;
  182211. png_uint_16 offset_table_count_free;
  182212. #endif
  182213. #if defined(PNG_READ_DITHER_SUPPORTED)
  182214. png_bytep palette_lookup; /* lookup table for dithering */
  182215. png_bytep dither_index; /* index translation for palette files */
  182216. #endif
  182217. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182218. png_uint_16p hist; /* histogram */
  182219. #endif
  182220. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182221. png_byte heuristic_method; /* heuristic for row filter selection */
  182222. png_byte num_prev_filters; /* number of weights for previous rows */
  182223. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182224. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182225. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182226. png_uint_16p filter_costs; /* relative filter calculation cost */
  182227. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182228. #endif
  182229. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182230. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182231. #endif
  182232. /* New members added in libpng-1.0.6 */
  182233. #ifdef PNG_FREE_ME_SUPPORTED
  182234. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182235. #endif
  182236. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182237. png_voidp user_chunk_ptr;
  182238. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182239. #endif
  182240. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182241. int num_chunk_list;
  182242. png_bytep chunk_list;
  182243. #endif
  182244. /* New members added in libpng-1.0.3 */
  182245. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182246. png_byte rgb_to_gray_status;
  182247. /* These were changed from png_byte in libpng-1.0.6 */
  182248. png_uint_16 rgb_to_gray_red_coeff;
  182249. png_uint_16 rgb_to_gray_green_coeff;
  182250. png_uint_16 rgb_to_gray_blue_coeff;
  182251. #endif
  182252. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182253. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182254. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182255. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182256. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182257. #ifdef PNG_1_0_X
  182258. png_byte mng_features_permitted;
  182259. #else
  182260. png_uint_32 mng_features_permitted;
  182261. #endif /* PNG_1_0_X */
  182262. #endif
  182263. /* New member added in libpng-1.0.7 */
  182264. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182265. png_fixed_point int_gamma;
  182266. #endif
  182267. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182268. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182269. png_byte filter_type;
  182270. #endif
  182271. #if defined(PNG_1_0_X)
  182272. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182273. png_uint_32 row_buf_size;
  182274. #endif
  182275. /* New members added in libpng-1.2.0 */
  182276. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182277. # if !defined(PNG_1_0_X)
  182278. # if defined(PNG_MMX_CODE_SUPPORTED)
  182279. png_byte mmx_bitdepth_threshold;
  182280. png_uint_32 mmx_rowbytes_threshold;
  182281. # endif
  182282. png_uint_32 asm_flags;
  182283. # endif
  182284. #endif
  182285. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182286. #ifdef PNG_USER_MEM_SUPPORTED
  182287. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182288. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182289. png_free_ptr free_fn; /* function for freeing memory */
  182290. #endif
  182291. /* New member added in libpng-1.0.13 and 1.2.0 */
  182292. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182293. #if defined(PNG_READ_DITHER_SUPPORTED)
  182294. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182295. png_bytep dither_sort; /* working sort array */
  182296. png_bytep index_to_palette; /* where the original index currently is */
  182297. /* in the palette */
  182298. png_bytep palette_to_index; /* which original index points to this */
  182299. /* palette color */
  182300. #endif
  182301. /* New members added in libpng-1.0.16 and 1.2.6 */
  182302. png_byte compression_type;
  182303. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182304. png_uint_32 user_width_max;
  182305. png_uint_32 user_height_max;
  182306. #endif
  182307. /* New member added in libpng-1.0.25 and 1.2.17 */
  182308. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182309. /* storage for unknown chunk that the library doesn't recognize. */
  182310. png_unknown_chunk unknown_chunk;
  182311. #endif
  182312. };
  182313. /* This triggers a compiler error in png.c, if png.c and png.h
  182314. * do not agree upon the version number.
  182315. */
  182316. typedef png_structp version_1_2_21;
  182317. typedef png_struct FAR * FAR * png_structpp;
  182318. /* Here are the function definitions most commonly used. This is not
  182319. * the place to find out how to use libpng. See libpng.txt for the
  182320. * full explanation, see example.c for the summary. This just provides
  182321. * a simple one line description of the use of each function.
  182322. */
  182323. /* Returns the version number of the library */
  182324. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182325. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182326. * Handling more than 8 bytes from the beginning of the file is an error.
  182327. */
  182328. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182329. int num_bytes));
  182330. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182331. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182332. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182333. * start > 7 will always fail (ie return non-zero).
  182334. */
  182335. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182336. png_size_t num_to_check));
  182337. /* Simple signature checking function. This is the same as calling
  182338. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182339. */
  182340. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182341. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182342. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182343. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182344. png_error_ptr error_fn, png_error_ptr warn_fn));
  182345. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182346. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182347. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182348. png_error_ptr error_fn, png_error_ptr warn_fn));
  182349. #ifdef PNG_WRITE_SUPPORTED
  182350. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182351. PNGARG((png_structp png_ptr));
  182352. #endif
  182353. #ifdef PNG_WRITE_SUPPORTED
  182354. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182355. PNGARG((png_structp png_ptr, png_uint_32 size));
  182356. #endif
  182357. /* Reset the compression stream */
  182358. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182359. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182360. #ifdef PNG_USER_MEM_SUPPORTED
  182361. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182362. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182363. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182364. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182365. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182366. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182367. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182368. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182369. #endif
  182370. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182371. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182372. png_bytep chunk_name, png_bytep data, png_size_t length));
  182373. /* Write the start of a PNG chunk - length and chunk name. */
  182374. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182375. png_bytep chunk_name, png_uint_32 length));
  182376. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182377. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182378. png_bytep data, png_size_t length));
  182379. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182380. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182381. /* Allocate and initialize the info structure */
  182382. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182383. PNGARG((png_structp png_ptr));
  182384. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182385. /* Initialize the info structure (old interface - DEPRECATED) */
  182386. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182387. #undef png_info_init
  182388. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182389. png_sizeof(png_info));
  182390. #endif
  182391. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182392. png_size_t png_info_struct_size));
  182393. /* Writes all the PNG information before the image. */
  182394. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182395. png_infop info_ptr));
  182396. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182397. png_infop info_ptr));
  182398. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182399. /* read the information before the actual image data. */
  182400. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182401. png_infop info_ptr));
  182402. #endif
  182403. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182404. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182405. PNGARG((png_structp png_ptr, png_timep ptime));
  182406. #endif
  182407. #if !defined(_WIN32_WCE)
  182408. /* "time.h" functions are not supported on WindowsCE */
  182409. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182410. /* convert from a struct tm to png_time */
  182411. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182412. struct tm FAR * ttime));
  182413. /* convert from time_t to png_time. Uses gmtime() */
  182414. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182415. time_t ttime));
  182416. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182417. #endif /* _WIN32_WCE */
  182418. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182419. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182420. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182421. #if !defined(PNG_1_0_X)
  182422. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182423. png_ptr));
  182424. #endif
  182425. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182426. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182427. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182428. /* Deprecated */
  182429. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182430. #endif
  182431. #endif
  182432. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182433. /* Use blue, green, red order for pixels. */
  182434. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182435. #endif
  182436. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182437. /* Expand the grayscale to 24-bit RGB if necessary. */
  182438. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182439. #endif
  182440. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182441. /* Reduce RGB to grayscale. */
  182442. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182443. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182444. int error_action, double red, double green ));
  182445. #endif
  182446. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182447. int error_action, png_fixed_point red, png_fixed_point green ));
  182448. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182449. png_ptr));
  182450. #endif
  182451. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182452. png_colorp palette));
  182453. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182454. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182455. #endif
  182456. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182457. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182458. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182459. #endif
  182460. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182461. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182462. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182463. #endif
  182464. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182465. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182466. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182467. png_uint_32 filler, int flags));
  182468. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182469. #define PNG_FILLER_BEFORE 0
  182470. #define PNG_FILLER_AFTER 1
  182471. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182472. #if !defined(PNG_1_0_X)
  182473. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182474. png_uint_32 filler, int flags));
  182475. #endif
  182476. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182477. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182478. /* Swap bytes in 16-bit depth files. */
  182479. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182480. #endif
  182481. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182482. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182483. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182484. #endif
  182485. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182486. /* Swap packing order of pixels in bytes. */
  182487. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182488. #endif
  182489. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182490. /* Converts files to legal bit depths. */
  182491. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182492. png_color_8p true_bits));
  182493. #endif
  182494. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182495. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182496. /* Have the code handle the interlacing. Returns the number of passes. */
  182497. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182498. #endif
  182499. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182500. /* Invert monochrome files */
  182501. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182502. #endif
  182503. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182504. /* Handle alpha and tRNS by replacing with a background color. */
  182505. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182506. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182507. png_color_16p background_color, int background_gamma_code,
  182508. int need_expand, double background_gamma));
  182509. #endif
  182510. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182511. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182512. #define PNG_BACKGROUND_GAMMA_FILE 2
  182513. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182514. #endif
  182515. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182516. /* strip the second byte of information from a 16-bit depth file. */
  182517. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182518. #endif
  182519. #if defined(PNG_READ_DITHER_SUPPORTED)
  182520. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182521. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182522. png_colorp palette, int num_palette, int maximum_colors,
  182523. png_uint_16p histogram, int full_dither));
  182524. #endif
  182525. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182526. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182527. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182528. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182529. double screen_gamma, double default_file_gamma));
  182530. #endif
  182531. #endif
  182532. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182533. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182534. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182535. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182536. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182537. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182538. int empty_plte_permitted));
  182539. #endif
  182540. #endif
  182541. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182542. /* Set how many lines between output flushes - 0 for no flushing */
  182543. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182544. /* Flush the current PNG output buffer */
  182545. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182546. #endif
  182547. /* optional update palette with requested transformations */
  182548. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182549. /* optional call to update the users info structure */
  182550. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182551. png_infop info_ptr));
  182552. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182553. /* read one or more rows of image data. */
  182554. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182555. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182556. #endif
  182557. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182558. /* read a row of data. */
  182559. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182560. png_bytep row,
  182561. png_bytep display_row));
  182562. #endif
  182563. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182564. /* read the whole image into memory at once. */
  182565. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182566. png_bytepp image));
  182567. #endif
  182568. /* write a row of image data */
  182569. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182570. png_bytep row));
  182571. /* write a few rows of image data */
  182572. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182573. png_bytepp row, png_uint_32 num_rows));
  182574. /* write the image data */
  182575. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182576. png_bytepp image));
  182577. /* writes the end of the PNG file. */
  182578. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182579. png_infop info_ptr));
  182580. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182581. /* read the end of the PNG file. */
  182582. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182583. png_infop info_ptr));
  182584. #endif
  182585. /* free any memory associated with the png_info_struct */
  182586. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182587. png_infopp info_ptr_ptr));
  182588. /* free any memory associated with the png_struct and the png_info_structs */
  182589. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182590. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182591. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182592. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182593. png_infop end_info_ptr));
  182594. /* free any memory associated with the png_struct and the png_info_structs */
  182595. extern PNG_EXPORT(void,png_destroy_write_struct)
  182596. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182597. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182598. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182599. /* set the libpng method of handling chunk CRC errors */
  182600. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182601. int crit_action, int ancil_action));
  182602. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182603. * ancillary and critical chunks, and whether to use the data contained
  182604. * therein. Note that it is impossible to "discard" data in a critical
  182605. * chunk. For versions prior to 0.90, the action was always error/quit,
  182606. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182607. * chunks is warn/discard. These values should NOT be changed.
  182608. *
  182609. * value action:critical action:ancillary
  182610. */
  182611. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182612. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182613. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182614. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182615. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182616. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182617. /* These functions give the user control over the scan-line filtering in
  182618. * libpng and the compression methods used by zlib. These functions are
  182619. * mainly useful for testing, as the defaults should work with most users.
  182620. * Those users who are tight on memory or want faster performance at the
  182621. * expense of compression can modify them. See the compression library
  182622. * header file (zlib.h) for an explination of the compression functions.
  182623. */
  182624. /* set the filtering method(s) used by libpng. Currently, the only valid
  182625. * value for "method" is 0.
  182626. */
  182627. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182628. int filters));
  182629. /* Flags for png_set_filter() to say which filters to use. The flags
  182630. * are chosen so that they don't conflict with real filter types
  182631. * below, in case they are supplied instead of the #defined constants.
  182632. * These values should NOT be changed.
  182633. */
  182634. #define PNG_NO_FILTERS 0x00
  182635. #define PNG_FILTER_NONE 0x08
  182636. #define PNG_FILTER_SUB 0x10
  182637. #define PNG_FILTER_UP 0x20
  182638. #define PNG_FILTER_AVG 0x40
  182639. #define PNG_FILTER_PAETH 0x80
  182640. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182641. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182642. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182643. * These defines should NOT be changed.
  182644. */
  182645. #define PNG_FILTER_VALUE_NONE 0
  182646. #define PNG_FILTER_VALUE_SUB 1
  182647. #define PNG_FILTER_VALUE_UP 2
  182648. #define PNG_FILTER_VALUE_AVG 3
  182649. #define PNG_FILTER_VALUE_PAETH 4
  182650. #define PNG_FILTER_VALUE_LAST 5
  182651. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182652. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182653. * defines, either the default (minimum-sum-of-absolute-differences), or
  182654. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182655. *
  182656. * Weights are factors >= 1.0, indicating how important it is to keep the
  182657. * filter type consistent between rows. Larger numbers mean the current
  182658. * filter is that many times as likely to be the same as the "num_weights"
  182659. * previous filters. This is cumulative for each previous row with a weight.
  182660. * There needs to be "num_weights" values in "filter_weights", or it can be
  182661. * NULL if the weights aren't being specified. Weights have no influence on
  182662. * the selection of the first row filter. Well chosen weights can (in theory)
  182663. * improve the compression for a given image.
  182664. *
  182665. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182666. * filter type. Higher costs indicate more decoding expense, and are
  182667. * therefore less likely to be selected over a filter with lower computational
  182668. * costs. There needs to be a value in "filter_costs" for each valid filter
  182669. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182670. * setting the costs. Costs try to improve the speed of decompression without
  182671. * unduly increasing the compressed image size.
  182672. *
  182673. * A negative weight or cost indicates the default value is to be used, and
  182674. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182675. * The default values for both weights and costs are currently 1.0, but may
  182676. * change if good general weighting/cost heuristics can be found. If both
  182677. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182678. * to the UNWEIGHTED method, but with added encoding time/computation.
  182679. */
  182680. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182681. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182682. int heuristic_method, int num_weights, png_doublep filter_weights,
  182683. png_doublep filter_costs));
  182684. #endif
  182685. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182686. /* Heuristic used for row filter selection. These defines should NOT be
  182687. * changed.
  182688. */
  182689. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182690. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182691. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182692. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182693. /* Set the library compression level. Currently, valid values range from
  182694. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182695. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182696. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182697. * for PNG images, and do considerably fewer caclulations. In the future,
  182698. * these values may not correspond directly to the zlib compression levels.
  182699. */
  182700. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182701. int level));
  182702. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182703. PNGARG((png_structp png_ptr, int mem_level));
  182704. extern PNG_EXPORT(void,png_set_compression_strategy)
  182705. PNGARG((png_structp png_ptr, int strategy));
  182706. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182707. PNGARG((png_structp png_ptr, int window_bits));
  182708. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182709. int method));
  182710. /* These next functions are called for input/output, memory, and error
  182711. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182712. * and call standard C I/O routines such as fread(), fwrite(), and
  182713. * fprintf(). These functions can be made to use other I/O routines
  182714. * at run time for those applications that need to handle I/O in a
  182715. * different manner by calling png_set_???_fn(). See libpng.txt for
  182716. * more information.
  182717. */
  182718. #if !defined(PNG_NO_STDIO)
  182719. /* Initialize the input/output for the PNG file to the default functions. */
  182720. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182721. #endif
  182722. /* Replace the (error and abort), and warning functions with user
  182723. * supplied functions. If no messages are to be printed you must still
  182724. * write and use replacement functions. The replacement error_fn should
  182725. * still do a longjmp to the last setjmp location if you are using this
  182726. * method of error handling. If error_fn or warning_fn is NULL, the
  182727. * default function will be used.
  182728. */
  182729. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182730. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182731. /* Return the user pointer associated with the error functions */
  182732. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182733. /* Replace the default data output functions with a user supplied one(s).
  182734. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182735. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182736. * output_flush_fn will be ignored (and thus can be NULL).
  182737. */
  182738. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182739. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182740. /* Replace the default data input function with a user supplied one. */
  182741. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182742. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182743. /* Return the user pointer associated with the I/O functions */
  182744. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182745. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182746. png_read_status_ptr read_row_fn));
  182747. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182748. png_write_status_ptr write_row_fn));
  182749. #ifdef PNG_USER_MEM_SUPPORTED
  182750. /* Replace the default memory allocation functions with user supplied one(s). */
  182751. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182752. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182753. /* Return the user pointer associated with the memory functions */
  182754. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182755. #endif
  182756. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182757. defined(PNG_LEGACY_SUPPORTED)
  182758. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182759. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182760. #endif
  182761. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182762. defined(PNG_LEGACY_SUPPORTED)
  182763. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182764. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182765. #endif
  182766. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182767. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182768. defined(PNG_LEGACY_SUPPORTED)
  182769. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182770. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182771. int user_transform_channels));
  182772. /* Return the user pointer associated with the user transform functions */
  182773. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182774. PNGARG((png_structp png_ptr));
  182775. #endif
  182776. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182777. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182778. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182779. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182780. png_ptr));
  182781. #endif
  182782. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182783. /* Sets the function callbacks for the push reader, and a pointer to a
  182784. * user-defined structure available to the callback functions.
  182785. */
  182786. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182787. png_voidp progressive_ptr,
  182788. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182789. png_progressive_end_ptr end_fn));
  182790. /* returns the user pointer associated with the push read functions */
  182791. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182792. PNGARG((png_structp png_ptr));
  182793. /* function to be called when data becomes available */
  182794. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182795. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182796. /* function that combines rows. Not very much different than the
  182797. * png_combine_row() call. Is this even used?????
  182798. */
  182799. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182800. png_bytep old_row, png_bytep new_row));
  182801. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182802. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182803. png_uint_32 size));
  182804. #if defined(PNG_1_0_X)
  182805. # define png_malloc_warn png_malloc
  182806. #else
  182807. /* Added at libpng version 1.2.4 */
  182808. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182809. png_uint_32 size));
  182810. #endif
  182811. /* frees a pointer allocated by png_malloc() */
  182812. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182813. #if defined(PNG_1_0_X)
  182814. /* Function to allocate memory for zlib. */
  182815. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182816. uInt size));
  182817. /* Function to free memory for zlib */
  182818. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182819. #endif
  182820. /* Free data that was allocated internally */
  182821. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182822. png_infop info_ptr, png_uint_32 free_me, int num));
  182823. #ifdef PNG_FREE_ME_SUPPORTED
  182824. /* Reassign responsibility for freeing existing data, whether allocated
  182825. * by libpng or by the application */
  182826. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182827. png_infop info_ptr, int freer, png_uint_32 mask));
  182828. #endif
  182829. /* assignments for png_data_freer */
  182830. #define PNG_DESTROY_WILL_FREE_DATA 1
  182831. #define PNG_SET_WILL_FREE_DATA 1
  182832. #define PNG_USER_WILL_FREE_DATA 2
  182833. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182834. #define PNG_FREE_HIST 0x0008
  182835. #define PNG_FREE_ICCP 0x0010
  182836. #define PNG_FREE_SPLT 0x0020
  182837. #define PNG_FREE_ROWS 0x0040
  182838. #define PNG_FREE_PCAL 0x0080
  182839. #define PNG_FREE_SCAL 0x0100
  182840. #define PNG_FREE_UNKN 0x0200
  182841. #define PNG_FREE_LIST 0x0400
  182842. #define PNG_FREE_PLTE 0x1000
  182843. #define PNG_FREE_TRNS 0x2000
  182844. #define PNG_FREE_TEXT 0x4000
  182845. #define PNG_FREE_ALL 0x7fff
  182846. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182847. #ifdef PNG_USER_MEM_SUPPORTED
  182848. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182849. png_uint_32 size));
  182850. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182851. png_voidp ptr));
  182852. #endif
  182853. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182854. png_voidp s1, png_voidp s2, png_uint_32 size));
  182855. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182856. png_voidp s1, int value, png_uint_32 size));
  182857. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182858. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182859. int check));
  182860. #endif /* USE_FAR_KEYWORD */
  182861. #ifndef PNG_NO_ERROR_TEXT
  182862. /* Fatal error in PNG image of libpng - can't continue */
  182863. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182864. png_const_charp error_message));
  182865. /* The same, but the chunk name is prepended to the error string. */
  182866. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182867. png_const_charp error_message));
  182868. #else
  182869. /* Fatal error in PNG image of libpng - can't continue */
  182870. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182871. #endif
  182872. #ifndef PNG_NO_WARNINGS
  182873. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182874. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182875. png_const_charp warning_message));
  182876. #ifdef PNG_READ_SUPPORTED
  182877. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182878. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182879. png_const_charp warning_message));
  182880. #endif /* PNG_READ_SUPPORTED */
  182881. #endif /* PNG_NO_WARNINGS */
  182882. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182883. * Similarly, the png_get_<chunk> calls are used to read values from the
  182884. * png_info_struct, either storing the parameters in the passed variables, or
  182885. * setting pointers into the png_info_struct where the data is stored. The
  182886. * png_get_<chunk> functions return a non-zero value if the data was available
  182887. * in info_ptr, or return zero and do not change any of the parameters if the
  182888. * data was not available.
  182889. *
  182890. * These functions should be used instead of directly accessing png_info
  182891. * to avoid problems with future changes in the size and internal layout of
  182892. * png_info_struct.
  182893. */
  182894. /* Returns "flag" if chunk data is valid in info_ptr. */
  182895. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182896. png_infop info_ptr, png_uint_32 flag));
  182897. /* Returns number of bytes needed to hold a transformed row. */
  182898. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182899. png_infop info_ptr));
  182900. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182901. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182902. returned from png_read_png(). */
  182903. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182904. png_infop info_ptr));
  182905. /* Set row_pointers, which is an array of pointers to scanlines for use
  182906. by png_write_png(). */
  182907. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182908. png_infop info_ptr, png_bytepp row_pointers));
  182909. #endif
  182910. /* Returns number of color channels in image. */
  182911. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182912. png_infop info_ptr));
  182913. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182914. /* Returns image width in pixels. */
  182915. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182916. png_ptr, png_infop info_ptr));
  182917. /* Returns image height in pixels. */
  182918. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182919. png_ptr, png_infop info_ptr));
  182920. /* Returns image bit_depth. */
  182921. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182922. png_ptr, png_infop info_ptr));
  182923. /* Returns image color_type. */
  182924. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182925. png_ptr, png_infop info_ptr));
  182926. /* Returns image filter_type. */
  182927. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182928. png_ptr, png_infop info_ptr));
  182929. /* Returns image interlace_type. */
  182930. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182931. png_ptr, png_infop info_ptr));
  182932. /* Returns image compression_type. */
  182933. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182934. png_ptr, png_infop info_ptr));
  182935. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182936. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182937. png_ptr, png_infop info_ptr));
  182938. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182939. png_ptr, png_infop info_ptr));
  182940. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182941. png_ptr, png_infop info_ptr));
  182942. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182943. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182944. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182945. png_ptr, png_infop info_ptr));
  182946. #endif
  182947. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182948. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182949. png_ptr, png_infop info_ptr));
  182950. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182951. png_ptr, png_infop info_ptr));
  182952. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182953. png_ptr, png_infop info_ptr));
  182954. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182955. png_ptr, png_infop info_ptr));
  182956. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182957. /* Returns pointer to signature string read from PNG header */
  182958. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182959. png_infop info_ptr));
  182960. #if defined(PNG_bKGD_SUPPORTED)
  182961. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182962. png_infop info_ptr, png_color_16p *background));
  182963. #endif
  182964. #if defined(PNG_bKGD_SUPPORTED)
  182965. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182966. png_infop info_ptr, png_color_16p background));
  182967. #endif
  182968. #if defined(PNG_cHRM_SUPPORTED)
  182969. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182970. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182971. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182972. double *red_y, double *green_x, double *green_y, double *blue_x,
  182973. double *blue_y));
  182974. #endif
  182975. #ifdef PNG_FIXED_POINT_SUPPORTED
  182976. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182977. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182978. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182979. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182980. *int_blue_x, png_fixed_point *int_blue_y));
  182981. #endif
  182982. #endif
  182983. #if defined(PNG_cHRM_SUPPORTED)
  182984. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182985. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182986. png_infop info_ptr, double white_x, double white_y, double red_x,
  182987. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182988. #endif
  182989. #ifdef PNG_FIXED_POINT_SUPPORTED
  182990. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182991. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182992. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182993. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182994. png_fixed_point int_blue_y));
  182995. #endif
  182996. #endif
  182997. #if defined(PNG_gAMA_SUPPORTED)
  182998. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182999. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183000. png_infop info_ptr, double *file_gamma));
  183001. #endif
  183002. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183003. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183004. #endif
  183005. #if defined(PNG_gAMA_SUPPORTED)
  183006. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183007. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183008. png_infop info_ptr, double file_gamma));
  183009. #endif
  183010. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183011. png_infop info_ptr, png_fixed_point int_file_gamma));
  183012. #endif
  183013. #if defined(PNG_hIST_SUPPORTED)
  183014. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183015. png_infop info_ptr, png_uint_16p *hist));
  183016. #endif
  183017. #if defined(PNG_hIST_SUPPORTED)
  183018. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183019. png_infop info_ptr, png_uint_16p hist));
  183020. #endif
  183021. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183022. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183023. int *bit_depth, int *color_type, int *interlace_method,
  183024. int *compression_method, int *filter_method));
  183025. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183026. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183027. int color_type, int interlace_method, int compression_method,
  183028. int filter_method));
  183029. #if defined(PNG_oFFs_SUPPORTED)
  183030. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183031. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183032. int *unit_type));
  183033. #endif
  183034. #if defined(PNG_oFFs_SUPPORTED)
  183035. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183036. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183037. int unit_type));
  183038. #endif
  183039. #if defined(PNG_pCAL_SUPPORTED)
  183040. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183041. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183042. int *type, int *nparams, png_charp *units, png_charpp *params));
  183043. #endif
  183044. #if defined(PNG_pCAL_SUPPORTED)
  183045. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183046. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183047. int type, int nparams, png_charp units, png_charpp params));
  183048. #endif
  183049. #if defined(PNG_pHYs_SUPPORTED)
  183050. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183051. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183052. #endif
  183053. #if defined(PNG_pHYs_SUPPORTED)
  183054. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183055. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183056. #endif
  183057. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183058. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183059. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183060. png_infop info_ptr, png_colorp palette, int num_palette));
  183061. #if defined(PNG_sBIT_SUPPORTED)
  183062. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183063. png_infop info_ptr, png_color_8p *sig_bit));
  183064. #endif
  183065. #if defined(PNG_sBIT_SUPPORTED)
  183066. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183067. png_infop info_ptr, png_color_8p sig_bit));
  183068. #endif
  183069. #if defined(PNG_sRGB_SUPPORTED)
  183070. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183071. png_infop info_ptr, int *intent));
  183072. #endif
  183073. #if defined(PNG_sRGB_SUPPORTED)
  183074. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183075. png_infop info_ptr, int intent));
  183076. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183077. png_infop info_ptr, int intent));
  183078. #endif
  183079. #if defined(PNG_iCCP_SUPPORTED)
  183080. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183081. png_infop info_ptr, png_charpp name, int *compression_type,
  183082. png_charpp profile, png_uint_32 *proflen));
  183083. /* Note to maintainer: profile should be png_bytepp */
  183084. #endif
  183085. #if defined(PNG_iCCP_SUPPORTED)
  183086. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183087. png_infop info_ptr, png_charp name, int compression_type,
  183088. png_charp profile, png_uint_32 proflen));
  183089. /* Note to maintainer: profile should be png_bytep */
  183090. #endif
  183091. #if defined(PNG_sPLT_SUPPORTED)
  183092. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183093. png_infop info_ptr, png_sPLT_tpp entries));
  183094. #endif
  183095. #if defined(PNG_sPLT_SUPPORTED)
  183096. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183097. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183098. #endif
  183099. #if defined(PNG_TEXT_SUPPORTED)
  183100. /* png_get_text also returns the number of text chunks in *num_text */
  183101. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183102. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183103. #endif
  183104. /*
  183105. * Note while png_set_text() will accept a structure whose text,
  183106. * language, and translated keywords are NULL pointers, the structure
  183107. * returned by png_get_text will always contain regular
  183108. * zero-terminated C strings. They might be empty strings but
  183109. * they will never be NULL pointers.
  183110. */
  183111. #if defined(PNG_TEXT_SUPPORTED)
  183112. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183113. png_infop info_ptr, png_textp text_ptr, int num_text));
  183114. #endif
  183115. #if defined(PNG_tIME_SUPPORTED)
  183116. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183117. png_infop info_ptr, png_timep *mod_time));
  183118. #endif
  183119. #if defined(PNG_tIME_SUPPORTED)
  183120. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183121. png_infop info_ptr, png_timep mod_time));
  183122. #endif
  183123. #if defined(PNG_tRNS_SUPPORTED)
  183124. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183125. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183126. png_color_16p *trans_values));
  183127. #endif
  183128. #if defined(PNG_tRNS_SUPPORTED)
  183129. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183130. png_infop info_ptr, png_bytep trans, int num_trans,
  183131. png_color_16p trans_values));
  183132. #endif
  183133. #if defined(PNG_tRNS_SUPPORTED)
  183134. #endif
  183135. #if defined(PNG_sCAL_SUPPORTED)
  183136. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183137. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183138. png_infop info_ptr, int *unit, double *width, double *height));
  183139. #else
  183140. #ifdef PNG_FIXED_POINT_SUPPORTED
  183141. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183142. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183143. #endif
  183144. #endif
  183145. #endif /* PNG_sCAL_SUPPORTED */
  183146. #if defined(PNG_sCAL_SUPPORTED)
  183147. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183148. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183149. png_infop info_ptr, int unit, double width, double height));
  183150. #else
  183151. #ifdef PNG_FIXED_POINT_SUPPORTED
  183152. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183153. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183154. #endif
  183155. #endif
  183156. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183157. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183158. /* provide a list of chunks and how they are to be handled, if the built-in
  183159. handling or default unknown chunk handling is not desired. Any chunks not
  183160. listed will be handled in the default manner. The IHDR and IEND chunks
  183161. must not be listed.
  183162. keep = 0: follow default behaviour
  183163. = 1: do not keep
  183164. = 2: keep only if safe-to-copy
  183165. = 3: keep even if unsafe-to-copy
  183166. */
  183167. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183168. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183169. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183170. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183171. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183172. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183173. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183174. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183175. #endif
  183176. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183177. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183178. chunk_name));
  183179. #endif
  183180. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183181. If you need to turn it off for a chunk that your application has freed,
  183182. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183183. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183184. png_infop info_ptr, int mask));
  183185. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183186. /* The "params" pointer is currently not used and is for future expansion. */
  183187. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183188. png_infop info_ptr,
  183189. int transforms,
  183190. png_voidp params));
  183191. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183192. png_infop info_ptr,
  183193. int transforms,
  183194. png_voidp params));
  183195. #endif
  183196. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183197. * numbers for PNG_DEBUG mean more debugging information. This has
  183198. * only been added since version 0.95 so it is not implemented throughout
  183199. * libpng yet, but more support will be added as needed.
  183200. */
  183201. #ifdef PNG_DEBUG
  183202. #if (PNG_DEBUG > 0)
  183203. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183204. #include <crtdbg.h>
  183205. #if (PNG_DEBUG > 1)
  183206. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183207. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183208. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183209. #endif
  183210. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183211. #ifndef PNG_DEBUG_FILE
  183212. #define PNG_DEBUG_FILE stderr
  183213. #endif /* PNG_DEBUG_FILE */
  183214. #if (PNG_DEBUG > 1)
  183215. #define png_debug(l,m) \
  183216. { \
  183217. int num_tabs=l; \
  183218. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183219. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183220. }
  183221. #define png_debug1(l,m,p1) \
  183222. { \
  183223. int num_tabs=l; \
  183224. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183225. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183226. }
  183227. #define png_debug2(l,m,p1,p2) \
  183228. { \
  183229. int num_tabs=l; \
  183230. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183231. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183232. }
  183233. #endif /* (PNG_DEBUG > 1) */
  183234. #endif /* _MSC_VER */
  183235. #endif /* (PNG_DEBUG > 0) */
  183236. #endif /* PNG_DEBUG */
  183237. #ifndef png_debug
  183238. #define png_debug(l, m)
  183239. #endif
  183240. #ifndef png_debug1
  183241. #define png_debug1(l, m, p1)
  183242. #endif
  183243. #ifndef png_debug2
  183244. #define png_debug2(l, m, p1, p2)
  183245. #endif
  183246. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183247. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183248. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183249. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183250. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183251. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183252. png_ptr, png_uint_32 mng_features_permitted));
  183253. #endif
  183254. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183255. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183256. #define PNG_HANDLE_CHUNK_NEVER 1
  183257. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183258. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183259. /* Added to version 1.2.0 */
  183260. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183261. #if defined(PNG_MMX_CODE_SUPPORTED)
  183262. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183263. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183264. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183265. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183266. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183267. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183268. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183269. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183270. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183271. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183272. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183273. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183274. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183275. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183276. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183277. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183278. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183279. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183280. | PNG_MMX_READ_FLAGS \
  183281. | PNG_MMX_WRITE_FLAGS )
  183282. #define PNG_SELECT_READ 1
  183283. #define PNG_SELECT_WRITE 2
  183284. #endif /* PNG_MMX_CODE_SUPPORTED */
  183285. #if !defined(PNG_1_0_X)
  183286. /* pngget.c */
  183287. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183288. PNGARG((int flag_select, int *compilerID));
  183289. /* pngget.c */
  183290. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183291. PNGARG((int flag_select));
  183292. /* pngget.c */
  183293. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183294. PNGARG((png_structp png_ptr));
  183295. /* pngget.c */
  183296. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183297. PNGARG((png_structp png_ptr));
  183298. /* pngget.c */
  183299. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183300. PNGARG((png_structp png_ptr));
  183301. /* pngset.c */
  183302. extern PNG_EXPORT(void,png_set_asm_flags)
  183303. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183304. /* pngset.c */
  183305. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183306. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183307. png_uint_32 mmx_rowbytes_threshold));
  183308. #endif /* PNG_1_0_X */
  183309. #if !defined(PNG_1_0_X)
  183310. /* png.c, pnggccrd.c, or pngvcrd.c */
  183311. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183312. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183313. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183314. * messages before passing them to the error or warning handler. */
  183315. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183316. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183317. png_ptr, png_uint_32 strip_mode));
  183318. #endif
  183319. #endif /* PNG_1_0_X */
  183320. /* Added at libpng-1.2.6 */
  183321. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183322. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183323. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183324. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183325. png_ptr));
  183326. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183327. png_ptr));
  183328. #endif
  183329. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183330. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183331. /* With these routines we avoid an integer divide, which will be slower on
  183332. * most machines. However, it does take more operations than the corresponding
  183333. * divide method, so it may be slower on a few RISC systems. There are two
  183334. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183335. *
  183336. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183337. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183338. * standard method.
  183339. *
  183340. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183341. */
  183342. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183343. # define png_composite(composite, fg, alpha, bg) \
  183344. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183345. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183346. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183347. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183348. # define png_composite_16(composite, fg, alpha, bg) \
  183349. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183350. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183351. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183352. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183353. #else /* standard method using integer division */
  183354. # define png_composite(composite, fg, alpha, bg) \
  183355. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183356. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183357. (png_uint_16)127) / 255)
  183358. # define png_composite_16(composite, fg, alpha, bg) \
  183359. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183360. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183361. (png_uint_32)32767) / (png_uint_32)65535L)
  183362. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183363. /* Inline macros to do direct reads of bytes from the input buffer. These
  183364. * require that you are using an architecture that uses PNG byte ordering
  183365. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183366. * in big-endian mode and 680x0 are the only ones that will support this.
  183367. * The x86 line of processors definitely do not. The png_get_int_32()
  183368. * routine also assumes we are using two's complement format for negative
  183369. * values, which is almost certainly true.
  183370. */
  183371. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183372. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183373. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183374. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183375. #else
  183376. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183377. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183378. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183379. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183380. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183381. PNGARG((png_structp png_ptr, png_bytep buf));
  183382. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183383. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183384. */
  183385. extern PNG_EXPORT(void,png_save_uint_32)
  183386. PNGARG((png_bytep buf, png_uint_32 i));
  183387. extern PNG_EXPORT(void,png_save_int_32)
  183388. PNGARG((png_bytep buf, png_int_32 i));
  183389. /* Place a 16-bit number into a buffer in PNG byte order.
  183390. * The parameter is declared unsigned int, not png_uint_16,
  183391. * just to avoid potential problems on pre-ANSI C compilers.
  183392. */
  183393. extern PNG_EXPORT(void,png_save_uint_16)
  183394. PNGARG((png_bytep buf, unsigned int i));
  183395. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183396. /* ************************************************************************* */
  183397. /* These next functions are used internally in the code. They generally
  183398. * shouldn't be used unless you are writing code to add or replace some
  183399. * functionality in libpng. More information about most functions can
  183400. * be found in the files where the functions are located.
  183401. */
  183402. /* Various modes of operation, that are visible to applications because
  183403. * they are used for unknown chunk location.
  183404. */
  183405. #define PNG_HAVE_IHDR 0x01
  183406. #define PNG_HAVE_PLTE 0x02
  183407. #define PNG_HAVE_IDAT 0x04
  183408. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183409. #define PNG_HAVE_IEND 0x10
  183410. #if defined(PNG_INTERNAL)
  183411. /* More modes of operation. Note that after an init, mode is set to
  183412. * zero automatically when the structure is created.
  183413. */
  183414. #define PNG_HAVE_gAMA 0x20
  183415. #define PNG_HAVE_cHRM 0x40
  183416. #define PNG_HAVE_sRGB 0x80
  183417. #define PNG_HAVE_CHUNK_HEADER 0x100
  183418. #define PNG_WROTE_tIME 0x200
  183419. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183420. #define PNG_BACKGROUND_IS_GRAY 0x800
  183421. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183422. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183423. /* flags for the transformations the PNG library does on the image data */
  183424. #define PNG_BGR 0x0001
  183425. #define PNG_INTERLACE 0x0002
  183426. #define PNG_PACK 0x0004
  183427. #define PNG_SHIFT 0x0008
  183428. #define PNG_SWAP_BYTES 0x0010
  183429. #define PNG_INVERT_MONO 0x0020
  183430. #define PNG_DITHER 0x0040
  183431. #define PNG_BACKGROUND 0x0080
  183432. #define PNG_BACKGROUND_EXPAND 0x0100
  183433. /* 0x0200 unused */
  183434. #define PNG_16_TO_8 0x0400
  183435. #define PNG_RGBA 0x0800
  183436. #define PNG_EXPAND 0x1000
  183437. #define PNG_GAMMA 0x2000
  183438. #define PNG_GRAY_TO_RGB 0x4000
  183439. #define PNG_FILLER 0x8000L
  183440. #define PNG_PACKSWAP 0x10000L
  183441. #define PNG_SWAP_ALPHA 0x20000L
  183442. #define PNG_STRIP_ALPHA 0x40000L
  183443. #define PNG_INVERT_ALPHA 0x80000L
  183444. #define PNG_USER_TRANSFORM 0x100000L
  183445. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183446. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183447. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183448. /* 0x800000L Unused */
  183449. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183450. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183451. /* 0x4000000L unused */
  183452. /* 0x8000000L unused */
  183453. /* 0x10000000L unused */
  183454. /* 0x20000000L unused */
  183455. /* 0x40000000L unused */
  183456. /* flags for png_create_struct */
  183457. #define PNG_STRUCT_PNG 0x0001
  183458. #define PNG_STRUCT_INFO 0x0002
  183459. /* Scaling factor for filter heuristic weighting calculations */
  183460. #define PNG_WEIGHT_SHIFT 8
  183461. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183462. #define PNG_COST_SHIFT 3
  183463. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183464. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183465. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183466. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183467. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183468. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183469. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183470. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183471. #define PNG_FLAG_ROW_INIT 0x0040
  183472. #define PNG_FLAG_FILLER_AFTER 0x0080
  183473. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183474. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183475. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183476. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183477. #define PNG_FLAG_FREE_PLTE 0x1000
  183478. #define PNG_FLAG_FREE_TRNS 0x2000
  183479. #define PNG_FLAG_FREE_HIST 0x4000
  183480. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183481. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183482. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183483. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183484. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183485. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183486. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183487. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183488. /* 0x800000L unused */
  183489. /* 0x1000000L unused */
  183490. /* 0x2000000L unused */
  183491. /* 0x4000000L unused */
  183492. /* 0x8000000L unused */
  183493. /* 0x10000000L unused */
  183494. /* 0x20000000L unused */
  183495. /* 0x40000000L unused */
  183496. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183497. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183498. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183499. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183500. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183501. PNG_FLAG_CRC_CRITICAL_MASK)
  183502. /* save typing and make code easier to understand */
  183503. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183504. abs((int)((c1).green) - (int)((c2).green)) + \
  183505. abs((int)((c1).blue) - (int)((c2).blue)))
  183506. /* Added to libpng-1.2.6 JB */
  183507. #define PNG_ROWBYTES(pixel_bits, width) \
  183508. ((pixel_bits) >= 8 ? \
  183509. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183510. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183511. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183512. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183513. "ideal" and "delta" should be constants, normally simple
  183514. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183515. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183516. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183517. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183518. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183519. /* place to hold the signature string for a PNG file. */
  183520. #ifdef PNG_USE_GLOBAL_ARRAYS
  183521. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183522. #else
  183523. #endif
  183524. #endif /* PNG_NO_EXTERN */
  183525. /* Constant strings for known chunk types. If you need to add a chunk,
  183526. * define the name here, and add an invocation of the macro in png.c and
  183527. * wherever it's needed.
  183528. */
  183529. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183530. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183531. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183532. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183533. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183534. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183535. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183536. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183537. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183538. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183539. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183540. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183541. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183542. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183543. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183544. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183545. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183546. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183547. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183548. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183549. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183550. #ifdef PNG_USE_GLOBAL_ARRAYS
  183551. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183552. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183553. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183554. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183555. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183556. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183557. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183558. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183559. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183560. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183561. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183562. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183563. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183564. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183565. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183566. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183567. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183568. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183569. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183570. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183571. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183572. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183573. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183574. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183575. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183576. */
  183577. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183578. #undef png_read_init
  183579. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183580. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183581. #endif
  183582. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183583. png_const_charp user_png_ver, png_size_t png_struct_size));
  183584. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183585. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183586. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183587. png_info_size));
  183588. #endif
  183589. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183590. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183591. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183592. */
  183593. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183594. #undef png_write_init
  183595. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183596. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183597. #endif
  183598. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183599. png_const_charp user_png_ver, png_size_t png_struct_size));
  183600. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183601. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183602. png_info_size));
  183603. /* Allocate memory for an internal libpng struct */
  183604. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183605. /* Free memory from internal libpng struct */
  183606. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183607. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183608. malloc_fn, png_voidp mem_ptr));
  183609. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183610. png_free_ptr free_fn, png_voidp mem_ptr));
  183611. /* Free any memory that info_ptr points to and reset struct. */
  183612. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183613. png_infop info_ptr));
  183614. #ifndef PNG_1_0_X
  183615. /* Function to allocate memory for zlib. */
  183616. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183617. /* Function to free memory for zlib */
  183618. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183619. #ifdef PNG_SIZE_T
  183620. /* Function to convert a sizeof an item to png_sizeof item */
  183621. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183622. #endif
  183623. /* Next four functions are used internally as callbacks. PNGAPI is required
  183624. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183625. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183626. png_bytep data, png_size_t length));
  183627. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183628. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183629. png_bytep buffer, png_size_t length));
  183630. #endif
  183631. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183632. png_bytep data, png_size_t length));
  183633. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183634. #if !defined(PNG_NO_STDIO)
  183635. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183636. #endif
  183637. #endif
  183638. #else /* PNG_1_0_X */
  183639. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183640. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183641. png_bytep buffer, png_size_t length));
  183642. #endif
  183643. #endif /* PNG_1_0_X */
  183644. /* Reset the CRC variable */
  183645. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183646. /* Write the "data" buffer to whatever output you are using. */
  183647. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183648. png_size_t length));
  183649. /* Read data from whatever input you are using into the "data" buffer */
  183650. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183651. png_size_t length));
  183652. /* Read bytes into buf, and update png_ptr->crc */
  183653. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183654. png_size_t length));
  183655. /* Decompress data in a chunk that uses compression */
  183656. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183657. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183658. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183659. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183660. png_size_t prefix_length, png_size_t *data_length));
  183661. #endif
  183662. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183663. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183664. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183665. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183666. /* Calculate the CRC over a section of data. Note that we are only
  183667. * passing a maximum of 64K on systems that have this as a memory limit,
  183668. * since this is the maximum buffer size we can specify.
  183669. */
  183670. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183671. png_size_t length));
  183672. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183673. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183674. #endif
  183675. /* simple function to write the signature */
  183676. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183677. /* write various chunks */
  183678. /* Write the IHDR chunk, and update the png_struct with the necessary
  183679. * information.
  183680. */
  183681. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183682. png_uint_32 height,
  183683. int bit_depth, int color_type, int compression_method, int filter_method,
  183684. int interlace_method));
  183685. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183686. png_uint_32 num_pal));
  183687. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183688. png_size_t length));
  183689. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183690. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183691. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183692. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183693. #endif
  183694. #ifdef PNG_FIXED_POINT_SUPPORTED
  183695. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183696. file_gamma));
  183697. #endif
  183698. #endif
  183699. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183700. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183701. int color_type));
  183702. #endif
  183703. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183704. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183705. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183706. double white_x, double white_y,
  183707. double red_x, double red_y, double green_x, double green_y,
  183708. double blue_x, double blue_y));
  183709. #endif
  183710. #ifdef PNG_FIXED_POINT_SUPPORTED
  183711. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183712. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183713. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183714. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183715. png_fixed_point int_blue_y));
  183716. #endif
  183717. #endif
  183718. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183719. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183720. int intent));
  183721. #endif
  183722. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183723. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183724. png_charp name, int compression_type,
  183725. png_charp profile, int proflen));
  183726. /* Note to maintainer: profile should be png_bytep */
  183727. #endif
  183728. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183729. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183730. png_sPLT_tp palette));
  183731. #endif
  183732. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183733. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183734. png_color_16p values, int number, int color_type));
  183735. #endif
  183736. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183737. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183738. png_color_16p values, int color_type));
  183739. #endif
  183740. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183741. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183742. int num_hist));
  183743. #endif
  183744. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183745. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183746. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183747. png_charp key, png_charpp new_key));
  183748. #endif
  183749. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183750. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183751. png_charp text, png_size_t text_len));
  183752. #endif
  183753. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183754. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183755. png_charp text, png_size_t text_len, int compression));
  183756. #endif
  183757. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183758. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183759. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183760. png_charp text));
  183761. #endif
  183762. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183763. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183764. png_infop info_ptr, png_textp text_ptr, int num_text));
  183765. #endif
  183766. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183767. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183768. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183769. #endif
  183770. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183771. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183772. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183773. png_charp units, png_charpp params));
  183774. #endif
  183775. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183776. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183777. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183778. int unit_type));
  183779. #endif
  183780. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183781. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183782. png_timep mod_time));
  183783. #endif
  183784. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183785. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183786. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183787. int unit, double width, double height));
  183788. #else
  183789. #ifdef PNG_FIXED_POINT_SUPPORTED
  183790. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183791. int unit, png_charp width, png_charp height));
  183792. #endif
  183793. #endif
  183794. #endif
  183795. /* Called when finished processing a row of data */
  183796. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183797. /* Internal use only. Called before first row of data */
  183798. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183799. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183800. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183801. #endif
  183802. /* combine a row of data, dealing with alpha, etc. if requested */
  183803. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183804. int mask));
  183805. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183806. /* expand an interlaced row */
  183807. /* OLD pre-1.0.9 interface:
  183808. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183809. png_bytep row, int pass, png_uint_32 transformations));
  183810. */
  183811. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183812. #endif
  183813. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183814. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183815. /* grab pixels out of a row for an interlaced pass */
  183816. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183817. png_bytep row, int pass));
  183818. #endif
  183819. /* unfilter a row */
  183820. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183821. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183822. /* Choose the best filter to use and filter the row data */
  183823. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183824. png_row_infop row_info));
  183825. /* Write out the filtered row. */
  183826. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183827. png_bytep filtered_row));
  183828. /* finish a row while reading, dealing with interlacing passes, etc. */
  183829. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183830. /* initialize the row buffers, etc. */
  183831. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183832. /* optional call to update the users info structure */
  183833. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183834. png_infop info_ptr));
  183835. /* these are the functions that do the transformations */
  183836. #if defined(PNG_READ_FILLER_SUPPORTED)
  183837. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183838. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183839. #endif
  183840. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183841. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183842. png_bytep row));
  183843. #endif
  183844. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183845. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183846. png_bytep row));
  183847. #endif
  183848. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183849. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183850. png_bytep row));
  183851. #endif
  183852. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183853. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183854. png_bytep row));
  183855. #endif
  183856. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183857. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183858. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183859. png_bytep row, png_uint_32 flags));
  183860. #endif
  183861. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183862. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183863. #endif
  183864. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183865. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183866. #endif
  183867. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183868. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183869. row_info, png_bytep row));
  183870. #endif
  183871. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183872. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183873. png_bytep row));
  183874. #endif
  183875. #if defined(PNG_READ_PACK_SUPPORTED)
  183876. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183877. #endif
  183878. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183879. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183880. png_color_8p sig_bits));
  183881. #endif
  183882. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183883. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183884. #endif
  183885. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183886. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183887. #endif
  183888. #if defined(PNG_READ_DITHER_SUPPORTED)
  183889. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183890. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183891. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183892. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183893. png_colorp palette, int num_palette));
  183894. # endif
  183895. #endif
  183896. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183897. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183898. #endif
  183899. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183900. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183901. png_bytep row, png_uint_32 bit_depth));
  183902. #endif
  183903. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183904. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183905. png_color_8p bit_depth));
  183906. #endif
  183907. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183908. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183909. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183910. png_color_16p trans_values, png_color_16p background,
  183911. png_color_16p background_1,
  183912. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183913. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183914. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183915. #else
  183916. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183917. png_color_16p trans_values, png_color_16p background));
  183918. #endif
  183919. #endif
  183920. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183921. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183922. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183923. int gamma_shift));
  183924. #endif
  183925. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183926. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183927. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183928. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183929. png_bytep row, png_color_16p trans_value));
  183930. #endif
  183931. /* The following decodes the appropriate chunks, and does error correction,
  183932. * then calls the appropriate callback for the chunk if it is valid.
  183933. */
  183934. /* decode the IHDR chunk */
  183935. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183936. png_uint_32 length));
  183937. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183938. png_uint_32 length));
  183939. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183940. png_uint_32 length));
  183941. #if defined(PNG_READ_bKGD_SUPPORTED)
  183942. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183943. png_uint_32 length));
  183944. #endif
  183945. #if defined(PNG_READ_cHRM_SUPPORTED)
  183946. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183947. png_uint_32 length));
  183948. #endif
  183949. #if defined(PNG_READ_gAMA_SUPPORTED)
  183950. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183951. png_uint_32 length));
  183952. #endif
  183953. #if defined(PNG_READ_hIST_SUPPORTED)
  183954. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183955. png_uint_32 length));
  183956. #endif
  183957. #if defined(PNG_READ_iCCP_SUPPORTED)
  183958. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183959. png_uint_32 length));
  183960. #endif /* PNG_READ_iCCP_SUPPORTED */
  183961. #if defined(PNG_READ_iTXt_SUPPORTED)
  183962. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183963. png_uint_32 length));
  183964. #endif
  183965. #if defined(PNG_READ_oFFs_SUPPORTED)
  183966. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183967. png_uint_32 length));
  183968. #endif
  183969. #if defined(PNG_READ_pCAL_SUPPORTED)
  183970. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183971. png_uint_32 length));
  183972. #endif
  183973. #if defined(PNG_READ_pHYs_SUPPORTED)
  183974. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183975. png_uint_32 length));
  183976. #endif
  183977. #if defined(PNG_READ_sBIT_SUPPORTED)
  183978. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183979. png_uint_32 length));
  183980. #endif
  183981. #if defined(PNG_READ_sCAL_SUPPORTED)
  183982. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183983. png_uint_32 length));
  183984. #endif
  183985. #if defined(PNG_READ_sPLT_SUPPORTED)
  183986. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183987. png_uint_32 length));
  183988. #endif /* PNG_READ_sPLT_SUPPORTED */
  183989. #if defined(PNG_READ_sRGB_SUPPORTED)
  183990. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183991. png_uint_32 length));
  183992. #endif
  183993. #if defined(PNG_READ_tEXt_SUPPORTED)
  183994. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183995. png_uint_32 length));
  183996. #endif
  183997. #if defined(PNG_READ_tIME_SUPPORTED)
  183998. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183999. png_uint_32 length));
  184000. #endif
  184001. #if defined(PNG_READ_tRNS_SUPPORTED)
  184002. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184003. png_uint_32 length));
  184004. #endif
  184005. #if defined(PNG_READ_zTXt_SUPPORTED)
  184006. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184007. png_uint_32 length));
  184008. #endif
  184009. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184010. png_infop info_ptr, png_uint_32 length));
  184011. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184012. png_bytep chunk_name));
  184013. /* handle the transformations for reading and writing */
  184014. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184015. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184016. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184017. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184018. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184019. png_infop info_ptr));
  184020. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184021. png_infop info_ptr));
  184022. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184023. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184024. png_uint_32 length));
  184025. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184026. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184027. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184028. png_bytep buffer, png_size_t buffer_length));
  184029. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184030. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184031. png_bytep buffer, png_size_t buffer_length));
  184032. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184033. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184034. png_infop info_ptr, png_uint_32 length));
  184035. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184036. png_infop info_ptr));
  184037. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184038. png_infop info_ptr));
  184039. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184040. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184041. png_infop info_ptr));
  184042. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184043. png_infop info_ptr));
  184044. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184045. #if defined(PNG_READ_tEXt_SUPPORTED)
  184046. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184047. png_infop info_ptr, png_uint_32 length));
  184048. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184049. png_infop info_ptr));
  184050. #endif
  184051. #if defined(PNG_READ_zTXt_SUPPORTED)
  184052. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184053. png_infop info_ptr, png_uint_32 length));
  184054. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184055. png_infop info_ptr));
  184056. #endif
  184057. #if defined(PNG_READ_iTXt_SUPPORTED)
  184058. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184059. png_infop info_ptr, png_uint_32 length));
  184060. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184061. png_infop info_ptr));
  184062. #endif
  184063. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184064. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184065. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184066. png_bytep row));
  184067. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184068. png_bytep row));
  184069. #endif
  184070. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184071. #if defined(PNG_MMX_CODE_SUPPORTED)
  184072. /* png.c */ /* PRIVATE */
  184073. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184074. #endif
  184075. #endif
  184076. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184077. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184078. png_infop info_ptr));
  184079. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184080. png_infop info_ptr));
  184081. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184082. png_infop info_ptr));
  184083. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184084. png_infop info_ptr));
  184085. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184086. png_infop info_ptr));
  184087. #if defined(PNG_pHYs_SUPPORTED)
  184088. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184089. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184090. #endif /* PNG_pHYs_SUPPORTED */
  184091. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184092. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184093. #endif /* PNG_INTERNAL */
  184094. #ifdef __cplusplus
  184095. //}
  184096. #endif
  184097. #endif /* PNG_VERSION_INFO_ONLY */
  184098. /* do not put anything past this line */
  184099. #endif /* PNG_H */
  184100. /*** End of inlined file: png.h ***/
  184101. #define PNG_NO_EXTERN
  184102. /*** Start of inlined file: png.c ***/
  184103. /* png.c - location for general purpose libpng functions
  184104. *
  184105. * Last changed in libpng 1.2.21 [October 4, 2007]
  184106. * For conditions of distribution and use, see copyright notice in png.h
  184107. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184108. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184109. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184110. */
  184111. #define PNG_INTERNAL
  184112. #define PNG_NO_EXTERN
  184113. /* Generate a compiler error if there is an old png.h in the search path. */
  184114. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184115. /* Version information for C files. This had better match the version
  184116. * string defined in png.h. */
  184117. #ifdef PNG_USE_GLOBAL_ARRAYS
  184118. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184119. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184120. #ifdef PNG_READ_SUPPORTED
  184121. /* png_sig was changed to a function in version 1.0.5c */
  184122. /* Place to hold the signature string for a PNG file. */
  184123. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184124. #endif /* PNG_READ_SUPPORTED */
  184125. /* Invoke global declarations for constant strings for known chunk types */
  184126. PNG_IHDR;
  184127. PNG_IDAT;
  184128. PNG_IEND;
  184129. PNG_PLTE;
  184130. PNG_bKGD;
  184131. PNG_cHRM;
  184132. PNG_gAMA;
  184133. PNG_hIST;
  184134. PNG_iCCP;
  184135. PNG_iTXt;
  184136. PNG_oFFs;
  184137. PNG_pCAL;
  184138. PNG_sCAL;
  184139. PNG_pHYs;
  184140. PNG_sBIT;
  184141. PNG_sPLT;
  184142. PNG_sRGB;
  184143. PNG_tEXt;
  184144. PNG_tIME;
  184145. PNG_tRNS;
  184146. PNG_zTXt;
  184147. #ifdef PNG_READ_SUPPORTED
  184148. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184149. /* start of interlace block */
  184150. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184151. /* offset to next interlace block */
  184152. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184153. /* start of interlace block in the y direction */
  184154. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184155. /* offset to next interlace block in the y direction */
  184156. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184157. /* Height of interlace block. This is not currently used - if you need
  184158. * it, uncomment it here and in png.h
  184159. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184160. */
  184161. /* Mask to determine which pixels are valid in a pass */
  184162. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184163. /* Mask to determine which pixels to overwrite while displaying */
  184164. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184165. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184166. #endif /* PNG_READ_SUPPORTED */
  184167. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184168. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184169. * of the PNG file signature. If the PNG data is embedded into another
  184170. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184171. * or write any of the magic bytes before it starts on the IHDR.
  184172. */
  184173. #ifdef PNG_READ_SUPPORTED
  184174. void PNGAPI
  184175. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184176. {
  184177. if(png_ptr == NULL) return;
  184178. png_debug(1, "in png_set_sig_bytes\n");
  184179. if (num_bytes > 8)
  184180. png_error(png_ptr, "Too many bytes for PNG signature.");
  184181. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184182. }
  184183. /* Checks whether the supplied bytes match the PNG signature. We allow
  184184. * checking less than the full 8-byte signature so that those apps that
  184185. * already read the first few bytes of a file to determine the file type
  184186. * can simply check the remaining bytes for extra assurance. Returns
  184187. * an integer less than, equal to, or greater than zero if sig is found,
  184188. * respectively, to be less than, to match, or be greater than the correct
  184189. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184190. */
  184191. int PNGAPI
  184192. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184193. {
  184194. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184195. if (num_to_check > 8)
  184196. num_to_check = 8;
  184197. else if (num_to_check < 1)
  184198. return (-1);
  184199. if (start > 7)
  184200. return (-1);
  184201. if (start + num_to_check > 8)
  184202. num_to_check = 8 - start;
  184203. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184204. }
  184205. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184206. /* (Obsolete) function to check signature bytes. It does not allow one
  184207. * to check a partial signature. This function might be removed in the
  184208. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184209. */
  184210. int PNGAPI
  184211. png_check_sig(png_bytep sig, int num)
  184212. {
  184213. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184214. }
  184215. #endif
  184216. #endif /* PNG_READ_SUPPORTED */
  184217. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184218. /* Function to allocate memory for zlib and clear it to 0. */
  184219. #ifdef PNG_1_0_X
  184220. voidpf PNGAPI
  184221. #else
  184222. voidpf /* private */
  184223. #endif
  184224. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184225. {
  184226. png_voidp ptr;
  184227. png_structp p=(png_structp)png_ptr;
  184228. png_uint_32 save_flags=p->flags;
  184229. png_uint_32 num_bytes;
  184230. if(png_ptr == NULL) return (NULL);
  184231. if (items > PNG_UINT_32_MAX/size)
  184232. {
  184233. png_warning (p, "Potential overflow in png_zalloc()");
  184234. return (NULL);
  184235. }
  184236. num_bytes = (png_uint_32)items * size;
  184237. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184238. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184239. p->flags=save_flags;
  184240. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184241. if (ptr == NULL)
  184242. return ((voidpf)ptr);
  184243. if (num_bytes > (png_uint_32)0x8000L)
  184244. {
  184245. png_memset(ptr, 0, (png_size_t)0x8000L);
  184246. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184247. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184248. }
  184249. else
  184250. {
  184251. png_memset(ptr, 0, (png_size_t)num_bytes);
  184252. }
  184253. #endif
  184254. return ((voidpf)ptr);
  184255. }
  184256. /* function to free memory for zlib */
  184257. #ifdef PNG_1_0_X
  184258. void PNGAPI
  184259. #else
  184260. void /* private */
  184261. #endif
  184262. png_zfree(voidpf png_ptr, voidpf ptr)
  184263. {
  184264. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184265. }
  184266. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184267. * in case CRC is > 32 bits to leave the top bits 0.
  184268. */
  184269. void /* PRIVATE */
  184270. png_reset_crc(png_structp png_ptr)
  184271. {
  184272. png_ptr->crc = crc32(0, Z_NULL, 0);
  184273. }
  184274. /* Calculate the CRC over a section of data. We can only pass as
  184275. * much data to this routine as the largest single buffer size. We
  184276. * also check that this data will actually be used before going to the
  184277. * trouble of calculating it.
  184278. */
  184279. void /* PRIVATE */
  184280. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184281. {
  184282. int need_crc = 1;
  184283. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184284. {
  184285. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184286. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184287. need_crc = 0;
  184288. }
  184289. else /* critical */
  184290. {
  184291. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184292. need_crc = 0;
  184293. }
  184294. if (need_crc)
  184295. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184296. }
  184297. /* Allocate the memory for an info_struct for the application. We don't
  184298. * really need the png_ptr, but it could potentially be useful in the
  184299. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184300. * and png_info_init() so that applications that want to use a shared
  184301. * libpng don't have to be recompiled if png_info changes size.
  184302. */
  184303. png_infop PNGAPI
  184304. png_create_info_struct(png_structp png_ptr)
  184305. {
  184306. png_infop info_ptr;
  184307. png_debug(1, "in png_create_info_struct\n");
  184308. if(png_ptr == NULL) return (NULL);
  184309. #ifdef PNG_USER_MEM_SUPPORTED
  184310. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184311. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184312. #else
  184313. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184314. #endif
  184315. if (info_ptr != NULL)
  184316. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184317. return (info_ptr);
  184318. }
  184319. /* This function frees the memory associated with a single info struct.
  184320. * Normally, one would use either png_destroy_read_struct() or
  184321. * png_destroy_write_struct() to free an info struct, but this may be
  184322. * useful for some applications.
  184323. */
  184324. void PNGAPI
  184325. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184326. {
  184327. png_infop info_ptr = NULL;
  184328. if(png_ptr == NULL) return;
  184329. png_debug(1, "in png_destroy_info_struct\n");
  184330. if (info_ptr_ptr != NULL)
  184331. info_ptr = *info_ptr_ptr;
  184332. if (info_ptr != NULL)
  184333. {
  184334. png_info_destroy(png_ptr, info_ptr);
  184335. #ifdef PNG_USER_MEM_SUPPORTED
  184336. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184337. png_ptr->mem_ptr);
  184338. #else
  184339. png_destroy_struct((png_voidp)info_ptr);
  184340. #endif
  184341. *info_ptr_ptr = NULL;
  184342. }
  184343. }
  184344. /* Initialize the info structure. This is now an internal function (0.89)
  184345. * and applications using it are urged to use png_create_info_struct()
  184346. * instead.
  184347. */
  184348. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184349. #undef png_info_init
  184350. void PNGAPI
  184351. png_info_init(png_infop info_ptr)
  184352. {
  184353. /* We only come here via pre-1.0.12-compiled applications */
  184354. png_info_init_3(&info_ptr, 0);
  184355. }
  184356. #endif
  184357. void PNGAPI
  184358. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184359. {
  184360. png_infop info_ptr = *ptr_ptr;
  184361. if(info_ptr == NULL) return;
  184362. png_debug(1, "in png_info_init_3\n");
  184363. if(png_sizeof(png_info) > png_info_struct_size)
  184364. {
  184365. png_destroy_struct(info_ptr);
  184366. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184367. *ptr_ptr = info_ptr;
  184368. }
  184369. /* set everything to 0 */
  184370. png_memset(info_ptr, 0, png_sizeof (png_info));
  184371. }
  184372. #ifdef PNG_FREE_ME_SUPPORTED
  184373. void PNGAPI
  184374. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184375. int freer, png_uint_32 mask)
  184376. {
  184377. png_debug(1, "in png_data_freer\n");
  184378. if (png_ptr == NULL || info_ptr == NULL)
  184379. return;
  184380. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184381. info_ptr->free_me |= mask;
  184382. else if(freer == PNG_USER_WILL_FREE_DATA)
  184383. info_ptr->free_me &= ~mask;
  184384. else
  184385. png_warning(png_ptr,
  184386. "Unknown freer parameter in png_data_freer.");
  184387. }
  184388. #endif
  184389. void PNGAPI
  184390. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184391. int num)
  184392. {
  184393. png_debug(1, "in png_free_data\n");
  184394. if (png_ptr == NULL || info_ptr == NULL)
  184395. return;
  184396. #if defined(PNG_TEXT_SUPPORTED)
  184397. /* free text item num or (if num == -1) all text items */
  184398. #ifdef PNG_FREE_ME_SUPPORTED
  184399. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184400. #else
  184401. if (mask & PNG_FREE_TEXT)
  184402. #endif
  184403. {
  184404. if (num != -1)
  184405. {
  184406. if (info_ptr->text && info_ptr->text[num].key)
  184407. {
  184408. png_free(png_ptr, info_ptr->text[num].key);
  184409. info_ptr->text[num].key = NULL;
  184410. }
  184411. }
  184412. else
  184413. {
  184414. int i;
  184415. for (i = 0; i < info_ptr->num_text; i++)
  184416. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184417. png_free(png_ptr, info_ptr->text);
  184418. info_ptr->text = NULL;
  184419. info_ptr->num_text=0;
  184420. }
  184421. }
  184422. #endif
  184423. #if defined(PNG_tRNS_SUPPORTED)
  184424. /* free any tRNS entry */
  184425. #ifdef PNG_FREE_ME_SUPPORTED
  184426. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184427. #else
  184428. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184429. #endif
  184430. {
  184431. png_free(png_ptr, info_ptr->trans);
  184432. info_ptr->valid &= ~PNG_INFO_tRNS;
  184433. #ifndef PNG_FREE_ME_SUPPORTED
  184434. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184435. #endif
  184436. info_ptr->trans = NULL;
  184437. }
  184438. #endif
  184439. #if defined(PNG_sCAL_SUPPORTED)
  184440. /* free any sCAL entry */
  184441. #ifdef PNG_FREE_ME_SUPPORTED
  184442. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184443. #else
  184444. if (mask & PNG_FREE_SCAL)
  184445. #endif
  184446. {
  184447. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184448. png_free(png_ptr, info_ptr->scal_s_width);
  184449. png_free(png_ptr, info_ptr->scal_s_height);
  184450. info_ptr->scal_s_width = NULL;
  184451. info_ptr->scal_s_height = NULL;
  184452. #endif
  184453. info_ptr->valid &= ~PNG_INFO_sCAL;
  184454. }
  184455. #endif
  184456. #if defined(PNG_pCAL_SUPPORTED)
  184457. /* free any pCAL entry */
  184458. #ifdef PNG_FREE_ME_SUPPORTED
  184459. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184460. #else
  184461. if (mask & PNG_FREE_PCAL)
  184462. #endif
  184463. {
  184464. png_free(png_ptr, info_ptr->pcal_purpose);
  184465. png_free(png_ptr, info_ptr->pcal_units);
  184466. info_ptr->pcal_purpose = NULL;
  184467. info_ptr->pcal_units = NULL;
  184468. if (info_ptr->pcal_params != NULL)
  184469. {
  184470. int i;
  184471. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184472. {
  184473. png_free(png_ptr, info_ptr->pcal_params[i]);
  184474. info_ptr->pcal_params[i]=NULL;
  184475. }
  184476. png_free(png_ptr, info_ptr->pcal_params);
  184477. info_ptr->pcal_params = NULL;
  184478. }
  184479. info_ptr->valid &= ~PNG_INFO_pCAL;
  184480. }
  184481. #endif
  184482. #if defined(PNG_iCCP_SUPPORTED)
  184483. /* free any iCCP entry */
  184484. #ifdef PNG_FREE_ME_SUPPORTED
  184485. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184486. #else
  184487. if (mask & PNG_FREE_ICCP)
  184488. #endif
  184489. {
  184490. png_free(png_ptr, info_ptr->iccp_name);
  184491. png_free(png_ptr, info_ptr->iccp_profile);
  184492. info_ptr->iccp_name = NULL;
  184493. info_ptr->iccp_profile = NULL;
  184494. info_ptr->valid &= ~PNG_INFO_iCCP;
  184495. }
  184496. #endif
  184497. #if defined(PNG_sPLT_SUPPORTED)
  184498. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184499. #ifdef PNG_FREE_ME_SUPPORTED
  184500. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184501. #else
  184502. if (mask & PNG_FREE_SPLT)
  184503. #endif
  184504. {
  184505. if (num != -1)
  184506. {
  184507. if(info_ptr->splt_palettes)
  184508. {
  184509. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184510. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184511. info_ptr->splt_palettes[num].name = NULL;
  184512. info_ptr->splt_palettes[num].entries = NULL;
  184513. }
  184514. }
  184515. else
  184516. {
  184517. if(info_ptr->splt_palettes_num)
  184518. {
  184519. int i;
  184520. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184521. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184522. png_free(png_ptr, info_ptr->splt_palettes);
  184523. info_ptr->splt_palettes = NULL;
  184524. info_ptr->splt_palettes_num = 0;
  184525. }
  184526. info_ptr->valid &= ~PNG_INFO_sPLT;
  184527. }
  184528. }
  184529. #endif
  184530. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184531. if(png_ptr->unknown_chunk.data)
  184532. {
  184533. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184534. png_ptr->unknown_chunk.data = NULL;
  184535. }
  184536. #ifdef PNG_FREE_ME_SUPPORTED
  184537. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184538. #else
  184539. if (mask & PNG_FREE_UNKN)
  184540. #endif
  184541. {
  184542. if (num != -1)
  184543. {
  184544. if(info_ptr->unknown_chunks)
  184545. {
  184546. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184547. info_ptr->unknown_chunks[num].data = NULL;
  184548. }
  184549. }
  184550. else
  184551. {
  184552. int i;
  184553. if(info_ptr->unknown_chunks_num)
  184554. {
  184555. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184556. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184557. png_free(png_ptr, info_ptr->unknown_chunks);
  184558. info_ptr->unknown_chunks = NULL;
  184559. info_ptr->unknown_chunks_num = 0;
  184560. }
  184561. }
  184562. }
  184563. #endif
  184564. #if defined(PNG_hIST_SUPPORTED)
  184565. /* free any hIST entry */
  184566. #ifdef PNG_FREE_ME_SUPPORTED
  184567. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184568. #else
  184569. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184570. #endif
  184571. {
  184572. png_free(png_ptr, info_ptr->hist);
  184573. info_ptr->hist = NULL;
  184574. info_ptr->valid &= ~PNG_INFO_hIST;
  184575. #ifndef PNG_FREE_ME_SUPPORTED
  184576. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184577. #endif
  184578. }
  184579. #endif
  184580. /* free any PLTE entry that was internally allocated */
  184581. #ifdef PNG_FREE_ME_SUPPORTED
  184582. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184583. #else
  184584. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184585. #endif
  184586. {
  184587. png_zfree(png_ptr, info_ptr->palette);
  184588. info_ptr->palette = NULL;
  184589. info_ptr->valid &= ~PNG_INFO_PLTE;
  184590. #ifndef PNG_FREE_ME_SUPPORTED
  184591. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184592. #endif
  184593. info_ptr->num_palette = 0;
  184594. }
  184595. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184596. /* free any image bits attached to the info structure */
  184597. #ifdef PNG_FREE_ME_SUPPORTED
  184598. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184599. #else
  184600. if (mask & PNG_FREE_ROWS)
  184601. #endif
  184602. {
  184603. if(info_ptr->row_pointers)
  184604. {
  184605. int row;
  184606. for (row = 0; row < (int)info_ptr->height; row++)
  184607. {
  184608. png_free(png_ptr, info_ptr->row_pointers[row]);
  184609. info_ptr->row_pointers[row]=NULL;
  184610. }
  184611. png_free(png_ptr, info_ptr->row_pointers);
  184612. info_ptr->row_pointers=NULL;
  184613. }
  184614. info_ptr->valid &= ~PNG_INFO_IDAT;
  184615. }
  184616. #endif
  184617. #ifdef PNG_FREE_ME_SUPPORTED
  184618. if(num == -1)
  184619. info_ptr->free_me &= ~mask;
  184620. else
  184621. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184622. #endif
  184623. }
  184624. /* This is an internal routine to free any memory that the info struct is
  184625. * pointing to before re-using it or freeing the struct itself. Recall
  184626. * that png_free() checks for NULL pointers for us.
  184627. */
  184628. void /* PRIVATE */
  184629. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184630. {
  184631. png_debug(1, "in png_info_destroy\n");
  184632. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184633. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184634. if (png_ptr->num_chunk_list)
  184635. {
  184636. png_free(png_ptr, png_ptr->chunk_list);
  184637. png_ptr->chunk_list=NULL;
  184638. png_ptr->num_chunk_list=0;
  184639. }
  184640. #endif
  184641. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184642. }
  184643. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184644. /* This function returns a pointer to the io_ptr associated with the user
  184645. * functions. The application should free any memory associated with this
  184646. * pointer before png_write_destroy() or png_read_destroy() are called.
  184647. */
  184648. png_voidp PNGAPI
  184649. png_get_io_ptr(png_structp png_ptr)
  184650. {
  184651. if(png_ptr == NULL) return (NULL);
  184652. return (png_ptr->io_ptr);
  184653. }
  184654. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184655. #if !defined(PNG_NO_STDIO)
  184656. /* Initialize the default input/output functions for the PNG file. If you
  184657. * use your own read or write routines, you can call either png_set_read_fn()
  184658. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184659. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184660. * necessarily available.
  184661. */
  184662. void PNGAPI
  184663. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184664. {
  184665. png_debug(1, "in png_init_io\n");
  184666. if(png_ptr == NULL) return;
  184667. png_ptr->io_ptr = (png_voidp)fp;
  184668. }
  184669. #endif
  184670. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184671. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184672. * a "Creation Time" or other text-based time string.
  184673. */
  184674. png_charp PNGAPI
  184675. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184676. {
  184677. static PNG_CONST char short_months[12][4] =
  184678. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184679. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184680. if(png_ptr == NULL) return (NULL);
  184681. if (png_ptr->time_buffer == NULL)
  184682. {
  184683. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184684. png_sizeof(char)));
  184685. }
  184686. #if defined(_WIN32_WCE)
  184687. {
  184688. wchar_t time_buf[29];
  184689. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184690. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184691. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184692. ptime->second % 61);
  184693. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184694. NULL, NULL);
  184695. }
  184696. #else
  184697. #ifdef USE_FAR_KEYWORD
  184698. {
  184699. char near_time_buf[29];
  184700. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184701. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184702. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184703. ptime->second % 61);
  184704. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184705. 29*png_sizeof(char));
  184706. }
  184707. #else
  184708. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184709. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184710. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184711. ptime->second % 61);
  184712. #endif
  184713. #endif /* _WIN32_WCE */
  184714. return ((png_charp)png_ptr->time_buffer);
  184715. }
  184716. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184717. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184718. png_charp PNGAPI
  184719. png_get_copyright(png_structp png_ptr)
  184720. {
  184721. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184722. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184723. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184724. Copyright (c) 1996-1997 Andreas Dilger\n\
  184725. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184726. }
  184727. /* The following return the library version as a short string in the
  184728. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184729. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184730. * is defined in png.h.
  184731. * Note: now there is no difference between png_get_libpng_ver() and
  184732. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184733. * it is guaranteed that png.c uses the correct version of png.h.
  184734. */
  184735. png_charp PNGAPI
  184736. png_get_libpng_ver(png_structp png_ptr)
  184737. {
  184738. /* Version of *.c files used when building libpng */
  184739. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184740. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184741. }
  184742. png_charp PNGAPI
  184743. png_get_header_ver(png_structp png_ptr)
  184744. {
  184745. /* Version of *.h files used when building libpng */
  184746. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184747. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184748. }
  184749. png_charp PNGAPI
  184750. png_get_header_version(png_structp png_ptr)
  184751. {
  184752. /* Returns longer string containing both version and date */
  184753. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184754. return ((png_charp) PNG_HEADER_VERSION_STRING
  184755. #ifndef PNG_READ_SUPPORTED
  184756. " (NO READ SUPPORT)"
  184757. #endif
  184758. "\n");
  184759. }
  184760. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184761. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184762. int PNGAPI
  184763. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184764. {
  184765. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184766. int i;
  184767. png_bytep p;
  184768. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184769. return 0;
  184770. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184771. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184772. if (!png_memcmp(chunk_name, p, 4))
  184773. return ((int)*(p+4));
  184774. return 0;
  184775. }
  184776. #endif
  184777. /* This function, added to libpng-1.0.6g, is untested. */
  184778. int PNGAPI
  184779. png_reset_zstream(png_structp png_ptr)
  184780. {
  184781. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184782. return (inflateReset(&png_ptr->zstream));
  184783. }
  184784. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184785. /* This function was added to libpng-1.0.7 */
  184786. png_uint_32 PNGAPI
  184787. png_access_version_number(void)
  184788. {
  184789. /* Version of *.c files used when building libpng */
  184790. return((png_uint_32) PNG_LIBPNG_VER);
  184791. }
  184792. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184793. #if !defined(PNG_1_0_X)
  184794. /* this function was added to libpng 1.2.0 */
  184795. int PNGAPI
  184796. png_mmx_support(void)
  184797. {
  184798. /* obsolete, to be removed from libpng-1.4.0 */
  184799. return -1;
  184800. }
  184801. #endif /* PNG_1_0_X */
  184802. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184803. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184804. #ifdef PNG_SIZE_T
  184805. /* Added at libpng version 1.2.6 */
  184806. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184807. png_size_t PNGAPI
  184808. png_convert_size(size_t size)
  184809. {
  184810. if (size > (png_size_t)-1)
  184811. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184812. return ((png_size_t)size);
  184813. }
  184814. #endif /* PNG_SIZE_T */
  184815. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184816. /*** End of inlined file: png.c ***/
  184817. /*** Start of inlined file: pngerror.c ***/
  184818. /* pngerror.c - stub functions for i/o and memory allocation
  184819. *
  184820. * Last changed in libpng 1.2.20 October 4, 2007
  184821. * For conditions of distribution and use, see copyright notice in png.h
  184822. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184823. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184824. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184825. *
  184826. * This file provides a location for all error handling. Users who
  184827. * need special error handling are expected to write replacement functions
  184828. * and use png_set_error_fn() to use those functions. See the instructions
  184829. * at each function.
  184830. */
  184831. #define PNG_INTERNAL
  184832. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184833. static void /* PRIVATE */
  184834. png_default_error PNGARG((png_structp png_ptr,
  184835. png_const_charp error_message));
  184836. #ifndef PNG_NO_WARNINGS
  184837. static void /* PRIVATE */
  184838. png_default_warning PNGARG((png_structp png_ptr,
  184839. png_const_charp warning_message));
  184840. #endif /* PNG_NO_WARNINGS */
  184841. /* This function is called whenever there is a fatal error. This function
  184842. * should not be changed. If there is a need to handle errors differently,
  184843. * you should supply a replacement error function and use png_set_error_fn()
  184844. * to replace the error function at run-time.
  184845. */
  184846. #ifndef PNG_NO_ERROR_TEXT
  184847. void PNGAPI
  184848. png_error(png_structp png_ptr, png_const_charp error_message)
  184849. {
  184850. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184851. char msg[16];
  184852. if (png_ptr != NULL)
  184853. {
  184854. if (png_ptr->flags&
  184855. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184856. {
  184857. if (*error_message == '#')
  184858. {
  184859. int offset;
  184860. for (offset=1; offset<15; offset++)
  184861. if (*(error_message+offset) == ' ')
  184862. break;
  184863. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184864. {
  184865. int i;
  184866. for (i=0; i<offset-1; i++)
  184867. msg[i]=error_message[i+1];
  184868. msg[i]='\0';
  184869. error_message=msg;
  184870. }
  184871. else
  184872. error_message+=offset;
  184873. }
  184874. else
  184875. {
  184876. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184877. {
  184878. msg[0]='0';
  184879. msg[1]='\0';
  184880. error_message=msg;
  184881. }
  184882. }
  184883. }
  184884. }
  184885. #endif
  184886. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184887. (*(png_ptr->error_fn))(png_ptr, error_message);
  184888. /* If the custom handler doesn't exist, or if it returns,
  184889. use the default handler, which will not return. */
  184890. png_default_error(png_ptr, error_message);
  184891. }
  184892. #else
  184893. void PNGAPI
  184894. png_err(png_structp png_ptr)
  184895. {
  184896. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184897. (*(png_ptr->error_fn))(png_ptr, '\0');
  184898. /* If the custom handler doesn't exist, or if it returns,
  184899. use the default handler, which will not return. */
  184900. png_default_error(png_ptr, '\0');
  184901. }
  184902. #endif /* PNG_NO_ERROR_TEXT */
  184903. #ifndef PNG_NO_WARNINGS
  184904. /* This function is called whenever there is a non-fatal error. This function
  184905. * should not be changed. If there is a need to handle warnings differently,
  184906. * you should supply a replacement warning function and use
  184907. * png_set_error_fn() to replace the warning function at run-time.
  184908. */
  184909. void PNGAPI
  184910. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184911. {
  184912. int offset = 0;
  184913. if (png_ptr != NULL)
  184914. {
  184915. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184916. if (png_ptr->flags&
  184917. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184918. #endif
  184919. {
  184920. if (*warning_message == '#')
  184921. {
  184922. for (offset=1; offset<15; offset++)
  184923. if (*(warning_message+offset) == ' ')
  184924. break;
  184925. }
  184926. }
  184927. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184928. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184929. }
  184930. else
  184931. png_default_warning(png_ptr, warning_message+offset);
  184932. }
  184933. #endif /* PNG_NO_WARNINGS */
  184934. /* These utilities are used internally to build an error message that relates
  184935. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184936. * this is used to prefix the message. The message is limited in length
  184937. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184938. * if the character is invalid.
  184939. */
  184940. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184941. /*static PNG_CONST char png_digit[16] = {
  184942. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184943. 'A', 'B', 'C', 'D', 'E', 'F'
  184944. };*/
  184945. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184946. static void /* PRIVATE */
  184947. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184948. error_message)
  184949. {
  184950. int iout = 0, iin = 0;
  184951. while (iin < 4)
  184952. {
  184953. int c = png_ptr->chunk_name[iin++];
  184954. if (isnonalpha(c))
  184955. {
  184956. buffer[iout++] = '[';
  184957. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184958. buffer[iout++] = png_digit[c & 0x0f];
  184959. buffer[iout++] = ']';
  184960. }
  184961. else
  184962. {
  184963. buffer[iout++] = (png_byte)c;
  184964. }
  184965. }
  184966. if (error_message == NULL)
  184967. buffer[iout] = 0;
  184968. else
  184969. {
  184970. buffer[iout++] = ':';
  184971. buffer[iout++] = ' ';
  184972. png_strncpy(buffer+iout, error_message, 63);
  184973. buffer[iout+63] = 0;
  184974. }
  184975. }
  184976. #ifdef PNG_READ_SUPPORTED
  184977. void PNGAPI
  184978. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184979. {
  184980. char msg[18+64];
  184981. if (png_ptr == NULL)
  184982. png_error(png_ptr, error_message);
  184983. else
  184984. {
  184985. png_format_buffer(png_ptr, msg, error_message);
  184986. png_error(png_ptr, msg);
  184987. }
  184988. }
  184989. #endif /* PNG_READ_SUPPORTED */
  184990. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184991. #ifndef PNG_NO_WARNINGS
  184992. void PNGAPI
  184993. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184994. {
  184995. char msg[18+64];
  184996. if (png_ptr == NULL)
  184997. png_warning(png_ptr, warning_message);
  184998. else
  184999. {
  185000. png_format_buffer(png_ptr, msg, warning_message);
  185001. png_warning(png_ptr, msg);
  185002. }
  185003. }
  185004. #endif /* PNG_NO_WARNINGS */
  185005. /* This is the default error handling function. Note that replacements for
  185006. * this function MUST NOT RETURN, or the program will likely crash. This
  185007. * function is used by default, or if the program supplies NULL for the
  185008. * error function pointer in png_set_error_fn().
  185009. */
  185010. static void /* PRIVATE */
  185011. png_default_error(png_structp, png_const_charp error_message)
  185012. {
  185013. #ifndef PNG_NO_CONSOLE_IO
  185014. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185015. if (*error_message == '#')
  185016. {
  185017. int offset;
  185018. char error_number[16];
  185019. for (offset=0; offset<15; offset++)
  185020. {
  185021. error_number[offset] = *(error_message+offset+1);
  185022. if (*(error_message+offset) == ' ')
  185023. break;
  185024. }
  185025. if((offset > 1) && (offset < 15))
  185026. {
  185027. error_number[offset-1]='\0';
  185028. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185029. error_message+offset);
  185030. }
  185031. else
  185032. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185033. }
  185034. else
  185035. #endif
  185036. fprintf(stderr, "libpng error: %s\n", error_message);
  185037. #endif
  185038. #ifdef PNG_SETJMP_SUPPORTED
  185039. if (png_ptr)
  185040. {
  185041. # ifdef USE_FAR_KEYWORD
  185042. {
  185043. jmp_buf jmpbuf;
  185044. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185045. longjmp(jmpbuf, 1);
  185046. }
  185047. # else
  185048. longjmp(png_ptr->jmpbuf, 1);
  185049. # endif
  185050. }
  185051. #else
  185052. PNG_ABORT();
  185053. #endif
  185054. #ifdef PNG_NO_CONSOLE_IO
  185055. error_message = error_message; /* make compiler happy */
  185056. #endif
  185057. }
  185058. #ifndef PNG_NO_WARNINGS
  185059. /* This function is called when there is a warning, but the library thinks
  185060. * it can continue anyway. Replacement functions don't have to do anything
  185061. * here if you don't want them to. In the default configuration, png_ptr is
  185062. * not used, but it is passed in case it may be useful.
  185063. */
  185064. static void /* PRIVATE */
  185065. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185066. {
  185067. #ifndef PNG_NO_CONSOLE_IO
  185068. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185069. if (*warning_message == '#')
  185070. {
  185071. int offset;
  185072. char warning_number[16];
  185073. for (offset=0; offset<15; offset++)
  185074. {
  185075. warning_number[offset]=*(warning_message+offset+1);
  185076. if (*(warning_message+offset) == ' ')
  185077. break;
  185078. }
  185079. if((offset > 1) && (offset < 15))
  185080. {
  185081. warning_number[offset-1]='\0';
  185082. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185083. warning_message+offset);
  185084. }
  185085. else
  185086. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185087. }
  185088. else
  185089. # endif
  185090. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185091. #else
  185092. warning_message = warning_message; /* make compiler happy */
  185093. #endif
  185094. png_ptr = png_ptr; /* make compiler happy */
  185095. }
  185096. #endif /* PNG_NO_WARNINGS */
  185097. /* This function is called when the application wants to use another method
  185098. * of handling errors and warnings. Note that the error function MUST NOT
  185099. * return to the calling routine or serious problems will occur. The return
  185100. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185101. */
  185102. void PNGAPI
  185103. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185104. png_error_ptr error_fn, png_error_ptr warning_fn)
  185105. {
  185106. if (png_ptr == NULL)
  185107. return;
  185108. png_ptr->error_ptr = error_ptr;
  185109. png_ptr->error_fn = error_fn;
  185110. png_ptr->warning_fn = warning_fn;
  185111. }
  185112. /* This function returns a pointer to the error_ptr associated with the user
  185113. * functions. The application should free any memory associated with this
  185114. * pointer before png_write_destroy and png_read_destroy are called.
  185115. */
  185116. png_voidp PNGAPI
  185117. png_get_error_ptr(png_structp png_ptr)
  185118. {
  185119. if (png_ptr == NULL)
  185120. return NULL;
  185121. return ((png_voidp)png_ptr->error_ptr);
  185122. }
  185123. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185124. void PNGAPI
  185125. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185126. {
  185127. if(png_ptr != NULL)
  185128. {
  185129. png_ptr->flags &=
  185130. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185131. }
  185132. }
  185133. #endif
  185134. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185135. /*** End of inlined file: pngerror.c ***/
  185136. /*** Start of inlined file: pngget.c ***/
  185137. /* pngget.c - retrieval of values from info struct
  185138. *
  185139. * Last changed in libpng 1.2.15 January 5, 2007
  185140. * For conditions of distribution and use, see copyright notice in png.h
  185141. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185142. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185143. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185144. */
  185145. #define PNG_INTERNAL
  185146. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185147. png_uint_32 PNGAPI
  185148. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185149. {
  185150. if (png_ptr != NULL && info_ptr != NULL)
  185151. return(info_ptr->valid & flag);
  185152. else
  185153. return(0);
  185154. }
  185155. png_uint_32 PNGAPI
  185156. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185157. {
  185158. if (png_ptr != NULL && info_ptr != NULL)
  185159. return(info_ptr->rowbytes);
  185160. else
  185161. return(0);
  185162. }
  185163. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185164. png_bytepp PNGAPI
  185165. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185166. {
  185167. if (png_ptr != NULL && info_ptr != NULL)
  185168. return(info_ptr->row_pointers);
  185169. else
  185170. return(0);
  185171. }
  185172. #endif
  185173. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185174. /* easy access to info, added in libpng-0.99 */
  185175. png_uint_32 PNGAPI
  185176. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185177. {
  185178. if (png_ptr != NULL && info_ptr != NULL)
  185179. {
  185180. return info_ptr->width;
  185181. }
  185182. return (0);
  185183. }
  185184. png_uint_32 PNGAPI
  185185. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185186. {
  185187. if (png_ptr != NULL && info_ptr != NULL)
  185188. {
  185189. return info_ptr->height;
  185190. }
  185191. return (0);
  185192. }
  185193. png_byte PNGAPI
  185194. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185195. {
  185196. if (png_ptr != NULL && info_ptr != NULL)
  185197. {
  185198. return info_ptr->bit_depth;
  185199. }
  185200. return (0);
  185201. }
  185202. png_byte PNGAPI
  185203. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185204. {
  185205. if (png_ptr != NULL && info_ptr != NULL)
  185206. {
  185207. return info_ptr->color_type;
  185208. }
  185209. return (0);
  185210. }
  185211. png_byte PNGAPI
  185212. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185213. {
  185214. if (png_ptr != NULL && info_ptr != NULL)
  185215. {
  185216. return info_ptr->filter_type;
  185217. }
  185218. return (0);
  185219. }
  185220. png_byte PNGAPI
  185221. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185222. {
  185223. if (png_ptr != NULL && info_ptr != NULL)
  185224. {
  185225. return info_ptr->interlace_type;
  185226. }
  185227. return (0);
  185228. }
  185229. png_byte PNGAPI
  185230. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185231. {
  185232. if (png_ptr != NULL && info_ptr != NULL)
  185233. {
  185234. return info_ptr->compression_type;
  185235. }
  185236. return (0);
  185237. }
  185238. png_uint_32 PNGAPI
  185239. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185240. {
  185241. if (png_ptr != NULL && info_ptr != NULL)
  185242. #if defined(PNG_pHYs_SUPPORTED)
  185243. if (info_ptr->valid & PNG_INFO_pHYs)
  185244. {
  185245. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185246. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185247. return (0);
  185248. else return (info_ptr->x_pixels_per_unit);
  185249. }
  185250. #else
  185251. return (0);
  185252. #endif
  185253. return (0);
  185254. }
  185255. png_uint_32 PNGAPI
  185256. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185257. {
  185258. if (png_ptr != NULL && info_ptr != NULL)
  185259. #if defined(PNG_pHYs_SUPPORTED)
  185260. if (info_ptr->valid & PNG_INFO_pHYs)
  185261. {
  185262. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185263. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185264. return (0);
  185265. else return (info_ptr->y_pixels_per_unit);
  185266. }
  185267. #else
  185268. return (0);
  185269. #endif
  185270. return (0);
  185271. }
  185272. png_uint_32 PNGAPI
  185273. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185274. {
  185275. if (png_ptr != NULL && info_ptr != NULL)
  185276. #if defined(PNG_pHYs_SUPPORTED)
  185277. if (info_ptr->valid & PNG_INFO_pHYs)
  185278. {
  185279. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185280. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185281. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185282. return (0);
  185283. else return (info_ptr->x_pixels_per_unit);
  185284. }
  185285. #else
  185286. return (0);
  185287. #endif
  185288. return (0);
  185289. }
  185290. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185291. float PNGAPI
  185292. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185293. {
  185294. if (png_ptr != NULL && info_ptr != NULL)
  185295. #if defined(PNG_pHYs_SUPPORTED)
  185296. if (info_ptr->valid & PNG_INFO_pHYs)
  185297. {
  185298. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185299. if (info_ptr->x_pixels_per_unit == 0)
  185300. return ((float)0.0);
  185301. else
  185302. return ((float)((float)info_ptr->y_pixels_per_unit
  185303. /(float)info_ptr->x_pixels_per_unit));
  185304. }
  185305. #else
  185306. return (0.0);
  185307. #endif
  185308. return ((float)0.0);
  185309. }
  185310. #endif
  185311. png_int_32 PNGAPI
  185312. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185313. {
  185314. if (png_ptr != NULL && info_ptr != NULL)
  185315. #if defined(PNG_oFFs_SUPPORTED)
  185316. if (info_ptr->valid & PNG_INFO_oFFs)
  185317. {
  185318. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185319. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185320. return (0);
  185321. else return (info_ptr->x_offset);
  185322. }
  185323. #else
  185324. return (0);
  185325. #endif
  185326. return (0);
  185327. }
  185328. png_int_32 PNGAPI
  185329. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185330. {
  185331. if (png_ptr != NULL && info_ptr != NULL)
  185332. #if defined(PNG_oFFs_SUPPORTED)
  185333. if (info_ptr->valid & PNG_INFO_oFFs)
  185334. {
  185335. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185336. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185337. return (0);
  185338. else return (info_ptr->y_offset);
  185339. }
  185340. #else
  185341. return (0);
  185342. #endif
  185343. return (0);
  185344. }
  185345. png_int_32 PNGAPI
  185346. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185347. {
  185348. if (png_ptr != NULL && info_ptr != NULL)
  185349. #if defined(PNG_oFFs_SUPPORTED)
  185350. if (info_ptr->valid & PNG_INFO_oFFs)
  185351. {
  185352. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185353. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185354. return (0);
  185355. else return (info_ptr->x_offset);
  185356. }
  185357. #else
  185358. return (0);
  185359. #endif
  185360. return (0);
  185361. }
  185362. png_int_32 PNGAPI
  185363. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185364. {
  185365. if (png_ptr != NULL && info_ptr != NULL)
  185366. #if defined(PNG_oFFs_SUPPORTED)
  185367. if (info_ptr->valid & PNG_INFO_oFFs)
  185368. {
  185369. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185370. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185371. return (0);
  185372. else return (info_ptr->y_offset);
  185373. }
  185374. #else
  185375. return (0);
  185376. #endif
  185377. return (0);
  185378. }
  185379. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185380. png_uint_32 PNGAPI
  185381. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185382. {
  185383. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185384. *.0254 +.5));
  185385. }
  185386. png_uint_32 PNGAPI
  185387. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185388. {
  185389. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185390. *.0254 +.5));
  185391. }
  185392. png_uint_32 PNGAPI
  185393. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185394. {
  185395. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185396. *.0254 +.5));
  185397. }
  185398. float PNGAPI
  185399. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185400. {
  185401. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185402. *.00003937);
  185403. }
  185404. float PNGAPI
  185405. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185406. {
  185407. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185408. *.00003937);
  185409. }
  185410. #if defined(PNG_pHYs_SUPPORTED)
  185411. png_uint_32 PNGAPI
  185412. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185413. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185414. {
  185415. png_uint_32 retval = 0;
  185416. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185417. {
  185418. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185419. if (res_x != NULL)
  185420. {
  185421. *res_x = info_ptr->x_pixels_per_unit;
  185422. retval |= PNG_INFO_pHYs;
  185423. }
  185424. if (res_y != NULL)
  185425. {
  185426. *res_y = info_ptr->y_pixels_per_unit;
  185427. retval |= PNG_INFO_pHYs;
  185428. }
  185429. if (unit_type != NULL)
  185430. {
  185431. *unit_type = (int)info_ptr->phys_unit_type;
  185432. retval |= PNG_INFO_pHYs;
  185433. if(*unit_type == 1)
  185434. {
  185435. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185436. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185437. }
  185438. }
  185439. }
  185440. return (retval);
  185441. }
  185442. #endif /* PNG_pHYs_SUPPORTED */
  185443. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185444. /* png_get_channels really belongs in here, too, but it's been around longer */
  185445. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185446. png_byte PNGAPI
  185447. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185448. {
  185449. if (png_ptr != NULL && info_ptr != NULL)
  185450. return(info_ptr->channels);
  185451. else
  185452. return (0);
  185453. }
  185454. png_bytep PNGAPI
  185455. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185456. {
  185457. if (png_ptr != NULL && info_ptr != NULL)
  185458. return(info_ptr->signature);
  185459. else
  185460. return (NULL);
  185461. }
  185462. #if defined(PNG_bKGD_SUPPORTED)
  185463. png_uint_32 PNGAPI
  185464. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185465. png_color_16p *background)
  185466. {
  185467. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185468. && background != NULL)
  185469. {
  185470. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185471. *background = &(info_ptr->background);
  185472. return (PNG_INFO_bKGD);
  185473. }
  185474. return (0);
  185475. }
  185476. #endif
  185477. #if defined(PNG_cHRM_SUPPORTED)
  185478. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185479. png_uint_32 PNGAPI
  185480. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185481. double *white_x, double *white_y, double *red_x, double *red_y,
  185482. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185483. {
  185484. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185485. {
  185486. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185487. if (white_x != NULL)
  185488. *white_x = (double)info_ptr->x_white;
  185489. if (white_y != NULL)
  185490. *white_y = (double)info_ptr->y_white;
  185491. if (red_x != NULL)
  185492. *red_x = (double)info_ptr->x_red;
  185493. if (red_y != NULL)
  185494. *red_y = (double)info_ptr->y_red;
  185495. if (green_x != NULL)
  185496. *green_x = (double)info_ptr->x_green;
  185497. if (green_y != NULL)
  185498. *green_y = (double)info_ptr->y_green;
  185499. if (blue_x != NULL)
  185500. *blue_x = (double)info_ptr->x_blue;
  185501. if (blue_y != NULL)
  185502. *blue_y = (double)info_ptr->y_blue;
  185503. return (PNG_INFO_cHRM);
  185504. }
  185505. return (0);
  185506. }
  185507. #endif
  185508. #ifdef PNG_FIXED_POINT_SUPPORTED
  185509. png_uint_32 PNGAPI
  185510. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185511. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185512. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185513. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185514. {
  185515. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185516. {
  185517. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185518. if (white_x != NULL)
  185519. *white_x = info_ptr->int_x_white;
  185520. if (white_y != NULL)
  185521. *white_y = info_ptr->int_y_white;
  185522. if (red_x != NULL)
  185523. *red_x = info_ptr->int_x_red;
  185524. if (red_y != NULL)
  185525. *red_y = info_ptr->int_y_red;
  185526. if (green_x != NULL)
  185527. *green_x = info_ptr->int_x_green;
  185528. if (green_y != NULL)
  185529. *green_y = info_ptr->int_y_green;
  185530. if (blue_x != NULL)
  185531. *blue_x = info_ptr->int_x_blue;
  185532. if (blue_y != NULL)
  185533. *blue_y = info_ptr->int_y_blue;
  185534. return (PNG_INFO_cHRM);
  185535. }
  185536. return (0);
  185537. }
  185538. #endif
  185539. #endif
  185540. #if defined(PNG_gAMA_SUPPORTED)
  185541. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185542. png_uint_32 PNGAPI
  185543. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185544. {
  185545. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185546. && file_gamma != NULL)
  185547. {
  185548. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185549. *file_gamma = (double)info_ptr->gamma;
  185550. return (PNG_INFO_gAMA);
  185551. }
  185552. return (0);
  185553. }
  185554. #endif
  185555. #ifdef PNG_FIXED_POINT_SUPPORTED
  185556. png_uint_32 PNGAPI
  185557. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185558. png_fixed_point *int_file_gamma)
  185559. {
  185560. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185561. && int_file_gamma != NULL)
  185562. {
  185563. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185564. *int_file_gamma = info_ptr->int_gamma;
  185565. return (PNG_INFO_gAMA);
  185566. }
  185567. return (0);
  185568. }
  185569. #endif
  185570. #endif
  185571. #if defined(PNG_sRGB_SUPPORTED)
  185572. png_uint_32 PNGAPI
  185573. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185574. {
  185575. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185576. && file_srgb_intent != NULL)
  185577. {
  185578. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185579. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185580. return (PNG_INFO_sRGB);
  185581. }
  185582. return (0);
  185583. }
  185584. #endif
  185585. #if defined(PNG_iCCP_SUPPORTED)
  185586. png_uint_32 PNGAPI
  185587. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185588. png_charpp name, int *compression_type,
  185589. png_charpp profile, png_uint_32 *proflen)
  185590. {
  185591. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185592. && name != NULL && profile != NULL && proflen != NULL)
  185593. {
  185594. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185595. *name = info_ptr->iccp_name;
  185596. *profile = info_ptr->iccp_profile;
  185597. /* compression_type is a dummy so the API won't have to change
  185598. if we introduce multiple compression types later. */
  185599. *proflen = (int)info_ptr->iccp_proflen;
  185600. *compression_type = (int)info_ptr->iccp_compression;
  185601. return (PNG_INFO_iCCP);
  185602. }
  185603. return (0);
  185604. }
  185605. #endif
  185606. #if defined(PNG_sPLT_SUPPORTED)
  185607. png_uint_32 PNGAPI
  185608. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185609. png_sPLT_tpp spalettes)
  185610. {
  185611. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185612. {
  185613. *spalettes = info_ptr->splt_palettes;
  185614. return ((png_uint_32)info_ptr->splt_palettes_num);
  185615. }
  185616. return (0);
  185617. }
  185618. #endif
  185619. #if defined(PNG_hIST_SUPPORTED)
  185620. png_uint_32 PNGAPI
  185621. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185622. {
  185623. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185624. && hist != NULL)
  185625. {
  185626. png_debug1(1, "in %s retrieval function\n", "hIST");
  185627. *hist = info_ptr->hist;
  185628. return (PNG_INFO_hIST);
  185629. }
  185630. return (0);
  185631. }
  185632. #endif
  185633. png_uint_32 PNGAPI
  185634. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185635. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185636. int *color_type, int *interlace_type, int *compression_type,
  185637. int *filter_type)
  185638. {
  185639. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185640. bit_depth != NULL && color_type != NULL)
  185641. {
  185642. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185643. *width = info_ptr->width;
  185644. *height = info_ptr->height;
  185645. *bit_depth = info_ptr->bit_depth;
  185646. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185647. png_error(png_ptr, "Invalid bit depth");
  185648. *color_type = info_ptr->color_type;
  185649. if (info_ptr->color_type > 6)
  185650. png_error(png_ptr, "Invalid color type");
  185651. if (compression_type != NULL)
  185652. *compression_type = info_ptr->compression_type;
  185653. if (filter_type != NULL)
  185654. *filter_type = info_ptr->filter_type;
  185655. if (interlace_type != NULL)
  185656. *interlace_type = info_ptr->interlace_type;
  185657. /* check for potential overflow of rowbytes */
  185658. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185659. png_error(png_ptr, "Invalid image width");
  185660. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185661. png_error(png_ptr, "Invalid image height");
  185662. if (info_ptr->width > (PNG_UINT_32_MAX
  185663. >> 3) /* 8-byte RGBA pixels */
  185664. - 64 /* bigrowbuf hack */
  185665. - 1 /* filter byte */
  185666. - 7*8 /* rounding of width to multiple of 8 pixels */
  185667. - 8) /* extra max_pixel_depth pad */
  185668. {
  185669. png_warning(png_ptr,
  185670. "Width too large for libpng to process image data.");
  185671. }
  185672. return (1);
  185673. }
  185674. return (0);
  185675. }
  185676. #if defined(PNG_oFFs_SUPPORTED)
  185677. png_uint_32 PNGAPI
  185678. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185679. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185680. {
  185681. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185682. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185683. {
  185684. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185685. *offset_x = info_ptr->x_offset;
  185686. *offset_y = info_ptr->y_offset;
  185687. *unit_type = (int)info_ptr->offset_unit_type;
  185688. return (PNG_INFO_oFFs);
  185689. }
  185690. return (0);
  185691. }
  185692. #endif
  185693. #if defined(PNG_pCAL_SUPPORTED)
  185694. png_uint_32 PNGAPI
  185695. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185696. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185697. png_charp *units, png_charpp *params)
  185698. {
  185699. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185700. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185701. nparams != NULL && units != NULL && params != NULL)
  185702. {
  185703. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185704. *purpose = info_ptr->pcal_purpose;
  185705. *X0 = info_ptr->pcal_X0;
  185706. *X1 = info_ptr->pcal_X1;
  185707. *type = (int)info_ptr->pcal_type;
  185708. *nparams = (int)info_ptr->pcal_nparams;
  185709. *units = info_ptr->pcal_units;
  185710. *params = info_ptr->pcal_params;
  185711. return (PNG_INFO_pCAL);
  185712. }
  185713. return (0);
  185714. }
  185715. #endif
  185716. #if defined(PNG_sCAL_SUPPORTED)
  185717. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185718. png_uint_32 PNGAPI
  185719. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185720. int *unit, double *width, double *height)
  185721. {
  185722. if (png_ptr != NULL && info_ptr != NULL &&
  185723. (info_ptr->valid & PNG_INFO_sCAL))
  185724. {
  185725. *unit = info_ptr->scal_unit;
  185726. *width = info_ptr->scal_pixel_width;
  185727. *height = info_ptr->scal_pixel_height;
  185728. return (PNG_INFO_sCAL);
  185729. }
  185730. return(0);
  185731. }
  185732. #else
  185733. #ifdef PNG_FIXED_POINT_SUPPORTED
  185734. png_uint_32 PNGAPI
  185735. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185736. int *unit, png_charpp width, png_charpp height)
  185737. {
  185738. if (png_ptr != NULL && info_ptr != NULL &&
  185739. (info_ptr->valid & PNG_INFO_sCAL))
  185740. {
  185741. *unit = info_ptr->scal_unit;
  185742. *width = info_ptr->scal_s_width;
  185743. *height = info_ptr->scal_s_height;
  185744. return (PNG_INFO_sCAL);
  185745. }
  185746. return(0);
  185747. }
  185748. #endif
  185749. #endif
  185750. #endif
  185751. #if defined(PNG_pHYs_SUPPORTED)
  185752. png_uint_32 PNGAPI
  185753. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185754. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185755. {
  185756. png_uint_32 retval = 0;
  185757. if (png_ptr != NULL && info_ptr != NULL &&
  185758. (info_ptr->valid & PNG_INFO_pHYs))
  185759. {
  185760. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185761. if (res_x != NULL)
  185762. {
  185763. *res_x = info_ptr->x_pixels_per_unit;
  185764. retval |= PNG_INFO_pHYs;
  185765. }
  185766. if (res_y != NULL)
  185767. {
  185768. *res_y = info_ptr->y_pixels_per_unit;
  185769. retval |= PNG_INFO_pHYs;
  185770. }
  185771. if (unit_type != NULL)
  185772. {
  185773. *unit_type = (int)info_ptr->phys_unit_type;
  185774. retval |= PNG_INFO_pHYs;
  185775. }
  185776. }
  185777. return (retval);
  185778. }
  185779. #endif
  185780. png_uint_32 PNGAPI
  185781. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185782. int *num_palette)
  185783. {
  185784. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185785. && palette != NULL)
  185786. {
  185787. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185788. *palette = info_ptr->palette;
  185789. *num_palette = info_ptr->num_palette;
  185790. png_debug1(3, "num_palette = %d\n", *num_palette);
  185791. return (PNG_INFO_PLTE);
  185792. }
  185793. return (0);
  185794. }
  185795. #if defined(PNG_sBIT_SUPPORTED)
  185796. png_uint_32 PNGAPI
  185797. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185798. {
  185799. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185800. && sig_bit != NULL)
  185801. {
  185802. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185803. *sig_bit = &(info_ptr->sig_bit);
  185804. return (PNG_INFO_sBIT);
  185805. }
  185806. return (0);
  185807. }
  185808. #endif
  185809. #if defined(PNG_TEXT_SUPPORTED)
  185810. png_uint_32 PNGAPI
  185811. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185812. int *num_text)
  185813. {
  185814. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185815. {
  185816. png_debug1(1, "in %s retrieval function\n",
  185817. (png_ptr->chunk_name[0] == '\0' ? "text"
  185818. : (png_const_charp)png_ptr->chunk_name));
  185819. if (text_ptr != NULL)
  185820. *text_ptr = info_ptr->text;
  185821. if (num_text != NULL)
  185822. *num_text = info_ptr->num_text;
  185823. return ((png_uint_32)info_ptr->num_text);
  185824. }
  185825. if (num_text != NULL)
  185826. *num_text = 0;
  185827. return(0);
  185828. }
  185829. #endif
  185830. #if defined(PNG_tIME_SUPPORTED)
  185831. png_uint_32 PNGAPI
  185832. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185833. {
  185834. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185835. && mod_time != NULL)
  185836. {
  185837. png_debug1(1, "in %s retrieval function\n", "tIME");
  185838. *mod_time = &(info_ptr->mod_time);
  185839. return (PNG_INFO_tIME);
  185840. }
  185841. return (0);
  185842. }
  185843. #endif
  185844. #if defined(PNG_tRNS_SUPPORTED)
  185845. png_uint_32 PNGAPI
  185846. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185847. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185848. {
  185849. png_uint_32 retval = 0;
  185850. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185851. {
  185852. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185853. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185854. {
  185855. if (trans != NULL)
  185856. {
  185857. *trans = info_ptr->trans;
  185858. retval |= PNG_INFO_tRNS;
  185859. }
  185860. if (trans_values != NULL)
  185861. *trans_values = &(info_ptr->trans_values);
  185862. }
  185863. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185864. {
  185865. if (trans_values != NULL)
  185866. {
  185867. *trans_values = &(info_ptr->trans_values);
  185868. retval |= PNG_INFO_tRNS;
  185869. }
  185870. if(trans != NULL)
  185871. *trans = NULL;
  185872. }
  185873. if(num_trans != NULL)
  185874. {
  185875. *num_trans = info_ptr->num_trans;
  185876. retval |= PNG_INFO_tRNS;
  185877. }
  185878. }
  185879. return (retval);
  185880. }
  185881. #endif
  185882. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185883. png_uint_32 PNGAPI
  185884. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185885. png_unknown_chunkpp unknowns)
  185886. {
  185887. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185888. {
  185889. *unknowns = info_ptr->unknown_chunks;
  185890. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185891. }
  185892. return (0);
  185893. }
  185894. #endif
  185895. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185896. png_byte PNGAPI
  185897. png_get_rgb_to_gray_status (png_structp png_ptr)
  185898. {
  185899. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185900. }
  185901. #endif
  185902. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185903. png_voidp PNGAPI
  185904. png_get_user_chunk_ptr(png_structp png_ptr)
  185905. {
  185906. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185907. }
  185908. #endif
  185909. #ifdef PNG_WRITE_SUPPORTED
  185910. png_uint_32 PNGAPI
  185911. png_get_compression_buffer_size(png_structp png_ptr)
  185912. {
  185913. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185914. }
  185915. #endif
  185916. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185917. #ifndef PNG_1_0_X
  185918. /* this function was added to libpng 1.2.0 and should exist by default */
  185919. png_uint_32 PNGAPI
  185920. png_get_asm_flags (png_structp png_ptr)
  185921. {
  185922. /* obsolete, to be removed from libpng-1.4.0 */
  185923. return (png_ptr? 0L: 0L);
  185924. }
  185925. /* this function was added to libpng 1.2.0 and should exist by default */
  185926. png_uint_32 PNGAPI
  185927. png_get_asm_flagmask (int flag_select)
  185928. {
  185929. /* obsolete, to be removed from libpng-1.4.0 */
  185930. flag_select=flag_select;
  185931. return 0L;
  185932. }
  185933. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185934. /* this function was added to libpng 1.2.0 */
  185935. png_uint_32 PNGAPI
  185936. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185937. {
  185938. /* obsolete, to be removed from libpng-1.4.0 */
  185939. flag_select=flag_select;
  185940. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185941. return 0L;
  185942. }
  185943. /* this function was added to libpng 1.2.0 */
  185944. png_byte PNGAPI
  185945. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185946. {
  185947. /* obsolete, to be removed from libpng-1.4.0 */
  185948. return (png_ptr? 0: 0);
  185949. }
  185950. /* this function was added to libpng 1.2.0 */
  185951. png_uint_32 PNGAPI
  185952. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185953. {
  185954. /* obsolete, to be removed from libpng-1.4.0 */
  185955. return (png_ptr? 0L: 0L);
  185956. }
  185957. #endif /* ?PNG_1_0_X */
  185958. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185959. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185960. /* these functions were added to libpng 1.2.6 */
  185961. png_uint_32 PNGAPI
  185962. png_get_user_width_max (png_structp png_ptr)
  185963. {
  185964. return (png_ptr? png_ptr->user_width_max : 0);
  185965. }
  185966. png_uint_32 PNGAPI
  185967. png_get_user_height_max (png_structp png_ptr)
  185968. {
  185969. return (png_ptr? png_ptr->user_height_max : 0);
  185970. }
  185971. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185972. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185973. /*** End of inlined file: pngget.c ***/
  185974. /*** Start of inlined file: pngmem.c ***/
  185975. /* pngmem.c - stub functions for memory allocation
  185976. *
  185977. * Last changed in libpng 1.2.13 November 13, 2006
  185978. * For conditions of distribution and use, see copyright notice in png.h
  185979. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185980. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185981. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185982. *
  185983. * This file provides a location for all memory allocation. Users who
  185984. * need special memory handling are expected to supply replacement
  185985. * functions for png_malloc() and png_free(), and to use
  185986. * png_create_read_struct_2() and png_create_write_struct_2() to
  185987. * identify the replacement functions.
  185988. */
  185989. #define PNG_INTERNAL
  185990. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185991. /* Borland DOS special memory handler */
  185992. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185993. /* if you change this, be sure to change the one in png.h also */
  185994. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185995. by a single call to calloc() if this is thought to improve performance. */
  185996. png_voidp /* PRIVATE */
  185997. png_create_struct(int type)
  185998. {
  185999. #ifdef PNG_USER_MEM_SUPPORTED
  186000. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186001. }
  186002. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186003. png_voidp /* PRIVATE */
  186004. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186005. {
  186006. #endif /* PNG_USER_MEM_SUPPORTED */
  186007. png_size_t size;
  186008. png_voidp struct_ptr;
  186009. if (type == PNG_STRUCT_INFO)
  186010. size = png_sizeof(png_info);
  186011. else if (type == PNG_STRUCT_PNG)
  186012. size = png_sizeof(png_struct);
  186013. else
  186014. return (png_get_copyright(NULL));
  186015. #ifdef PNG_USER_MEM_SUPPORTED
  186016. if(malloc_fn != NULL)
  186017. {
  186018. png_struct dummy_struct;
  186019. png_structp png_ptr = &dummy_struct;
  186020. png_ptr->mem_ptr=mem_ptr;
  186021. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186022. }
  186023. else
  186024. #endif /* PNG_USER_MEM_SUPPORTED */
  186025. struct_ptr = (png_voidp)farmalloc(size);
  186026. if (struct_ptr != NULL)
  186027. png_memset(struct_ptr, 0, size);
  186028. return (struct_ptr);
  186029. }
  186030. /* Free memory allocated by a png_create_struct() call */
  186031. void /* PRIVATE */
  186032. png_destroy_struct(png_voidp struct_ptr)
  186033. {
  186034. #ifdef PNG_USER_MEM_SUPPORTED
  186035. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186036. }
  186037. /* Free memory allocated by a png_create_struct() call */
  186038. void /* PRIVATE */
  186039. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186040. png_voidp mem_ptr)
  186041. {
  186042. #endif
  186043. if (struct_ptr != NULL)
  186044. {
  186045. #ifdef PNG_USER_MEM_SUPPORTED
  186046. if(free_fn != NULL)
  186047. {
  186048. png_struct dummy_struct;
  186049. png_structp png_ptr = &dummy_struct;
  186050. png_ptr->mem_ptr=mem_ptr;
  186051. (*(free_fn))(png_ptr, struct_ptr);
  186052. return;
  186053. }
  186054. #endif /* PNG_USER_MEM_SUPPORTED */
  186055. farfree (struct_ptr);
  186056. }
  186057. }
  186058. /* Allocate memory. For reasonable files, size should never exceed
  186059. * 64K. However, zlib may allocate more then 64K if you don't tell
  186060. * it not to. See zconf.h and png.h for more information. zlib does
  186061. * need to allocate exactly 64K, so whatever you call here must
  186062. * have the ability to do that.
  186063. *
  186064. * Borland seems to have a problem in DOS mode for exactly 64K.
  186065. * It gives you a segment with an offset of 8 (perhaps to store its
  186066. * memory stuff). zlib doesn't like this at all, so we have to
  186067. * detect and deal with it. This code should not be needed in
  186068. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186069. * been updated by Alexander Lehmann for version 0.89 to waste less
  186070. * memory.
  186071. *
  186072. * Note that we can't use png_size_t for the "size" declaration,
  186073. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186074. * result, we would be truncating potentially larger memory requests
  186075. * (which should cause a fatal error) and introducing major problems.
  186076. */
  186077. png_voidp PNGAPI
  186078. png_malloc(png_structp png_ptr, png_uint_32 size)
  186079. {
  186080. png_voidp ret;
  186081. if (png_ptr == NULL || size == 0)
  186082. return (NULL);
  186083. #ifdef PNG_USER_MEM_SUPPORTED
  186084. if(png_ptr->malloc_fn != NULL)
  186085. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186086. else
  186087. ret = (png_malloc_default(png_ptr, size));
  186088. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186089. png_error(png_ptr, "Out of memory!");
  186090. return (ret);
  186091. }
  186092. png_voidp PNGAPI
  186093. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186094. {
  186095. png_voidp ret;
  186096. #endif /* PNG_USER_MEM_SUPPORTED */
  186097. if (png_ptr == NULL || size == 0)
  186098. return (NULL);
  186099. #ifdef PNG_MAX_MALLOC_64K
  186100. if (size > (png_uint_32)65536L)
  186101. {
  186102. png_warning(png_ptr, "Cannot Allocate > 64K");
  186103. ret = NULL;
  186104. }
  186105. else
  186106. #endif
  186107. if (size != (size_t)size)
  186108. ret = NULL;
  186109. else if (size == (png_uint_32)65536L)
  186110. {
  186111. if (png_ptr->offset_table == NULL)
  186112. {
  186113. /* try to see if we need to do any of this fancy stuff */
  186114. ret = farmalloc(size);
  186115. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186116. {
  186117. int num_blocks;
  186118. png_uint_32 total_size;
  186119. png_bytep table;
  186120. int i;
  186121. png_byte huge * hptr;
  186122. if (ret != NULL)
  186123. {
  186124. farfree(ret);
  186125. ret = NULL;
  186126. }
  186127. if(png_ptr->zlib_window_bits > 14)
  186128. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186129. else
  186130. num_blocks = 1;
  186131. if (png_ptr->zlib_mem_level >= 7)
  186132. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186133. else
  186134. num_blocks++;
  186135. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186136. table = farmalloc(total_size);
  186137. if (table == NULL)
  186138. {
  186139. #ifndef PNG_USER_MEM_SUPPORTED
  186140. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186141. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186142. else
  186143. png_warning(png_ptr, "Out Of Memory.");
  186144. #endif
  186145. return (NULL);
  186146. }
  186147. if ((png_size_t)table & 0xfff0)
  186148. {
  186149. #ifndef PNG_USER_MEM_SUPPORTED
  186150. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186151. png_error(png_ptr,
  186152. "Farmalloc didn't return normalized pointer");
  186153. else
  186154. png_warning(png_ptr,
  186155. "Farmalloc didn't return normalized pointer");
  186156. #endif
  186157. return (NULL);
  186158. }
  186159. png_ptr->offset_table = table;
  186160. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186161. png_sizeof (png_bytep));
  186162. if (png_ptr->offset_table_ptr == NULL)
  186163. {
  186164. #ifndef PNG_USER_MEM_SUPPORTED
  186165. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186166. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186167. else
  186168. png_warning(png_ptr, "Out Of memory.");
  186169. #endif
  186170. return (NULL);
  186171. }
  186172. hptr = (png_byte huge *)table;
  186173. if ((png_size_t)hptr & 0xf)
  186174. {
  186175. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186176. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186177. }
  186178. for (i = 0; i < num_blocks; i++)
  186179. {
  186180. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186181. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186182. }
  186183. png_ptr->offset_table_number = num_blocks;
  186184. png_ptr->offset_table_count = 0;
  186185. png_ptr->offset_table_count_free = 0;
  186186. }
  186187. }
  186188. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186189. {
  186190. #ifndef PNG_USER_MEM_SUPPORTED
  186191. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186192. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186193. else
  186194. png_warning(png_ptr, "Out of Memory.");
  186195. #endif
  186196. return (NULL);
  186197. }
  186198. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186199. }
  186200. else
  186201. ret = farmalloc(size);
  186202. #ifndef PNG_USER_MEM_SUPPORTED
  186203. if (ret == NULL)
  186204. {
  186205. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186206. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186207. else
  186208. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186209. }
  186210. #endif
  186211. return (ret);
  186212. }
  186213. /* free a pointer allocated by png_malloc(). In the default
  186214. configuration, png_ptr is not used, but is passed in case it
  186215. is needed. If ptr is NULL, return without taking any action. */
  186216. void PNGAPI
  186217. png_free(png_structp png_ptr, png_voidp ptr)
  186218. {
  186219. if (png_ptr == NULL || ptr == NULL)
  186220. return;
  186221. #ifdef PNG_USER_MEM_SUPPORTED
  186222. if (png_ptr->free_fn != NULL)
  186223. {
  186224. (*(png_ptr->free_fn))(png_ptr, ptr);
  186225. return;
  186226. }
  186227. else png_free_default(png_ptr, ptr);
  186228. }
  186229. void PNGAPI
  186230. png_free_default(png_structp png_ptr, png_voidp ptr)
  186231. {
  186232. #endif /* PNG_USER_MEM_SUPPORTED */
  186233. if(png_ptr == NULL) return;
  186234. if (png_ptr->offset_table != NULL)
  186235. {
  186236. int i;
  186237. for (i = 0; i < png_ptr->offset_table_count; i++)
  186238. {
  186239. if (ptr == png_ptr->offset_table_ptr[i])
  186240. {
  186241. ptr = NULL;
  186242. png_ptr->offset_table_count_free++;
  186243. break;
  186244. }
  186245. }
  186246. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186247. {
  186248. farfree(png_ptr->offset_table);
  186249. farfree(png_ptr->offset_table_ptr);
  186250. png_ptr->offset_table = NULL;
  186251. png_ptr->offset_table_ptr = NULL;
  186252. }
  186253. }
  186254. if (ptr != NULL)
  186255. {
  186256. farfree(ptr);
  186257. }
  186258. }
  186259. #else /* Not the Borland DOS special memory handler */
  186260. /* Allocate memory for a png_struct or a png_info. The malloc and
  186261. memset can be replaced by a single call to calloc() if this is thought
  186262. to improve performance noticably. */
  186263. png_voidp /* PRIVATE */
  186264. png_create_struct(int type)
  186265. {
  186266. #ifdef PNG_USER_MEM_SUPPORTED
  186267. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186268. }
  186269. /* Allocate memory for a png_struct or a png_info. The malloc and
  186270. memset can be replaced by a single call to calloc() if this is thought
  186271. to improve performance noticably. */
  186272. png_voidp /* PRIVATE */
  186273. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186274. {
  186275. #endif /* PNG_USER_MEM_SUPPORTED */
  186276. png_size_t size;
  186277. png_voidp struct_ptr;
  186278. if (type == PNG_STRUCT_INFO)
  186279. size = png_sizeof(png_info);
  186280. else if (type == PNG_STRUCT_PNG)
  186281. size = png_sizeof(png_struct);
  186282. else
  186283. return (NULL);
  186284. #ifdef PNG_USER_MEM_SUPPORTED
  186285. if(malloc_fn != NULL)
  186286. {
  186287. png_struct dummy_struct;
  186288. png_structp png_ptr = &dummy_struct;
  186289. png_ptr->mem_ptr=mem_ptr;
  186290. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186291. if (struct_ptr != NULL)
  186292. png_memset(struct_ptr, 0, size);
  186293. return (struct_ptr);
  186294. }
  186295. #endif /* PNG_USER_MEM_SUPPORTED */
  186296. #if defined(__TURBOC__) && !defined(__FLAT__)
  186297. struct_ptr = (png_voidp)farmalloc(size);
  186298. #else
  186299. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186300. struct_ptr = (png_voidp)halloc(size,1);
  186301. # else
  186302. struct_ptr = (png_voidp)malloc(size);
  186303. # endif
  186304. #endif
  186305. if (struct_ptr != NULL)
  186306. png_memset(struct_ptr, 0, size);
  186307. return (struct_ptr);
  186308. }
  186309. /* Free memory allocated by a png_create_struct() call */
  186310. void /* PRIVATE */
  186311. png_destroy_struct(png_voidp struct_ptr)
  186312. {
  186313. #ifdef PNG_USER_MEM_SUPPORTED
  186314. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186315. }
  186316. /* Free memory allocated by a png_create_struct() call */
  186317. void /* PRIVATE */
  186318. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186319. png_voidp mem_ptr)
  186320. {
  186321. #endif /* PNG_USER_MEM_SUPPORTED */
  186322. if (struct_ptr != NULL)
  186323. {
  186324. #ifdef PNG_USER_MEM_SUPPORTED
  186325. if(free_fn != NULL)
  186326. {
  186327. png_struct dummy_struct;
  186328. png_structp png_ptr = &dummy_struct;
  186329. png_ptr->mem_ptr=mem_ptr;
  186330. (*(free_fn))(png_ptr, struct_ptr);
  186331. return;
  186332. }
  186333. #endif /* PNG_USER_MEM_SUPPORTED */
  186334. #if defined(__TURBOC__) && !defined(__FLAT__)
  186335. farfree(struct_ptr);
  186336. #else
  186337. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186338. hfree(struct_ptr);
  186339. # else
  186340. free(struct_ptr);
  186341. # endif
  186342. #endif
  186343. }
  186344. }
  186345. /* Allocate memory. For reasonable files, size should never exceed
  186346. 64K. However, zlib may allocate more then 64K if you don't tell
  186347. it not to. See zconf.h and png.h for more information. zlib does
  186348. need to allocate exactly 64K, so whatever you call here must
  186349. have the ability to do that. */
  186350. png_voidp PNGAPI
  186351. png_malloc(png_structp png_ptr, png_uint_32 size)
  186352. {
  186353. png_voidp ret;
  186354. #ifdef PNG_USER_MEM_SUPPORTED
  186355. if (png_ptr == NULL || size == 0)
  186356. return (NULL);
  186357. if(png_ptr->malloc_fn != NULL)
  186358. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186359. else
  186360. ret = (png_malloc_default(png_ptr, size));
  186361. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186362. png_error(png_ptr, "Out of Memory!");
  186363. return (ret);
  186364. }
  186365. png_voidp PNGAPI
  186366. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186367. {
  186368. png_voidp ret;
  186369. #endif /* PNG_USER_MEM_SUPPORTED */
  186370. if (png_ptr == NULL || size == 0)
  186371. return (NULL);
  186372. #ifdef PNG_MAX_MALLOC_64K
  186373. if (size > (png_uint_32)65536L)
  186374. {
  186375. #ifndef PNG_USER_MEM_SUPPORTED
  186376. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186377. png_error(png_ptr, "Cannot Allocate > 64K");
  186378. else
  186379. #endif
  186380. return NULL;
  186381. }
  186382. #endif
  186383. /* Check for overflow */
  186384. #if defined(__TURBOC__) && !defined(__FLAT__)
  186385. if (size != (unsigned long)size)
  186386. ret = NULL;
  186387. else
  186388. ret = farmalloc(size);
  186389. #else
  186390. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186391. if (size != (unsigned long)size)
  186392. ret = NULL;
  186393. else
  186394. ret = halloc(size, 1);
  186395. # else
  186396. if (size != (size_t)size)
  186397. ret = NULL;
  186398. else
  186399. ret = malloc((size_t)size);
  186400. # endif
  186401. #endif
  186402. #ifndef PNG_USER_MEM_SUPPORTED
  186403. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186404. png_error(png_ptr, "Out of Memory");
  186405. #endif
  186406. return (ret);
  186407. }
  186408. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186409. without taking any action. */
  186410. void PNGAPI
  186411. png_free(png_structp png_ptr, png_voidp ptr)
  186412. {
  186413. if (png_ptr == NULL || ptr == NULL)
  186414. return;
  186415. #ifdef PNG_USER_MEM_SUPPORTED
  186416. if (png_ptr->free_fn != NULL)
  186417. {
  186418. (*(png_ptr->free_fn))(png_ptr, ptr);
  186419. return;
  186420. }
  186421. else png_free_default(png_ptr, ptr);
  186422. }
  186423. void PNGAPI
  186424. png_free_default(png_structp png_ptr, png_voidp ptr)
  186425. {
  186426. if (png_ptr == NULL || ptr == NULL)
  186427. return;
  186428. #endif /* PNG_USER_MEM_SUPPORTED */
  186429. #if defined(__TURBOC__) && !defined(__FLAT__)
  186430. farfree(ptr);
  186431. #else
  186432. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186433. hfree(ptr);
  186434. # else
  186435. free(ptr);
  186436. # endif
  186437. #endif
  186438. }
  186439. #endif /* Not Borland DOS special memory handler */
  186440. #if defined(PNG_1_0_X)
  186441. # define png_malloc_warn png_malloc
  186442. #else
  186443. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186444. * function will set up png_malloc() to issue a png_warning and return NULL
  186445. * instead of issuing a png_error, if it fails to allocate the requested
  186446. * memory.
  186447. */
  186448. png_voidp PNGAPI
  186449. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186450. {
  186451. png_voidp ptr;
  186452. png_uint_32 save_flags;
  186453. if(png_ptr == NULL) return (NULL);
  186454. save_flags=png_ptr->flags;
  186455. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186456. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186457. png_ptr->flags=save_flags;
  186458. return(ptr);
  186459. }
  186460. #endif
  186461. png_voidp PNGAPI
  186462. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186463. png_uint_32 length)
  186464. {
  186465. png_size_t size;
  186466. size = (png_size_t)length;
  186467. if ((png_uint_32)size != length)
  186468. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186469. return(png_memcpy (s1, s2, size));
  186470. }
  186471. png_voidp PNGAPI
  186472. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186473. png_uint_32 length)
  186474. {
  186475. png_size_t size;
  186476. size = (png_size_t)length;
  186477. if ((png_uint_32)size != length)
  186478. png_error(png_ptr,"Overflow in png_memset_check.");
  186479. return (png_memset (s1, value, size));
  186480. }
  186481. #ifdef PNG_USER_MEM_SUPPORTED
  186482. /* This function is called when the application wants to use another method
  186483. * of allocating and freeing memory.
  186484. */
  186485. void PNGAPI
  186486. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186487. malloc_fn, png_free_ptr free_fn)
  186488. {
  186489. if(png_ptr != NULL) {
  186490. png_ptr->mem_ptr = mem_ptr;
  186491. png_ptr->malloc_fn = malloc_fn;
  186492. png_ptr->free_fn = free_fn;
  186493. }
  186494. }
  186495. /* This function returns a pointer to the mem_ptr associated with the user
  186496. * functions. The application should free any memory associated with this
  186497. * pointer before png_write_destroy and png_read_destroy are called.
  186498. */
  186499. png_voidp PNGAPI
  186500. png_get_mem_ptr(png_structp png_ptr)
  186501. {
  186502. if(png_ptr == NULL) return (NULL);
  186503. return ((png_voidp)png_ptr->mem_ptr);
  186504. }
  186505. #endif /* PNG_USER_MEM_SUPPORTED */
  186506. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186507. /*** End of inlined file: pngmem.c ***/
  186508. /*** Start of inlined file: pngread.c ***/
  186509. /* pngread.c - read a PNG file
  186510. *
  186511. * Last changed in libpng 1.2.20 September 7, 2007
  186512. * For conditions of distribution and use, see copyright notice in png.h
  186513. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186514. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186515. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186516. *
  186517. * This file contains routines that an application calls directly to
  186518. * read a PNG file or stream.
  186519. */
  186520. #define PNG_INTERNAL
  186521. #if defined(PNG_READ_SUPPORTED)
  186522. /* Create a PNG structure for reading, and allocate any memory needed. */
  186523. png_structp PNGAPI
  186524. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186525. png_error_ptr error_fn, png_error_ptr warn_fn)
  186526. {
  186527. #ifdef PNG_USER_MEM_SUPPORTED
  186528. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186529. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186530. }
  186531. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186532. png_structp PNGAPI
  186533. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186534. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186535. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186536. {
  186537. #endif /* PNG_USER_MEM_SUPPORTED */
  186538. png_structp png_ptr;
  186539. #ifdef PNG_SETJMP_SUPPORTED
  186540. #ifdef USE_FAR_KEYWORD
  186541. jmp_buf jmpbuf;
  186542. #endif
  186543. #endif
  186544. int i;
  186545. png_debug(1, "in png_create_read_struct\n");
  186546. #ifdef PNG_USER_MEM_SUPPORTED
  186547. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186548. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186549. #else
  186550. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186551. #endif
  186552. if (png_ptr == NULL)
  186553. return (NULL);
  186554. /* added at libpng-1.2.6 */
  186555. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186556. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186557. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186558. #endif
  186559. #ifdef PNG_SETJMP_SUPPORTED
  186560. #ifdef USE_FAR_KEYWORD
  186561. if (setjmp(jmpbuf))
  186562. #else
  186563. if (setjmp(png_ptr->jmpbuf))
  186564. #endif
  186565. {
  186566. png_free(png_ptr, png_ptr->zbuf);
  186567. png_ptr->zbuf=NULL;
  186568. #ifdef PNG_USER_MEM_SUPPORTED
  186569. png_destroy_struct_2((png_voidp)png_ptr,
  186570. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186571. #else
  186572. png_destroy_struct((png_voidp)png_ptr);
  186573. #endif
  186574. return (NULL);
  186575. }
  186576. #ifdef USE_FAR_KEYWORD
  186577. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186578. #endif
  186579. #endif
  186580. #ifdef PNG_USER_MEM_SUPPORTED
  186581. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186582. #endif
  186583. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186584. i=0;
  186585. do
  186586. {
  186587. if(user_png_ver[i] != png_libpng_ver[i])
  186588. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186589. } while (png_libpng_ver[i++]);
  186590. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186591. {
  186592. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186593. * we must recompile any applications that use any older library version.
  186594. * For versions after libpng 1.0, we will be compatible, so we need
  186595. * only check the first digit.
  186596. */
  186597. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186598. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186599. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186600. {
  186601. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186602. char msg[80];
  186603. if (user_png_ver)
  186604. {
  186605. png_snprintf(msg, 80,
  186606. "Application was compiled with png.h from libpng-%.20s",
  186607. user_png_ver);
  186608. png_warning(png_ptr, msg);
  186609. }
  186610. png_snprintf(msg, 80,
  186611. "Application is running with png.c from libpng-%.20s",
  186612. png_libpng_ver);
  186613. png_warning(png_ptr, msg);
  186614. #endif
  186615. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186616. png_ptr->flags=0;
  186617. #endif
  186618. png_error(png_ptr,
  186619. "Incompatible libpng version in application and library");
  186620. }
  186621. }
  186622. /* initialize zbuf - compression buffer */
  186623. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186624. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186625. (png_uint_32)png_ptr->zbuf_size);
  186626. png_ptr->zstream.zalloc = png_zalloc;
  186627. png_ptr->zstream.zfree = png_zfree;
  186628. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186629. switch (inflateInit(&png_ptr->zstream))
  186630. {
  186631. case Z_OK: /* Do nothing */ break;
  186632. case Z_MEM_ERROR:
  186633. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186634. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186635. default: png_error(png_ptr, "Unknown zlib error");
  186636. }
  186637. png_ptr->zstream.next_out = png_ptr->zbuf;
  186638. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186639. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186640. #ifdef PNG_SETJMP_SUPPORTED
  186641. /* Applications that neglect to set up their own setjmp() and then encounter
  186642. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186643. abort instead of returning. */
  186644. #ifdef USE_FAR_KEYWORD
  186645. if (setjmp(jmpbuf))
  186646. PNG_ABORT();
  186647. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186648. #else
  186649. if (setjmp(png_ptr->jmpbuf))
  186650. PNG_ABORT();
  186651. #endif
  186652. #endif
  186653. return (png_ptr);
  186654. }
  186655. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186656. /* Initialize PNG structure for reading, and allocate any memory needed.
  186657. This interface is deprecated in favour of the png_create_read_struct(),
  186658. and it will disappear as of libpng-1.3.0. */
  186659. #undef png_read_init
  186660. void PNGAPI
  186661. png_read_init(png_structp png_ptr)
  186662. {
  186663. /* We only come here via pre-1.0.7-compiled applications */
  186664. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186665. }
  186666. void PNGAPI
  186667. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186668. png_size_t png_struct_size, png_size_t png_info_size)
  186669. {
  186670. /* We only come here via pre-1.0.12-compiled applications */
  186671. if(png_ptr == NULL) return;
  186672. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186673. if(png_sizeof(png_struct) > png_struct_size ||
  186674. png_sizeof(png_info) > png_info_size)
  186675. {
  186676. char msg[80];
  186677. png_ptr->warning_fn=NULL;
  186678. if (user_png_ver)
  186679. {
  186680. png_snprintf(msg, 80,
  186681. "Application was compiled with png.h from libpng-%.20s",
  186682. user_png_ver);
  186683. png_warning(png_ptr, msg);
  186684. }
  186685. png_snprintf(msg, 80,
  186686. "Application is running with png.c from libpng-%.20s",
  186687. png_libpng_ver);
  186688. png_warning(png_ptr, msg);
  186689. }
  186690. #endif
  186691. if(png_sizeof(png_struct) > png_struct_size)
  186692. {
  186693. png_ptr->error_fn=NULL;
  186694. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186695. png_ptr->flags=0;
  186696. #endif
  186697. png_error(png_ptr,
  186698. "The png struct allocated by the application for reading is too small.");
  186699. }
  186700. if(png_sizeof(png_info) > png_info_size)
  186701. {
  186702. png_ptr->error_fn=NULL;
  186703. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186704. png_ptr->flags=0;
  186705. #endif
  186706. png_error(png_ptr,
  186707. "The info struct allocated by application for reading is too small.");
  186708. }
  186709. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186710. }
  186711. #endif /* PNG_1_0_X || PNG_1_2_X */
  186712. void PNGAPI
  186713. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186714. png_size_t png_struct_size)
  186715. {
  186716. #ifdef PNG_SETJMP_SUPPORTED
  186717. jmp_buf tmp_jmp; /* to save current jump buffer */
  186718. #endif
  186719. int i=0;
  186720. png_structp png_ptr=*ptr_ptr;
  186721. if(png_ptr == NULL) return;
  186722. do
  186723. {
  186724. if(user_png_ver[i] != png_libpng_ver[i])
  186725. {
  186726. #ifdef PNG_LEGACY_SUPPORTED
  186727. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186728. #else
  186729. png_ptr->warning_fn=NULL;
  186730. png_warning(png_ptr,
  186731. "Application uses deprecated png_read_init() and should be recompiled.");
  186732. break;
  186733. #endif
  186734. }
  186735. } while (png_libpng_ver[i++]);
  186736. png_debug(1, "in png_read_init_3\n");
  186737. #ifdef PNG_SETJMP_SUPPORTED
  186738. /* save jump buffer and error functions */
  186739. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186740. #endif
  186741. if(png_sizeof(png_struct) > png_struct_size)
  186742. {
  186743. png_destroy_struct(png_ptr);
  186744. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186745. png_ptr = *ptr_ptr;
  186746. }
  186747. /* reset all variables to 0 */
  186748. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186749. #ifdef PNG_SETJMP_SUPPORTED
  186750. /* restore jump buffer */
  186751. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186752. #endif
  186753. /* added at libpng-1.2.6 */
  186754. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186755. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186756. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186757. #endif
  186758. /* initialize zbuf - compression buffer */
  186759. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186760. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186761. (png_uint_32)png_ptr->zbuf_size);
  186762. png_ptr->zstream.zalloc = png_zalloc;
  186763. png_ptr->zstream.zfree = png_zfree;
  186764. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186765. switch (inflateInit(&png_ptr->zstream))
  186766. {
  186767. case Z_OK: /* Do nothing */ break;
  186768. case Z_MEM_ERROR:
  186769. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186770. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186771. default: png_error(png_ptr, "Unknown zlib error");
  186772. }
  186773. png_ptr->zstream.next_out = png_ptr->zbuf;
  186774. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186775. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186776. }
  186777. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186778. /* Read the information before the actual image data. This has been
  186779. * changed in v0.90 to allow reading a file that already has the magic
  186780. * bytes read from the stream. You can tell libpng how many bytes have
  186781. * been read from the beginning of the stream (up to the maximum of 8)
  186782. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186783. * here. The application can then have access to the signature bytes we
  186784. * read if it is determined that this isn't a valid PNG file.
  186785. */
  186786. void PNGAPI
  186787. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186788. {
  186789. if(png_ptr == NULL) return;
  186790. png_debug(1, "in png_read_info\n");
  186791. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186792. if (png_ptr->sig_bytes < 8)
  186793. {
  186794. png_size_t num_checked = png_ptr->sig_bytes,
  186795. num_to_check = 8 - num_checked;
  186796. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186797. png_ptr->sig_bytes = 8;
  186798. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186799. {
  186800. if (num_checked < 4 &&
  186801. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186802. png_error(png_ptr, "Not a PNG file");
  186803. else
  186804. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186805. }
  186806. if (num_checked < 3)
  186807. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186808. }
  186809. for(;;)
  186810. {
  186811. #ifdef PNG_USE_LOCAL_ARRAYS
  186812. PNG_CONST PNG_IHDR;
  186813. PNG_CONST PNG_IDAT;
  186814. PNG_CONST PNG_IEND;
  186815. PNG_CONST PNG_PLTE;
  186816. #if defined(PNG_READ_bKGD_SUPPORTED)
  186817. PNG_CONST PNG_bKGD;
  186818. #endif
  186819. #if defined(PNG_READ_cHRM_SUPPORTED)
  186820. PNG_CONST PNG_cHRM;
  186821. #endif
  186822. #if defined(PNG_READ_gAMA_SUPPORTED)
  186823. PNG_CONST PNG_gAMA;
  186824. #endif
  186825. #if defined(PNG_READ_hIST_SUPPORTED)
  186826. PNG_CONST PNG_hIST;
  186827. #endif
  186828. #if defined(PNG_READ_iCCP_SUPPORTED)
  186829. PNG_CONST PNG_iCCP;
  186830. #endif
  186831. #if defined(PNG_READ_iTXt_SUPPORTED)
  186832. PNG_CONST PNG_iTXt;
  186833. #endif
  186834. #if defined(PNG_READ_oFFs_SUPPORTED)
  186835. PNG_CONST PNG_oFFs;
  186836. #endif
  186837. #if defined(PNG_READ_pCAL_SUPPORTED)
  186838. PNG_CONST PNG_pCAL;
  186839. #endif
  186840. #if defined(PNG_READ_pHYs_SUPPORTED)
  186841. PNG_CONST PNG_pHYs;
  186842. #endif
  186843. #if defined(PNG_READ_sBIT_SUPPORTED)
  186844. PNG_CONST PNG_sBIT;
  186845. #endif
  186846. #if defined(PNG_READ_sCAL_SUPPORTED)
  186847. PNG_CONST PNG_sCAL;
  186848. #endif
  186849. #if defined(PNG_READ_sPLT_SUPPORTED)
  186850. PNG_CONST PNG_sPLT;
  186851. #endif
  186852. #if defined(PNG_READ_sRGB_SUPPORTED)
  186853. PNG_CONST PNG_sRGB;
  186854. #endif
  186855. #if defined(PNG_READ_tEXt_SUPPORTED)
  186856. PNG_CONST PNG_tEXt;
  186857. #endif
  186858. #if defined(PNG_READ_tIME_SUPPORTED)
  186859. PNG_CONST PNG_tIME;
  186860. #endif
  186861. #if defined(PNG_READ_tRNS_SUPPORTED)
  186862. PNG_CONST PNG_tRNS;
  186863. #endif
  186864. #if defined(PNG_READ_zTXt_SUPPORTED)
  186865. PNG_CONST PNG_zTXt;
  186866. #endif
  186867. #endif /* PNG_USE_LOCAL_ARRAYS */
  186868. png_byte chunk_length[4];
  186869. png_uint_32 length;
  186870. png_read_data(png_ptr, chunk_length, 4);
  186871. length = png_get_uint_31(png_ptr,chunk_length);
  186872. png_reset_crc(png_ptr);
  186873. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186874. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186875. length);
  186876. /* This should be a binary subdivision search or a hash for
  186877. * matching the chunk name rather than a linear search.
  186878. */
  186879. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186880. if(png_ptr->mode & PNG_AFTER_IDAT)
  186881. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186882. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186883. png_handle_IHDR(png_ptr, info_ptr, length);
  186884. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186885. png_handle_IEND(png_ptr, info_ptr, length);
  186886. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186887. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186888. {
  186889. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186890. png_ptr->mode |= PNG_HAVE_IDAT;
  186891. png_handle_unknown(png_ptr, info_ptr, length);
  186892. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186893. png_ptr->mode |= PNG_HAVE_PLTE;
  186894. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186895. {
  186896. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186897. png_error(png_ptr, "Missing IHDR before IDAT");
  186898. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186899. !(png_ptr->mode & PNG_HAVE_PLTE))
  186900. png_error(png_ptr, "Missing PLTE before IDAT");
  186901. break;
  186902. }
  186903. }
  186904. #endif
  186905. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186906. png_handle_PLTE(png_ptr, info_ptr, length);
  186907. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186908. {
  186909. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186910. png_error(png_ptr, "Missing IHDR before IDAT");
  186911. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186912. !(png_ptr->mode & PNG_HAVE_PLTE))
  186913. png_error(png_ptr, "Missing PLTE before IDAT");
  186914. png_ptr->idat_size = length;
  186915. png_ptr->mode |= PNG_HAVE_IDAT;
  186916. break;
  186917. }
  186918. #if defined(PNG_READ_bKGD_SUPPORTED)
  186919. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186920. png_handle_bKGD(png_ptr, info_ptr, length);
  186921. #endif
  186922. #if defined(PNG_READ_cHRM_SUPPORTED)
  186923. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186924. png_handle_cHRM(png_ptr, info_ptr, length);
  186925. #endif
  186926. #if defined(PNG_READ_gAMA_SUPPORTED)
  186927. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186928. png_handle_gAMA(png_ptr, info_ptr, length);
  186929. #endif
  186930. #if defined(PNG_READ_hIST_SUPPORTED)
  186931. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186932. png_handle_hIST(png_ptr, info_ptr, length);
  186933. #endif
  186934. #if defined(PNG_READ_oFFs_SUPPORTED)
  186935. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186936. png_handle_oFFs(png_ptr, info_ptr, length);
  186937. #endif
  186938. #if defined(PNG_READ_pCAL_SUPPORTED)
  186939. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186940. png_handle_pCAL(png_ptr, info_ptr, length);
  186941. #endif
  186942. #if defined(PNG_READ_sCAL_SUPPORTED)
  186943. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186944. png_handle_sCAL(png_ptr, info_ptr, length);
  186945. #endif
  186946. #if defined(PNG_READ_pHYs_SUPPORTED)
  186947. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186948. png_handle_pHYs(png_ptr, info_ptr, length);
  186949. #endif
  186950. #if defined(PNG_READ_sBIT_SUPPORTED)
  186951. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186952. png_handle_sBIT(png_ptr, info_ptr, length);
  186953. #endif
  186954. #if defined(PNG_READ_sRGB_SUPPORTED)
  186955. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186956. png_handle_sRGB(png_ptr, info_ptr, length);
  186957. #endif
  186958. #if defined(PNG_READ_iCCP_SUPPORTED)
  186959. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186960. png_handle_iCCP(png_ptr, info_ptr, length);
  186961. #endif
  186962. #if defined(PNG_READ_sPLT_SUPPORTED)
  186963. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186964. png_handle_sPLT(png_ptr, info_ptr, length);
  186965. #endif
  186966. #if defined(PNG_READ_tEXt_SUPPORTED)
  186967. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186968. png_handle_tEXt(png_ptr, info_ptr, length);
  186969. #endif
  186970. #if defined(PNG_READ_tIME_SUPPORTED)
  186971. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186972. png_handle_tIME(png_ptr, info_ptr, length);
  186973. #endif
  186974. #if defined(PNG_READ_tRNS_SUPPORTED)
  186975. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186976. png_handle_tRNS(png_ptr, info_ptr, length);
  186977. #endif
  186978. #if defined(PNG_READ_zTXt_SUPPORTED)
  186979. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186980. png_handle_zTXt(png_ptr, info_ptr, length);
  186981. #endif
  186982. #if defined(PNG_READ_iTXt_SUPPORTED)
  186983. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186984. png_handle_iTXt(png_ptr, info_ptr, length);
  186985. #endif
  186986. else
  186987. png_handle_unknown(png_ptr, info_ptr, length);
  186988. }
  186989. }
  186990. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186991. /* optional call to update the users info_ptr structure */
  186992. void PNGAPI
  186993. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186994. {
  186995. png_debug(1, "in png_read_update_info\n");
  186996. if(png_ptr == NULL) return;
  186997. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186998. png_read_start_row(png_ptr);
  186999. else
  187000. png_warning(png_ptr,
  187001. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187002. png_read_transform_info(png_ptr, info_ptr);
  187003. }
  187004. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187005. /* Initialize palette, background, etc, after transformations
  187006. * are set, but before any reading takes place. This allows
  187007. * the user to obtain a gamma-corrected palette, for example.
  187008. * If the user doesn't call this, we will do it ourselves.
  187009. */
  187010. void PNGAPI
  187011. png_start_read_image(png_structp png_ptr)
  187012. {
  187013. png_debug(1, "in png_start_read_image\n");
  187014. if(png_ptr == NULL) return;
  187015. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187016. png_read_start_row(png_ptr);
  187017. }
  187018. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187019. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187020. void PNGAPI
  187021. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187022. {
  187023. #ifdef PNG_USE_LOCAL_ARRAYS
  187024. PNG_CONST PNG_IDAT;
  187025. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187026. 0xff};
  187027. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187028. #endif
  187029. int ret;
  187030. if(png_ptr == NULL) return;
  187031. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187032. png_ptr->row_number, png_ptr->pass);
  187033. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187034. png_read_start_row(png_ptr);
  187035. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187036. {
  187037. /* check for transforms that have been set but were defined out */
  187038. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187039. if (png_ptr->transformations & PNG_INVERT_MONO)
  187040. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187041. #endif
  187042. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187043. if (png_ptr->transformations & PNG_FILLER)
  187044. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187045. #endif
  187046. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187047. if (png_ptr->transformations & PNG_PACKSWAP)
  187048. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187049. #endif
  187050. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187051. if (png_ptr->transformations & PNG_PACK)
  187052. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187053. #endif
  187054. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187055. if (png_ptr->transformations & PNG_SHIFT)
  187056. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187057. #endif
  187058. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187059. if (png_ptr->transformations & PNG_BGR)
  187060. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187061. #endif
  187062. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187063. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187064. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187065. #endif
  187066. }
  187067. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187068. /* if interlaced and we do not need a new row, combine row and return */
  187069. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187070. {
  187071. switch (png_ptr->pass)
  187072. {
  187073. case 0:
  187074. if (png_ptr->row_number & 0x07)
  187075. {
  187076. if (dsp_row != NULL)
  187077. png_combine_row(png_ptr, dsp_row,
  187078. png_pass_dsp_mask[png_ptr->pass]);
  187079. png_read_finish_row(png_ptr);
  187080. return;
  187081. }
  187082. break;
  187083. case 1:
  187084. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187085. {
  187086. if (dsp_row != NULL)
  187087. png_combine_row(png_ptr, dsp_row,
  187088. png_pass_dsp_mask[png_ptr->pass]);
  187089. png_read_finish_row(png_ptr);
  187090. return;
  187091. }
  187092. break;
  187093. case 2:
  187094. if ((png_ptr->row_number & 0x07) != 4)
  187095. {
  187096. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187097. png_combine_row(png_ptr, dsp_row,
  187098. png_pass_dsp_mask[png_ptr->pass]);
  187099. png_read_finish_row(png_ptr);
  187100. return;
  187101. }
  187102. break;
  187103. case 3:
  187104. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187105. {
  187106. if (dsp_row != NULL)
  187107. png_combine_row(png_ptr, dsp_row,
  187108. png_pass_dsp_mask[png_ptr->pass]);
  187109. png_read_finish_row(png_ptr);
  187110. return;
  187111. }
  187112. break;
  187113. case 4:
  187114. if ((png_ptr->row_number & 3) != 2)
  187115. {
  187116. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187117. png_combine_row(png_ptr, dsp_row,
  187118. png_pass_dsp_mask[png_ptr->pass]);
  187119. png_read_finish_row(png_ptr);
  187120. return;
  187121. }
  187122. break;
  187123. case 5:
  187124. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187125. {
  187126. if (dsp_row != NULL)
  187127. png_combine_row(png_ptr, dsp_row,
  187128. png_pass_dsp_mask[png_ptr->pass]);
  187129. png_read_finish_row(png_ptr);
  187130. return;
  187131. }
  187132. break;
  187133. case 6:
  187134. if (!(png_ptr->row_number & 1))
  187135. {
  187136. png_read_finish_row(png_ptr);
  187137. return;
  187138. }
  187139. break;
  187140. }
  187141. }
  187142. #endif
  187143. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187144. png_error(png_ptr, "Invalid attempt to read row data");
  187145. png_ptr->zstream.next_out = png_ptr->row_buf;
  187146. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187147. do
  187148. {
  187149. if (!(png_ptr->zstream.avail_in))
  187150. {
  187151. while (!png_ptr->idat_size)
  187152. {
  187153. png_byte chunk_length[4];
  187154. png_crc_finish(png_ptr, 0);
  187155. png_read_data(png_ptr, chunk_length, 4);
  187156. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187157. png_reset_crc(png_ptr);
  187158. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187159. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187160. png_error(png_ptr, "Not enough image data");
  187161. }
  187162. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187163. png_ptr->zstream.next_in = png_ptr->zbuf;
  187164. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187165. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187166. png_crc_read(png_ptr, png_ptr->zbuf,
  187167. (png_size_t)png_ptr->zstream.avail_in);
  187168. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187169. }
  187170. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187171. if (ret == Z_STREAM_END)
  187172. {
  187173. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187174. png_ptr->idat_size)
  187175. png_error(png_ptr, "Extra compressed data");
  187176. png_ptr->mode |= PNG_AFTER_IDAT;
  187177. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187178. break;
  187179. }
  187180. if (ret != Z_OK)
  187181. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187182. "Decompression error");
  187183. } while (png_ptr->zstream.avail_out);
  187184. png_ptr->row_info.color_type = png_ptr->color_type;
  187185. png_ptr->row_info.width = png_ptr->iwidth;
  187186. png_ptr->row_info.channels = png_ptr->channels;
  187187. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187188. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187189. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187190. png_ptr->row_info.width);
  187191. if(png_ptr->row_buf[0])
  187192. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187193. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187194. (int)(png_ptr->row_buf[0]));
  187195. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187196. png_ptr->rowbytes + 1);
  187197. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187198. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187199. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187200. {
  187201. /* Intrapixel differencing */
  187202. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187203. }
  187204. #endif
  187205. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187206. png_do_read_transformations(png_ptr);
  187207. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187208. /* blow up interlaced rows to full size */
  187209. if (png_ptr->interlaced &&
  187210. (png_ptr->transformations & PNG_INTERLACE))
  187211. {
  187212. if (png_ptr->pass < 6)
  187213. /* old interface (pre-1.0.9):
  187214. png_do_read_interlace(&(png_ptr->row_info),
  187215. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187216. */
  187217. png_do_read_interlace(png_ptr);
  187218. if (dsp_row != NULL)
  187219. png_combine_row(png_ptr, dsp_row,
  187220. png_pass_dsp_mask[png_ptr->pass]);
  187221. if (row != NULL)
  187222. png_combine_row(png_ptr, row,
  187223. png_pass_mask[png_ptr->pass]);
  187224. }
  187225. else
  187226. #endif
  187227. {
  187228. if (row != NULL)
  187229. png_combine_row(png_ptr, row, 0xff);
  187230. if (dsp_row != NULL)
  187231. png_combine_row(png_ptr, dsp_row, 0xff);
  187232. }
  187233. png_read_finish_row(png_ptr);
  187234. if (png_ptr->read_row_fn != NULL)
  187235. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187236. }
  187237. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187238. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187239. /* Read one or more rows of image data. If the image is interlaced,
  187240. * and png_set_interlace_handling() has been called, the rows need to
  187241. * contain the contents of the rows from the previous pass. If the
  187242. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187243. * called, the rows contents must be initialized to the contents of the
  187244. * screen.
  187245. *
  187246. * "row" holds the actual image, and pixels are placed in it
  187247. * as they arrive. If the image is displayed after each pass, it will
  187248. * appear to "sparkle" in. "display_row" can be used to display a
  187249. * "chunky" progressive image, with finer detail added as it becomes
  187250. * available. If you do not want this "chunky" display, you may pass
  187251. * NULL for display_row. If you do not want the sparkle display, and
  187252. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187253. * If you have called png_handle_alpha(), and the image has either an
  187254. * alpha channel or a transparency chunk, you must provide a buffer for
  187255. * rows. In this case, you do not have to provide a display_row buffer
  187256. * also, but you may. If the image is not interlaced, or if you have
  187257. * not called png_set_interlace_handling(), the display_row buffer will
  187258. * be ignored, so pass NULL to it.
  187259. *
  187260. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187261. */
  187262. void PNGAPI
  187263. png_read_rows(png_structp png_ptr, png_bytepp row,
  187264. png_bytepp display_row, png_uint_32 num_rows)
  187265. {
  187266. png_uint_32 i;
  187267. png_bytepp rp;
  187268. png_bytepp dp;
  187269. png_debug(1, "in png_read_rows\n");
  187270. if(png_ptr == NULL) return;
  187271. rp = row;
  187272. dp = display_row;
  187273. if (rp != NULL && dp != NULL)
  187274. for (i = 0; i < num_rows; i++)
  187275. {
  187276. png_bytep rptr = *rp++;
  187277. png_bytep dptr = *dp++;
  187278. png_read_row(png_ptr, rptr, dptr);
  187279. }
  187280. else if(rp != NULL)
  187281. for (i = 0; i < num_rows; i++)
  187282. {
  187283. png_bytep rptr = *rp;
  187284. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187285. rp++;
  187286. }
  187287. else if(dp != NULL)
  187288. for (i = 0; i < num_rows; i++)
  187289. {
  187290. png_bytep dptr = *dp;
  187291. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187292. dp++;
  187293. }
  187294. }
  187295. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187296. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187297. /* Read the entire image. If the image has an alpha channel or a tRNS
  187298. * chunk, and you have called png_handle_alpha()[*], you will need to
  187299. * initialize the image to the current image that PNG will be overlaying.
  187300. * We set the num_rows again here, in case it was incorrectly set in
  187301. * png_read_start_row() by a call to png_read_update_info() or
  187302. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187303. * prior to either of these functions like it should have been. You can
  187304. * only call this function once. If you desire to have an image for
  187305. * each pass of a interlaced image, use png_read_rows() instead.
  187306. *
  187307. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187308. */
  187309. void PNGAPI
  187310. png_read_image(png_structp png_ptr, png_bytepp image)
  187311. {
  187312. png_uint_32 i,image_height;
  187313. int pass, j;
  187314. png_bytepp rp;
  187315. png_debug(1, "in png_read_image\n");
  187316. if(png_ptr == NULL) return;
  187317. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187318. pass = png_set_interlace_handling(png_ptr);
  187319. #else
  187320. if (png_ptr->interlaced)
  187321. png_error(png_ptr,
  187322. "Cannot read interlaced image -- interlace handler disabled.");
  187323. pass = 1;
  187324. #endif
  187325. image_height=png_ptr->height;
  187326. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187327. for (j = 0; j < pass; j++)
  187328. {
  187329. rp = image;
  187330. for (i = 0; i < image_height; i++)
  187331. {
  187332. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187333. rp++;
  187334. }
  187335. }
  187336. }
  187337. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187338. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187339. /* Read the end of the PNG file. Will not read past the end of the
  187340. * file, will verify the end is accurate, and will read any comments
  187341. * or time information at the end of the file, if info is not NULL.
  187342. */
  187343. void PNGAPI
  187344. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187345. {
  187346. png_byte chunk_length[4];
  187347. png_uint_32 length;
  187348. png_debug(1, "in png_read_end\n");
  187349. if(png_ptr == NULL) return;
  187350. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187351. do
  187352. {
  187353. #ifdef PNG_USE_LOCAL_ARRAYS
  187354. PNG_CONST PNG_IHDR;
  187355. PNG_CONST PNG_IDAT;
  187356. PNG_CONST PNG_IEND;
  187357. PNG_CONST PNG_PLTE;
  187358. #if defined(PNG_READ_bKGD_SUPPORTED)
  187359. PNG_CONST PNG_bKGD;
  187360. #endif
  187361. #if defined(PNG_READ_cHRM_SUPPORTED)
  187362. PNG_CONST PNG_cHRM;
  187363. #endif
  187364. #if defined(PNG_READ_gAMA_SUPPORTED)
  187365. PNG_CONST PNG_gAMA;
  187366. #endif
  187367. #if defined(PNG_READ_hIST_SUPPORTED)
  187368. PNG_CONST PNG_hIST;
  187369. #endif
  187370. #if defined(PNG_READ_iCCP_SUPPORTED)
  187371. PNG_CONST PNG_iCCP;
  187372. #endif
  187373. #if defined(PNG_READ_iTXt_SUPPORTED)
  187374. PNG_CONST PNG_iTXt;
  187375. #endif
  187376. #if defined(PNG_READ_oFFs_SUPPORTED)
  187377. PNG_CONST PNG_oFFs;
  187378. #endif
  187379. #if defined(PNG_READ_pCAL_SUPPORTED)
  187380. PNG_CONST PNG_pCAL;
  187381. #endif
  187382. #if defined(PNG_READ_pHYs_SUPPORTED)
  187383. PNG_CONST PNG_pHYs;
  187384. #endif
  187385. #if defined(PNG_READ_sBIT_SUPPORTED)
  187386. PNG_CONST PNG_sBIT;
  187387. #endif
  187388. #if defined(PNG_READ_sCAL_SUPPORTED)
  187389. PNG_CONST PNG_sCAL;
  187390. #endif
  187391. #if defined(PNG_READ_sPLT_SUPPORTED)
  187392. PNG_CONST PNG_sPLT;
  187393. #endif
  187394. #if defined(PNG_READ_sRGB_SUPPORTED)
  187395. PNG_CONST PNG_sRGB;
  187396. #endif
  187397. #if defined(PNG_READ_tEXt_SUPPORTED)
  187398. PNG_CONST PNG_tEXt;
  187399. #endif
  187400. #if defined(PNG_READ_tIME_SUPPORTED)
  187401. PNG_CONST PNG_tIME;
  187402. #endif
  187403. #if defined(PNG_READ_tRNS_SUPPORTED)
  187404. PNG_CONST PNG_tRNS;
  187405. #endif
  187406. #if defined(PNG_READ_zTXt_SUPPORTED)
  187407. PNG_CONST PNG_zTXt;
  187408. #endif
  187409. #endif /* PNG_USE_LOCAL_ARRAYS */
  187410. png_read_data(png_ptr, chunk_length, 4);
  187411. length = png_get_uint_31(png_ptr,chunk_length);
  187412. png_reset_crc(png_ptr);
  187413. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187414. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187415. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187416. png_handle_IHDR(png_ptr, info_ptr, length);
  187417. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187418. png_handle_IEND(png_ptr, info_ptr, length);
  187419. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187420. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187421. {
  187422. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187423. {
  187424. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187425. png_error(png_ptr, "Too many IDAT's found");
  187426. }
  187427. png_handle_unknown(png_ptr, info_ptr, length);
  187428. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187429. png_ptr->mode |= PNG_HAVE_PLTE;
  187430. }
  187431. #endif
  187432. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187433. {
  187434. /* Zero length IDATs are legal after the last IDAT has been
  187435. * read, but not after other chunks have been read.
  187436. */
  187437. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187438. png_error(png_ptr, "Too many IDAT's found");
  187439. png_crc_finish(png_ptr, length);
  187440. }
  187441. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187442. png_handle_PLTE(png_ptr, info_ptr, length);
  187443. #if defined(PNG_READ_bKGD_SUPPORTED)
  187444. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187445. png_handle_bKGD(png_ptr, info_ptr, length);
  187446. #endif
  187447. #if defined(PNG_READ_cHRM_SUPPORTED)
  187448. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187449. png_handle_cHRM(png_ptr, info_ptr, length);
  187450. #endif
  187451. #if defined(PNG_READ_gAMA_SUPPORTED)
  187452. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187453. png_handle_gAMA(png_ptr, info_ptr, length);
  187454. #endif
  187455. #if defined(PNG_READ_hIST_SUPPORTED)
  187456. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187457. png_handle_hIST(png_ptr, info_ptr, length);
  187458. #endif
  187459. #if defined(PNG_READ_oFFs_SUPPORTED)
  187460. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187461. png_handle_oFFs(png_ptr, info_ptr, length);
  187462. #endif
  187463. #if defined(PNG_READ_pCAL_SUPPORTED)
  187464. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187465. png_handle_pCAL(png_ptr, info_ptr, length);
  187466. #endif
  187467. #if defined(PNG_READ_sCAL_SUPPORTED)
  187468. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187469. png_handle_sCAL(png_ptr, info_ptr, length);
  187470. #endif
  187471. #if defined(PNG_READ_pHYs_SUPPORTED)
  187472. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187473. png_handle_pHYs(png_ptr, info_ptr, length);
  187474. #endif
  187475. #if defined(PNG_READ_sBIT_SUPPORTED)
  187476. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187477. png_handle_sBIT(png_ptr, info_ptr, length);
  187478. #endif
  187479. #if defined(PNG_READ_sRGB_SUPPORTED)
  187480. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187481. png_handle_sRGB(png_ptr, info_ptr, length);
  187482. #endif
  187483. #if defined(PNG_READ_iCCP_SUPPORTED)
  187484. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187485. png_handle_iCCP(png_ptr, info_ptr, length);
  187486. #endif
  187487. #if defined(PNG_READ_sPLT_SUPPORTED)
  187488. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187489. png_handle_sPLT(png_ptr, info_ptr, length);
  187490. #endif
  187491. #if defined(PNG_READ_tEXt_SUPPORTED)
  187492. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187493. png_handle_tEXt(png_ptr, info_ptr, length);
  187494. #endif
  187495. #if defined(PNG_READ_tIME_SUPPORTED)
  187496. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187497. png_handle_tIME(png_ptr, info_ptr, length);
  187498. #endif
  187499. #if defined(PNG_READ_tRNS_SUPPORTED)
  187500. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187501. png_handle_tRNS(png_ptr, info_ptr, length);
  187502. #endif
  187503. #if defined(PNG_READ_zTXt_SUPPORTED)
  187504. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187505. png_handle_zTXt(png_ptr, info_ptr, length);
  187506. #endif
  187507. #if defined(PNG_READ_iTXt_SUPPORTED)
  187508. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187509. png_handle_iTXt(png_ptr, info_ptr, length);
  187510. #endif
  187511. else
  187512. png_handle_unknown(png_ptr, info_ptr, length);
  187513. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187514. }
  187515. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187516. /* free all memory used by the read */
  187517. void PNGAPI
  187518. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187519. png_infopp end_info_ptr_ptr)
  187520. {
  187521. png_structp png_ptr = NULL;
  187522. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187523. #ifdef PNG_USER_MEM_SUPPORTED
  187524. png_free_ptr free_fn;
  187525. png_voidp mem_ptr;
  187526. #endif
  187527. png_debug(1, "in png_destroy_read_struct\n");
  187528. if (png_ptr_ptr != NULL)
  187529. png_ptr = *png_ptr_ptr;
  187530. if (info_ptr_ptr != NULL)
  187531. info_ptr = *info_ptr_ptr;
  187532. if (end_info_ptr_ptr != NULL)
  187533. end_info_ptr = *end_info_ptr_ptr;
  187534. #ifdef PNG_USER_MEM_SUPPORTED
  187535. free_fn = png_ptr->free_fn;
  187536. mem_ptr = png_ptr->mem_ptr;
  187537. #endif
  187538. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187539. if (info_ptr != NULL)
  187540. {
  187541. #if defined(PNG_TEXT_SUPPORTED)
  187542. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187543. #endif
  187544. #ifdef PNG_USER_MEM_SUPPORTED
  187545. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187546. (png_voidp)mem_ptr);
  187547. #else
  187548. png_destroy_struct((png_voidp)info_ptr);
  187549. #endif
  187550. *info_ptr_ptr = NULL;
  187551. }
  187552. if (end_info_ptr != NULL)
  187553. {
  187554. #if defined(PNG_READ_TEXT_SUPPORTED)
  187555. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187556. #endif
  187557. #ifdef PNG_USER_MEM_SUPPORTED
  187558. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187559. (png_voidp)mem_ptr);
  187560. #else
  187561. png_destroy_struct((png_voidp)end_info_ptr);
  187562. #endif
  187563. *end_info_ptr_ptr = NULL;
  187564. }
  187565. if (png_ptr != NULL)
  187566. {
  187567. #ifdef PNG_USER_MEM_SUPPORTED
  187568. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187569. (png_voidp)mem_ptr);
  187570. #else
  187571. png_destroy_struct((png_voidp)png_ptr);
  187572. #endif
  187573. *png_ptr_ptr = NULL;
  187574. }
  187575. }
  187576. /* free all memory used by the read (old method) */
  187577. void /* PRIVATE */
  187578. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187579. {
  187580. #ifdef PNG_SETJMP_SUPPORTED
  187581. jmp_buf tmp_jmp;
  187582. #endif
  187583. png_error_ptr error_fn;
  187584. png_error_ptr warning_fn;
  187585. png_voidp error_ptr;
  187586. #ifdef PNG_USER_MEM_SUPPORTED
  187587. png_free_ptr free_fn;
  187588. #endif
  187589. png_debug(1, "in png_read_destroy\n");
  187590. if (info_ptr != NULL)
  187591. png_info_destroy(png_ptr, info_ptr);
  187592. if (end_info_ptr != NULL)
  187593. png_info_destroy(png_ptr, end_info_ptr);
  187594. png_free(png_ptr, png_ptr->zbuf);
  187595. png_free(png_ptr, png_ptr->big_row_buf);
  187596. png_free(png_ptr, png_ptr->prev_row);
  187597. #if defined(PNG_READ_DITHER_SUPPORTED)
  187598. png_free(png_ptr, png_ptr->palette_lookup);
  187599. png_free(png_ptr, png_ptr->dither_index);
  187600. #endif
  187601. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187602. png_free(png_ptr, png_ptr->gamma_table);
  187603. #endif
  187604. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187605. png_free(png_ptr, png_ptr->gamma_from_1);
  187606. png_free(png_ptr, png_ptr->gamma_to_1);
  187607. #endif
  187608. #ifdef PNG_FREE_ME_SUPPORTED
  187609. if (png_ptr->free_me & PNG_FREE_PLTE)
  187610. png_zfree(png_ptr, png_ptr->palette);
  187611. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187612. #else
  187613. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187614. png_zfree(png_ptr, png_ptr->palette);
  187615. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187616. #endif
  187617. #if defined(PNG_tRNS_SUPPORTED) || \
  187618. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187619. #ifdef PNG_FREE_ME_SUPPORTED
  187620. if (png_ptr->free_me & PNG_FREE_TRNS)
  187621. png_free(png_ptr, png_ptr->trans);
  187622. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187623. #else
  187624. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187625. png_free(png_ptr, png_ptr->trans);
  187626. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187627. #endif
  187628. #endif
  187629. #if defined(PNG_READ_hIST_SUPPORTED)
  187630. #ifdef PNG_FREE_ME_SUPPORTED
  187631. if (png_ptr->free_me & PNG_FREE_HIST)
  187632. png_free(png_ptr, png_ptr->hist);
  187633. png_ptr->free_me &= ~PNG_FREE_HIST;
  187634. #else
  187635. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187636. png_free(png_ptr, png_ptr->hist);
  187637. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187638. #endif
  187639. #endif
  187640. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187641. if (png_ptr->gamma_16_table != NULL)
  187642. {
  187643. int i;
  187644. int istop = (1 << (8 - png_ptr->gamma_shift));
  187645. for (i = 0; i < istop; i++)
  187646. {
  187647. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187648. }
  187649. png_free(png_ptr, png_ptr->gamma_16_table);
  187650. }
  187651. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187652. if (png_ptr->gamma_16_from_1 != NULL)
  187653. {
  187654. int i;
  187655. int istop = (1 << (8 - png_ptr->gamma_shift));
  187656. for (i = 0; i < istop; i++)
  187657. {
  187658. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187659. }
  187660. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187661. }
  187662. if (png_ptr->gamma_16_to_1 != NULL)
  187663. {
  187664. int i;
  187665. int istop = (1 << (8 - png_ptr->gamma_shift));
  187666. for (i = 0; i < istop; i++)
  187667. {
  187668. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187669. }
  187670. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187671. }
  187672. #endif
  187673. #endif
  187674. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187675. png_free(png_ptr, png_ptr->time_buffer);
  187676. #endif
  187677. inflateEnd(&png_ptr->zstream);
  187678. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187679. png_free(png_ptr, png_ptr->save_buffer);
  187680. #endif
  187681. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187682. #ifdef PNG_TEXT_SUPPORTED
  187683. png_free(png_ptr, png_ptr->current_text);
  187684. #endif /* PNG_TEXT_SUPPORTED */
  187685. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187686. /* Save the important info out of the png_struct, in case it is
  187687. * being used again.
  187688. */
  187689. #ifdef PNG_SETJMP_SUPPORTED
  187690. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187691. #endif
  187692. error_fn = png_ptr->error_fn;
  187693. warning_fn = png_ptr->warning_fn;
  187694. error_ptr = png_ptr->error_ptr;
  187695. #ifdef PNG_USER_MEM_SUPPORTED
  187696. free_fn = png_ptr->free_fn;
  187697. #endif
  187698. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187699. png_ptr->error_fn = error_fn;
  187700. png_ptr->warning_fn = warning_fn;
  187701. png_ptr->error_ptr = error_ptr;
  187702. #ifdef PNG_USER_MEM_SUPPORTED
  187703. png_ptr->free_fn = free_fn;
  187704. #endif
  187705. #ifdef PNG_SETJMP_SUPPORTED
  187706. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187707. #endif
  187708. }
  187709. void PNGAPI
  187710. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187711. {
  187712. if(png_ptr == NULL) return;
  187713. png_ptr->read_row_fn = read_row_fn;
  187714. }
  187715. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187716. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187717. void PNGAPI
  187718. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187719. int transforms,
  187720. voidp params)
  187721. {
  187722. int row;
  187723. if(png_ptr == NULL) return;
  187724. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187725. /* invert the alpha channel from opacity to transparency
  187726. */
  187727. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187728. png_set_invert_alpha(png_ptr);
  187729. #endif
  187730. /* png_read_info() gives us all of the information from the
  187731. * PNG file before the first IDAT (image data chunk).
  187732. */
  187733. png_read_info(png_ptr, info_ptr);
  187734. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187735. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187736. /* -------------- image transformations start here ------------------- */
  187737. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187738. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187739. */
  187740. if (transforms & PNG_TRANSFORM_STRIP_16)
  187741. png_set_strip_16(png_ptr);
  187742. #endif
  187743. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187744. /* Strip alpha bytes from the input data without combining with
  187745. * the background (not recommended).
  187746. */
  187747. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187748. png_set_strip_alpha(png_ptr);
  187749. #endif
  187750. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187751. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187752. * byte into separate bytes (useful for paletted and grayscale images).
  187753. */
  187754. if (transforms & PNG_TRANSFORM_PACKING)
  187755. png_set_packing(png_ptr);
  187756. #endif
  187757. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187758. /* Change the order of packed pixels to least significant bit first
  187759. * (not useful if you are using png_set_packing).
  187760. */
  187761. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187762. png_set_packswap(png_ptr);
  187763. #endif
  187764. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187765. /* Expand paletted colors into true RGB triplets
  187766. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187767. * Expand paletted or RGB images with transparency to full alpha
  187768. * channels so the data will be available as RGBA quartets.
  187769. */
  187770. if (transforms & PNG_TRANSFORM_EXPAND)
  187771. if ((png_ptr->bit_depth < 8) ||
  187772. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187773. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187774. png_set_expand(png_ptr);
  187775. #endif
  187776. /* We don't handle background color or gamma transformation or dithering.
  187777. */
  187778. #if defined(PNG_READ_INVERT_SUPPORTED)
  187779. /* invert monochrome files to have 0 as white and 1 as black
  187780. */
  187781. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187782. png_set_invert_mono(png_ptr);
  187783. #endif
  187784. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187785. /* If you want to shift the pixel values from the range [0,255] or
  187786. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187787. * colors were originally in:
  187788. */
  187789. if ((transforms & PNG_TRANSFORM_SHIFT)
  187790. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187791. {
  187792. png_color_8p sig_bit;
  187793. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187794. png_set_shift(png_ptr, sig_bit);
  187795. }
  187796. #endif
  187797. #if defined(PNG_READ_BGR_SUPPORTED)
  187798. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187799. */
  187800. if (transforms & PNG_TRANSFORM_BGR)
  187801. png_set_bgr(png_ptr);
  187802. #endif
  187803. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187804. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187805. */
  187806. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187807. png_set_swap_alpha(png_ptr);
  187808. #endif
  187809. #if defined(PNG_READ_SWAP_SUPPORTED)
  187810. /* swap bytes of 16 bit files to least significant byte first
  187811. */
  187812. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187813. png_set_swap(png_ptr);
  187814. #endif
  187815. /* We don't handle adding filler bytes */
  187816. /* Optional call to gamma correct and add the background to the palette
  187817. * and update info structure. REQUIRED if you are expecting libpng to
  187818. * update the palette for you (i.e., you selected such a transform above).
  187819. */
  187820. png_read_update_info(png_ptr, info_ptr);
  187821. /* -------------- image transformations end here ------------------- */
  187822. #ifdef PNG_FREE_ME_SUPPORTED
  187823. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187824. #endif
  187825. if(info_ptr->row_pointers == NULL)
  187826. {
  187827. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187828. info_ptr->height * png_sizeof(png_bytep));
  187829. #ifdef PNG_FREE_ME_SUPPORTED
  187830. info_ptr->free_me |= PNG_FREE_ROWS;
  187831. #endif
  187832. for (row = 0; row < (int)info_ptr->height; row++)
  187833. {
  187834. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187835. png_get_rowbytes(png_ptr, info_ptr));
  187836. }
  187837. }
  187838. png_read_image(png_ptr, info_ptr->row_pointers);
  187839. info_ptr->valid |= PNG_INFO_IDAT;
  187840. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187841. png_read_end(png_ptr, info_ptr);
  187842. transforms = transforms; /* quiet compiler warnings */
  187843. params = params;
  187844. }
  187845. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187846. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187847. #endif /* PNG_READ_SUPPORTED */
  187848. /*** End of inlined file: pngread.c ***/
  187849. /*** Start of inlined file: pngpread.c ***/
  187850. /* pngpread.c - read a png file in push mode
  187851. *
  187852. * Last changed in libpng 1.2.21 October 4, 2007
  187853. * For conditions of distribution and use, see copyright notice in png.h
  187854. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187855. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187856. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187857. */
  187858. #define PNG_INTERNAL
  187859. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187860. /* push model modes */
  187861. #define PNG_READ_SIG_MODE 0
  187862. #define PNG_READ_CHUNK_MODE 1
  187863. #define PNG_READ_IDAT_MODE 2
  187864. #define PNG_SKIP_MODE 3
  187865. #define PNG_READ_tEXt_MODE 4
  187866. #define PNG_READ_zTXt_MODE 5
  187867. #define PNG_READ_DONE_MODE 6
  187868. #define PNG_READ_iTXt_MODE 7
  187869. #define PNG_ERROR_MODE 8
  187870. void PNGAPI
  187871. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187872. png_bytep buffer, png_size_t buffer_size)
  187873. {
  187874. if(png_ptr == NULL) return;
  187875. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187876. while (png_ptr->buffer_size)
  187877. {
  187878. png_process_some_data(png_ptr, info_ptr);
  187879. }
  187880. }
  187881. /* What we do with the incoming data depends on what we were previously
  187882. * doing before we ran out of data...
  187883. */
  187884. void /* PRIVATE */
  187885. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187886. {
  187887. if(png_ptr == NULL) return;
  187888. switch (png_ptr->process_mode)
  187889. {
  187890. case PNG_READ_SIG_MODE:
  187891. {
  187892. png_push_read_sig(png_ptr, info_ptr);
  187893. break;
  187894. }
  187895. case PNG_READ_CHUNK_MODE:
  187896. {
  187897. png_push_read_chunk(png_ptr, info_ptr);
  187898. break;
  187899. }
  187900. case PNG_READ_IDAT_MODE:
  187901. {
  187902. png_push_read_IDAT(png_ptr);
  187903. break;
  187904. }
  187905. #if defined(PNG_READ_tEXt_SUPPORTED)
  187906. case PNG_READ_tEXt_MODE:
  187907. {
  187908. png_push_read_tEXt(png_ptr, info_ptr);
  187909. break;
  187910. }
  187911. #endif
  187912. #if defined(PNG_READ_zTXt_SUPPORTED)
  187913. case PNG_READ_zTXt_MODE:
  187914. {
  187915. png_push_read_zTXt(png_ptr, info_ptr);
  187916. break;
  187917. }
  187918. #endif
  187919. #if defined(PNG_READ_iTXt_SUPPORTED)
  187920. case PNG_READ_iTXt_MODE:
  187921. {
  187922. png_push_read_iTXt(png_ptr, info_ptr);
  187923. break;
  187924. }
  187925. #endif
  187926. case PNG_SKIP_MODE:
  187927. {
  187928. png_push_crc_finish(png_ptr);
  187929. break;
  187930. }
  187931. default:
  187932. {
  187933. png_ptr->buffer_size = 0;
  187934. break;
  187935. }
  187936. }
  187937. }
  187938. /* Read any remaining signature bytes from the stream and compare them with
  187939. * the correct PNG signature. It is possible that this routine is called
  187940. * with bytes already read from the signature, either because they have been
  187941. * checked by the calling application, or because of multiple calls to this
  187942. * routine.
  187943. */
  187944. void /* PRIVATE */
  187945. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187946. {
  187947. png_size_t num_checked = png_ptr->sig_bytes,
  187948. num_to_check = 8 - num_checked;
  187949. if (png_ptr->buffer_size < num_to_check)
  187950. {
  187951. num_to_check = png_ptr->buffer_size;
  187952. }
  187953. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187954. num_to_check);
  187955. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187956. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187957. {
  187958. if (num_checked < 4 &&
  187959. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187960. png_error(png_ptr, "Not a PNG file");
  187961. else
  187962. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187963. }
  187964. else
  187965. {
  187966. if (png_ptr->sig_bytes >= 8)
  187967. {
  187968. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187969. }
  187970. }
  187971. }
  187972. void /* PRIVATE */
  187973. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187974. {
  187975. #ifdef PNG_USE_LOCAL_ARRAYS
  187976. PNG_CONST PNG_IHDR;
  187977. PNG_CONST PNG_IDAT;
  187978. PNG_CONST PNG_IEND;
  187979. PNG_CONST PNG_PLTE;
  187980. #if defined(PNG_READ_bKGD_SUPPORTED)
  187981. PNG_CONST PNG_bKGD;
  187982. #endif
  187983. #if defined(PNG_READ_cHRM_SUPPORTED)
  187984. PNG_CONST PNG_cHRM;
  187985. #endif
  187986. #if defined(PNG_READ_gAMA_SUPPORTED)
  187987. PNG_CONST PNG_gAMA;
  187988. #endif
  187989. #if defined(PNG_READ_hIST_SUPPORTED)
  187990. PNG_CONST PNG_hIST;
  187991. #endif
  187992. #if defined(PNG_READ_iCCP_SUPPORTED)
  187993. PNG_CONST PNG_iCCP;
  187994. #endif
  187995. #if defined(PNG_READ_iTXt_SUPPORTED)
  187996. PNG_CONST PNG_iTXt;
  187997. #endif
  187998. #if defined(PNG_READ_oFFs_SUPPORTED)
  187999. PNG_CONST PNG_oFFs;
  188000. #endif
  188001. #if defined(PNG_READ_pCAL_SUPPORTED)
  188002. PNG_CONST PNG_pCAL;
  188003. #endif
  188004. #if defined(PNG_READ_pHYs_SUPPORTED)
  188005. PNG_CONST PNG_pHYs;
  188006. #endif
  188007. #if defined(PNG_READ_sBIT_SUPPORTED)
  188008. PNG_CONST PNG_sBIT;
  188009. #endif
  188010. #if defined(PNG_READ_sCAL_SUPPORTED)
  188011. PNG_CONST PNG_sCAL;
  188012. #endif
  188013. #if defined(PNG_READ_sRGB_SUPPORTED)
  188014. PNG_CONST PNG_sRGB;
  188015. #endif
  188016. #if defined(PNG_READ_sPLT_SUPPORTED)
  188017. PNG_CONST PNG_sPLT;
  188018. #endif
  188019. #if defined(PNG_READ_tEXt_SUPPORTED)
  188020. PNG_CONST PNG_tEXt;
  188021. #endif
  188022. #if defined(PNG_READ_tIME_SUPPORTED)
  188023. PNG_CONST PNG_tIME;
  188024. #endif
  188025. #if defined(PNG_READ_tRNS_SUPPORTED)
  188026. PNG_CONST PNG_tRNS;
  188027. #endif
  188028. #if defined(PNG_READ_zTXt_SUPPORTED)
  188029. PNG_CONST PNG_zTXt;
  188030. #endif
  188031. #endif /* PNG_USE_LOCAL_ARRAYS */
  188032. /* First we make sure we have enough data for the 4 byte chunk name
  188033. * and the 4 byte chunk length before proceeding with decoding the
  188034. * chunk data. To fully decode each of these chunks, we also make
  188035. * sure we have enough data in the buffer for the 4 byte CRC at the
  188036. * end of every chunk (except IDAT, which is handled separately).
  188037. */
  188038. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188039. {
  188040. png_byte chunk_length[4];
  188041. if (png_ptr->buffer_size < 8)
  188042. {
  188043. png_push_save_buffer(png_ptr);
  188044. return;
  188045. }
  188046. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188047. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188048. png_reset_crc(png_ptr);
  188049. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188050. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188051. }
  188052. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188053. if(png_ptr->mode & PNG_AFTER_IDAT)
  188054. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188055. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188056. {
  188057. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188058. {
  188059. png_push_save_buffer(png_ptr);
  188060. return;
  188061. }
  188062. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188063. }
  188064. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188065. {
  188066. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188067. {
  188068. png_push_save_buffer(png_ptr);
  188069. return;
  188070. }
  188071. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188072. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188073. png_push_have_end(png_ptr, info_ptr);
  188074. }
  188075. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188076. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188077. {
  188078. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188079. {
  188080. png_push_save_buffer(png_ptr);
  188081. return;
  188082. }
  188083. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188084. png_ptr->mode |= PNG_HAVE_IDAT;
  188085. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188086. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188087. png_ptr->mode |= PNG_HAVE_PLTE;
  188088. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188089. {
  188090. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188091. png_error(png_ptr, "Missing IHDR before IDAT");
  188092. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188093. !(png_ptr->mode & PNG_HAVE_PLTE))
  188094. png_error(png_ptr, "Missing PLTE before IDAT");
  188095. }
  188096. }
  188097. #endif
  188098. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188099. {
  188100. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188101. {
  188102. png_push_save_buffer(png_ptr);
  188103. return;
  188104. }
  188105. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188106. }
  188107. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188108. {
  188109. /* If we reach an IDAT chunk, this means we have read all of the
  188110. * header chunks, and we can start reading the image (or if this
  188111. * is called after the image has been read - we have an error).
  188112. */
  188113. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188114. png_error(png_ptr, "Missing IHDR before IDAT");
  188115. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188116. !(png_ptr->mode & PNG_HAVE_PLTE))
  188117. png_error(png_ptr, "Missing PLTE before IDAT");
  188118. if (png_ptr->mode & PNG_HAVE_IDAT)
  188119. {
  188120. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188121. if (png_ptr->push_length == 0)
  188122. return;
  188123. if (png_ptr->mode & PNG_AFTER_IDAT)
  188124. png_error(png_ptr, "Too many IDAT's found");
  188125. }
  188126. png_ptr->idat_size = png_ptr->push_length;
  188127. png_ptr->mode |= PNG_HAVE_IDAT;
  188128. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188129. png_push_have_info(png_ptr, info_ptr);
  188130. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188131. png_ptr->zstream.next_out = png_ptr->row_buf;
  188132. return;
  188133. }
  188134. #if defined(PNG_READ_gAMA_SUPPORTED)
  188135. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188136. {
  188137. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188138. {
  188139. png_push_save_buffer(png_ptr);
  188140. return;
  188141. }
  188142. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188143. }
  188144. #endif
  188145. #if defined(PNG_READ_sBIT_SUPPORTED)
  188146. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188147. {
  188148. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188149. {
  188150. png_push_save_buffer(png_ptr);
  188151. return;
  188152. }
  188153. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188154. }
  188155. #endif
  188156. #if defined(PNG_READ_cHRM_SUPPORTED)
  188157. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188158. {
  188159. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188160. {
  188161. png_push_save_buffer(png_ptr);
  188162. return;
  188163. }
  188164. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188165. }
  188166. #endif
  188167. #if defined(PNG_READ_sRGB_SUPPORTED)
  188168. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188169. {
  188170. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188171. {
  188172. png_push_save_buffer(png_ptr);
  188173. return;
  188174. }
  188175. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188176. }
  188177. #endif
  188178. #if defined(PNG_READ_iCCP_SUPPORTED)
  188179. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188180. {
  188181. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188182. {
  188183. png_push_save_buffer(png_ptr);
  188184. return;
  188185. }
  188186. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188187. }
  188188. #endif
  188189. #if defined(PNG_READ_sPLT_SUPPORTED)
  188190. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188191. {
  188192. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188193. {
  188194. png_push_save_buffer(png_ptr);
  188195. return;
  188196. }
  188197. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188198. }
  188199. #endif
  188200. #if defined(PNG_READ_tRNS_SUPPORTED)
  188201. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188202. {
  188203. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188204. {
  188205. png_push_save_buffer(png_ptr);
  188206. return;
  188207. }
  188208. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188209. }
  188210. #endif
  188211. #if defined(PNG_READ_bKGD_SUPPORTED)
  188212. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188213. {
  188214. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188215. {
  188216. png_push_save_buffer(png_ptr);
  188217. return;
  188218. }
  188219. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188220. }
  188221. #endif
  188222. #if defined(PNG_READ_hIST_SUPPORTED)
  188223. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188224. {
  188225. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188226. {
  188227. png_push_save_buffer(png_ptr);
  188228. return;
  188229. }
  188230. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188231. }
  188232. #endif
  188233. #if defined(PNG_READ_pHYs_SUPPORTED)
  188234. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188235. {
  188236. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188237. {
  188238. png_push_save_buffer(png_ptr);
  188239. return;
  188240. }
  188241. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188242. }
  188243. #endif
  188244. #if defined(PNG_READ_oFFs_SUPPORTED)
  188245. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188246. {
  188247. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188248. {
  188249. png_push_save_buffer(png_ptr);
  188250. return;
  188251. }
  188252. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188253. }
  188254. #endif
  188255. #if defined(PNG_READ_pCAL_SUPPORTED)
  188256. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188257. {
  188258. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188259. {
  188260. png_push_save_buffer(png_ptr);
  188261. return;
  188262. }
  188263. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188264. }
  188265. #endif
  188266. #if defined(PNG_READ_sCAL_SUPPORTED)
  188267. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188268. {
  188269. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188270. {
  188271. png_push_save_buffer(png_ptr);
  188272. return;
  188273. }
  188274. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188275. }
  188276. #endif
  188277. #if defined(PNG_READ_tIME_SUPPORTED)
  188278. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188279. {
  188280. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188281. {
  188282. png_push_save_buffer(png_ptr);
  188283. return;
  188284. }
  188285. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188286. }
  188287. #endif
  188288. #if defined(PNG_READ_tEXt_SUPPORTED)
  188289. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188290. {
  188291. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188292. {
  188293. png_push_save_buffer(png_ptr);
  188294. return;
  188295. }
  188296. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188297. }
  188298. #endif
  188299. #if defined(PNG_READ_zTXt_SUPPORTED)
  188300. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188301. {
  188302. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188303. {
  188304. png_push_save_buffer(png_ptr);
  188305. return;
  188306. }
  188307. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188308. }
  188309. #endif
  188310. #if defined(PNG_READ_iTXt_SUPPORTED)
  188311. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188312. {
  188313. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188314. {
  188315. png_push_save_buffer(png_ptr);
  188316. return;
  188317. }
  188318. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188319. }
  188320. #endif
  188321. else
  188322. {
  188323. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188324. {
  188325. png_push_save_buffer(png_ptr);
  188326. return;
  188327. }
  188328. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188329. }
  188330. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188331. }
  188332. void /* PRIVATE */
  188333. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188334. {
  188335. png_ptr->process_mode = PNG_SKIP_MODE;
  188336. png_ptr->skip_length = skip;
  188337. }
  188338. void /* PRIVATE */
  188339. png_push_crc_finish(png_structp png_ptr)
  188340. {
  188341. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188342. {
  188343. png_size_t save_size;
  188344. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188345. save_size = (png_size_t)png_ptr->skip_length;
  188346. else
  188347. save_size = png_ptr->save_buffer_size;
  188348. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188349. png_ptr->skip_length -= save_size;
  188350. png_ptr->buffer_size -= save_size;
  188351. png_ptr->save_buffer_size -= save_size;
  188352. png_ptr->save_buffer_ptr += save_size;
  188353. }
  188354. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188355. {
  188356. png_size_t save_size;
  188357. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188358. save_size = (png_size_t)png_ptr->skip_length;
  188359. else
  188360. save_size = png_ptr->current_buffer_size;
  188361. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188362. png_ptr->skip_length -= save_size;
  188363. png_ptr->buffer_size -= save_size;
  188364. png_ptr->current_buffer_size -= save_size;
  188365. png_ptr->current_buffer_ptr += save_size;
  188366. }
  188367. if (!png_ptr->skip_length)
  188368. {
  188369. if (png_ptr->buffer_size < 4)
  188370. {
  188371. png_push_save_buffer(png_ptr);
  188372. return;
  188373. }
  188374. png_crc_finish(png_ptr, 0);
  188375. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188376. }
  188377. }
  188378. void PNGAPI
  188379. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188380. {
  188381. png_bytep ptr;
  188382. if(png_ptr == NULL) return;
  188383. ptr = buffer;
  188384. if (png_ptr->save_buffer_size)
  188385. {
  188386. png_size_t save_size;
  188387. if (length < png_ptr->save_buffer_size)
  188388. save_size = length;
  188389. else
  188390. save_size = png_ptr->save_buffer_size;
  188391. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188392. length -= save_size;
  188393. ptr += save_size;
  188394. png_ptr->buffer_size -= save_size;
  188395. png_ptr->save_buffer_size -= save_size;
  188396. png_ptr->save_buffer_ptr += save_size;
  188397. }
  188398. if (length && png_ptr->current_buffer_size)
  188399. {
  188400. png_size_t save_size;
  188401. if (length < png_ptr->current_buffer_size)
  188402. save_size = length;
  188403. else
  188404. save_size = png_ptr->current_buffer_size;
  188405. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188406. png_ptr->buffer_size -= save_size;
  188407. png_ptr->current_buffer_size -= save_size;
  188408. png_ptr->current_buffer_ptr += save_size;
  188409. }
  188410. }
  188411. void /* PRIVATE */
  188412. png_push_save_buffer(png_structp png_ptr)
  188413. {
  188414. if (png_ptr->save_buffer_size)
  188415. {
  188416. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188417. {
  188418. png_size_t i,istop;
  188419. png_bytep sp;
  188420. png_bytep dp;
  188421. istop = png_ptr->save_buffer_size;
  188422. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188423. i < istop; i++, sp++, dp++)
  188424. {
  188425. *dp = *sp;
  188426. }
  188427. }
  188428. }
  188429. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188430. png_ptr->save_buffer_max)
  188431. {
  188432. png_size_t new_max;
  188433. png_bytep old_buffer;
  188434. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188435. (png_ptr->current_buffer_size + 256))
  188436. {
  188437. png_error(png_ptr, "Potential overflow of save_buffer");
  188438. }
  188439. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188440. old_buffer = png_ptr->save_buffer;
  188441. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188442. (png_uint_32)new_max);
  188443. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188444. png_free(png_ptr, old_buffer);
  188445. png_ptr->save_buffer_max = new_max;
  188446. }
  188447. if (png_ptr->current_buffer_size)
  188448. {
  188449. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188450. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188451. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188452. png_ptr->current_buffer_size = 0;
  188453. }
  188454. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188455. png_ptr->buffer_size = 0;
  188456. }
  188457. void /* PRIVATE */
  188458. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188459. png_size_t buffer_length)
  188460. {
  188461. png_ptr->current_buffer = buffer;
  188462. png_ptr->current_buffer_size = buffer_length;
  188463. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188464. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188465. }
  188466. void /* PRIVATE */
  188467. png_push_read_IDAT(png_structp png_ptr)
  188468. {
  188469. #ifdef PNG_USE_LOCAL_ARRAYS
  188470. PNG_CONST PNG_IDAT;
  188471. #endif
  188472. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188473. {
  188474. png_byte chunk_length[4];
  188475. if (png_ptr->buffer_size < 8)
  188476. {
  188477. png_push_save_buffer(png_ptr);
  188478. return;
  188479. }
  188480. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188481. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188482. png_reset_crc(png_ptr);
  188483. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188484. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188485. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188486. {
  188487. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188488. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188489. png_error(png_ptr, "Not enough compressed data");
  188490. return;
  188491. }
  188492. png_ptr->idat_size = png_ptr->push_length;
  188493. }
  188494. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188495. {
  188496. png_size_t save_size;
  188497. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188498. {
  188499. save_size = (png_size_t)png_ptr->idat_size;
  188500. /* check for overflow */
  188501. if((png_uint_32)save_size != png_ptr->idat_size)
  188502. png_error(png_ptr, "save_size overflowed in pngpread");
  188503. }
  188504. else
  188505. save_size = png_ptr->save_buffer_size;
  188506. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188507. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188508. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188509. png_ptr->idat_size -= save_size;
  188510. png_ptr->buffer_size -= save_size;
  188511. png_ptr->save_buffer_size -= save_size;
  188512. png_ptr->save_buffer_ptr += save_size;
  188513. }
  188514. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188515. {
  188516. png_size_t save_size;
  188517. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188518. {
  188519. save_size = (png_size_t)png_ptr->idat_size;
  188520. /* check for overflow */
  188521. if((png_uint_32)save_size != png_ptr->idat_size)
  188522. png_error(png_ptr, "save_size overflowed in pngpread");
  188523. }
  188524. else
  188525. save_size = png_ptr->current_buffer_size;
  188526. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188527. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188528. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188529. png_ptr->idat_size -= save_size;
  188530. png_ptr->buffer_size -= save_size;
  188531. png_ptr->current_buffer_size -= save_size;
  188532. png_ptr->current_buffer_ptr += save_size;
  188533. }
  188534. if (!png_ptr->idat_size)
  188535. {
  188536. if (png_ptr->buffer_size < 4)
  188537. {
  188538. png_push_save_buffer(png_ptr);
  188539. return;
  188540. }
  188541. png_crc_finish(png_ptr, 0);
  188542. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188543. png_ptr->mode |= PNG_AFTER_IDAT;
  188544. }
  188545. }
  188546. void /* PRIVATE */
  188547. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188548. png_size_t buffer_length)
  188549. {
  188550. int ret;
  188551. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188552. png_error(png_ptr, "Extra compression data");
  188553. png_ptr->zstream.next_in = buffer;
  188554. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188555. for(;;)
  188556. {
  188557. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188558. if (ret != Z_OK)
  188559. {
  188560. if (ret == Z_STREAM_END)
  188561. {
  188562. if (png_ptr->zstream.avail_in)
  188563. png_error(png_ptr, "Extra compressed data");
  188564. if (!(png_ptr->zstream.avail_out))
  188565. {
  188566. png_push_process_row(png_ptr);
  188567. }
  188568. png_ptr->mode |= PNG_AFTER_IDAT;
  188569. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188570. break;
  188571. }
  188572. else if (ret == Z_BUF_ERROR)
  188573. break;
  188574. else
  188575. png_error(png_ptr, "Decompression Error");
  188576. }
  188577. if (!(png_ptr->zstream.avail_out))
  188578. {
  188579. if ((
  188580. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188581. png_ptr->interlaced && png_ptr->pass > 6) ||
  188582. (!png_ptr->interlaced &&
  188583. #endif
  188584. png_ptr->row_number == png_ptr->num_rows))
  188585. {
  188586. if (png_ptr->zstream.avail_in)
  188587. {
  188588. png_warning(png_ptr, "Too much data in IDAT chunks");
  188589. }
  188590. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188591. break;
  188592. }
  188593. png_push_process_row(png_ptr);
  188594. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188595. png_ptr->zstream.next_out = png_ptr->row_buf;
  188596. }
  188597. else
  188598. break;
  188599. }
  188600. }
  188601. void /* PRIVATE */
  188602. png_push_process_row(png_structp png_ptr)
  188603. {
  188604. png_ptr->row_info.color_type = png_ptr->color_type;
  188605. png_ptr->row_info.width = png_ptr->iwidth;
  188606. png_ptr->row_info.channels = png_ptr->channels;
  188607. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188608. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188609. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188610. png_ptr->row_info.width);
  188611. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188612. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188613. (int)(png_ptr->row_buf[0]));
  188614. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188615. png_ptr->rowbytes + 1);
  188616. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188617. png_do_read_transformations(png_ptr);
  188618. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188619. /* blow up interlaced rows to full size */
  188620. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188621. {
  188622. if (png_ptr->pass < 6)
  188623. /* old interface (pre-1.0.9):
  188624. png_do_read_interlace(&(png_ptr->row_info),
  188625. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188626. */
  188627. png_do_read_interlace(png_ptr);
  188628. switch (png_ptr->pass)
  188629. {
  188630. case 0:
  188631. {
  188632. int i;
  188633. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188634. {
  188635. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188636. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188637. }
  188638. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188639. {
  188640. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188641. {
  188642. png_push_have_row(png_ptr, png_bytep_NULL);
  188643. png_read_push_finish_row(png_ptr);
  188644. }
  188645. }
  188646. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188647. {
  188648. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188649. {
  188650. png_push_have_row(png_ptr, png_bytep_NULL);
  188651. png_read_push_finish_row(png_ptr);
  188652. }
  188653. }
  188654. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188655. {
  188656. png_push_have_row(png_ptr, png_bytep_NULL);
  188657. png_read_push_finish_row(png_ptr);
  188658. }
  188659. break;
  188660. }
  188661. case 1:
  188662. {
  188663. int i;
  188664. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188665. {
  188666. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188667. png_read_push_finish_row(png_ptr);
  188668. }
  188669. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188670. {
  188671. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188672. {
  188673. png_push_have_row(png_ptr, png_bytep_NULL);
  188674. png_read_push_finish_row(png_ptr);
  188675. }
  188676. }
  188677. break;
  188678. }
  188679. case 2:
  188680. {
  188681. int i;
  188682. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188683. {
  188684. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188685. png_read_push_finish_row(png_ptr);
  188686. }
  188687. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188688. {
  188689. png_push_have_row(png_ptr, png_bytep_NULL);
  188690. png_read_push_finish_row(png_ptr);
  188691. }
  188692. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188693. {
  188694. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188695. {
  188696. png_push_have_row(png_ptr, png_bytep_NULL);
  188697. png_read_push_finish_row(png_ptr);
  188698. }
  188699. }
  188700. break;
  188701. }
  188702. case 3:
  188703. {
  188704. int i;
  188705. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188706. {
  188707. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188708. png_read_push_finish_row(png_ptr);
  188709. }
  188710. if (png_ptr->pass == 4) /* skip top two generated rows */
  188711. {
  188712. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188713. {
  188714. png_push_have_row(png_ptr, png_bytep_NULL);
  188715. png_read_push_finish_row(png_ptr);
  188716. }
  188717. }
  188718. break;
  188719. }
  188720. case 4:
  188721. {
  188722. int i;
  188723. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188724. {
  188725. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188726. png_read_push_finish_row(png_ptr);
  188727. }
  188728. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188729. {
  188730. png_push_have_row(png_ptr, png_bytep_NULL);
  188731. png_read_push_finish_row(png_ptr);
  188732. }
  188733. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188734. {
  188735. png_push_have_row(png_ptr, png_bytep_NULL);
  188736. png_read_push_finish_row(png_ptr);
  188737. }
  188738. break;
  188739. }
  188740. case 5:
  188741. {
  188742. int i;
  188743. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188744. {
  188745. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188746. png_read_push_finish_row(png_ptr);
  188747. }
  188748. if (png_ptr->pass == 6) /* skip top generated row */
  188749. {
  188750. png_push_have_row(png_ptr, png_bytep_NULL);
  188751. png_read_push_finish_row(png_ptr);
  188752. }
  188753. break;
  188754. }
  188755. case 6:
  188756. {
  188757. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188758. png_read_push_finish_row(png_ptr);
  188759. if (png_ptr->pass != 6)
  188760. break;
  188761. png_push_have_row(png_ptr, png_bytep_NULL);
  188762. png_read_push_finish_row(png_ptr);
  188763. }
  188764. }
  188765. }
  188766. else
  188767. #endif
  188768. {
  188769. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188770. png_read_push_finish_row(png_ptr);
  188771. }
  188772. }
  188773. void /* PRIVATE */
  188774. png_read_push_finish_row(png_structp png_ptr)
  188775. {
  188776. #ifdef PNG_USE_LOCAL_ARRAYS
  188777. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188778. /* start of interlace block */
  188779. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188780. /* offset to next interlace block */
  188781. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188782. /* start of interlace block in the y direction */
  188783. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188784. /* offset to next interlace block in the y direction */
  188785. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188786. /* Height of interlace block. This is not currently used - if you need
  188787. * it, uncomment it here and in png.h
  188788. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188789. */
  188790. #endif
  188791. png_ptr->row_number++;
  188792. if (png_ptr->row_number < png_ptr->num_rows)
  188793. return;
  188794. if (png_ptr->interlaced)
  188795. {
  188796. png_ptr->row_number = 0;
  188797. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188798. png_ptr->rowbytes + 1);
  188799. do
  188800. {
  188801. png_ptr->pass++;
  188802. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188803. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188804. (png_ptr->pass == 5 && png_ptr->width < 2))
  188805. png_ptr->pass++;
  188806. if (png_ptr->pass > 7)
  188807. png_ptr->pass--;
  188808. if (png_ptr->pass >= 7)
  188809. break;
  188810. png_ptr->iwidth = (png_ptr->width +
  188811. png_pass_inc[png_ptr->pass] - 1 -
  188812. png_pass_start[png_ptr->pass]) /
  188813. png_pass_inc[png_ptr->pass];
  188814. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188815. png_ptr->iwidth) + 1;
  188816. if (png_ptr->transformations & PNG_INTERLACE)
  188817. break;
  188818. png_ptr->num_rows = (png_ptr->height +
  188819. png_pass_yinc[png_ptr->pass] - 1 -
  188820. png_pass_ystart[png_ptr->pass]) /
  188821. png_pass_yinc[png_ptr->pass];
  188822. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188823. }
  188824. }
  188825. #if defined(PNG_READ_tEXt_SUPPORTED)
  188826. void /* PRIVATE */
  188827. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188828. length)
  188829. {
  188830. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188831. {
  188832. png_error(png_ptr, "Out of place tEXt");
  188833. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188834. }
  188835. #ifdef PNG_MAX_MALLOC_64K
  188836. png_ptr->skip_length = 0; /* This may not be necessary */
  188837. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188838. {
  188839. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188840. png_ptr->skip_length = length - (png_uint_32)65535L;
  188841. length = (png_uint_32)65535L;
  188842. }
  188843. #endif
  188844. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188845. (png_uint_32)(length+1));
  188846. png_ptr->current_text[length] = '\0';
  188847. png_ptr->current_text_ptr = png_ptr->current_text;
  188848. png_ptr->current_text_size = (png_size_t)length;
  188849. png_ptr->current_text_left = (png_size_t)length;
  188850. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188851. }
  188852. void /* PRIVATE */
  188853. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188854. {
  188855. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188856. {
  188857. png_size_t text_size;
  188858. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188859. text_size = png_ptr->buffer_size;
  188860. else
  188861. text_size = png_ptr->current_text_left;
  188862. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188863. png_ptr->current_text_left -= text_size;
  188864. png_ptr->current_text_ptr += text_size;
  188865. }
  188866. if (!(png_ptr->current_text_left))
  188867. {
  188868. png_textp text_ptr;
  188869. png_charp text;
  188870. png_charp key;
  188871. int ret;
  188872. if (png_ptr->buffer_size < 4)
  188873. {
  188874. png_push_save_buffer(png_ptr);
  188875. return;
  188876. }
  188877. png_push_crc_finish(png_ptr);
  188878. #if defined(PNG_MAX_MALLOC_64K)
  188879. if (png_ptr->skip_length)
  188880. return;
  188881. #endif
  188882. key = png_ptr->current_text;
  188883. for (text = key; *text; text++)
  188884. /* empty loop */ ;
  188885. if (text < key + png_ptr->current_text_size)
  188886. text++;
  188887. text_ptr = (png_textp)png_malloc(png_ptr,
  188888. (png_uint_32)png_sizeof(png_text));
  188889. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188890. text_ptr->key = key;
  188891. #ifdef PNG_iTXt_SUPPORTED
  188892. text_ptr->lang = NULL;
  188893. text_ptr->lang_key = NULL;
  188894. #endif
  188895. text_ptr->text = text;
  188896. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188897. png_free(png_ptr, key);
  188898. png_free(png_ptr, text_ptr);
  188899. png_ptr->current_text = NULL;
  188900. if (ret)
  188901. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188902. }
  188903. }
  188904. #endif
  188905. #if defined(PNG_READ_zTXt_SUPPORTED)
  188906. void /* PRIVATE */
  188907. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188908. length)
  188909. {
  188910. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188911. {
  188912. png_error(png_ptr, "Out of place zTXt");
  188913. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188914. }
  188915. #ifdef PNG_MAX_MALLOC_64K
  188916. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188917. * to be able to store the uncompressed data. Actually, the threshold
  188918. * is probably around 32K, but it isn't as definite as 64K is.
  188919. */
  188920. if (length > (png_uint_32)65535L)
  188921. {
  188922. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188923. png_push_crc_skip(png_ptr, length);
  188924. return;
  188925. }
  188926. #endif
  188927. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188928. (png_uint_32)(length+1));
  188929. png_ptr->current_text[length] = '\0';
  188930. png_ptr->current_text_ptr = png_ptr->current_text;
  188931. png_ptr->current_text_size = (png_size_t)length;
  188932. png_ptr->current_text_left = (png_size_t)length;
  188933. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188934. }
  188935. void /* PRIVATE */
  188936. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188937. {
  188938. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188939. {
  188940. png_size_t text_size;
  188941. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188942. text_size = png_ptr->buffer_size;
  188943. else
  188944. text_size = png_ptr->current_text_left;
  188945. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188946. png_ptr->current_text_left -= text_size;
  188947. png_ptr->current_text_ptr += text_size;
  188948. }
  188949. if (!(png_ptr->current_text_left))
  188950. {
  188951. png_textp text_ptr;
  188952. png_charp text;
  188953. png_charp key;
  188954. int ret;
  188955. png_size_t text_size, key_size;
  188956. if (png_ptr->buffer_size < 4)
  188957. {
  188958. png_push_save_buffer(png_ptr);
  188959. return;
  188960. }
  188961. png_push_crc_finish(png_ptr);
  188962. key = png_ptr->current_text;
  188963. for (text = key; *text; text++)
  188964. /* empty loop */ ;
  188965. /* zTXt can't have zero text */
  188966. if (text >= key + png_ptr->current_text_size)
  188967. {
  188968. png_ptr->current_text = NULL;
  188969. png_free(png_ptr, key);
  188970. return;
  188971. }
  188972. text++;
  188973. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188974. {
  188975. png_ptr->current_text = NULL;
  188976. png_free(png_ptr, key);
  188977. return;
  188978. }
  188979. text++;
  188980. png_ptr->zstream.next_in = (png_bytep )text;
  188981. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188982. (text - key));
  188983. png_ptr->zstream.next_out = png_ptr->zbuf;
  188984. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188985. key_size = text - key;
  188986. text_size = 0;
  188987. text = NULL;
  188988. ret = Z_STREAM_END;
  188989. while (png_ptr->zstream.avail_in)
  188990. {
  188991. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188992. if (ret != Z_OK && ret != Z_STREAM_END)
  188993. {
  188994. inflateReset(&png_ptr->zstream);
  188995. png_ptr->zstream.avail_in = 0;
  188996. png_ptr->current_text = NULL;
  188997. png_free(png_ptr, key);
  188998. png_free(png_ptr, text);
  188999. return;
  189000. }
  189001. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189002. {
  189003. if (text == NULL)
  189004. {
  189005. text = (png_charp)png_malloc(png_ptr,
  189006. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189007. + key_size + 1));
  189008. png_memcpy(text + key_size, png_ptr->zbuf,
  189009. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189010. png_memcpy(text, key, key_size);
  189011. text_size = key_size + png_ptr->zbuf_size -
  189012. png_ptr->zstream.avail_out;
  189013. *(text + text_size) = '\0';
  189014. }
  189015. else
  189016. {
  189017. png_charp tmp;
  189018. tmp = text;
  189019. text = (png_charp)png_malloc(png_ptr, text_size +
  189020. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189021. + 1));
  189022. png_memcpy(text, tmp, text_size);
  189023. png_free(png_ptr, tmp);
  189024. png_memcpy(text + text_size, png_ptr->zbuf,
  189025. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189026. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189027. *(text + text_size) = '\0';
  189028. }
  189029. if (ret != Z_STREAM_END)
  189030. {
  189031. png_ptr->zstream.next_out = png_ptr->zbuf;
  189032. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189033. }
  189034. }
  189035. else
  189036. {
  189037. break;
  189038. }
  189039. if (ret == Z_STREAM_END)
  189040. break;
  189041. }
  189042. inflateReset(&png_ptr->zstream);
  189043. png_ptr->zstream.avail_in = 0;
  189044. if (ret != Z_STREAM_END)
  189045. {
  189046. png_ptr->current_text = NULL;
  189047. png_free(png_ptr, key);
  189048. png_free(png_ptr, text);
  189049. return;
  189050. }
  189051. png_ptr->current_text = NULL;
  189052. png_free(png_ptr, key);
  189053. key = text;
  189054. text += key_size;
  189055. text_ptr = (png_textp)png_malloc(png_ptr,
  189056. (png_uint_32)png_sizeof(png_text));
  189057. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189058. text_ptr->key = key;
  189059. #ifdef PNG_iTXt_SUPPORTED
  189060. text_ptr->lang = NULL;
  189061. text_ptr->lang_key = NULL;
  189062. #endif
  189063. text_ptr->text = text;
  189064. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189065. png_free(png_ptr, key);
  189066. png_free(png_ptr, text_ptr);
  189067. if (ret)
  189068. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189069. }
  189070. }
  189071. #endif
  189072. #if defined(PNG_READ_iTXt_SUPPORTED)
  189073. void /* PRIVATE */
  189074. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189075. length)
  189076. {
  189077. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189078. {
  189079. png_error(png_ptr, "Out of place iTXt");
  189080. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189081. }
  189082. #ifdef PNG_MAX_MALLOC_64K
  189083. png_ptr->skip_length = 0; /* This may not be necessary */
  189084. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189085. {
  189086. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189087. png_ptr->skip_length = length - (png_uint_32)65535L;
  189088. length = (png_uint_32)65535L;
  189089. }
  189090. #endif
  189091. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189092. (png_uint_32)(length+1));
  189093. png_ptr->current_text[length] = '\0';
  189094. png_ptr->current_text_ptr = png_ptr->current_text;
  189095. png_ptr->current_text_size = (png_size_t)length;
  189096. png_ptr->current_text_left = (png_size_t)length;
  189097. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189098. }
  189099. void /* PRIVATE */
  189100. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189101. {
  189102. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189103. {
  189104. png_size_t text_size;
  189105. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189106. text_size = png_ptr->buffer_size;
  189107. else
  189108. text_size = png_ptr->current_text_left;
  189109. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189110. png_ptr->current_text_left -= text_size;
  189111. png_ptr->current_text_ptr += text_size;
  189112. }
  189113. if (!(png_ptr->current_text_left))
  189114. {
  189115. png_textp text_ptr;
  189116. png_charp key;
  189117. int comp_flag;
  189118. png_charp lang;
  189119. png_charp lang_key;
  189120. png_charp text;
  189121. int ret;
  189122. if (png_ptr->buffer_size < 4)
  189123. {
  189124. png_push_save_buffer(png_ptr);
  189125. return;
  189126. }
  189127. png_push_crc_finish(png_ptr);
  189128. #if defined(PNG_MAX_MALLOC_64K)
  189129. if (png_ptr->skip_length)
  189130. return;
  189131. #endif
  189132. key = png_ptr->current_text;
  189133. for (lang = key; *lang; lang++)
  189134. /* empty loop */ ;
  189135. if (lang < key + png_ptr->current_text_size - 3)
  189136. lang++;
  189137. comp_flag = *lang++;
  189138. lang++; /* skip comp_type, always zero */
  189139. for (lang_key = lang; *lang_key; lang_key++)
  189140. /* empty loop */ ;
  189141. lang_key++; /* skip NUL separator */
  189142. text=lang_key;
  189143. if (lang_key < key + png_ptr->current_text_size - 1)
  189144. {
  189145. for (; *text; text++)
  189146. /* empty loop */ ;
  189147. }
  189148. if (text < key + png_ptr->current_text_size)
  189149. text++;
  189150. text_ptr = (png_textp)png_malloc(png_ptr,
  189151. (png_uint_32)png_sizeof(png_text));
  189152. text_ptr->compression = comp_flag + 2;
  189153. text_ptr->key = key;
  189154. text_ptr->lang = lang;
  189155. text_ptr->lang_key = lang_key;
  189156. text_ptr->text = text;
  189157. text_ptr->text_length = 0;
  189158. text_ptr->itxt_length = png_strlen(text);
  189159. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189160. png_ptr->current_text = NULL;
  189161. png_free(png_ptr, text_ptr);
  189162. if (ret)
  189163. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189164. }
  189165. }
  189166. #endif
  189167. /* This function is called when we haven't found a handler for this
  189168. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189169. * name or a critical chunk), the chunk is (currently) silently ignored.
  189170. */
  189171. void /* PRIVATE */
  189172. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189173. length)
  189174. {
  189175. png_uint_32 skip=0;
  189176. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189177. if (!(png_ptr->chunk_name[0] & 0x20))
  189178. {
  189179. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189180. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189181. PNG_HANDLE_CHUNK_ALWAYS
  189182. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189183. && png_ptr->read_user_chunk_fn == NULL
  189184. #endif
  189185. )
  189186. #endif
  189187. png_chunk_error(png_ptr, "unknown critical chunk");
  189188. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189189. }
  189190. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189191. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189192. {
  189193. #ifdef PNG_MAX_MALLOC_64K
  189194. if (length > (png_uint_32)65535L)
  189195. {
  189196. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189197. skip = length - (png_uint_32)65535L;
  189198. length = (png_uint_32)65535L;
  189199. }
  189200. #endif
  189201. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189202. (png_charp)png_ptr->chunk_name, 5);
  189203. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189204. png_ptr->unknown_chunk.size = (png_size_t)length;
  189205. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189206. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189207. if(png_ptr->read_user_chunk_fn != NULL)
  189208. {
  189209. /* callback to user unknown chunk handler */
  189210. int ret;
  189211. ret = (*(png_ptr->read_user_chunk_fn))
  189212. (png_ptr, &png_ptr->unknown_chunk);
  189213. if (ret < 0)
  189214. png_chunk_error(png_ptr, "error in user chunk");
  189215. if (ret == 0)
  189216. {
  189217. if (!(png_ptr->chunk_name[0] & 0x20))
  189218. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189219. PNG_HANDLE_CHUNK_ALWAYS)
  189220. png_chunk_error(png_ptr, "unknown critical chunk");
  189221. png_set_unknown_chunks(png_ptr, info_ptr,
  189222. &png_ptr->unknown_chunk, 1);
  189223. }
  189224. }
  189225. #else
  189226. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189227. #endif
  189228. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189229. png_ptr->unknown_chunk.data = NULL;
  189230. }
  189231. else
  189232. #endif
  189233. skip=length;
  189234. png_push_crc_skip(png_ptr, skip);
  189235. }
  189236. void /* PRIVATE */
  189237. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189238. {
  189239. if (png_ptr->info_fn != NULL)
  189240. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189241. }
  189242. void /* PRIVATE */
  189243. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189244. {
  189245. if (png_ptr->end_fn != NULL)
  189246. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189247. }
  189248. void /* PRIVATE */
  189249. png_push_have_row(png_structp png_ptr, png_bytep row)
  189250. {
  189251. if (png_ptr->row_fn != NULL)
  189252. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189253. (int)png_ptr->pass);
  189254. }
  189255. void PNGAPI
  189256. png_progressive_combine_row (png_structp png_ptr,
  189257. png_bytep old_row, png_bytep new_row)
  189258. {
  189259. #ifdef PNG_USE_LOCAL_ARRAYS
  189260. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189261. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189262. #endif
  189263. if(png_ptr == NULL) return;
  189264. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189265. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189266. }
  189267. void PNGAPI
  189268. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189269. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189270. png_progressive_end_ptr end_fn)
  189271. {
  189272. if(png_ptr == NULL) return;
  189273. png_ptr->info_fn = info_fn;
  189274. png_ptr->row_fn = row_fn;
  189275. png_ptr->end_fn = end_fn;
  189276. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189277. }
  189278. png_voidp PNGAPI
  189279. png_get_progressive_ptr(png_structp png_ptr)
  189280. {
  189281. if(png_ptr == NULL) return (NULL);
  189282. return png_ptr->io_ptr;
  189283. }
  189284. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189285. /*** End of inlined file: pngpread.c ***/
  189286. /*** Start of inlined file: pngrio.c ***/
  189287. /* pngrio.c - functions for data input
  189288. *
  189289. * Last changed in libpng 1.2.13 November 13, 2006
  189290. * For conditions of distribution and use, see copyright notice in png.h
  189291. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189292. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189293. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189294. *
  189295. * This file provides a location for all input. Users who need
  189296. * special handling are expected to write a function that has the same
  189297. * arguments as this and performs a similar function, but that possibly
  189298. * has a different input method. Note that you shouldn't change this
  189299. * function, but rather write a replacement function and then make
  189300. * libpng use it at run time with png_set_read_fn(...).
  189301. */
  189302. #define PNG_INTERNAL
  189303. #if defined(PNG_READ_SUPPORTED)
  189304. /* Read the data from whatever input you are using. The default routine
  189305. reads from a file pointer. Note that this routine sometimes gets called
  189306. with very small lengths, so you should implement some kind of simple
  189307. buffering if you are using unbuffered reads. This should never be asked
  189308. to read more then 64K on a 16 bit machine. */
  189309. void /* PRIVATE */
  189310. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189311. {
  189312. png_debug1(4,"reading %d bytes\n", (int)length);
  189313. if (png_ptr->read_data_fn != NULL)
  189314. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189315. else
  189316. png_error(png_ptr, "Call to NULL read function");
  189317. }
  189318. #if !defined(PNG_NO_STDIO)
  189319. /* This is the function that does the actual reading of data. If you are
  189320. not reading from a standard C stream, you should create a replacement
  189321. read_data function and use it at run time with png_set_read_fn(), rather
  189322. than changing the library. */
  189323. #ifndef USE_FAR_KEYWORD
  189324. void PNGAPI
  189325. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189326. {
  189327. png_size_t check;
  189328. if(png_ptr == NULL) return;
  189329. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189330. * instead of an int, which is what fread() actually returns.
  189331. */
  189332. #if defined(_WIN32_WCE)
  189333. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189334. check = 0;
  189335. #else
  189336. check = (png_size_t)fread(data, (png_size_t)1, length,
  189337. (png_FILE_p)png_ptr->io_ptr);
  189338. #endif
  189339. if (check != length)
  189340. png_error(png_ptr, "Read Error");
  189341. }
  189342. #else
  189343. /* this is the model-independent version. Since the standard I/O library
  189344. can't handle far buffers in the medium and small models, we have to copy
  189345. the data.
  189346. */
  189347. #define NEAR_BUF_SIZE 1024
  189348. #define MIN(a,b) (a <= b ? a : b)
  189349. static void PNGAPI
  189350. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189351. {
  189352. int check;
  189353. png_byte *n_data;
  189354. png_FILE_p io_ptr;
  189355. if(png_ptr == NULL) return;
  189356. /* Check if data really is near. If so, use usual code. */
  189357. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189358. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189359. if ((png_bytep)n_data == data)
  189360. {
  189361. #if defined(_WIN32_WCE)
  189362. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189363. check = 0;
  189364. #else
  189365. check = fread(n_data, 1, length, io_ptr);
  189366. #endif
  189367. }
  189368. else
  189369. {
  189370. png_byte buf[NEAR_BUF_SIZE];
  189371. png_size_t read, remaining, err;
  189372. check = 0;
  189373. remaining = length;
  189374. do
  189375. {
  189376. read = MIN(NEAR_BUF_SIZE, remaining);
  189377. #if defined(_WIN32_WCE)
  189378. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189379. err = 0;
  189380. #else
  189381. err = fread(buf, (png_size_t)1, read, io_ptr);
  189382. #endif
  189383. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189384. if(err != read)
  189385. break;
  189386. else
  189387. check += err;
  189388. data += read;
  189389. remaining -= read;
  189390. }
  189391. while (remaining != 0);
  189392. }
  189393. if ((png_uint_32)check != (png_uint_32)length)
  189394. png_error(png_ptr, "read Error");
  189395. }
  189396. #endif
  189397. #endif
  189398. /* This function allows the application to supply a new input function
  189399. for libpng if standard C streams aren't being used.
  189400. This function takes as its arguments:
  189401. png_ptr - pointer to a png input data structure
  189402. io_ptr - pointer to user supplied structure containing info about
  189403. the input functions. May be NULL.
  189404. read_data_fn - pointer to a new input function that takes as its
  189405. arguments a pointer to a png_struct, a pointer to
  189406. a location where input data can be stored, and a 32-bit
  189407. unsigned int that is the number of bytes to be read.
  189408. To exit and output any fatal error messages the new write
  189409. function should call png_error(png_ptr, "Error msg"). */
  189410. void PNGAPI
  189411. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189412. png_rw_ptr read_data_fn)
  189413. {
  189414. if(png_ptr == NULL) return;
  189415. png_ptr->io_ptr = io_ptr;
  189416. #if !defined(PNG_NO_STDIO)
  189417. if (read_data_fn != NULL)
  189418. png_ptr->read_data_fn = read_data_fn;
  189419. else
  189420. png_ptr->read_data_fn = png_default_read_data;
  189421. #else
  189422. png_ptr->read_data_fn = read_data_fn;
  189423. #endif
  189424. /* It is an error to write to a read device */
  189425. if (png_ptr->write_data_fn != NULL)
  189426. {
  189427. png_ptr->write_data_fn = NULL;
  189428. png_warning(png_ptr,
  189429. "It's an error to set both read_data_fn and write_data_fn in the ");
  189430. png_warning(png_ptr,
  189431. "same structure. Resetting write_data_fn to NULL.");
  189432. }
  189433. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189434. png_ptr->output_flush_fn = NULL;
  189435. #endif
  189436. }
  189437. #endif /* PNG_READ_SUPPORTED */
  189438. /*** End of inlined file: pngrio.c ***/
  189439. /*** Start of inlined file: pngrtran.c ***/
  189440. /* pngrtran.c - transforms the data in a row for PNG readers
  189441. *
  189442. * Last changed in libpng 1.2.21 [October 4, 2007]
  189443. * For conditions of distribution and use, see copyright notice in png.h
  189444. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189445. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189446. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189447. *
  189448. * This file contains functions optionally called by an application
  189449. * in order to tell libpng how to handle data when reading a PNG.
  189450. * Transformations that are used in both reading and writing are
  189451. * in pngtrans.c.
  189452. */
  189453. #define PNG_INTERNAL
  189454. #if defined(PNG_READ_SUPPORTED)
  189455. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189456. void PNGAPI
  189457. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189458. {
  189459. png_debug(1, "in png_set_crc_action\n");
  189460. /* Tell libpng how we react to CRC errors in critical chunks */
  189461. if(png_ptr == NULL) return;
  189462. switch (crit_action)
  189463. {
  189464. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189465. break;
  189466. case PNG_CRC_WARN_USE: /* warn/use data */
  189467. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189468. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189469. break;
  189470. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189471. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189472. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189473. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189474. break;
  189475. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189476. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189477. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189478. case PNG_CRC_DEFAULT:
  189479. default:
  189480. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189481. break;
  189482. }
  189483. switch (ancil_action)
  189484. {
  189485. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189486. break;
  189487. case PNG_CRC_WARN_USE: /* warn/use data */
  189488. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189489. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189490. break;
  189491. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189492. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189493. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189494. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189495. break;
  189496. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189497. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189498. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189499. break;
  189500. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189501. case PNG_CRC_DEFAULT:
  189502. default:
  189503. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189504. break;
  189505. }
  189506. }
  189507. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189508. defined(PNG_FLOATING_POINT_SUPPORTED)
  189509. /* handle alpha and tRNS via a background color */
  189510. void PNGAPI
  189511. png_set_background(png_structp png_ptr,
  189512. png_color_16p background_color, int background_gamma_code,
  189513. int need_expand, double background_gamma)
  189514. {
  189515. png_debug(1, "in png_set_background\n");
  189516. if(png_ptr == NULL) return;
  189517. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189518. {
  189519. png_warning(png_ptr, "Application must supply a known background gamma");
  189520. return;
  189521. }
  189522. png_ptr->transformations |= PNG_BACKGROUND;
  189523. png_memcpy(&(png_ptr->background), background_color,
  189524. png_sizeof(png_color_16));
  189525. png_ptr->background_gamma = (float)background_gamma;
  189526. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189527. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189528. }
  189529. #endif
  189530. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189531. /* strip 16 bit depth files to 8 bit depth */
  189532. void PNGAPI
  189533. png_set_strip_16(png_structp png_ptr)
  189534. {
  189535. png_debug(1, "in png_set_strip_16\n");
  189536. if(png_ptr == NULL) return;
  189537. png_ptr->transformations |= PNG_16_TO_8;
  189538. }
  189539. #endif
  189540. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189541. void PNGAPI
  189542. png_set_strip_alpha(png_structp png_ptr)
  189543. {
  189544. png_debug(1, "in png_set_strip_alpha\n");
  189545. if(png_ptr == NULL) return;
  189546. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189547. }
  189548. #endif
  189549. #if defined(PNG_READ_DITHER_SUPPORTED)
  189550. /* Dither file to 8 bit. Supply a palette, the current number
  189551. * of elements in the palette, the maximum number of elements
  189552. * allowed, and a histogram if possible. If the current number
  189553. * of colors is greater then the maximum number, the palette will be
  189554. * modified to fit in the maximum number. "full_dither" indicates
  189555. * whether we need a dithering cube set up for RGB images, or if we
  189556. * simply are reducing the number of colors in a paletted image.
  189557. */
  189558. typedef struct png_dsort_struct
  189559. {
  189560. struct png_dsort_struct FAR * next;
  189561. png_byte left;
  189562. png_byte right;
  189563. } png_dsort;
  189564. typedef png_dsort FAR * png_dsortp;
  189565. typedef png_dsort FAR * FAR * png_dsortpp;
  189566. void PNGAPI
  189567. png_set_dither(png_structp png_ptr, png_colorp palette,
  189568. int num_palette, int maximum_colors, png_uint_16p histogram,
  189569. int full_dither)
  189570. {
  189571. png_debug(1, "in png_set_dither\n");
  189572. if(png_ptr == NULL) return;
  189573. png_ptr->transformations |= PNG_DITHER;
  189574. if (!full_dither)
  189575. {
  189576. int i;
  189577. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189578. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189579. for (i = 0; i < num_palette; i++)
  189580. png_ptr->dither_index[i] = (png_byte)i;
  189581. }
  189582. if (num_palette > maximum_colors)
  189583. {
  189584. if (histogram != NULL)
  189585. {
  189586. /* This is easy enough, just throw out the least used colors.
  189587. Perhaps not the best solution, but good enough. */
  189588. int i;
  189589. /* initialize an array to sort colors */
  189590. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189591. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189592. /* initialize the dither_sort array */
  189593. for (i = 0; i < num_palette; i++)
  189594. png_ptr->dither_sort[i] = (png_byte)i;
  189595. /* Find the least used palette entries by starting a
  189596. bubble sort, and running it until we have sorted
  189597. out enough colors. Note that we don't care about
  189598. sorting all the colors, just finding which are
  189599. least used. */
  189600. for (i = num_palette - 1; i >= maximum_colors; i--)
  189601. {
  189602. int done; /* to stop early if the list is pre-sorted */
  189603. int j;
  189604. done = 1;
  189605. for (j = 0; j < i; j++)
  189606. {
  189607. if (histogram[png_ptr->dither_sort[j]]
  189608. < histogram[png_ptr->dither_sort[j + 1]])
  189609. {
  189610. png_byte t;
  189611. t = png_ptr->dither_sort[j];
  189612. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189613. png_ptr->dither_sort[j + 1] = t;
  189614. done = 0;
  189615. }
  189616. }
  189617. if (done)
  189618. break;
  189619. }
  189620. /* swap the palette around, and set up a table, if necessary */
  189621. if (full_dither)
  189622. {
  189623. int j = num_palette;
  189624. /* put all the useful colors within the max, but don't
  189625. move the others */
  189626. for (i = 0; i < maximum_colors; i++)
  189627. {
  189628. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189629. {
  189630. do
  189631. j--;
  189632. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189633. palette[i] = palette[j];
  189634. }
  189635. }
  189636. }
  189637. else
  189638. {
  189639. int j = num_palette;
  189640. /* move all the used colors inside the max limit, and
  189641. develop a translation table */
  189642. for (i = 0; i < maximum_colors; i++)
  189643. {
  189644. /* only move the colors we need to */
  189645. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189646. {
  189647. png_color tmp_color;
  189648. do
  189649. j--;
  189650. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189651. tmp_color = palette[j];
  189652. palette[j] = palette[i];
  189653. palette[i] = tmp_color;
  189654. /* indicate where the color went */
  189655. png_ptr->dither_index[j] = (png_byte)i;
  189656. png_ptr->dither_index[i] = (png_byte)j;
  189657. }
  189658. }
  189659. /* find closest color for those colors we are not using */
  189660. for (i = 0; i < num_palette; i++)
  189661. {
  189662. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189663. {
  189664. int min_d, k, min_k, d_index;
  189665. /* find the closest color to one we threw out */
  189666. d_index = png_ptr->dither_index[i];
  189667. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189668. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189669. {
  189670. int d;
  189671. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189672. if (d < min_d)
  189673. {
  189674. min_d = d;
  189675. min_k = k;
  189676. }
  189677. }
  189678. /* point to closest color */
  189679. png_ptr->dither_index[i] = (png_byte)min_k;
  189680. }
  189681. }
  189682. }
  189683. png_free(png_ptr, png_ptr->dither_sort);
  189684. png_ptr->dither_sort=NULL;
  189685. }
  189686. else
  189687. {
  189688. /* This is much harder to do simply (and quickly). Perhaps
  189689. we need to go through a median cut routine, but those
  189690. don't always behave themselves with only a few colors
  189691. as input. So we will just find the closest two colors,
  189692. and throw out one of them (chosen somewhat randomly).
  189693. [We don't understand this at all, so if someone wants to
  189694. work on improving it, be our guest - AED, GRP]
  189695. */
  189696. int i;
  189697. int max_d;
  189698. int num_new_palette;
  189699. png_dsortp t;
  189700. png_dsortpp hash;
  189701. t=NULL;
  189702. /* initialize palette index arrays */
  189703. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189704. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189705. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189706. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189707. /* initialize the sort array */
  189708. for (i = 0; i < num_palette; i++)
  189709. {
  189710. png_ptr->index_to_palette[i] = (png_byte)i;
  189711. png_ptr->palette_to_index[i] = (png_byte)i;
  189712. }
  189713. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189714. png_sizeof (png_dsortp)));
  189715. for (i = 0; i < 769; i++)
  189716. hash[i] = NULL;
  189717. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189718. num_new_palette = num_palette;
  189719. /* initial wild guess at how far apart the farthest pixel
  189720. pair we will be eliminating will be. Larger
  189721. numbers mean more areas will be allocated, Smaller
  189722. numbers run the risk of not saving enough data, and
  189723. having to do this all over again.
  189724. I have not done extensive checking on this number.
  189725. */
  189726. max_d = 96;
  189727. while (num_new_palette > maximum_colors)
  189728. {
  189729. for (i = 0; i < num_new_palette - 1; i++)
  189730. {
  189731. int j;
  189732. for (j = i + 1; j < num_new_palette; j++)
  189733. {
  189734. int d;
  189735. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189736. if (d <= max_d)
  189737. {
  189738. t = (png_dsortp)png_malloc_warn(png_ptr,
  189739. (png_uint_32)(png_sizeof(png_dsort)));
  189740. if (t == NULL)
  189741. break;
  189742. t->next = hash[d];
  189743. t->left = (png_byte)i;
  189744. t->right = (png_byte)j;
  189745. hash[d] = t;
  189746. }
  189747. }
  189748. if (t == NULL)
  189749. break;
  189750. }
  189751. if (t != NULL)
  189752. for (i = 0; i <= max_d; i++)
  189753. {
  189754. if (hash[i] != NULL)
  189755. {
  189756. png_dsortp p;
  189757. for (p = hash[i]; p; p = p->next)
  189758. {
  189759. if ((int)png_ptr->index_to_palette[p->left]
  189760. < num_new_palette &&
  189761. (int)png_ptr->index_to_palette[p->right]
  189762. < num_new_palette)
  189763. {
  189764. int j, next_j;
  189765. if (num_new_palette & 0x01)
  189766. {
  189767. j = p->left;
  189768. next_j = p->right;
  189769. }
  189770. else
  189771. {
  189772. j = p->right;
  189773. next_j = p->left;
  189774. }
  189775. num_new_palette--;
  189776. palette[png_ptr->index_to_palette[j]]
  189777. = palette[num_new_palette];
  189778. if (!full_dither)
  189779. {
  189780. int k;
  189781. for (k = 0; k < num_palette; k++)
  189782. {
  189783. if (png_ptr->dither_index[k] ==
  189784. png_ptr->index_to_palette[j])
  189785. png_ptr->dither_index[k] =
  189786. png_ptr->index_to_palette[next_j];
  189787. if ((int)png_ptr->dither_index[k] ==
  189788. num_new_palette)
  189789. png_ptr->dither_index[k] =
  189790. png_ptr->index_to_palette[j];
  189791. }
  189792. }
  189793. png_ptr->index_to_palette[png_ptr->palette_to_index
  189794. [num_new_palette]] = png_ptr->index_to_palette[j];
  189795. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189796. = png_ptr->palette_to_index[num_new_palette];
  189797. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189798. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189799. }
  189800. if (num_new_palette <= maximum_colors)
  189801. break;
  189802. }
  189803. if (num_new_palette <= maximum_colors)
  189804. break;
  189805. }
  189806. }
  189807. for (i = 0; i < 769; i++)
  189808. {
  189809. if (hash[i] != NULL)
  189810. {
  189811. png_dsortp p = hash[i];
  189812. while (p)
  189813. {
  189814. t = p->next;
  189815. png_free(png_ptr, p);
  189816. p = t;
  189817. }
  189818. }
  189819. hash[i] = 0;
  189820. }
  189821. max_d += 96;
  189822. }
  189823. png_free(png_ptr, hash);
  189824. png_free(png_ptr, png_ptr->palette_to_index);
  189825. png_free(png_ptr, png_ptr->index_to_palette);
  189826. png_ptr->palette_to_index=NULL;
  189827. png_ptr->index_to_palette=NULL;
  189828. }
  189829. num_palette = maximum_colors;
  189830. }
  189831. if (png_ptr->palette == NULL)
  189832. {
  189833. png_ptr->palette = palette;
  189834. }
  189835. png_ptr->num_palette = (png_uint_16)num_palette;
  189836. if (full_dither)
  189837. {
  189838. int i;
  189839. png_bytep distance;
  189840. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189841. PNG_DITHER_BLUE_BITS;
  189842. int num_red = (1 << PNG_DITHER_RED_BITS);
  189843. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189844. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189845. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189846. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189847. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189848. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189849. png_sizeof (png_byte));
  189850. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189851. png_sizeof(png_byte)));
  189852. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189853. for (i = 0; i < num_palette; i++)
  189854. {
  189855. int ir, ig, ib;
  189856. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189857. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189858. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189859. for (ir = 0; ir < num_red; ir++)
  189860. {
  189861. /* int dr = abs(ir - r); */
  189862. int dr = ((ir > r) ? ir - r : r - ir);
  189863. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189864. for (ig = 0; ig < num_green; ig++)
  189865. {
  189866. /* int dg = abs(ig - g); */
  189867. int dg = ((ig > g) ? ig - g : g - ig);
  189868. int dt = dr + dg;
  189869. int dm = ((dr > dg) ? dr : dg);
  189870. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189871. for (ib = 0; ib < num_blue; ib++)
  189872. {
  189873. int d_index = index_g | ib;
  189874. /* int db = abs(ib - b); */
  189875. int db = ((ib > b) ? ib - b : b - ib);
  189876. int dmax = ((dm > db) ? dm : db);
  189877. int d = dmax + dt + db;
  189878. if (d < (int)distance[d_index])
  189879. {
  189880. distance[d_index] = (png_byte)d;
  189881. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189882. }
  189883. }
  189884. }
  189885. }
  189886. }
  189887. png_free(png_ptr, distance);
  189888. }
  189889. }
  189890. #endif
  189891. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189892. /* Transform the image from the file_gamma to the screen_gamma. We
  189893. * only do transformations on images where the file_gamma and screen_gamma
  189894. * are not close reciprocals, otherwise it slows things down slightly, and
  189895. * also needlessly introduces small errors.
  189896. *
  189897. * We will turn off gamma transformation later if no semitransparent entries
  189898. * are present in the tRNS array for palette images. We can't do it here
  189899. * because we don't necessarily have the tRNS chunk yet.
  189900. */
  189901. void PNGAPI
  189902. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189903. {
  189904. png_debug(1, "in png_set_gamma\n");
  189905. if(png_ptr == NULL) return;
  189906. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189907. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189908. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189909. png_ptr->transformations |= PNG_GAMMA;
  189910. png_ptr->gamma = (float)file_gamma;
  189911. png_ptr->screen_gamma = (float)scrn_gamma;
  189912. }
  189913. #endif
  189914. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189915. /* Expand paletted images to RGB, expand grayscale images of
  189916. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189917. * to alpha channels.
  189918. */
  189919. void PNGAPI
  189920. png_set_expand(png_structp png_ptr)
  189921. {
  189922. png_debug(1, "in png_set_expand\n");
  189923. if(png_ptr == NULL) return;
  189924. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189925. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189926. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189927. #endif
  189928. }
  189929. /* GRR 19990627: the following three functions currently are identical
  189930. * to png_set_expand(). However, it is entirely reasonable that someone
  189931. * might wish to expand an indexed image to RGB but *not* expand a single,
  189932. * fully transparent palette entry to a full alpha channel--perhaps instead
  189933. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189934. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189935. * IOW, a future version of the library may make the transformations flag
  189936. * a bit more fine-grained, with separate bits for each of these three
  189937. * functions.
  189938. *
  189939. * More to the point, these functions make it obvious what libpng will be
  189940. * doing, whereas "expand" can (and does) mean any number of things.
  189941. *
  189942. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189943. * to expand only the sample depth but not to expand the tRNS to alpha.
  189944. */
  189945. /* Expand paletted images to RGB. */
  189946. void PNGAPI
  189947. png_set_palette_to_rgb(png_structp png_ptr)
  189948. {
  189949. png_debug(1, "in png_set_palette_to_rgb\n");
  189950. if(png_ptr == NULL) return;
  189951. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189952. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189953. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189954. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189955. #endif
  189956. }
  189957. #if !defined(PNG_1_0_X)
  189958. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189959. void PNGAPI
  189960. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189961. {
  189962. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189963. if(png_ptr == NULL) return;
  189964. png_ptr->transformations |= PNG_EXPAND;
  189965. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189966. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189967. #endif
  189968. }
  189969. #endif
  189970. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189971. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189972. /* Deprecated as of libpng-1.2.9 */
  189973. void PNGAPI
  189974. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189975. {
  189976. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189977. if(png_ptr == NULL) return;
  189978. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189979. }
  189980. #endif
  189981. /* Expand tRNS chunks to alpha channels. */
  189982. void PNGAPI
  189983. png_set_tRNS_to_alpha(png_structp png_ptr)
  189984. {
  189985. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189986. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189987. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189988. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189989. #endif
  189990. }
  189991. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189992. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189993. void PNGAPI
  189994. png_set_gray_to_rgb(png_structp png_ptr)
  189995. {
  189996. png_debug(1, "in png_set_gray_to_rgb\n");
  189997. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189998. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189999. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190000. #endif
  190001. }
  190002. #endif
  190003. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190004. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190005. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190006. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190007. */
  190008. void PNGAPI
  190009. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190010. double green)
  190011. {
  190012. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190013. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190014. if(png_ptr == NULL) return;
  190015. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190016. }
  190017. #endif
  190018. void PNGAPI
  190019. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190020. png_fixed_point red, png_fixed_point green)
  190021. {
  190022. png_debug(1, "in png_set_rgb_to_gray\n");
  190023. if(png_ptr == NULL) return;
  190024. switch(error_action)
  190025. {
  190026. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190027. break;
  190028. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190029. break;
  190030. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190031. }
  190032. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190033. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190034. png_ptr->transformations |= PNG_EXPAND;
  190035. #else
  190036. {
  190037. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190038. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190039. }
  190040. #endif
  190041. {
  190042. png_uint_16 red_int, green_int;
  190043. if(red < 0 || green < 0)
  190044. {
  190045. red_int = 6968; /* .212671 * 32768 + .5 */
  190046. green_int = 23434; /* .715160 * 32768 + .5 */
  190047. }
  190048. else if(red + green < 100000L)
  190049. {
  190050. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190051. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190052. }
  190053. else
  190054. {
  190055. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190056. red_int = 6968;
  190057. green_int = 23434;
  190058. }
  190059. png_ptr->rgb_to_gray_red_coeff = red_int;
  190060. png_ptr->rgb_to_gray_green_coeff = green_int;
  190061. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190062. }
  190063. }
  190064. #endif
  190065. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190066. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190067. defined(PNG_LEGACY_SUPPORTED)
  190068. void PNGAPI
  190069. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190070. read_user_transform_fn)
  190071. {
  190072. png_debug(1, "in png_set_read_user_transform_fn\n");
  190073. if(png_ptr == NULL) return;
  190074. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190075. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190076. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190077. #endif
  190078. #ifdef PNG_LEGACY_SUPPORTED
  190079. if(read_user_transform_fn)
  190080. png_warning(png_ptr,
  190081. "This version of libpng does not support user transforms");
  190082. #endif
  190083. }
  190084. #endif
  190085. /* Initialize everything needed for the read. This includes modifying
  190086. * the palette.
  190087. */
  190088. void /* PRIVATE */
  190089. png_init_read_transformations(png_structp png_ptr)
  190090. {
  190091. png_debug(1, "in png_init_read_transformations\n");
  190092. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190093. if(png_ptr != NULL)
  190094. #endif
  190095. {
  190096. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190097. || defined(PNG_READ_GAMMA_SUPPORTED)
  190098. int color_type = png_ptr->color_type;
  190099. #endif
  190100. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190101. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190102. /* Detect gray background and attempt to enable optimization
  190103. * for gray --> RGB case */
  190104. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190105. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190106. * background color might actually be gray yet not be flagged as such.
  190107. * This is not a problem for the current code, which uses
  190108. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190109. * png_do_gray_to_rgb() transformation.
  190110. */
  190111. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190112. !(color_type & PNG_COLOR_MASK_COLOR))
  190113. {
  190114. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190115. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190116. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190117. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190118. png_ptr->background.red == png_ptr->background.green &&
  190119. png_ptr->background.red == png_ptr->background.blue)
  190120. {
  190121. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190122. png_ptr->background.gray = png_ptr->background.red;
  190123. }
  190124. #endif
  190125. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190126. (png_ptr->transformations & PNG_EXPAND))
  190127. {
  190128. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190129. {
  190130. /* expand background and tRNS chunks */
  190131. switch (png_ptr->bit_depth)
  190132. {
  190133. case 1:
  190134. png_ptr->background.gray *= (png_uint_16)0xff;
  190135. png_ptr->background.red = png_ptr->background.green
  190136. = png_ptr->background.blue = png_ptr->background.gray;
  190137. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190138. {
  190139. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190140. png_ptr->trans_values.red = png_ptr->trans_values.green
  190141. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190142. }
  190143. break;
  190144. case 2:
  190145. png_ptr->background.gray *= (png_uint_16)0x55;
  190146. png_ptr->background.red = png_ptr->background.green
  190147. = png_ptr->background.blue = png_ptr->background.gray;
  190148. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190149. {
  190150. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190151. png_ptr->trans_values.red = png_ptr->trans_values.green
  190152. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190153. }
  190154. break;
  190155. case 4:
  190156. png_ptr->background.gray *= (png_uint_16)0x11;
  190157. png_ptr->background.red = png_ptr->background.green
  190158. = png_ptr->background.blue = png_ptr->background.gray;
  190159. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190160. {
  190161. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190162. png_ptr->trans_values.red = png_ptr->trans_values.green
  190163. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190164. }
  190165. break;
  190166. case 8:
  190167. case 16:
  190168. png_ptr->background.red = png_ptr->background.green
  190169. = png_ptr->background.blue = png_ptr->background.gray;
  190170. break;
  190171. }
  190172. }
  190173. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190174. {
  190175. png_ptr->background.red =
  190176. png_ptr->palette[png_ptr->background.index].red;
  190177. png_ptr->background.green =
  190178. png_ptr->palette[png_ptr->background.index].green;
  190179. png_ptr->background.blue =
  190180. png_ptr->palette[png_ptr->background.index].blue;
  190181. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190182. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190183. {
  190184. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190185. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190186. #endif
  190187. {
  190188. /* invert the alpha channel (in tRNS) unless the pixels are
  190189. going to be expanded, in which case leave it for later */
  190190. int i,istop;
  190191. istop=(int)png_ptr->num_trans;
  190192. for (i=0; i<istop; i++)
  190193. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190194. }
  190195. }
  190196. #endif
  190197. }
  190198. }
  190199. #endif
  190200. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190201. png_ptr->background_1 = png_ptr->background;
  190202. #endif
  190203. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190204. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190205. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190206. < PNG_GAMMA_THRESHOLD))
  190207. {
  190208. int i,k;
  190209. k=0;
  190210. for (i=0; i<png_ptr->num_trans; i++)
  190211. {
  190212. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190213. k=1; /* partial transparency is present */
  190214. }
  190215. if (k == 0)
  190216. png_ptr->transformations &= (~PNG_GAMMA);
  190217. }
  190218. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190219. png_ptr->gamma != 0.0)
  190220. {
  190221. png_build_gamma_table(png_ptr);
  190222. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190223. if (png_ptr->transformations & PNG_BACKGROUND)
  190224. {
  190225. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190226. {
  190227. /* could skip if no transparency and
  190228. */
  190229. png_color back, back_1;
  190230. png_colorp palette = png_ptr->palette;
  190231. int num_palette = png_ptr->num_palette;
  190232. int i;
  190233. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190234. {
  190235. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190236. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190237. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190238. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190239. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190240. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190241. }
  190242. else
  190243. {
  190244. double g, gs;
  190245. switch (png_ptr->background_gamma_type)
  190246. {
  190247. case PNG_BACKGROUND_GAMMA_SCREEN:
  190248. g = (png_ptr->screen_gamma);
  190249. gs = 1.0;
  190250. break;
  190251. case PNG_BACKGROUND_GAMMA_FILE:
  190252. g = 1.0 / (png_ptr->gamma);
  190253. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190254. break;
  190255. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190256. g = 1.0 / (png_ptr->background_gamma);
  190257. gs = 1.0 / (png_ptr->background_gamma *
  190258. png_ptr->screen_gamma);
  190259. break;
  190260. default:
  190261. g = 1.0; /* back_1 */
  190262. gs = 1.0; /* back */
  190263. }
  190264. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190265. {
  190266. back.red = (png_byte)png_ptr->background.red;
  190267. back.green = (png_byte)png_ptr->background.green;
  190268. back.blue = (png_byte)png_ptr->background.blue;
  190269. }
  190270. else
  190271. {
  190272. back.red = (png_byte)(pow(
  190273. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190274. back.green = (png_byte)(pow(
  190275. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190276. back.blue = (png_byte)(pow(
  190277. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190278. }
  190279. back_1.red = (png_byte)(pow(
  190280. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190281. back_1.green = (png_byte)(pow(
  190282. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190283. back_1.blue = (png_byte)(pow(
  190284. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190285. }
  190286. for (i = 0; i < num_palette; i++)
  190287. {
  190288. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190289. {
  190290. if (png_ptr->trans[i] == 0)
  190291. {
  190292. palette[i] = back;
  190293. }
  190294. else /* if (png_ptr->trans[i] != 0xff) */
  190295. {
  190296. png_byte v, w;
  190297. v = png_ptr->gamma_to_1[palette[i].red];
  190298. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190299. palette[i].red = png_ptr->gamma_from_1[w];
  190300. v = png_ptr->gamma_to_1[palette[i].green];
  190301. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190302. palette[i].green = png_ptr->gamma_from_1[w];
  190303. v = png_ptr->gamma_to_1[palette[i].blue];
  190304. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190305. palette[i].blue = png_ptr->gamma_from_1[w];
  190306. }
  190307. }
  190308. else
  190309. {
  190310. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190311. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190312. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190313. }
  190314. }
  190315. }
  190316. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190317. else
  190318. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190319. {
  190320. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190321. double g = 1.0;
  190322. double gs = 1.0;
  190323. switch (png_ptr->background_gamma_type)
  190324. {
  190325. case PNG_BACKGROUND_GAMMA_SCREEN:
  190326. g = (png_ptr->screen_gamma);
  190327. gs = 1.0;
  190328. break;
  190329. case PNG_BACKGROUND_GAMMA_FILE:
  190330. g = 1.0 / (png_ptr->gamma);
  190331. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190332. break;
  190333. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190334. g = 1.0 / (png_ptr->background_gamma);
  190335. gs = 1.0 / (png_ptr->background_gamma *
  190336. png_ptr->screen_gamma);
  190337. break;
  190338. }
  190339. png_ptr->background_1.gray = (png_uint_16)(pow(
  190340. (double)png_ptr->background.gray / m, g) * m + .5);
  190341. png_ptr->background.gray = (png_uint_16)(pow(
  190342. (double)png_ptr->background.gray / m, gs) * m + .5);
  190343. if ((png_ptr->background.red != png_ptr->background.green) ||
  190344. (png_ptr->background.red != png_ptr->background.blue) ||
  190345. (png_ptr->background.red != png_ptr->background.gray))
  190346. {
  190347. /* RGB or RGBA with color background */
  190348. png_ptr->background_1.red = (png_uint_16)(pow(
  190349. (double)png_ptr->background.red / m, g) * m + .5);
  190350. png_ptr->background_1.green = (png_uint_16)(pow(
  190351. (double)png_ptr->background.green / m, g) * m + .5);
  190352. png_ptr->background_1.blue = (png_uint_16)(pow(
  190353. (double)png_ptr->background.blue / m, g) * m + .5);
  190354. png_ptr->background.red = (png_uint_16)(pow(
  190355. (double)png_ptr->background.red / m, gs) * m + .5);
  190356. png_ptr->background.green = (png_uint_16)(pow(
  190357. (double)png_ptr->background.green / m, gs) * m + .5);
  190358. png_ptr->background.blue = (png_uint_16)(pow(
  190359. (double)png_ptr->background.blue / m, gs) * m + .5);
  190360. }
  190361. else
  190362. {
  190363. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190364. png_ptr->background_1.red = png_ptr->background_1.green
  190365. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190366. png_ptr->background.red = png_ptr->background.green
  190367. = png_ptr->background.blue = png_ptr->background.gray;
  190368. }
  190369. }
  190370. }
  190371. else
  190372. /* transformation does not include PNG_BACKGROUND */
  190373. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190374. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190375. {
  190376. png_colorp palette = png_ptr->palette;
  190377. int num_palette = png_ptr->num_palette;
  190378. int i;
  190379. for (i = 0; i < num_palette; i++)
  190380. {
  190381. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190382. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190383. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190384. }
  190385. }
  190386. }
  190387. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190388. else
  190389. #endif
  190390. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190391. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190392. /* No GAMMA transformation */
  190393. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190394. (color_type == PNG_COLOR_TYPE_PALETTE))
  190395. {
  190396. int i;
  190397. int istop = (int)png_ptr->num_trans;
  190398. png_color back;
  190399. png_colorp palette = png_ptr->palette;
  190400. back.red = (png_byte)png_ptr->background.red;
  190401. back.green = (png_byte)png_ptr->background.green;
  190402. back.blue = (png_byte)png_ptr->background.blue;
  190403. for (i = 0; i < istop; i++)
  190404. {
  190405. if (png_ptr->trans[i] == 0)
  190406. {
  190407. palette[i] = back;
  190408. }
  190409. else if (png_ptr->trans[i] != 0xff)
  190410. {
  190411. /* The png_composite() macro is defined in png.h */
  190412. png_composite(palette[i].red, palette[i].red,
  190413. png_ptr->trans[i], back.red);
  190414. png_composite(palette[i].green, palette[i].green,
  190415. png_ptr->trans[i], back.green);
  190416. png_composite(palette[i].blue, palette[i].blue,
  190417. png_ptr->trans[i], back.blue);
  190418. }
  190419. }
  190420. }
  190421. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190422. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190423. if ((png_ptr->transformations & PNG_SHIFT) &&
  190424. (color_type == PNG_COLOR_TYPE_PALETTE))
  190425. {
  190426. png_uint_16 i;
  190427. png_uint_16 istop = png_ptr->num_palette;
  190428. int sr = 8 - png_ptr->sig_bit.red;
  190429. int sg = 8 - png_ptr->sig_bit.green;
  190430. int sb = 8 - png_ptr->sig_bit.blue;
  190431. if (sr < 0 || sr > 8)
  190432. sr = 0;
  190433. if (sg < 0 || sg > 8)
  190434. sg = 0;
  190435. if (sb < 0 || sb > 8)
  190436. sb = 0;
  190437. for (i = 0; i < istop; i++)
  190438. {
  190439. png_ptr->palette[i].red >>= sr;
  190440. png_ptr->palette[i].green >>= sg;
  190441. png_ptr->palette[i].blue >>= sb;
  190442. }
  190443. }
  190444. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190445. }
  190446. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190447. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190448. if(png_ptr)
  190449. return;
  190450. #endif
  190451. }
  190452. /* Modify the info structure to reflect the transformations. The
  190453. * info should be updated so a PNG file could be written with it,
  190454. * assuming the transformations result in valid PNG data.
  190455. */
  190456. void /* PRIVATE */
  190457. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190458. {
  190459. png_debug(1, "in png_read_transform_info\n");
  190460. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190461. if (png_ptr->transformations & PNG_EXPAND)
  190462. {
  190463. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190464. {
  190465. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190466. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190467. else
  190468. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190469. info_ptr->bit_depth = 8;
  190470. info_ptr->num_trans = 0;
  190471. }
  190472. else
  190473. {
  190474. if (png_ptr->num_trans)
  190475. {
  190476. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190477. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190478. else
  190479. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190480. }
  190481. if (info_ptr->bit_depth < 8)
  190482. info_ptr->bit_depth = 8;
  190483. info_ptr->num_trans = 0;
  190484. }
  190485. }
  190486. #endif
  190487. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190488. if (png_ptr->transformations & PNG_BACKGROUND)
  190489. {
  190490. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190491. info_ptr->num_trans = 0;
  190492. info_ptr->background = png_ptr->background;
  190493. }
  190494. #endif
  190495. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190496. if (png_ptr->transformations & PNG_GAMMA)
  190497. {
  190498. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190499. info_ptr->gamma = png_ptr->gamma;
  190500. #endif
  190501. #ifdef PNG_FIXED_POINT_SUPPORTED
  190502. info_ptr->int_gamma = png_ptr->int_gamma;
  190503. #endif
  190504. }
  190505. #endif
  190506. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190507. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190508. info_ptr->bit_depth = 8;
  190509. #endif
  190510. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190511. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190512. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190513. #endif
  190514. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190515. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190516. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190517. #endif
  190518. #if defined(PNG_READ_DITHER_SUPPORTED)
  190519. if (png_ptr->transformations & PNG_DITHER)
  190520. {
  190521. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190522. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190523. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190524. {
  190525. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190526. }
  190527. }
  190528. #endif
  190529. #if defined(PNG_READ_PACK_SUPPORTED)
  190530. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190531. info_ptr->bit_depth = 8;
  190532. #endif
  190533. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190534. info_ptr->channels = 1;
  190535. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190536. info_ptr->channels = 3;
  190537. else
  190538. info_ptr->channels = 1;
  190539. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190540. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190541. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190542. #endif
  190543. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190544. info_ptr->channels++;
  190545. #if defined(PNG_READ_FILLER_SUPPORTED)
  190546. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190547. if ((png_ptr->transformations & PNG_FILLER) &&
  190548. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190549. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190550. {
  190551. info_ptr->channels++;
  190552. /* if adding a true alpha channel not just filler */
  190553. #if !defined(PNG_1_0_X)
  190554. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190555. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190556. #endif
  190557. }
  190558. #endif
  190559. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190560. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190561. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190562. {
  190563. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190564. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190565. if(info_ptr->channels < png_ptr->user_transform_channels)
  190566. info_ptr->channels = png_ptr->user_transform_channels;
  190567. }
  190568. #endif
  190569. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190570. info_ptr->bit_depth);
  190571. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190572. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190573. if(png_ptr)
  190574. return;
  190575. #endif
  190576. }
  190577. /* Transform the row. The order of transformations is significant,
  190578. * and is very touchy. If you add a transformation, take care to
  190579. * decide how it fits in with the other transformations here.
  190580. */
  190581. void /* PRIVATE */
  190582. png_do_read_transformations(png_structp png_ptr)
  190583. {
  190584. png_debug(1, "in png_do_read_transformations\n");
  190585. if (png_ptr->row_buf == NULL)
  190586. {
  190587. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190588. char msg[50];
  190589. png_snprintf2(msg, 50,
  190590. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190591. png_ptr->pass);
  190592. png_error(png_ptr, msg);
  190593. #else
  190594. png_error(png_ptr, "NULL row buffer");
  190595. #endif
  190596. }
  190597. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190598. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190599. /* Application has failed to call either png_read_start_image()
  190600. * or png_read_update_info() after setting transforms that expand
  190601. * pixels. This check added to libpng-1.2.19 */
  190602. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190603. png_error(png_ptr, "Uninitialized row");
  190604. #else
  190605. png_warning(png_ptr, "Uninitialized row");
  190606. #endif
  190607. #endif
  190608. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190609. if (png_ptr->transformations & PNG_EXPAND)
  190610. {
  190611. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190612. {
  190613. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190614. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190615. }
  190616. else
  190617. {
  190618. if (png_ptr->num_trans &&
  190619. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190620. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190621. &(png_ptr->trans_values));
  190622. else
  190623. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190624. NULL);
  190625. }
  190626. }
  190627. #endif
  190628. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190629. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190630. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190631. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190632. #endif
  190633. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190634. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190635. {
  190636. int rgb_error =
  190637. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190638. if(rgb_error)
  190639. {
  190640. png_ptr->rgb_to_gray_status=1;
  190641. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190642. PNG_RGB_TO_GRAY_WARN)
  190643. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190644. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190645. PNG_RGB_TO_GRAY_ERR)
  190646. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190647. }
  190648. }
  190649. #endif
  190650. /*
  190651. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190652. In most cases, the "simple transparency" should be done prior to doing
  190653. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190654. pixel is transparent. You would also need to make sure that the
  190655. transparency information is upgraded to RGB.
  190656. To summarize, the current flow is:
  190657. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190658. with background "in place" if transparent,
  190659. convert to RGB if necessary
  190660. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190661. convert to RGB if necessary
  190662. To support RGB backgrounds for gray images we need:
  190663. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190664. 3 or 6 bytes and composite with background
  190665. "in place" if transparent (3x compare/pixel
  190666. compared to doing composite with gray bkgrnd)
  190667. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190668. remove alpha bytes (3x float operations/pixel
  190669. compared with composite on gray background)
  190670. Greg's change will do this. The reason it wasn't done before is for
  190671. performance, as this increases the per-pixel operations. If we would check
  190672. in advance if the background was gray or RGB, and position the gray-to-RGB
  190673. transform appropriately, then it would save a lot of work/time.
  190674. */
  190675. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190676. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190677. * for performance reasons */
  190678. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190679. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190680. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190681. #endif
  190682. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190683. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190684. ((png_ptr->num_trans != 0 ) ||
  190685. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190686. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190687. &(png_ptr->trans_values), &(png_ptr->background)
  190688. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190689. , &(png_ptr->background_1),
  190690. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190691. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190692. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190693. png_ptr->gamma_shift
  190694. #endif
  190695. );
  190696. #endif
  190697. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190698. if ((png_ptr->transformations & PNG_GAMMA) &&
  190699. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190700. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190701. ((png_ptr->num_trans != 0) ||
  190702. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190703. #endif
  190704. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190705. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190706. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190707. png_ptr->gamma_shift);
  190708. #endif
  190709. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190710. if (png_ptr->transformations & PNG_16_TO_8)
  190711. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190712. #endif
  190713. #if defined(PNG_READ_DITHER_SUPPORTED)
  190714. if (png_ptr->transformations & PNG_DITHER)
  190715. {
  190716. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190717. png_ptr->palette_lookup, png_ptr->dither_index);
  190718. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190719. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190720. }
  190721. #endif
  190722. #if defined(PNG_READ_INVERT_SUPPORTED)
  190723. if (png_ptr->transformations & PNG_INVERT_MONO)
  190724. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190725. #endif
  190726. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190727. if (png_ptr->transformations & PNG_SHIFT)
  190728. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190729. &(png_ptr->shift));
  190730. #endif
  190731. #if defined(PNG_READ_PACK_SUPPORTED)
  190732. if (png_ptr->transformations & PNG_PACK)
  190733. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190734. #endif
  190735. #if defined(PNG_READ_BGR_SUPPORTED)
  190736. if (png_ptr->transformations & PNG_BGR)
  190737. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190738. #endif
  190739. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190740. if (png_ptr->transformations & PNG_PACKSWAP)
  190741. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190742. #endif
  190743. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190744. /* if gray -> RGB, do so now only if we did not do so above */
  190745. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190746. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190747. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190748. #endif
  190749. #if defined(PNG_READ_FILLER_SUPPORTED)
  190750. if (png_ptr->transformations & PNG_FILLER)
  190751. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190752. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190753. #endif
  190754. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190755. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190756. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190757. #endif
  190758. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190759. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190760. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190761. #endif
  190762. #if defined(PNG_READ_SWAP_SUPPORTED)
  190763. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190764. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190765. #endif
  190766. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190767. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190768. {
  190769. if(png_ptr->read_user_transform_fn != NULL)
  190770. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190771. (png_ptr, /* png_ptr */
  190772. &(png_ptr->row_info), /* row_info: */
  190773. /* png_uint_32 width; width of row */
  190774. /* png_uint_32 rowbytes; number of bytes in row */
  190775. /* png_byte color_type; color type of pixels */
  190776. /* png_byte bit_depth; bit depth of samples */
  190777. /* png_byte channels; number of channels (1-4) */
  190778. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190779. png_ptr->row_buf + 1); /* start of pixel data for row */
  190780. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190781. if(png_ptr->user_transform_depth)
  190782. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190783. if(png_ptr->user_transform_channels)
  190784. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190785. #endif
  190786. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190787. png_ptr->row_info.channels);
  190788. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190789. png_ptr->row_info.width);
  190790. }
  190791. #endif
  190792. }
  190793. #if defined(PNG_READ_PACK_SUPPORTED)
  190794. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190795. * without changing the actual values. Thus, if you had a row with
  190796. * a bit depth of 1, you would end up with bytes that only contained
  190797. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190798. * png_do_shift() after this.
  190799. */
  190800. void /* PRIVATE */
  190801. png_do_unpack(png_row_infop row_info, png_bytep row)
  190802. {
  190803. png_debug(1, "in png_do_unpack\n");
  190804. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190805. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190806. #else
  190807. if (row_info->bit_depth < 8)
  190808. #endif
  190809. {
  190810. png_uint_32 i;
  190811. png_uint_32 row_width=row_info->width;
  190812. switch (row_info->bit_depth)
  190813. {
  190814. case 1:
  190815. {
  190816. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190817. png_bytep dp = row + (png_size_t)row_width - 1;
  190818. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190819. for (i = 0; i < row_width; i++)
  190820. {
  190821. *dp = (png_byte)((*sp >> shift) & 0x01);
  190822. if (shift == 7)
  190823. {
  190824. shift = 0;
  190825. sp--;
  190826. }
  190827. else
  190828. shift++;
  190829. dp--;
  190830. }
  190831. break;
  190832. }
  190833. case 2:
  190834. {
  190835. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190836. png_bytep dp = row + (png_size_t)row_width - 1;
  190837. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190838. for (i = 0; i < row_width; i++)
  190839. {
  190840. *dp = (png_byte)((*sp >> shift) & 0x03);
  190841. if (shift == 6)
  190842. {
  190843. shift = 0;
  190844. sp--;
  190845. }
  190846. else
  190847. shift += 2;
  190848. dp--;
  190849. }
  190850. break;
  190851. }
  190852. case 4:
  190853. {
  190854. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190855. png_bytep dp = row + (png_size_t)row_width - 1;
  190856. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190857. for (i = 0; i < row_width; i++)
  190858. {
  190859. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190860. if (shift == 4)
  190861. {
  190862. shift = 0;
  190863. sp--;
  190864. }
  190865. else
  190866. shift = 4;
  190867. dp--;
  190868. }
  190869. break;
  190870. }
  190871. }
  190872. row_info->bit_depth = 8;
  190873. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190874. row_info->rowbytes = row_width * row_info->channels;
  190875. }
  190876. }
  190877. #endif
  190878. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190879. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190880. * pixels back to their significant bits values. Thus, if you have
  190881. * a row of bit depth 8, but only 5 are significant, this will shift
  190882. * the values back to 0 through 31.
  190883. */
  190884. void /* PRIVATE */
  190885. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190886. {
  190887. png_debug(1, "in png_do_unshift\n");
  190888. if (
  190889. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190890. row != NULL && row_info != NULL && sig_bits != NULL &&
  190891. #endif
  190892. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190893. {
  190894. int shift[4];
  190895. int channels = 0;
  190896. int c;
  190897. png_uint_16 value = 0;
  190898. png_uint_32 row_width = row_info->width;
  190899. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190900. {
  190901. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190902. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190903. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190904. }
  190905. else
  190906. {
  190907. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190908. }
  190909. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190910. {
  190911. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190912. }
  190913. for (c = 0; c < channels; c++)
  190914. {
  190915. if (shift[c] <= 0)
  190916. shift[c] = 0;
  190917. else
  190918. value = 1;
  190919. }
  190920. if (!value)
  190921. return;
  190922. switch (row_info->bit_depth)
  190923. {
  190924. case 2:
  190925. {
  190926. png_bytep bp;
  190927. png_uint_32 i;
  190928. png_uint_32 istop = row_info->rowbytes;
  190929. for (bp = row, i = 0; i < istop; i++)
  190930. {
  190931. *bp >>= 1;
  190932. *bp++ &= 0x55;
  190933. }
  190934. break;
  190935. }
  190936. case 4:
  190937. {
  190938. png_bytep bp = row;
  190939. png_uint_32 i;
  190940. png_uint_32 istop = row_info->rowbytes;
  190941. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190942. (png_byte)((int)0xf >> shift[0]));
  190943. for (i = 0; i < istop; i++)
  190944. {
  190945. *bp >>= shift[0];
  190946. *bp++ &= mask;
  190947. }
  190948. break;
  190949. }
  190950. case 8:
  190951. {
  190952. png_bytep bp = row;
  190953. png_uint_32 i;
  190954. png_uint_32 istop = row_width * channels;
  190955. for (i = 0; i < istop; i++)
  190956. {
  190957. *bp++ >>= shift[i%channels];
  190958. }
  190959. break;
  190960. }
  190961. case 16:
  190962. {
  190963. png_bytep bp = row;
  190964. png_uint_32 i;
  190965. png_uint_32 istop = channels * row_width;
  190966. for (i = 0; i < istop; i++)
  190967. {
  190968. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190969. value >>= shift[i%channels];
  190970. *bp++ = (png_byte)(value >> 8);
  190971. *bp++ = (png_byte)(value & 0xff);
  190972. }
  190973. break;
  190974. }
  190975. }
  190976. }
  190977. }
  190978. #endif
  190979. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190980. /* chop rows of bit depth 16 down to 8 */
  190981. void /* PRIVATE */
  190982. png_do_chop(png_row_infop row_info, png_bytep row)
  190983. {
  190984. png_debug(1, "in png_do_chop\n");
  190985. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190986. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190987. #else
  190988. if (row_info->bit_depth == 16)
  190989. #endif
  190990. {
  190991. png_bytep sp = row;
  190992. png_bytep dp = row;
  190993. png_uint_32 i;
  190994. png_uint_32 istop = row_info->width * row_info->channels;
  190995. for (i = 0; i<istop; i++, sp += 2, dp++)
  190996. {
  190997. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190998. /* This does a more accurate scaling of the 16-bit color
  190999. * value, rather than a simple low-byte truncation.
  191000. *
  191001. * What the ideal calculation should be:
  191002. * *dp = (((((png_uint_32)(*sp) << 8) |
  191003. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191004. *
  191005. * GRR: no, I think this is what it really should be:
  191006. * *dp = (((((png_uint_32)(*sp) << 8) |
  191007. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191008. *
  191009. * GRR: here's the exact calculation with shifts:
  191010. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191011. * *dp = (temp - (temp >> 8)) >> 8;
  191012. *
  191013. * Approximate calculation with shift/add instead of multiply/divide:
  191014. * *dp = ((((png_uint_32)(*sp) << 8) |
  191015. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191016. *
  191017. * What we actually do to avoid extra shifting and conversion:
  191018. */
  191019. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191020. #else
  191021. /* Simply discard the low order byte */
  191022. *dp = *sp;
  191023. #endif
  191024. }
  191025. row_info->bit_depth = 8;
  191026. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191027. row_info->rowbytes = row_info->width * row_info->channels;
  191028. }
  191029. }
  191030. #endif
  191031. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191032. void /* PRIVATE */
  191033. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191034. {
  191035. png_debug(1, "in png_do_read_swap_alpha\n");
  191036. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191037. if (row != NULL && row_info != NULL)
  191038. #endif
  191039. {
  191040. png_uint_32 row_width = row_info->width;
  191041. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191042. {
  191043. /* This converts from RGBA to ARGB */
  191044. if (row_info->bit_depth == 8)
  191045. {
  191046. png_bytep sp = row + row_info->rowbytes;
  191047. png_bytep dp = sp;
  191048. png_byte save;
  191049. png_uint_32 i;
  191050. for (i = 0; i < row_width; i++)
  191051. {
  191052. save = *(--sp);
  191053. *(--dp) = *(--sp);
  191054. *(--dp) = *(--sp);
  191055. *(--dp) = *(--sp);
  191056. *(--dp) = save;
  191057. }
  191058. }
  191059. /* This converts from RRGGBBAA to AARRGGBB */
  191060. else
  191061. {
  191062. png_bytep sp = row + row_info->rowbytes;
  191063. png_bytep dp = sp;
  191064. png_byte save[2];
  191065. png_uint_32 i;
  191066. for (i = 0; i < row_width; i++)
  191067. {
  191068. save[0] = *(--sp);
  191069. save[1] = *(--sp);
  191070. *(--dp) = *(--sp);
  191071. *(--dp) = *(--sp);
  191072. *(--dp) = *(--sp);
  191073. *(--dp) = *(--sp);
  191074. *(--dp) = *(--sp);
  191075. *(--dp) = *(--sp);
  191076. *(--dp) = save[0];
  191077. *(--dp) = save[1];
  191078. }
  191079. }
  191080. }
  191081. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191082. {
  191083. /* This converts from GA to AG */
  191084. if (row_info->bit_depth == 8)
  191085. {
  191086. png_bytep sp = row + row_info->rowbytes;
  191087. png_bytep dp = sp;
  191088. png_byte save;
  191089. png_uint_32 i;
  191090. for (i = 0; i < row_width; i++)
  191091. {
  191092. save = *(--sp);
  191093. *(--dp) = *(--sp);
  191094. *(--dp) = save;
  191095. }
  191096. }
  191097. /* This converts from GGAA to AAGG */
  191098. else
  191099. {
  191100. png_bytep sp = row + row_info->rowbytes;
  191101. png_bytep dp = sp;
  191102. png_byte save[2];
  191103. png_uint_32 i;
  191104. for (i = 0; i < row_width; i++)
  191105. {
  191106. save[0] = *(--sp);
  191107. save[1] = *(--sp);
  191108. *(--dp) = *(--sp);
  191109. *(--dp) = *(--sp);
  191110. *(--dp) = save[0];
  191111. *(--dp) = save[1];
  191112. }
  191113. }
  191114. }
  191115. }
  191116. }
  191117. #endif
  191118. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191119. void /* PRIVATE */
  191120. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191121. {
  191122. png_debug(1, "in png_do_read_invert_alpha\n");
  191123. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191124. if (row != NULL && row_info != NULL)
  191125. #endif
  191126. {
  191127. png_uint_32 row_width = row_info->width;
  191128. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191129. {
  191130. /* This inverts the alpha channel in RGBA */
  191131. if (row_info->bit_depth == 8)
  191132. {
  191133. png_bytep sp = row + row_info->rowbytes;
  191134. png_bytep dp = sp;
  191135. png_uint_32 i;
  191136. for (i = 0; i < row_width; i++)
  191137. {
  191138. *(--dp) = (png_byte)(255 - *(--sp));
  191139. /* This does nothing:
  191140. *(--dp) = *(--sp);
  191141. *(--dp) = *(--sp);
  191142. *(--dp) = *(--sp);
  191143. We can replace it with:
  191144. */
  191145. sp-=3;
  191146. dp=sp;
  191147. }
  191148. }
  191149. /* This inverts the alpha channel in RRGGBBAA */
  191150. else
  191151. {
  191152. png_bytep sp = row + row_info->rowbytes;
  191153. png_bytep dp = sp;
  191154. png_uint_32 i;
  191155. for (i = 0; i < row_width; i++)
  191156. {
  191157. *(--dp) = (png_byte)(255 - *(--sp));
  191158. *(--dp) = (png_byte)(255 - *(--sp));
  191159. /* This does nothing:
  191160. *(--dp) = *(--sp);
  191161. *(--dp) = *(--sp);
  191162. *(--dp) = *(--sp);
  191163. *(--dp) = *(--sp);
  191164. *(--dp) = *(--sp);
  191165. *(--dp) = *(--sp);
  191166. We can replace it with:
  191167. */
  191168. sp-=6;
  191169. dp=sp;
  191170. }
  191171. }
  191172. }
  191173. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191174. {
  191175. /* This inverts the alpha channel in GA */
  191176. if (row_info->bit_depth == 8)
  191177. {
  191178. png_bytep sp = row + row_info->rowbytes;
  191179. png_bytep dp = sp;
  191180. png_uint_32 i;
  191181. for (i = 0; i < row_width; i++)
  191182. {
  191183. *(--dp) = (png_byte)(255 - *(--sp));
  191184. *(--dp) = *(--sp);
  191185. }
  191186. }
  191187. /* This inverts the alpha channel in GGAA */
  191188. else
  191189. {
  191190. png_bytep sp = row + row_info->rowbytes;
  191191. png_bytep dp = sp;
  191192. png_uint_32 i;
  191193. for (i = 0; i < row_width; i++)
  191194. {
  191195. *(--dp) = (png_byte)(255 - *(--sp));
  191196. *(--dp) = (png_byte)(255 - *(--sp));
  191197. /*
  191198. *(--dp) = *(--sp);
  191199. *(--dp) = *(--sp);
  191200. */
  191201. sp-=2;
  191202. dp=sp;
  191203. }
  191204. }
  191205. }
  191206. }
  191207. }
  191208. #endif
  191209. #if defined(PNG_READ_FILLER_SUPPORTED)
  191210. /* Add filler channel if we have RGB color */
  191211. void /* PRIVATE */
  191212. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191213. png_uint_32 filler, png_uint_32 flags)
  191214. {
  191215. png_uint_32 i;
  191216. png_uint_32 row_width = row_info->width;
  191217. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191218. png_byte lo_filler = (png_byte)(filler & 0xff);
  191219. png_debug(1, "in png_do_read_filler\n");
  191220. if (
  191221. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191222. row != NULL && row_info != NULL &&
  191223. #endif
  191224. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191225. {
  191226. if(row_info->bit_depth == 8)
  191227. {
  191228. /* This changes the data from G to GX */
  191229. if (flags & PNG_FLAG_FILLER_AFTER)
  191230. {
  191231. png_bytep sp = row + (png_size_t)row_width;
  191232. png_bytep dp = sp + (png_size_t)row_width;
  191233. for (i = 1; i < row_width; i++)
  191234. {
  191235. *(--dp) = lo_filler;
  191236. *(--dp) = *(--sp);
  191237. }
  191238. *(--dp) = lo_filler;
  191239. row_info->channels = 2;
  191240. row_info->pixel_depth = 16;
  191241. row_info->rowbytes = row_width * 2;
  191242. }
  191243. /* This changes the data from G to XG */
  191244. else
  191245. {
  191246. png_bytep sp = row + (png_size_t)row_width;
  191247. png_bytep dp = sp + (png_size_t)row_width;
  191248. for (i = 0; i < row_width; i++)
  191249. {
  191250. *(--dp) = *(--sp);
  191251. *(--dp) = lo_filler;
  191252. }
  191253. row_info->channels = 2;
  191254. row_info->pixel_depth = 16;
  191255. row_info->rowbytes = row_width * 2;
  191256. }
  191257. }
  191258. else if(row_info->bit_depth == 16)
  191259. {
  191260. /* This changes the data from GG to GGXX */
  191261. if (flags & PNG_FLAG_FILLER_AFTER)
  191262. {
  191263. png_bytep sp = row + (png_size_t)row_width * 2;
  191264. png_bytep dp = sp + (png_size_t)row_width * 2;
  191265. for (i = 1; i < row_width; i++)
  191266. {
  191267. *(--dp) = hi_filler;
  191268. *(--dp) = lo_filler;
  191269. *(--dp) = *(--sp);
  191270. *(--dp) = *(--sp);
  191271. }
  191272. *(--dp) = hi_filler;
  191273. *(--dp) = lo_filler;
  191274. row_info->channels = 2;
  191275. row_info->pixel_depth = 32;
  191276. row_info->rowbytes = row_width * 4;
  191277. }
  191278. /* This changes the data from GG to XXGG */
  191279. else
  191280. {
  191281. png_bytep sp = row + (png_size_t)row_width * 2;
  191282. png_bytep dp = sp + (png_size_t)row_width * 2;
  191283. for (i = 0; i < row_width; i++)
  191284. {
  191285. *(--dp) = *(--sp);
  191286. *(--dp) = *(--sp);
  191287. *(--dp) = hi_filler;
  191288. *(--dp) = lo_filler;
  191289. }
  191290. row_info->channels = 2;
  191291. row_info->pixel_depth = 32;
  191292. row_info->rowbytes = row_width * 4;
  191293. }
  191294. }
  191295. } /* COLOR_TYPE == GRAY */
  191296. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191297. {
  191298. if(row_info->bit_depth == 8)
  191299. {
  191300. /* This changes the data from RGB to RGBX */
  191301. if (flags & PNG_FLAG_FILLER_AFTER)
  191302. {
  191303. png_bytep sp = row + (png_size_t)row_width * 3;
  191304. png_bytep dp = sp + (png_size_t)row_width;
  191305. for (i = 1; i < row_width; i++)
  191306. {
  191307. *(--dp) = lo_filler;
  191308. *(--dp) = *(--sp);
  191309. *(--dp) = *(--sp);
  191310. *(--dp) = *(--sp);
  191311. }
  191312. *(--dp) = lo_filler;
  191313. row_info->channels = 4;
  191314. row_info->pixel_depth = 32;
  191315. row_info->rowbytes = row_width * 4;
  191316. }
  191317. /* This changes the data from RGB to XRGB */
  191318. else
  191319. {
  191320. png_bytep sp = row + (png_size_t)row_width * 3;
  191321. png_bytep dp = sp + (png_size_t)row_width;
  191322. for (i = 0; i < row_width; i++)
  191323. {
  191324. *(--dp) = *(--sp);
  191325. *(--dp) = *(--sp);
  191326. *(--dp) = *(--sp);
  191327. *(--dp) = lo_filler;
  191328. }
  191329. row_info->channels = 4;
  191330. row_info->pixel_depth = 32;
  191331. row_info->rowbytes = row_width * 4;
  191332. }
  191333. }
  191334. else if(row_info->bit_depth == 16)
  191335. {
  191336. /* This changes the data from RRGGBB to RRGGBBXX */
  191337. if (flags & PNG_FLAG_FILLER_AFTER)
  191338. {
  191339. png_bytep sp = row + (png_size_t)row_width * 6;
  191340. png_bytep dp = sp + (png_size_t)row_width * 2;
  191341. for (i = 1; i < row_width; i++)
  191342. {
  191343. *(--dp) = hi_filler;
  191344. *(--dp) = lo_filler;
  191345. *(--dp) = *(--sp);
  191346. *(--dp) = *(--sp);
  191347. *(--dp) = *(--sp);
  191348. *(--dp) = *(--sp);
  191349. *(--dp) = *(--sp);
  191350. *(--dp) = *(--sp);
  191351. }
  191352. *(--dp) = hi_filler;
  191353. *(--dp) = lo_filler;
  191354. row_info->channels = 4;
  191355. row_info->pixel_depth = 64;
  191356. row_info->rowbytes = row_width * 8;
  191357. }
  191358. /* This changes the data from RRGGBB to XXRRGGBB */
  191359. else
  191360. {
  191361. png_bytep sp = row + (png_size_t)row_width * 6;
  191362. png_bytep dp = sp + (png_size_t)row_width * 2;
  191363. for (i = 0; i < row_width; i++)
  191364. {
  191365. *(--dp) = *(--sp);
  191366. *(--dp) = *(--sp);
  191367. *(--dp) = *(--sp);
  191368. *(--dp) = *(--sp);
  191369. *(--dp) = *(--sp);
  191370. *(--dp) = *(--sp);
  191371. *(--dp) = hi_filler;
  191372. *(--dp) = lo_filler;
  191373. }
  191374. row_info->channels = 4;
  191375. row_info->pixel_depth = 64;
  191376. row_info->rowbytes = row_width * 8;
  191377. }
  191378. }
  191379. } /* COLOR_TYPE == RGB */
  191380. }
  191381. #endif
  191382. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191383. /* expand grayscale files to RGB, with or without alpha */
  191384. void /* PRIVATE */
  191385. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191386. {
  191387. png_uint_32 i;
  191388. png_uint_32 row_width = row_info->width;
  191389. png_debug(1, "in png_do_gray_to_rgb\n");
  191390. if (row_info->bit_depth >= 8 &&
  191391. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191392. row != NULL && row_info != NULL &&
  191393. #endif
  191394. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191395. {
  191396. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191397. {
  191398. if (row_info->bit_depth == 8)
  191399. {
  191400. png_bytep sp = row + (png_size_t)row_width - 1;
  191401. png_bytep dp = sp + (png_size_t)row_width * 2;
  191402. for (i = 0; i < row_width; i++)
  191403. {
  191404. *(dp--) = *sp;
  191405. *(dp--) = *sp;
  191406. *(dp--) = *(sp--);
  191407. }
  191408. }
  191409. else
  191410. {
  191411. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191412. png_bytep dp = sp + (png_size_t)row_width * 4;
  191413. for (i = 0; i < row_width; i++)
  191414. {
  191415. *(dp--) = *sp;
  191416. *(dp--) = *(sp - 1);
  191417. *(dp--) = *sp;
  191418. *(dp--) = *(sp - 1);
  191419. *(dp--) = *(sp--);
  191420. *(dp--) = *(sp--);
  191421. }
  191422. }
  191423. }
  191424. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191425. {
  191426. if (row_info->bit_depth == 8)
  191427. {
  191428. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191429. png_bytep dp = sp + (png_size_t)row_width * 2;
  191430. for (i = 0; i < row_width; i++)
  191431. {
  191432. *(dp--) = *(sp--);
  191433. *(dp--) = *sp;
  191434. *(dp--) = *sp;
  191435. *(dp--) = *(sp--);
  191436. }
  191437. }
  191438. else
  191439. {
  191440. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191441. png_bytep dp = sp + (png_size_t)row_width * 4;
  191442. for (i = 0; i < row_width; i++)
  191443. {
  191444. *(dp--) = *(sp--);
  191445. *(dp--) = *(sp--);
  191446. *(dp--) = *sp;
  191447. *(dp--) = *(sp - 1);
  191448. *(dp--) = *sp;
  191449. *(dp--) = *(sp - 1);
  191450. *(dp--) = *(sp--);
  191451. *(dp--) = *(sp--);
  191452. }
  191453. }
  191454. }
  191455. row_info->channels += (png_byte)2;
  191456. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191457. row_info->pixel_depth = (png_byte)(row_info->channels *
  191458. row_info->bit_depth);
  191459. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191460. }
  191461. }
  191462. #endif
  191463. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191464. /* reduce RGB files to grayscale, with or without alpha
  191465. * using the equation given in Poynton's ColorFAQ at
  191466. * <http://www.inforamp.net/~poynton/>
  191467. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191468. *
  191469. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191470. *
  191471. * We approximate this with
  191472. *
  191473. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191474. *
  191475. * which can be expressed with integers as
  191476. *
  191477. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191478. *
  191479. * The calculation is to be done in a linear colorspace.
  191480. *
  191481. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191482. */
  191483. int /* PRIVATE */
  191484. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191485. {
  191486. png_uint_32 i;
  191487. png_uint_32 row_width = row_info->width;
  191488. int rgb_error = 0;
  191489. png_debug(1, "in png_do_rgb_to_gray\n");
  191490. if (
  191491. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191492. row != NULL && row_info != NULL &&
  191493. #endif
  191494. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191495. {
  191496. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191497. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191498. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191499. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191500. {
  191501. if (row_info->bit_depth == 8)
  191502. {
  191503. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191504. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191505. {
  191506. png_bytep sp = row;
  191507. png_bytep dp = row;
  191508. for (i = 0; i < row_width; i++)
  191509. {
  191510. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191511. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191512. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191513. if(red != green || red != blue)
  191514. {
  191515. rgb_error |= 1;
  191516. *(dp++) = png_ptr->gamma_from_1[
  191517. (rc*red+gc*green+bc*blue)>>15];
  191518. }
  191519. else
  191520. *(dp++) = *(sp-1);
  191521. }
  191522. }
  191523. else
  191524. #endif
  191525. {
  191526. png_bytep sp = row;
  191527. png_bytep dp = row;
  191528. for (i = 0; i < row_width; i++)
  191529. {
  191530. png_byte red = *(sp++);
  191531. png_byte green = *(sp++);
  191532. png_byte blue = *(sp++);
  191533. if(red != green || red != blue)
  191534. {
  191535. rgb_error |= 1;
  191536. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191537. }
  191538. else
  191539. *(dp++) = *(sp-1);
  191540. }
  191541. }
  191542. }
  191543. else /* RGB bit_depth == 16 */
  191544. {
  191545. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191546. if (png_ptr->gamma_16_to_1 != NULL &&
  191547. png_ptr->gamma_16_from_1 != NULL)
  191548. {
  191549. png_bytep sp = row;
  191550. png_bytep dp = row;
  191551. for (i = 0; i < row_width; i++)
  191552. {
  191553. png_uint_16 red, green, blue, w;
  191554. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191555. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191556. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191557. if(red == green && red == blue)
  191558. w = red;
  191559. else
  191560. {
  191561. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191562. png_ptr->gamma_shift][red>>8];
  191563. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191564. png_ptr->gamma_shift][green>>8];
  191565. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191566. png_ptr->gamma_shift][blue>>8];
  191567. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191568. + bc*blue_1)>>15);
  191569. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191570. png_ptr->gamma_shift][gray16 >> 8];
  191571. rgb_error |= 1;
  191572. }
  191573. *(dp++) = (png_byte)((w>>8) & 0xff);
  191574. *(dp++) = (png_byte)(w & 0xff);
  191575. }
  191576. }
  191577. else
  191578. #endif
  191579. {
  191580. png_bytep sp = row;
  191581. png_bytep dp = row;
  191582. for (i = 0; i < row_width; i++)
  191583. {
  191584. png_uint_16 red, green, blue, gray16;
  191585. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191586. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191587. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191588. if(red != green || red != blue)
  191589. rgb_error |= 1;
  191590. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191591. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191592. *(dp++) = (png_byte)(gray16 & 0xff);
  191593. }
  191594. }
  191595. }
  191596. }
  191597. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191598. {
  191599. if (row_info->bit_depth == 8)
  191600. {
  191601. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191602. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191603. {
  191604. png_bytep sp = row;
  191605. png_bytep dp = row;
  191606. for (i = 0; i < row_width; i++)
  191607. {
  191608. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191609. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191610. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191611. if(red != green || red != blue)
  191612. rgb_error |= 1;
  191613. *(dp++) = png_ptr->gamma_from_1
  191614. [(rc*red + gc*green + bc*blue)>>15];
  191615. *(dp++) = *(sp++); /* alpha */
  191616. }
  191617. }
  191618. else
  191619. #endif
  191620. {
  191621. png_bytep sp = row;
  191622. png_bytep dp = row;
  191623. for (i = 0; i < row_width; i++)
  191624. {
  191625. png_byte red = *(sp++);
  191626. png_byte green = *(sp++);
  191627. png_byte blue = *(sp++);
  191628. if(red != green || red != blue)
  191629. rgb_error |= 1;
  191630. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191631. *(dp++) = *(sp++); /* alpha */
  191632. }
  191633. }
  191634. }
  191635. else /* RGBA bit_depth == 16 */
  191636. {
  191637. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191638. if (png_ptr->gamma_16_to_1 != NULL &&
  191639. png_ptr->gamma_16_from_1 != NULL)
  191640. {
  191641. png_bytep sp = row;
  191642. png_bytep dp = row;
  191643. for (i = 0; i < row_width; i++)
  191644. {
  191645. png_uint_16 red, green, blue, w;
  191646. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191647. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191648. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191649. if(red == green && red == blue)
  191650. w = red;
  191651. else
  191652. {
  191653. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191654. png_ptr->gamma_shift][red>>8];
  191655. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191656. png_ptr->gamma_shift][green>>8];
  191657. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191658. png_ptr->gamma_shift][blue>>8];
  191659. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191660. + gc * green_1 + bc * blue_1)>>15);
  191661. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191662. png_ptr->gamma_shift][gray16 >> 8];
  191663. rgb_error |= 1;
  191664. }
  191665. *(dp++) = (png_byte)((w>>8) & 0xff);
  191666. *(dp++) = (png_byte)(w & 0xff);
  191667. *(dp++) = *(sp++); /* alpha */
  191668. *(dp++) = *(sp++);
  191669. }
  191670. }
  191671. else
  191672. #endif
  191673. {
  191674. png_bytep sp = row;
  191675. png_bytep dp = row;
  191676. for (i = 0; i < row_width; i++)
  191677. {
  191678. png_uint_16 red, green, blue, gray16;
  191679. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191680. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191681. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191682. if(red != green || red != blue)
  191683. rgb_error |= 1;
  191684. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191685. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191686. *(dp++) = (png_byte)(gray16 & 0xff);
  191687. *(dp++) = *(sp++); /* alpha */
  191688. *(dp++) = *(sp++);
  191689. }
  191690. }
  191691. }
  191692. }
  191693. row_info->channels -= (png_byte)2;
  191694. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191695. row_info->pixel_depth = (png_byte)(row_info->channels *
  191696. row_info->bit_depth);
  191697. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191698. }
  191699. return rgb_error;
  191700. }
  191701. #endif
  191702. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191703. * large of png_color. This lets grayscale images be treated as
  191704. * paletted. Most useful for gamma correction and simplification
  191705. * of code.
  191706. */
  191707. void PNGAPI
  191708. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191709. {
  191710. int num_palette;
  191711. int color_inc;
  191712. int i;
  191713. int v;
  191714. png_debug(1, "in png_do_build_grayscale_palette\n");
  191715. if (palette == NULL)
  191716. return;
  191717. switch (bit_depth)
  191718. {
  191719. case 1:
  191720. num_palette = 2;
  191721. color_inc = 0xff;
  191722. break;
  191723. case 2:
  191724. num_palette = 4;
  191725. color_inc = 0x55;
  191726. break;
  191727. case 4:
  191728. num_palette = 16;
  191729. color_inc = 0x11;
  191730. break;
  191731. case 8:
  191732. num_palette = 256;
  191733. color_inc = 1;
  191734. break;
  191735. default:
  191736. num_palette = 0;
  191737. color_inc = 0;
  191738. break;
  191739. }
  191740. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191741. {
  191742. palette[i].red = (png_byte)v;
  191743. palette[i].green = (png_byte)v;
  191744. palette[i].blue = (png_byte)v;
  191745. }
  191746. }
  191747. /* This function is currently unused. Do we really need it? */
  191748. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191749. void /* PRIVATE */
  191750. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191751. int num_palette)
  191752. {
  191753. png_debug(1, "in png_correct_palette\n");
  191754. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191755. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191756. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191757. {
  191758. png_color back, back_1;
  191759. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191760. {
  191761. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191762. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191763. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191764. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191765. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191766. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191767. }
  191768. else
  191769. {
  191770. double g;
  191771. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191772. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191773. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191774. {
  191775. back.red = png_ptr->background.red;
  191776. back.green = png_ptr->background.green;
  191777. back.blue = png_ptr->background.blue;
  191778. }
  191779. else
  191780. {
  191781. back.red =
  191782. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191783. 255.0 + 0.5);
  191784. back.green =
  191785. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191786. 255.0 + 0.5);
  191787. back.blue =
  191788. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191789. 255.0 + 0.5);
  191790. }
  191791. g = 1.0 / png_ptr->background_gamma;
  191792. back_1.red =
  191793. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191794. 255.0 + 0.5);
  191795. back_1.green =
  191796. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191797. 255.0 + 0.5);
  191798. back_1.blue =
  191799. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191800. 255.0 + 0.5);
  191801. }
  191802. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191803. {
  191804. png_uint_32 i;
  191805. for (i = 0; i < (png_uint_32)num_palette; i++)
  191806. {
  191807. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191808. {
  191809. palette[i] = back;
  191810. }
  191811. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191812. {
  191813. png_byte v, w;
  191814. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191815. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191816. palette[i].red = png_ptr->gamma_from_1[w];
  191817. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191818. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191819. palette[i].green = png_ptr->gamma_from_1[w];
  191820. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191821. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191822. palette[i].blue = png_ptr->gamma_from_1[w];
  191823. }
  191824. else
  191825. {
  191826. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191827. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191828. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191829. }
  191830. }
  191831. }
  191832. else
  191833. {
  191834. int i;
  191835. for (i = 0; i < num_palette; i++)
  191836. {
  191837. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191838. {
  191839. palette[i] = back;
  191840. }
  191841. else
  191842. {
  191843. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191844. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191845. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191846. }
  191847. }
  191848. }
  191849. }
  191850. else
  191851. #endif
  191852. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191853. if (png_ptr->transformations & PNG_GAMMA)
  191854. {
  191855. int i;
  191856. for (i = 0; i < num_palette; i++)
  191857. {
  191858. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191859. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191860. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191861. }
  191862. }
  191863. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191864. else
  191865. #endif
  191866. #endif
  191867. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191868. if (png_ptr->transformations & PNG_BACKGROUND)
  191869. {
  191870. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191871. {
  191872. png_color back;
  191873. back.red = (png_byte)png_ptr->background.red;
  191874. back.green = (png_byte)png_ptr->background.green;
  191875. back.blue = (png_byte)png_ptr->background.blue;
  191876. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191877. {
  191878. if (png_ptr->trans[i] == 0)
  191879. {
  191880. palette[i].red = back.red;
  191881. palette[i].green = back.green;
  191882. palette[i].blue = back.blue;
  191883. }
  191884. else if (png_ptr->trans[i] != 0xff)
  191885. {
  191886. png_composite(palette[i].red, png_ptr->palette[i].red,
  191887. png_ptr->trans[i], back.red);
  191888. png_composite(palette[i].green, png_ptr->palette[i].green,
  191889. png_ptr->trans[i], back.green);
  191890. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191891. png_ptr->trans[i], back.blue);
  191892. }
  191893. }
  191894. }
  191895. else /* assume grayscale palette (what else could it be?) */
  191896. {
  191897. int i;
  191898. for (i = 0; i < num_palette; i++)
  191899. {
  191900. if (i == (png_byte)png_ptr->trans_values.gray)
  191901. {
  191902. palette[i].red = (png_byte)png_ptr->background.red;
  191903. palette[i].green = (png_byte)png_ptr->background.green;
  191904. palette[i].blue = (png_byte)png_ptr->background.blue;
  191905. }
  191906. }
  191907. }
  191908. }
  191909. #endif
  191910. }
  191911. #endif
  191912. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191913. /* Replace any alpha or transparency with the supplied background color.
  191914. * "background" is already in the screen gamma, while "background_1" is
  191915. * at a gamma of 1.0. Paletted files have already been taken care of.
  191916. */
  191917. void /* PRIVATE */
  191918. png_do_background(png_row_infop row_info, png_bytep row,
  191919. png_color_16p trans_values, png_color_16p background
  191920. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191921. , png_color_16p background_1,
  191922. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191923. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191924. png_uint_16pp gamma_16_to_1, int gamma_shift
  191925. #endif
  191926. )
  191927. {
  191928. png_bytep sp, dp;
  191929. png_uint_32 i;
  191930. png_uint_32 row_width=row_info->width;
  191931. int shift;
  191932. png_debug(1, "in png_do_background\n");
  191933. if (background != NULL &&
  191934. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191935. row != NULL && row_info != NULL &&
  191936. #endif
  191937. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191938. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191939. {
  191940. switch (row_info->color_type)
  191941. {
  191942. case PNG_COLOR_TYPE_GRAY:
  191943. {
  191944. switch (row_info->bit_depth)
  191945. {
  191946. case 1:
  191947. {
  191948. sp = row;
  191949. shift = 7;
  191950. for (i = 0; i < row_width; i++)
  191951. {
  191952. if ((png_uint_16)((*sp >> shift) & 0x01)
  191953. == trans_values->gray)
  191954. {
  191955. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191956. *sp |= (png_byte)(background->gray << shift);
  191957. }
  191958. if (!shift)
  191959. {
  191960. shift = 7;
  191961. sp++;
  191962. }
  191963. else
  191964. shift--;
  191965. }
  191966. break;
  191967. }
  191968. case 2:
  191969. {
  191970. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191971. if (gamma_table != NULL)
  191972. {
  191973. sp = row;
  191974. shift = 6;
  191975. for (i = 0; i < row_width; i++)
  191976. {
  191977. if ((png_uint_16)((*sp >> shift) & 0x03)
  191978. == trans_values->gray)
  191979. {
  191980. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191981. *sp |= (png_byte)(background->gray << shift);
  191982. }
  191983. else
  191984. {
  191985. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191986. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191987. (p << 4) | (p << 6)] >> 6) & 0x03);
  191988. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191989. *sp |= (png_byte)(g << shift);
  191990. }
  191991. if (!shift)
  191992. {
  191993. shift = 6;
  191994. sp++;
  191995. }
  191996. else
  191997. shift -= 2;
  191998. }
  191999. }
  192000. else
  192001. #endif
  192002. {
  192003. sp = row;
  192004. shift = 6;
  192005. for (i = 0; i < row_width; i++)
  192006. {
  192007. if ((png_uint_16)((*sp >> shift) & 0x03)
  192008. == trans_values->gray)
  192009. {
  192010. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192011. *sp |= (png_byte)(background->gray << shift);
  192012. }
  192013. if (!shift)
  192014. {
  192015. shift = 6;
  192016. sp++;
  192017. }
  192018. else
  192019. shift -= 2;
  192020. }
  192021. }
  192022. break;
  192023. }
  192024. case 4:
  192025. {
  192026. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192027. if (gamma_table != NULL)
  192028. {
  192029. sp = row;
  192030. shift = 4;
  192031. for (i = 0; i < row_width; i++)
  192032. {
  192033. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192034. == trans_values->gray)
  192035. {
  192036. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192037. *sp |= (png_byte)(background->gray << shift);
  192038. }
  192039. else
  192040. {
  192041. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192042. png_byte g = (png_byte)((gamma_table[p |
  192043. (p << 4)] >> 4) & 0x0f);
  192044. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192045. *sp |= (png_byte)(g << shift);
  192046. }
  192047. if (!shift)
  192048. {
  192049. shift = 4;
  192050. sp++;
  192051. }
  192052. else
  192053. shift -= 4;
  192054. }
  192055. }
  192056. else
  192057. #endif
  192058. {
  192059. sp = row;
  192060. shift = 4;
  192061. for (i = 0; i < row_width; i++)
  192062. {
  192063. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192064. == trans_values->gray)
  192065. {
  192066. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192067. *sp |= (png_byte)(background->gray << shift);
  192068. }
  192069. if (!shift)
  192070. {
  192071. shift = 4;
  192072. sp++;
  192073. }
  192074. else
  192075. shift -= 4;
  192076. }
  192077. }
  192078. break;
  192079. }
  192080. case 8:
  192081. {
  192082. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192083. if (gamma_table != NULL)
  192084. {
  192085. sp = row;
  192086. for (i = 0; i < row_width; i++, sp++)
  192087. {
  192088. if (*sp == trans_values->gray)
  192089. {
  192090. *sp = (png_byte)background->gray;
  192091. }
  192092. else
  192093. {
  192094. *sp = gamma_table[*sp];
  192095. }
  192096. }
  192097. }
  192098. else
  192099. #endif
  192100. {
  192101. sp = row;
  192102. for (i = 0; i < row_width; i++, sp++)
  192103. {
  192104. if (*sp == trans_values->gray)
  192105. {
  192106. *sp = (png_byte)background->gray;
  192107. }
  192108. }
  192109. }
  192110. break;
  192111. }
  192112. case 16:
  192113. {
  192114. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192115. if (gamma_16 != NULL)
  192116. {
  192117. sp = row;
  192118. for (i = 0; i < row_width; i++, sp += 2)
  192119. {
  192120. png_uint_16 v;
  192121. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192122. if (v == trans_values->gray)
  192123. {
  192124. /* background is already in screen gamma */
  192125. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192126. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192127. }
  192128. else
  192129. {
  192130. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192131. *sp = (png_byte)((v >> 8) & 0xff);
  192132. *(sp + 1) = (png_byte)(v & 0xff);
  192133. }
  192134. }
  192135. }
  192136. else
  192137. #endif
  192138. {
  192139. sp = row;
  192140. for (i = 0; i < row_width; i++, sp += 2)
  192141. {
  192142. png_uint_16 v;
  192143. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192144. if (v == trans_values->gray)
  192145. {
  192146. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192147. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192148. }
  192149. }
  192150. }
  192151. break;
  192152. }
  192153. }
  192154. break;
  192155. }
  192156. case PNG_COLOR_TYPE_RGB:
  192157. {
  192158. if (row_info->bit_depth == 8)
  192159. {
  192160. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192161. if (gamma_table != NULL)
  192162. {
  192163. sp = row;
  192164. for (i = 0; i < row_width; i++, sp += 3)
  192165. {
  192166. if (*sp == trans_values->red &&
  192167. *(sp + 1) == trans_values->green &&
  192168. *(sp + 2) == trans_values->blue)
  192169. {
  192170. *sp = (png_byte)background->red;
  192171. *(sp + 1) = (png_byte)background->green;
  192172. *(sp + 2) = (png_byte)background->blue;
  192173. }
  192174. else
  192175. {
  192176. *sp = gamma_table[*sp];
  192177. *(sp + 1) = gamma_table[*(sp + 1)];
  192178. *(sp + 2) = gamma_table[*(sp + 2)];
  192179. }
  192180. }
  192181. }
  192182. else
  192183. #endif
  192184. {
  192185. sp = row;
  192186. for (i = 0; i < row_width; i++, sp += 3)
  192187. {
  192188. if (*sp == trans_values->red &&
  192189. *(sp + 1) == trans_values->green &&
  192190. *(sp + 2) == trans_values->blue)
  192191. {
  192192. *sp = (png_byte)background->red;
  192193. *(sp + 1) = (png_byte)background->green;
  192194. *(sp + 2) = (png_byte)background->blue;
  192195. }
  192196. }
  192197. }
  192198. }
  192199. else /* if (row_info->bit_depth == 16) */
  192200. {
  192201. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192202. if (gamma_16 != NULL)
  192203. {
  192204. sp = row;
  192205. for (i = 0; i < row_width; i++, sp += 6)
  192206. {
  192207. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192208. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192209. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192210. if (r == trans_values->red && g == trans_values->green &&
  192211. b == trans_values->blue)
  192212. {
  192213. /* background is already in screen gamma */
  192214. *sp = (png_byte)((background->red >> 8) & 0xff);
  192215. *(sp + 1) = (png_byte)(background->red & 0xff);
  192216. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192217. *(sp + 3) = (png_byte)(background->green & 0xff);
  192218. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192219. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192220. }
  192221. else
  192222. {
  192223. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192224. *sp = (png_byte)((v >> 8) & 0xff);
  192225. *(sp + 1) = (png_byte)(v & 0xff);
  192226. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192227. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192228. *(sp + 3) = (png_byte)(v & 0xff);
  192229. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192230. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192231. *(sp + 5) = (png_byte)(v & 0xff);
  192232. }
  192233. }
  192234. }
  192235. else
  192236. #endif
  192237. {
  192238. sp = row;
  192239. for (i = 0; i < row_width; i++, sp += 6)
  192240. {
  192241. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192242. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192243. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192244. if (r == trans_values->red && g == trans_values->green &&
  192245. b == trans_values->blue)
  192246. {
  192247. *sp = (png_byte)((background->red >> 8) & 0xff);
  192248. *(sp + 1) = (png_byte)(background->red & 0xff);
  192249. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192250. *(sp + 3) = (png_byte)(background->green & 0xff);
  192251. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192252. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192253. }
  192254. }
  192255. }
  192256. }
  192257. break;
  192258. }
  192259. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192260. {
  192261. if (row_info->bit_depth == 8)
  192262. {
  192263. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192264. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192265. gamma_table != NULL)
  192266. {
  192267. sp = row;
  192268. dp = row;
  192269. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192270. {
  192271. png_uint_16 a = *(sp + 1);
  192272. if (a == 0xff)
  192273. {
  192274. *dp = gamma_table[*sp];
  192275. }
  192276. else if (a == 0)
  192277. {
  192278. /* background is already in screen gamma */
  192279. *dp = (png_byte)background->gray;
  192280. }
  192281. else
  192282. {
  192283. png_byte v, w;
  192284. v = gamma_to_1[*sp];
  192285. png_composite(w, v, a, background_1->gray);
  192286. *dp = gamma_from_1[w];
  192287. }
  192288. }
  192289. }
  192290. else
  192291. #endif
  192292. {
  192293. sp = row;
  192294. dp = row;
  192295. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192296. {
  192297. png_byte a = *(sp + 1);
  192298. if (a == 0xff)
  192299. {
  192300. *dp = *sp;
  192301. }
  192302. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192303. else if (a == 0)
  192304. {
  192305. *dp = (png_byte)background->gray;
  192306. }
  192307. else
  192308. {
  192309. png_composite(*dp, *sp, a, background_1->gray);
  192310. }
  192311. #else
  192312. *dp = (png_byte)background->gray;
  192313. #endif
  192314. }
  192315. }
  192316. }
  192317. else /* if (png_ptr->bit_depth == 16) */
  192318. {
  192319. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192320. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192321. gamma_16_to_1 != NULL)
  192322. {
  192323. sp = row;
  192324. dp = row;
  192325. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192326. {
  192327. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192328. if (a == (png_uint_16)0xffff)
  192329. {
  192330. png_uint_16 v;
  192331. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192332. *dp = (png_byte)((v >> 8) & 0xff);
  192333. *(dp + 1) = (png_byte)(v & 0xff);
  192334. }
  192335. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192336. else if (a == 0)
  192337. #else
  192338. else
  192339. #endif
  192340. {
  192341. /* background is already in screen gamma */
  192342. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192343. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192344. }
  192345. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192346. else
  192347. {
  192348. png_uint_16 g, v, w;
  192349. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192350. png_composite_16(v, g, a, background_1->gray);
  192351. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192352. *dp = (png_byte)((w >> 8) & 0xff);
  192353. *(dp + 1) = (png_byte)(w & 0xff);
  192354. }
  192355. #endif
  192356. }
  192357. }
  192358. else
  192359. #endif
  192360. {
  192361. sp = row;
  192362. dp = row;
  192363. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192364. {
  192365. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192366. if (a == (png_uint_16)0xffff)
  192367. {
  192368. png_memcpy(dp, sp, 2);
  192369. }
  192370. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192371. else if (a == 0)
  192372. #else
  192373. else
  192374. #endif
  192375. {
  192376. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192377. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192378. }
  192379. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192380. else
  192381. {
  192382. png_uint_16 g, v;
  192383. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192384. png_composite_16(v, g, a, background_1->gray);
  192385. *dp = (png_byte)((v >> 8) & 0xff);
  192386. *(dp + 1) = (png_byte)(v & 0xff);
  192387. }
  192388. #endif
  192389. }
  192390. }
  192391. }
  192392. break;
  192393. }
  192394. case PNG_COLOR_TYPE_RGB_ALPHA:
  192395. {
  192396. if (row_info->bit_depth == 8)
  192397. {
  192398. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192399. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192400. gamma_table != NULL)
  192401. {
  192402. sp = row;
  192403. dp = row;
  192404. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192405. {
  192406. png_byte a = *(sp + 3);
  192407. if (a == 0xff)
  192408. {
  192409. *dp = gamma_table[*sp];
  192410. *(dp + 1) = gamma_table[*(sp + 1)];
  192411. *(dp + 2) = gamma_table[*(sp + 2)];
  192412. }
  192413. else if (a == 0)
  192414. {
  192415. /* background is already in screen gamma */
  192416. *dp = (png_byte)background->red;
  192417. *(dp + 1) = (png_byte)background->green;
  192418. *(dp + 2) = (png_byte)background->blue;
  192419. }
  192420. else
  192421. {
  192422. png_byte v, w;
  192423. v = gamma_to_1[*sp];
  192424. png_composite(w, v, a, background_1->red);
  192425. *dp = gamma_from_1[w];
  192426. v = gamma_to_1[*(sp + 1)];
  192427. png_composite(w, v, a, background_1->green);
  192428. *(dp + 1) = gamma_from_1[w];
  192429. v = gamma_to_1[*(sp + 2)];
  192430. png_composite(w, v, a, background_1->blue);
  192431. *(dp + 2) = gamma_from_1[w];
  192432. }
  192433. }
  192434. }
  192435. else
  192436. #endif
  192437. {
  192438. sp = row;
  192439. dp = row;
  192440. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192441. {
  192442. png_byte a = *(sp + 3);
  192443. if (a == 0xff)
  192444. {
  192445. *dp = *sp;
  192446. *(dp + 1) = *(sp + 1);
  192447. *(dp + 2) = *(sp + 2);
  192448. }
  192449. else if (a == 0)
  192450. {
  192451. *dp = (png_byte)background->red;
  192452. *(dp + 1) = (png_byte)background->green;
  192453. *(dp + 2) = (png_byte)background->blue;
  192454. }
  192455. else
  192456. {
  192457. png_composite(*dp, *sp, a, background->red);
  192458. png_composite(*(dp + 1), *(sp + 1), a,
  192459. background->green);
  192460. png_composite(*(dp + 2), *(sp + 2), a,
  192461. background->blue);
  192462. }
  192463. }
  192464. }
  192465. }
  192466. else /* if (row_info->bit_depth == 16) */
  192467. {
  192468. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192469. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192470. gamma_16_to_1 != NULL)
  192471. {
  192472. sp = row;
  192473. dp = row;
  192474. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192475. {
  192476. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192477. << 8) + (png_uint_16)(*(sp + 7)));
  192478. if (a == (png_uint_16)0xffff)
  192479. {
  192480. png_uint_16 v;
  192481. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192482. *dp = (png_byte)((v >> 8) & 0xff);
  192483. *(dp + 1) = (png_byte)(v & 0xff);
  192484. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192485. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192486. *(dp + 3) = (png_byte)(v & 0xff);
  192487. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192488. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192489. *(dp + 5) = (png_byte)(v & 0xff);
  192490. }
  192491. else if (a == 0)
  192492. {
  192493. /* background is already in screen gamma */
  192494. *dp = (png_byte)((background->red >> 8) & 0xff);
  192495. *(dp + 1) = (png_byte)(background->red & 0xff);
  192496. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192497. *(dp + 3) = (png_byte)(background->green & 0xff);
  192498. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192499. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192500. }
  192501. else
  192502. {
  192503. png_uint_16 v, w, x;
  192504. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192505. png_composite_16(w, v, a, background_1->red);
  192506. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192507. *dp = (png_byte)((x >> 8) & 0xff);
  192508. *(dp + 1) = (png_byte)(x & 0xff);
  192509. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192510. png_composite_16(w, v, a, background_1->green);
  192511. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192512. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192513. *(dp + 3) = (png_byte)(x & 0xff);
  192514. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192515. png_composite_16(w, v, a, background_1->blue);
  192516. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192517. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192518. *(dp + 5) = (png_byte)(x & 0xff);
  192519. }
  192520. }
  192521. }
  192522. else
  192523. #endif
  192524. {
  192525. sp = row;
  192526. dp = row;
  192527. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192528. {
  192529. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192530. << 8) + (png_uint_16)(*(sp + 7)));
  192531. if (a == (png_uint_16)0xffff)
  192532. {
  192533. png_memcpy(dp, sp, 6);
  192534. }
  192535. else if (a == 0)
  192536. {
  192537. *dp = (png_byte)((background->red >> 8) & 0xff);
  192538. *(dp + 1) = (png_byte)(background->red & 0xff);
  192539. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192540. *(dp + 3) = (png_byte)(background->green & 0xff);
  192541. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192542. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192543. }
  192544. else
  192545. {
  192546. png_uint_16 v;
  192547. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192548. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192549. + *(sp + 3));
  192550. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192551. + *(sp + 5));
  192552. png_composite_16(v, r, a, background->red);
  192553. *dp = (png_byte)((v >> 8) & 0xff);
  192554. *(dp + 1) = (png_byte)(v & 0xff);
  192555. png_composite_16(v, g, a, background->green);
  192556. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192557. *(dp + 3) = (png_byte)(v & 0xff);
  192558. png_composite_16(v, b, a, background->blue);
  192559. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192560. *(dp + 5) = (png_byte)(v & 0xff);
  192561. }
  192562. }
  192563. }
  192564. }
  192565. break;
  192566. }
  192567. }
  192568. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192569. {
  192570. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192571. row_info->channels--;
  192572. row_info->pixel_depth = (png_byte)(row_info->channels *
  192573. row_info->bit_depth);
  192574. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192575. }
  192576. }
  192577. }
  192578. #endif
  192579. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192580. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192581. * you do this after you deal with the transparency issue on grayscale
  192582. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192583. * is 16, use gamma_16_table and gamma_shift. Build these with
  192584. * build_gamma_table().
  192585. */
  192586. void /* PRIVATE */
  192587. png_do_gamma(png_row_infop row_info, png_bytep row,
  192588. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192589. int gamma_shift)
  192590. {
  192591. png_bytep sp;
  192592. png_uint_32 i;
  192593. png_uint_32 row_width=row_info->width;
  192594. png_debug(1, "in png_do_gamma\n");
  192595. if (
  192596. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192597. row != NULL && row_info != NULL &&
  192598. #endif
  192599. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192600. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192601. {
  192602. switch (row_info->color_type)
  192603. {
  192604. case PNG_COLOR_TYPE_RGB:
  192605. {
  192606. if (row_info->bit_depth == 8)
  192607. {
  192608. sp = row;
  192609. for (i = 0; i < row_width; i++)
  192610. {
  192611. *sp = gamma_table[*sp];
  192612. sp++;
  192613. *sp = gamma_table[*sp];
  192614. sp++;
  192615. *sp = gamma_table[*sp];
  192616. sp++;
  192617. }
  192618. }
  192619. else /* if (row_info->bit_depth == 16) */
  192620. {
  192621. sp = row;
  192622. for (i = 0; i < row_width; i++)
  192623. {
  192624. png_uint_16 v;
  192625. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192626. *sp = (png_byte)((v >> 8) & 0xff);
  192627. *(sp + 1) = (png_byte)(v & 0xff);
  192628. sp += 2;
  192629. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192630. *sp = (png_byte)((v >> 8) & 0xff);
  192631. *(sp + 1) = (png_byte)(v & 0xff);
  192632. sp += 2;
  192633. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192634. *sp = (png_byte)((v >> 8) & 0xff);
  192635. *(sp + 1) = (png_byte)(v & 0xff);
  192636. sp += 2;
  192637. }
  192638. }
  192639. break;
  192640. }
  192641. case PNG_COLOR_TYPE_RGB_ALPHA:
  192642. {
  192643. if (row_info->bit_depth == 8)
  192644. {
  192645. sp = row;
  192646. for (i = 0; i < row_width; i++)
  192647. {
  192648. *sp = gamma_table[*sp];
  192649. sp++;
  192650. *sp = gamma_table[*sp];
  192651. sp++;
  192652. *sp = gamma_table[*sp];
  192653. sp++;
  192654. sp++;
  192655. }
  192656. }
  192657. else /* if (row_info->bit_depth == 16) */
  192658. {
  192659. sp = row;
  192660. for (i = 0; i < row_width; i++)
  192661. {
  192662. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192663. *sp = (png_byte)((v >> 8) & 0xff);
  192664. *(sp + 1) = (png_byte)(v & 0xff);
  192665. sp += 2;
  192666. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192667. *sp = (png_byte)((v >> 8) & 0xff);
  192668. *(sp + 1) = (png_byte)(v & 0xff);
  192669. sp += 2;
  192670. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192671. *sp = (png_byte)((v >> 8) & 0xff);
  192672. *(sp + 1) = (png_byte)(v & 0xff);
  192673. sp += 4;
  192674. }
  192675. }
  192676. break;
  192677. }
  192678. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192679. {
  192680. if (row_info->bit_depth == 8)
  192681. {
  192682. sp = row;
  192683. for (i = 0; i < row_width; i++)
  192684. {
  192685. *sp = gamma_table[*sp];
  192686. sp += 2;
  192687. }
  192688. }
  192689. else /* if (row_info->bit_depth == 16) */
  192690. {
  192691. sp = row;
  192692. for (i = 0; i < row_width; i++)
  192693. {
  192694. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192695. *sp = (png_byte)((v >> 8) & 0xff);
  192696. *(sp + 1) = (png_byte)(v & 0xff);
  192697. sp += 4;
  192698. }
  192699. }
  192700. break;
  192701. }
  192702. case PNG_COLOR_TYPE_GRAY:
  192703. {
  192704. if (row_info->bit_depth == 2)
  192705. {
  192706. sp = row;
  192707. for (i = 0; i < row_width; i += 4)
  192708. {
  192709. int a = *sp & 0xc0;
  192710. int b = *sp & 0x30;
  192711. int c = *sp & 0x0c;
  192712. int d = *sp & 0x03;
  192713. *sp = (png_byte)(
  192714. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192715. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192716. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192717. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192718. sp++;
  192719. }
  192720. }
  192721. if (row_info->bit_depth == 4)
  192722. {
  192723. sp = row;
  192724. for (i = 0; i < row_width; i += 2)
  192725. {
  192726. int msb = *sp & 0xf0;
  192727. int lsb = *sp & 0x0f;
  192728. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192729. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192730. sp++;
  192731. }
  192732. }
  192733. else if (row_info->bit_depth == 8)
  192734. {
  192735. sp = row;
  192736. for (i = 0; i < row_width; i++)
  192737. {
  192738. *sp = gamma_table[*sp];
  192739. sp++;
  192740. }
  192741. }
  192742. else if (row_info->bit_depth == 16)
  192743. {
  192744. sp = row;
  192745. for (i = 0; i < row_width; i++)
  192746. {
  192747. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192748. *sp = (png_byte)((v >> 8) & 0xff);
  192749. *(sp + 1) = (png_byte)(v & 0xff);
  192750. sp += 2;
  192751. }
  192752. }
  192753. break;
  192754. }
  192755. }
  192756. }
  192757. }
  192758. #endif
  192759. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192760. /* Expands a palette row to an RGB or RGBA row depending
  192761. * upon whether you supply trans and num_trans.
  192762. */
  192763. void /* PRIVATE */
  192764. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192765. png_colorp palette, png_bytep trans, int num_trans)
  192766. {
  192767. int shift, value;
  192768. png_bytep sp, dp;
  192769. png_uint_32 i;
  192770. png_uint_32 row_width=row_info->width;
  192771. png_debug(1, "in png_do_expand_palette\n");
  192772. if (
  192773. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192774. row != NULL && row_info != NULL &&
  192775. #endif
  192776. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192777. {
  192778. if (row_info->bit_depth < 8)
  192779. {
  192780. switch (row_info->bit_depth)
  192781. {
  192782. case 1:
  192783. {
  192784. sp = row + (png_size_t)((row_width - 1) >> 3);
  192785. dp = row + (png_size_t)row_width - 1;
  192786. shift = 7 - (int)((row_width + 7) & 0x07);
  192787. for (i = 0; i < row_width; i++)
  192788. {
  192789. if ((*sp >> shift) & 0x01)
  192790. *dp = 1;
  192791. else
  192792. *dp = 0;
  192793. if (shift == 7)
  192794. {
  192795. shift = 0;
  192796. sp--;
  192797. }
  192798. else
  192799. shift++;
  192800. dp--;
  192801. }
  192802. break;
  192803. }
  192804. case 2:
  192805. {
  192806. sp = row + (png_size_t)((row_width - 1) >> 2);
  192807. dp = row + (png_size_t)row_width - 1;
  192808. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192809. for (i = 0; i < row_width; i++)
  192810. {
  192811. value = (*sp >> shift) & 0x03;
  192812. *dp = (png_byte)value;
  192813. if (shift == 6)
  192814. {
  192815. shift = 0;
  192816. sp--;
  192817. }
  192818. else
  192819. shift += 2;
  192820. dp--;
  192821. }
  192822. break;
  192823. }
  192824. case 4:
  192825. {
  192826. sp = row + (png_size_t)((row_width - 1) >> 1);
  192827. dp = row + (png_size_t)row_width - 1;
  192828. shift = (int)((row_width & 0x01) << 2);
  192829. for (i = 0; i < row_width; i++)
  192830. {
  192831. value = (*sp >> shift) & 0x0f;
  192832. *dp = (png_byte)value;
  192833. if (shift == 4)
  192834. {
  192835. shift = 0;
  192836. sp--;
  192837. }
  192838. else
  192839. shift += 4;
  192840. dp--;
  192841. }
  192842. break;
  192843. }
  192844. }
  192845. row_info->bit_depth = 8;
  192846. row_info->pixel_depth = 8;
  192847. row_info->rowbytes = row_width;
  192848. }
  192849. switch (row_info->bit_depth)
  192850. {
  192851. case 8:
  192852. {
  192853. if (trans != NULL)
  192854. {
  192855. sp = row + (png_size_t)row_width - 1;
  192856. dp = row + (png_size_t)(row_width << 2) - 1;
  192857. for (i = 0; i < row_width; i++)
  192858. {
  192859. if ((int)(*sp) >= num_trans)
  192860. *dp-- = 0xff;
  192861. else
  192862. *dp-- = trans[*sp];
  192863. *dp-- = palette[*sp].blue;
  192864. *dp-- = palette[*sp].green;
  192865. *dp-- = palette[*sp].red;
  192866. sp--;
  192867. }
  192868. row_info->bit_depth = 8;
  192869. row_info->pixel_depth = 32;
  192870. row_info->rowbytes = row_width * 4;
  192871. row_info->color_type = 6;
  192872. row_info->channels = 4;
  192873. }
  192874. else
  192875. {
  192876. sp = row + (png_size_t)row_width - 1;
  192877. dp = row + (png_size_t)(row_width * 3) - 1;
  192878. for (i = 0; i < row_width; i++)
  192879. {
  192880. *dp-- = palette[*sp].blue;
  192881. *dp-- = palette[*sp].green;
  192882. *dp-- = palette[*sp].red;
  192883. sp--;
  192884. }
  192885. row_info->bit_depth = 8;
  192886. row_info->pixel_depth = 24;
  192887. row_info->rowbytes = row_width * 3;
  192888. row_info->color_type = 2;
  192889. row_info->channels = 3;
  192890. }
  192891. break;
  192892. }
  192893. }
  192894. }
  192895. }
  192896. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192897. * expanded transparency value is supplied, an alpha channel is built.
  192898. */
  192899. void /* PRIVATE */
  192900. png_do_expand(png_row_infop row_info, png_bytep row,
  192901. png_color_16p trans_value)
  192902. {
  192903. int shift, value;
  192904. png_bytep sp, dp;
  192905. png_uint_32 i;
  192906. png_uint_32 row_width=row_info->width;
  192907. png_debug(1, "in png_do_expand\n");
  192908. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192909. if (row != NULL && row_info != NULL)
  192910. #endif
  192911. {
  192912. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192913. {
  192914. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192915. if (row_info->bit_depth < 8)
  192916. {
  192917. switch (row_info->bit_depth)
  192918. {
  192919. case 1:
  192920. {
  192921. gray = (png_uint_16)((gray&0x01)*0xff);
  192922. sp = row + (png_size_t)((row_width - 1) >> 3);
  192923. dp = row + (png_size_t)row_width - 1;
  192924. shift = 7 - (int)((row_width + 7) & 0x07);
  192925. for (i = 0; i < row_width; i++)
  192926. {
  192927. if ((*sp >> shift) & 0x01)
  192928. *dp = 0xff;
  192929. else
  192930. *dp = 0;
  192931. if (shift == 7)
  192932. {
  192933. shift = 0;
  192934. sp--;
  192935. }
  192936. else
  192937. shift++;
  192938. dp--;
  192939. }
  192940. break;
  192941. }
  192942. case 2:
  192943. {
  192944. gray = (png_uint_16)((gray&0x03)*0x55);
  192945. sp = row + (png_size_t)((row_width - 1) >> 2);
  192946. dp = row + (png_size_t)row_width - 1;
  192947. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192948. for (i = 0; i < row_width; i++)
  192949. {
  192950. value = (*sp >> shift) & 0x03;
  192951. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192952. (value << 6));
  192953. if (shift == 6)
  192954. {
  192955. shift = 0;
  192956. sp--;
  192957. }
  192958. else
  192959. shift += 2;
  192960. dp--;
  192961. }
  192962. break;
  192963. }
  192964. case 4:
  192965. {
  192966. gray = (png_uint_16)((gray&0x0f)*0x11);
  192967. sp = row + (png_size_t)((row_width - 1) >> 1);
  192968. dp = row + (png_size_t)row_width - 1;
  192969. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192970. for (i = 0; i < row_width; i++)
  192971. {
  192972. value = (*sp >> shift) & 0x0f;
  192973. *dp = (png_byte)(value | (value << 4));
  192974. if (shift == 4)
  192975. {
  192976. shift = 0;
  192977. sp--;
  192978. }
  192979. else
  192980. shift = 4;
  192981. dp--;
  192982. }
  192983. break;
  192984. }
  192985. }
  192986. row_info->bit_depth = 8;
  192987. row_info->pixel_depth = 8;
  192988. row_info->rowbytes = row_width;
  192989. }
  192990. if (trans_value != NULL)
  192991. {
  192992. if (row_info->bit_depth == 8)
  192993. {
  192994. gray = gray & 0xff;
  192995. sp = row + (png_size_t)row_width - 1;
  192996. dp = row + (png_size_t)(row_width << 1) - 1;
  192997. for (i = 0; i < row_width; i++)
  192998. {
  192999. if (*sp == gray)
  193000. *dp-- = 0;
  193001. else
  193002. *dp-- = 0xff;
  193003. *dp-- = *sp--;
  193004. }
  193005. }
  193006. else if (row_info->bit_depth == 16)
  193007. {
  193008. png_byte gray_high = (gray >> 8) & 0xff;
  193009. png_byte gray_low = gray & 0xff;
  193010. sp = row + row_info->rowbytes - 1;
  193011. dp = row + (row_info->rowbytes << 1) - 1;
  193012. for (i = 0; i < row_width; i++)
  193013. {
  193014. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193015. {
  193016. *dp-- = 0;
  193017. *dp-- = 0;
  193018. }
  193019. else
  193020. {
  193021. *dp-- = 0xff;
  193022. *dp-- = 0xff;
  193023. }
  193024. *dp-- = *sp--;
  193025. *dp-- = *sp--;
  193026. }
  193027. }
  193028. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193029. row_info->channels = 2;
  193030. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193031. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193032. row_width);
  193033. }
  193034. }
  193035. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193036. {
  193037. if (row_info->bit_depth == 8)
  193038. {
  193039. png_byte red = trans_value->red & 0xff;
  193040. png_byte green = trans_value->green & 0xff;
  193041. png_byte blue = trans_value->blue & 0xff;
  193042. sp = row + (png_size_t)row_info->rowbytes - 1;
  193043. dp = row + (png_size_t)(row_width << 2) - 1;
  193044. for (i = 0; i < row_width; i++)
  193045. {
  193046. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193047. *dp-- = 0;
  193048. else
  193049. *dp-- = 0xff;
  193050. *dp-- = *sp--;
  193051. *dp-- = *sp--;
  193052. *dp-- = *sp--;
  193053. }
  193054. }
  193055. else if (row_info->bit_depth == 16)
  193056. {
  193057. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193058. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193059. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193060. png_byte red_low = trans_value->red & 0xff;
  193061. png_byte green_low = trans_value->green & 0xff;
  193062. png_byte blue_low = trans_value->blue & 0xff;
  193063. sp = row + row_info->rowbytes - 1;
  193064. dp = row + (png_size_t)(row_width << 3) - 1;
  193065. for (i = 0; i < row_width; i++)
  193066. {
  193067. if (*(sp - 5) == red_high &&
  193068. *(sp - 4) == red_low &&
  193069. *(sp - 3) == green_high &&
  193070. *(sp - 2) == green_low &&
  193071. *(sp - 1) == blue_high &&
  193072. *(sp ) == blue_low)
  193073. {
  193074. *dp-- = 0;
  193075. *dp-- = 0;
  193076. }
  193077. else
  193078. {
  193079. *dp-- = 0xff;
  193080. *dp-- = 0xff;
  193081. }
  193082. *dp-- = *sp--;
  193083. *dp-- = *sp--;
  193084. *dp-- = *sp--;
  193085. *dp-- = *sp--;
  193086. *dp-- = *sp--;
  193087. *dp-- = *sp--;
  193088. }
  193089. }
  193090. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193091. row_info->channels = 4;
  193092. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193093. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193094. }
  193095. }
  193096. }
  193097. #endif
  193098. #if defined(PNG_READ_DITHER_SUPPORTED)
  193099. void /* PRIVATE */
  193100. png_do_dither(png_row_infop row_info, png_bytep row,
  193101. png_bytep palette_lookup, png_bytep dither_lookup)
  193102. {
  193103. png_bytep sp, dp;
  193104. png_uint_32 i;
  193105. png_uint_32 row_width=row_info->width;
  193106. png_debug(1, "in png_do_dither\n");
  193107. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193108. if (row != NULL && row_info != NULL)
  193109. #endif
  193110. {
  193111. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193112. palette_lookup && row_info->bit_depth == 8)
  193113. {
  193114. int r, g, b, p;
  193115. sp = row;
  193116. dp = row;
  193117. for (i = 0; i < row_width; i++)
  193118. {
  193119. r = *sp++;
  193120. g = *sp++;
  193121. b = *sp++;
  193122. /* this looks real messy, but the compiler will reduce
  193123. it down to a reasonable formula. For example, with
  193124. 5 bits per color, we get:
  193125. p = (((r >> 3) & 0x1f) << 10) |
  193126. (((g >> 3) & 0x1f) << 5) |
  193127. ((b >> 3) & 0x1f);
  193128. */
  193129. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193130. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193131. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193132. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193133. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193134. (PNG_DITHER_BLUE_BITS)) |
  193135. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193136. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193137. *dp++ = palette_lookup[p];
  193138. }
  193139. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193140. row_info->channels = 1;
  193141. row_info->pixel_depth = row_info->bit_depth;
  193142. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193143. }
  193144. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193145. palette_lookup != NULL && row_info->bit_depth == 8)
  193146. {
  193147. int r, g, b, p;
  193148. sp = row;
  193149. dp = row;
  193150. for (i = 0; i < row_width; i++)
  193151. {
  193152. r = *sp++;
  193153. g = *sp++;
  193154. b = *sp++;
  193155. sp++;
  193156. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193157. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193158. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193159. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193160. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193161. (PNG_DITHER_BLUE_BITS)) |
  193162. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193163. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193164. *dp++ = palette_lookup[p];
  193165. }
  193166. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193167. row_info->channels = 1;
  193168. row_info->pixel_depth = row_info->bit_depth;
  193169. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193170. }
  193171. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193172. dither_lookup && row_info->bit_depth == 8)
  193173. {
  193174. sp = row;
  193175. for (i = 0; i < row_width; i++, sp++)
  193176. {
  193177. *sp = dither_lookup[*sp];
  193178. }
  193179. }
  193180. }
  193181. }
  193182. #endif
  193183. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193184. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193185. static PNG_CONST int png_gamma_shift[] =
  193186. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193187. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193188. * tables, we don't make a full table if we are reducing to 8-bit in
  193189. * the future. Note also how the gamma_16 tables are segmented so that
  193190. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193191. */
  193192. void /* PRIVATE */
  193193. png_build_gamma_table(png_structp png_ptr)
  193194. {
  193195. png_debug(1, "in png_build_gamma_table\n");
  193196. if (png_ptr->bit_depth <= 8)
  193197. {
  193198. int i;
  193199. double g;
  193200. if (png_ptr->screen_gamma > .000001)
  193201. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193202. else
  193203. g = 1.0;
  193204. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193205. (png_uint_32)256);
  193206. for (i = 0; i < 256; i++)
  193207. {
  193208. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193209. g) * 255.0 + .5);
  193210. }
  193211. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193212. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193213. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193214. {
  193215. g = 1.0 / (png_ptr->gamma);
  193216. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193217. (png_uint_32)256);
  193218. for (i = 0; i < 256; i++)
  193219. {
  193220. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193221. g) * 255.0 + .5);
  193222. }
  193223. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193224. (png_uint_32)256);
  193225. if(png_ptr->screen_gamma > 0.000001)
  193226. g = 1.0 / png_ptr->screen_gamma;
  193227. else
  193228. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193229. for (i = 0; i < 256; i++)
  193230. {
  193231. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193232. g) * 255.0 + .5);
  193233. }
  193234. }
  193235. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193236. }
  193237. else
  193238. {
  193239. double g;
  193240. int i, j, shift, num;
  193241. int sig_bit;
  193242. png_uint_32 ig;
  193243. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193244. {
  193245. sig_bit = (int)png_ptr->sig_bit.red;
  193246. if ((int)png_ptr->sig_bit.green > sig_bit)
  193247. sig_bit = png_ptr->sig_bit.green;
  193248. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193249. sig_bit = png_ptr->sig_bit.blue;
  193250. }
  193251. else
  193252. {
  193253. sig_bit = (int)png_ptr->sig_bit.gray;
  193254. }
  193255. if (sig_bit > 0)
  193256. shift = 16 - sig_bit;
  193257. else
  193258. shift = 0;
  193259. if (png_ptr->transformations & PNG_16_TO_8)
  193260. {
  193261. if (shift < (16 - PNG_MAX_GAMMA_8))
  193262. shift = (16 - PNG_MAX_GAMMA_8);
  193263. }
  193264. if (shift > 8)
  193265. shift = 8;
  193266. if (shift < 0)
  193267. shift = 0;
  193268. png_ptr->gamma_shift = (png_byte)shift;
  193269. num = (1 << (8 - shift));
  193270. if (png_ptr->screen_gamma > .000001)
  193271. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193272. else
  193273. g = 1.0;
  193274. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193275. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193276. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193277. {
  193278. double fin, fout;
  193279. png_uint_32 last, max;
  193280. for (i = 0; i < num; i++)
  193281. {
  193282. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193283. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193284. }
  193285. g = 1.0 / g;
  193286. last = 0;
  193287. for (i = 0; i < 256; i++)
  193288. {
  193289. fout = ((double)i + 0.5) / 256.0;
  193290. fin = pow(fout, g);
  193291. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193292. while (last <= max)
  193293. {
  193294. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193295. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193296. (png_uint_16)i | ((png_uint_16)i << 8));
  193297. last++;
  193298. }
  193299. }
  193300. while (last < ((png_uint_32)num << 8))
  193301. {
  193302. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193303. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193304. last++;
  193305. }
  193306. }
  193307. else
  193308. {
  193309. for (i = 0; i < num; i++)
  193310. {
  193311. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193312. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193313. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193314. for (j = 0; j < 256; j++)
  193315. {
  193316. png_ptr->gamma_16_table[i][j] =
  193317. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193318. 65535.0, g) * 65535.0 + .5);
  193319. }
  193320. }
  193321. }
  193322. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193323. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193324. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193325. {
  193326. g = 1.0 / (png_ptr->gamma);
  193327. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193328. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193329. for (i = 0; i < num; i++)
  193330. {
  193331. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193332. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193333. ig = (((png_uint_32)i *
  193334. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193335. for (j = 0; j < 256; j++)
  193336. {
  193337. png_ptr->gamma_16_to_1[i][j] =
  193338. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193339. 65535.0, g) * 65535.0 + .5);
  193340. }
  193341. }
  193342. if(png_ptr->screen_gamma > 0.000001)
  193343. g = 1.0 / png_ptr->screen_gamma;
  193344. else
  193345. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193346. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193347. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193348. for (i = 0; i < num; i++)
  193349. {
  193350. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193351. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193352. ig = (((png_uint_32)i *
  193353. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193354. for (j = 0; j < 256; j++)
  193355. {
  193356. png_ptr->gamma_16_from_1[i][j] =
  193357. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193358. 65535.0, g) * 65535.0 + .5);
  193359. }
  193360. }
  193361. }
  193362. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193363. }
  193364. }
  193365. #endif
  193366. /* To do: install integer version of png_build_gamma_table here */
  193367. #endif
  193368. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193369. /* undoes intrapixel differencing */
  193370. void /* PRIVATE */
  193371. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193372. {
  193373. png_debug(1, "in png_do_read_intrapixel\n");
  193374. if (
  193375. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193376. row != NULL && row_info != NULL &&
  193377. #endif
  193378. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193379. {
  193380. int bytes_per_pixel;
  193381. png_uint_32 row_width = row_info->width;
  193382. if (row_info->bit_depth == 8)
  193383. {
  193384. png_bytep rp;
  193385. png_uint_32 i;
  193386. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193387. bytes_per_pixel = 3;
  193388. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193389. bytes_per_pixel = 4;
  193390. else
  193391. return;
  193392. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193393. {
  193394. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193395. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193396. }
  193397. }
  193398. else if (row_info->bit_depth == 16)
  193399. {
  193400. png_bytep rp;
  193401. png_uint_32 i;
  193402. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193403. bytes_per_pixel = 6;
  193404. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193405. bytes_per_pixel = 8;
  193406. else
  193407. return;
  193408. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193409. {
  193410. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193411. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193412. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193413. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193414. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193415. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193416. *(rp+1) = (png_byte)(red & 0xff);
  193417. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193418. *(rp+5) = (png_byte)(blue & 0xff);
  193419. }
  193420. }
  193421. }
  193422. }
  193423. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193424. #endif /* PNG_READ_SUPPORTED */
  193425. /*** End of inlined file: pngrtran.c ***/
  193426. /*** Start of inlined file: pngrutil.c ***/
  193427. /* pngrutil.c - utilities to read a PNG file
  193428. *
  193429. * Last changed in libpng 1.2.21 [October 4, 2007]
  193430. * For conditions of distribution and use, see copyright notice in png.h
  193431. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193432. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193433. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193434. *
  193435. * This file contains routines that are only called from within
  193436. * libpng itself during the course of reading an image.
  193437. */
  193438. #define PNG_INTERNAL
  193439. #if defined(PNG_READ_SUPPORTED)
  193440. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193441. # define WIN32_WCE_OLD
  193442. #endif
  193443. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193444. # if defined(WIN32_WCE_OLD)
  193445. /* strtod() function is not supported on WindowsCE */
  193446. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193447. {
  193448. double result = 0;
  193449. int len;
  193450. wchar_t *str, *end;
  193451. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193452. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193453. if ( NULL != str )
  193454. {
  193455. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193456. result = wcstod(str, &end);
  193457. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193458. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193459. png_free(png_ptr, str);
  193460. }
  193461. return result;
  193462. }
  193463. # else
  193464. # define png_strtod(p,a,b) strtod(a,b)
  193465. # endif
  193466. #endif
  193467. png_uint_32 PNGAPI
  193468. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193469. {
  193470. png_uint_32 i = png_get_uint_32(buf);
  193471. if (i > PNG_UINT_31_MAX)
  193472. png_error(png_ptr, "PNG unsigned integer out of range.");
  193473. return (i);
  193474. }
  193475. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193476. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193477. png_uint_32 PNGAPI
  193478. png_get_uint_32(png_bytep buf)
  193479. {
  193480. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193481. ((png_uint_32)(*(buf + 1)) << 16) +
  193482. ((png_uint_32)(*(buf + 2)) << 8) +
  193483. (png_uint_32)(*(buf + 3));
  193484. return (i);
  193485. }
  193486. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193487. * data is stored in the PNG file in two's complement format, and it is
  193488. * assumed that the machine format for signed integers is the same. */
  193489. png_int_32 PNGAPI
  193490. png_get_int_32(png_bytep buf)
  193491. {
  193492. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193493. ((png_int_32)(*(buf + 1)) << 16) +
  193494. ((png_int_32)(*(buf + 2)) << 8) +
  193495. (png_int_32)(*(buf + 3));
  193496. return (i);
  193497. }
  193498. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193499. png_uint_16 PNGAPI
  193500. png_get_uint_16(png_bytep buf)
  193501. {
  193502. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193503. (png_uint_16)(*(buf + 1)));
  193504. return (i);
  193505. }
  193506. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193507. /* Read data, and (optionally) run it through the CRC. */
  193508. void /* PRIVATE */
  193509. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193510. {
  193511. if(png_ptr == NULL) return;
  193512. png_read_data(png_ptr, buf, length);
  193513. png_calculate_crc(png_ptr, buf, length);
  193514. }
  193515. /* Optionally skip data and then check the CRC. Depending on whether we
  193516. are reading a ancillary or critical chunk, and how the program has set
  193517. things up, we may calculate the CRC on the data and print a message.
  193518. Returns '1' if there was a CRC error, '0' otherwise. */
  193519. int /* PRIVATE */
  193520. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193521. {
  193522. png_size_t i;
  193523. png_size_t istop = png_ptr->zbuf_size;
  193524. for (i = (png_size_t)skip; i > istop; i -= istop)
  193525. {
  193526. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193527. }
  193528. if (i)
  193529. {
  193530. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193531. }
  193532. if (png_crc_error(png_ptr))
  193533. {
  193534. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193535. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193536. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193537. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193538. {
  193539. png_chunk_warning(png_ptr, "CRC error");
  193540. }
  193541. else
  193542. {
  193543. png_chunk_error(png_ptr, "CRC error");
  193544. }
  193545. return (1);
  193546. }
  193547. return (0);
  193548. }
  193549. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193550. the data it has read thus far. */
  193551. int /* PRIVATE */
  193552. png_crc_error(png_structp png_ptr)
  193553. {
  193554. png_byte crc_bytes[4];
  193555. png_uint_32 crc;
  193556. int need_crc = 1;
  193557. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193558. {
  193559. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193560. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193561. need_crc = 0;
  193562. }
  193563. else /* critical */
  193564. {
  193565. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193566. need_crc = 0;
  193567. }
  193568. png_read_data(png_ptr, crc_bytes, 4);
  193569. if (need_crc)
  193570. {
  193571. crc = png_get_uint_32(crc_bytes);
  193572. return ((int)(crc != png_ptr->crc));
  193573. }
  193574. else
  193575. return (0);
  193576. }
  193577. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193578. defined(PNG_READ_iCCP_SUPPORTED)
  193579. /*
  193580. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193581. * points at an allocated area holding the contents of a chunk with a
  193582. * trailing compressed part. What we get back is an allocated area
  193583. * holding the original prefix part and an uncompressed version of the
  193584. * trailing part (the malloc area passed in is freed).
  193585. */
  193586. png_charp /* PRIVATE */
  193587. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193588. png_charp chunkdata, png_size_t chunklength,
  193589. png_size_t prefix_size, png_size_t *newlength)
  193590. {
  193591. static PNG_CONST char msg[] = "Error decoding compressed text";
  193592. png_charp text;
  193593. png_size_t text_size;
  193594. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193595. {
  193596. int ret = Z_OK;
  193597. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193598. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193599. png_ptr->zstream.next_out = png_ptr->zbuf;
  193600. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193601. text_size = 0;
  193602. text = NULL;
  193603. while (png_ptr->zstream.avail_in)
  193604. {
  193605. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193606. if (ret != Z_OK && ret != Z_STREAM_END)
  193607. {
  193608. if (png_ptr->zstream.msg != NULL)
  193609. png_warning(png_ptr, png_ptr->zstream.msg);
  193610. else
  193611. png_warning(png_ptr, msg);
  193612. inflateReset(&png_ptr->zstream);
  193613. png_ptr->zstream.avail_in = 0;
  193614. if (text == NULL)
  193615. {
  193616. text_size = prefix_size + png_sizeof(msg) + 1;
  193617. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193618. if (text == NULL)
  193619. {
  193620. png_free(png_ptr,chunkdata);
  193621. png_error(png_ptr,"Not enough memory to decompress chunk");
  193622. }
  193623. png_memcpy(text, chunkdata, prefix_size);
  193624. }
  193625. text[text_size - 1] = 0x00;
  193626. /* Copy what we can of the error message into the text chunk */
  193627. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193628. text_size = png_sizeof(msg) > text_size ? text_size :
  193629. png_sizeof(msg);
  193630. png_memcpy(text + prefix_size, msg, text_size + 1);
  193631. break;
  193632. }
  193633. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193634. {
  193635. if (text == NULL)
  193636. {
  193637. text_size = prefix_size +
  193638. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193639. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193640. if (text == NULL)
  193641. {
  193642. png_free(png_ptr,chunkdata);
  193643. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193644. }
  193645. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193646. text_size - prefix_size);
  193647. png_memcpy(text, chunkdata, prefix_size);
  193648. *(text + text_size) = 0x00;
  193649. }
  193650. else
  193651. {
  193652. png_charp tmp;
  193653. tmp = text;
  193654. text = (png_charp)png_malloc_warn(png_ptr,
  193655. (png_uint_32)(text_size +
  193656. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193657. if (text == NULL)
  193658. {
  193659. png_free(png_ptr, tmp);
  193660. png_free(png_ptr, chunkdata);
  193661. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193662. }
  193663. png_memcpy(text, tmp, text_size);
  193664. png_free(png_ptr, tmp);
  193665. png_memcpy(text + text_size, png_ptr->zbuf,
  193666. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193667. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193668. *(text + text_size) = 0x00;
  193669. }
  193670. if (ret == Z_STREAM_END)
  193671. break;
  193672. else
  193673. {
  193674. png_ptr->zstream.next_out = png_ptr->zbuf;
  193675. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193676. }
  193677. }
  193678. }
  193679. if (ret != Z_STREAM_END)
  193680. {
  193681. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193682. char umsg[52];
  193683. if (ret == Z_BUF_ERROR)
  193684. png_snprintf(umsg, 52,
  193685. "Buffer error in compressed datastream in %s chunk",
  193686. png_ptr->chunk_name);
  193687. else if (ret == Z_DATA_ERROR)
  193688. png_snprintf(umsg, 52,
  193689. "Data error in compressed datastream in %s chunk",
  193690. png_ptr->chunk_name);
  193691. else
  193692. png_snprintf(umsg, 52,
  193693. "Incomplete compressed datastream in %s chunk",
  193694. png_ptr->chunk_name);
  193695. png_warning(png_ptr, umsg);
  193696. #else
  193697. png_warning(png_ptr,
  193698. "Incomplete compressed datastream in chunk other than IDAT");
  193699. #endif
  193700. text_size=prefix_size;
  193701. if (text == NULL)
  193702. {
  193703. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193704. if (text == NULL)
  193705. {
  193706. png_free(png_ptr, chunkdata);
  193707. png_error(png_ptr,"Not enough memory for text.");
  193708. }
  193709. png_memcpy(text, chunkdata, prefix_size);
  193710. }
  193711. *(text + text_size) = 0x00;
  193712. }
  193713. inflateReset(&png_ptr->zstream);
  193714. png_ptr->zstream.avail_in = 0;
  193715. png_free(png_ptr, chunkdata);
  193716. chunkdata = text;
  193717. *newlength=text_size;
  193718. }
  193719. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193720. {
  193721. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193722. char umsg[50];
  193723. png_snprintf(umsg, 50,
  193724. "Unknown zTXt compression type %d", comp_type);
  193725. png_warning(png_ptr, umsg);
  193726. #else
  193727. png_warning(png_ptr, "Unknown zTXt compression type");
  193728. #endif
  193729. *(chunkdata + prefix_size) = 0x00;
  193730. *newlength=prefix_size;
  193731. }
  193732. return chunkdata;
  193733. }
  193734. #endif
  193735. /* read and check the IDHR chunk */
  193736. void /* PRIVATE */
  193737. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193738. {
  193739. png_byte buf[13];
  193740. png_uint_32 width, height;
  193741. int bit_depth, color_type, compression_type, filter_type;
  193742. int interlace_type;
  193743. png_debug(1, "in png_handle_IHDR\n");
  193744. if (png_ptr->mode & PNG_HAVE_IHDR)
  193745. png_error(png_ptr, "Out of place IHDR");
  193746. /* check the length */
  193747. if (length != 13)
  193748. png_error(png_ptr, "Invalid IHDR chunk");
  193749. png_ptr->mode |= PNG_HAVE_IHDR;
  193750. png_crc_read(png_ptr, buf, 13);
  193751. png_crc_finish(png_ptr, 0);
  193752. width = png_get_uint_31(png_ptr, buf);
  193753. height = png_get_uint_31(png_ptr, buf + 4);
  193754. bit_depth = buf[8];
  193755. color_type = buf[9];
  193756. compression_type = buf[10];
  193757. filter_type = buf[11];
  193758. interlace_type = buf[12];
  193759. /* set internal variables */
  193760. png_ptr->width = width;
  193761. png_ptr->height = height;
  193762. png_ptr->bit_depth = (png_byte)bit_depth;
  193763. png_ptr->interlaced = (png_byte)interlace_type;
  193764. png_ptr->color_type = (png_byte)color_type;
  193765. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193766. png_ptr->filter_type = (png_byte)filter_type;
  193767. #endif
  193768. png_ptr->compression_type = (png_byte)compression_type;
  193769. /* find number of channels */
  193770. switch (png_ptr->color_type)
  193771. {
  193772. case PNG_COLOR_TYPE_GRAY:
  193773. case PNG_COLOR_TYPE_PALETTE:
  193774. png_ptr->channels = 1;
  193775. break;
  193776. case PNG_COLOR_TYPE_RGB:
  193777. png_ptr->channels = 3;
  193778. break;
  193779. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193780. png_ptr->channels = 2;
  193781. break;
  193782. case PNG_COLOR_TYPE_RGB_ALPHA:
  193783. png_ptr->channels = 4;
  193784. break;
  193785. }
  193786. /* set up other useful info */
  193787. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193788. png_ptr->channels);
  193789. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193790. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193791. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193792. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193793. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193794. color_type, interlace_type, compression_type, filter_type);
  193795. }
  193796. /* read and check the palette */
  193797. void /* PRIVATE */
  193798. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193799. {
  193800. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193801. int num, i;
  193802. #ifndef PNG_NO_POINTER_INDEXING
  193803. png_colorp pal_ptr;
  193804. #endif
  193805. png_debug(1, "in png_handle_PLTE\n");
  193806. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193807. png_error(png_ptr, "Missing IHDR before PLTE");
  193808. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193809. {
  193810. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193811. png_crc_finish(png_ptr, length);
  193812. return;
  193813. }
  193814. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193815. png_error(png_ptr, "Duplicate PLTE chunk");
  193816. png_ptr->mode |= PNG_HAVE_PLTE;
  193817. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193818. {
  193819. png_warning(png_ptr,
  193820. "Ignoring PLTE chunk in grayscale PNG");
  193821. png_crc_finish(png_ptr, length);
  193822. return;
  193823. }
  193824. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193825. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193826. {
  193827. png_crc_finish(png_ptr, length);
  193828. return;
  193829. }
  193830. #endif
  193831. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193832. {
  193833. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193834. {
  193835. png_warning(png_ptr, "Invalid palette chunk");
  193836. png_crc_finish(png_ptr, length);
  193837. return;
  193838. }
  193839. else
  193840. {
  193841. png_error(png_ptr, "Invalid palette chunk");
  193842. }
  193843. }
  193844. num = (int)length / 3;
  193845. #ifndef PNG_NO_POINTER_INDEXING
  193846. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193847. {
  193848. png_byte buf[3];
  193849. png_crc_read(png_ptr, buf, 3);
  193850. pal_ptr->red = buf[0];
  193851. pal_ptr->green = buf[1];
  193852. pal_ptr->blue = buf[2];
  193853. }
  193854. #else
  193855. for (i = 0; i < num; i++)
  193856. {
  193857. png_byte buf[3];
  193858. png_crc_read(png_ptr, buf, 3);
  193859. /* don't depend upon png_color being any order */
  193860. palette[i].red = buf[0];
  193861. palette[i].green = buf[1];
  193862. palette[i].blue = buf[2];
  193863. }
  193864. #endif
  193865. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193866. whatever the normal CRC configuration tells us. However, if we
  193867. have an RGB image, the PLTE can be considered ancillary, so
  193868. we will act as though it is. */
  193869. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193870. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193871. #endif
  193872. {
  193873. png_crc_finish(png_ptr, 0);
  193874. }
  193875. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193876. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193877. {
  193878. /* If we don't want to use the data from an ancillary chunk,
  193879. we have two options: an error abort, or a warning and we
  193880. ignore the data in this chunk (which should be OK, since
  193881. it's considered ancillary for a RGB or RGBA image). */
  193882. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193883. {
  193884. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193885. {
  193886. png_chunk_error(png_ptr, "CRC error");
  193887. }
  193888. else
  193889. {
  193890. png_chunk_warning(png_ptr, "CRC error");
  193891. return;
  193892. }
  193893. }
  193894. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193895. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193896. {
  193897. png_chunk_warning(png_ptr, "CRC error");
  193898. }
  193899. }
  193900. #endif
  193901. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193902. #if defined(PNG_READ_tRNS_SUPPORTED)
  193903. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193904. {
  193905. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193906. {
  193907. if (png_ptr->num_trans > (png_uint_16)num)
  193908. {
  193909. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193910. png_ptr->num_trans = (png_uint_16)num;
  193911. }
  193912. if (info_ptr->num_trans > (png_uint_16)num)
  193913. {
  193914. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193915. info_ptr->num_trans = (png_uint_16)num;
  193916. }
  193917. }
  193918. }
  193919. #endif
  193920. }
  193921. void /* PRIVATE */
  193922. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193923. {
  193924. png_debug(1, "in png_handle_IEND\n");
  193925. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193926. {
  193927. png_error(png_ptr, "No image in file");
  193928. }
  193929. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193930. if (length != 0)
  193931. {
  193932. png_warning(png_ptr, "Incorrect IEND chunk length");
  193933. }
  193934. png_crc_finish(png_ptr, length);
  193935. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193936. }
  193937. #if defined(PNG_READ_gAMA_SUPPORTED)
  193938. void /* PRIVATE */
  193939. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193940. {
  193941. png_fixed_point igamma;
  193942. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193943. float file_gamma;
  193944. #endif
  193945. png_byte buf[4];
  193946. png_debug(1, "in png_handle_gAMA\n");
  193947. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193948. png_error(png_ptr, "Missing IHDR before gAMA");
  193949. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193950. {
  193951. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193952. png_crc_finish(png_ptr, length);
  193953. return;
  193954. }
  193955. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193956. /* Should be an error, but we can cope with it */
  193957. png_warning(png_ptr, "Out of place gAMA chunk");
  193958. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193959. #if defined(PNG_READ_sRGB_SUPPORTED)
  193960. && !(info_ptr->valid & PNG_INFO_sRGB)
  193961. #endif
  193962. )
  193963. {
  193964. png_warning(png_ptr, "Duplicate gAMA chunk");
  193965. png_crc_finish(png_ptr, length);
  193966. return;
  193967. }
  193968. if (length != 4)
  193969. {
  193970. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193971. png_crc_finish(png_ptr, length);
  193972. return;
  193973. }
  193974. png_crc_read(png_ptr, buf, 4);
  193975. if (png_crc_finish(png_ptr, 0))
  193976. return;
  193977. igamma = (png_fixed_point)png_get_uint_32(buf);
  193978. /* check for zero gamma */
  193979. if (igamma == 0)
  193980. {
  193981. png_warning(png_ptr,
  193982. "Ignoring gAMA chunk with gamma=0");
  193983. return;
  193984. }
  193985. #if defined(PNG_READ_sRGB_SUPPORTED)
  193986. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193987. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193988. {
  193989. png_warning(png_ptr,
  193990. "Ignoring incorrect gAMA value when sRGB is also present");
  193991. #ifndef PNG_NO_CONSOLE_IO
  193992. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193993. #endif
  193994. return;
  193995. }
  193996. #endif /* PNG_READ_sRGB_SUPPORTED */
  193997. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193998. file_gamma = (float)igamma / (float)100000.0;
  193999. # ifdef PNG_READ_GAMMA_SUPPORTED
  194000. png_ptr->gamma = file_gamma;
  194001. # endif
  194002. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194003. #endif
  194004. #ifdef PNG_FIXED_POINT_SUPPORTED
  194005. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194006. #endif
  194007. }
  194008. #endif
  194009. #if defined(PNG_READ_sBIT_SUPPORTED)
  194010. void /* PRIVATE */
  194011. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194012. {
  194013. png_size_t truelen;
  194014. png_byte buf[4];
  194015. png_debug(1, "in png_handle_sBIT\n");
  194016. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194017. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194018. png_error(png_ptr, "Missing IHDR before sBIT");
  194019. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194020. {
  194021. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194022. png_crc_finish(png_ptr, length);
  194023. return;
  194024. }
  194025. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194026. {
  194027. /* Should be an error, but we can cope with it */
  194028. png_warning(png_ptr, "Out of place sBIT chunk");
  194029. }
  194030. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194031. {
  194032. png_warning(png_ptr, "Duplicate sBIT chunk");
  194033. png_crc_finish(png_ptr, length);
  194034. return;
  194035. }
  194036. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194037. truelen = 3;
  194038. else
  194039. truelen = (png_size_t)png_ptr->channels;
  194040. if (length != truelen || length > 4)
  194041. {
  194042. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194043. png_crc_finish(png_ptr, length);
  194044. return;
  194045. }
  194046. png_crc_read(png_ptr, buf, truelen);
  194047. if (png_crc_finish(png_ptr, 0))
  194048. return;
  194049. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194050. {
  194051. png_ptr->sig_bit.red = buf[0];
  194052. png_ptr->sig_bit.green = buf[1];
  194053. png_ptr->sig_bit.blue = buf[2];
  194054. png_ptr->sig_bit.alpha = buf[3];
  194055. }
  194056. else
  194057. {
  194058. png_ptr->sig_bit.gray = buf[0];
  194059. png_ptr->sig_bit.red = buf[0];
  194060. png_ptr->sig_bit.green = buf[0];
  194061. png_ptr->sig_bit.blue = buf[0];
  194062. png_ptr->sig_bit.alpha = buf[1];
  194063. }
  194064. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194065. }
  194066. #endif
  194067. #if defined(PNG_READ_cHRM_SUPPORTED)
  194068. void /* PRIVATE */
  194069. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194070. {
  194071. png_byte buf[4];
  194072. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194073. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194074. #endif
  194075. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194076. int_y_green, int_x_blue, int_y_blue;
  194077. png_uint_32 uint_x, uint_y;
  194078. png_debug(1, "in png_handle_cHRM\n");
  194079. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194080. png_error(png_ptr, "Missing IHDR before cHRM");
  194081. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194082. {
  194083. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194084. png_crc_finish(png_ptr, length);
  194085. return;
  194086. }
  194087. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194088. /* Should be an error, but we can cope with it */
  194089. png_warning(png_ptr, "Missing PLTE before cHRM");
  194090. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194091. #if defined(PNG_READ_sRGB_SUPPORTED)
  194092. && !(info_ptr->valid & PNG_INFO_sRGB)
  194093. #endif
  194094. )
  194095. {
  194096. png_warning(png_ptr, "Duplicate cHRM chunk");
  194097. png_crc_finish(png_ptr, length);
  194098. return;
  194099. }
  194100. if (length != 32)
  194101. {
  194102. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194103. png_crc_finish(png_ptr, length);
  194104. return;
  194105. }
  194106. png_crc_read(png_ptr, buf, 4);
  194107. uint_x = png_get_uint_32(buf);
  194108. png_crc_read(png_ptr, buf, 4);
  194109. uint_y = png_get_uint_32(buf);
  194110. if (uint_x > 80000L || uint_y > 80000L ||
  194111. uint_x + uint_y > 100000L)
  194112. {
  194113. png_warning(png_ptr, "Invalid cHRM white point");
  194114. png_crc_finish(png_ptr, 24);
  194115. return;
  194116. }
  194117. int_x_white = (png_fixed_point)uint_x;
  194118. int_y_white = (png_fixed_point)uint_y;
  194119. png_crc_read(png_ptr, buf, 4);
  194120. uint_x = png_get_uint_32(buf);
  194121. png_crc_read(png_ptr, buf, 4);
  194122. uint_y = png_get_uint_32(buf);
  194123. if (uint_x + uint_y > 100000L)
  194124. {
  194125. png_warning(png_ptr, "Invalid cHRM red point");
  194126. png_crc_finish(png_ptr, 16);
  194127. return;
  194128. }
  194129. int_x_red = (png_fixed_point)uint_x;
  194130. int_y_red = (png_fixed_point)uint_y;
  194131. png_crc_read(png_ptr, buf, 4);
  194132. uint_x = png_get_uint_32(buf);
  194133. png_crc_read(png_ptr, buf, 4);
  194134. uint_y = png_get_uint_32(buf);
  194135. if (uint_x + uint_y > 100000L)
  194136. {
  194137. png_warning(png_ptr, "Invalid cHRM green point");
  194138. png_crc_finish(png_ptr, 8);
  194139. return;
  194140. }
  194141. int_x_green = (png_fixed_point)uint_x;
  194142. int_y_green = (png_fixed_point)uint_y;
  194143. png_crc_read(png_ptr, buf, 4);
  194144. uint_x = png_get_uint_32(buf);
  194145. png_crc_read(png_ptr, buf, 4);
  194146. uint_y = png_get_uint_32(buf);
  194147. if (uint_x + uint_y > 100000L)
  194148. {
  194149. png_warning(png_ptr, "Invalid cHRM blue point");
  194150. png_crc_finish(png_ptr, 0);
  194151. return;
  194152. }
  194153. int_x_blue = (png_fixed_point)uint_x;
  194154. int_y_blue = (png_fixed_point)uint_y;
  194155. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194156. white_x = (float)int_x_white / (float)100000.0;
  194157. white_y = (float)int_y_white / (float)100000.0;
  194158. red_x = (float)int_x_red / (float)100000.0;
  194159. red_y = (float)int_y_red / (float)100000.0;
  194160. green_x = (float)int_x_green / (float)100000.0;
  194161. green_y = (float)int_y_green / (float)100000.0;
  194162. blue_x = (float)int_x_blue / (float)100000.0;
  194163. blue_y = (float)int_y_blue / (float)100000.0;
  194164. #endif
  194165. #if defined(PNG_READ_sRGB_SUPPORTED)
  194166. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194167. {
  194168. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194169. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194170. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194171. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194172. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194173. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194174. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194175. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194176. {
  194177. png_warning(png_ptr,
  194178. "Ignoring incorrect cHRM value when sRGB is also present");
  194179. #ifndef PNG_NO_CONSOLE_IO
  194180. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194181. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194182. white_x, white_y, red_x, red_y);
  194183. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194184. green_x, green_y, blue_x, blue_y);
  194185. #else
  194186. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194187. int_x_white, int_y_white, int_x_red, int_y_red);
  194188. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194189. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194190. #endif
  194191. #endif /* PNG_NO_CONSOLE_IO */
  194192. }
  194193. png_crc_finish(png_ptr, 0);
  194194. return;
  194195. }
  194196. #endif /* PNG_READ_sRGB_SUPPORTED */
  194197. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194198. png_set_cHRM(png_ptr, info_ptr,
  194199. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194200. #endif
  194201. #ifdef PNG_FIXED_POINT_SUPPORTED
  194202. png_set_cHRM_fixed(png_ptr, info_ptr,
  194203. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194204. int_y_green, int_x_blue, int_y_blue);
  194205. #endif
  194206. if (png_crc_finish(png_ptr, 0))
  194207. return;
  194208. }
  194209. #endif
  194210. #if defined(PNG_READ_sRGB_SUPPORTED)
  194211. void /* PRIVATE */
  194212. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194213. {
  194214. int intent;
  194215. png_byte buf[1];
  194216. png_debug(1, "in png_handle_sRGB\n");
  194217. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194218. png_error(png_ptr, "Missing IHDR before sRGB");
  194219. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194220. {
  194221. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194222. png_crc_finish(png_ptr, length);
  194223. return;
  194224. }
  194225. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194226. /* Should be an error, but we can cope with it */
  194227. png_warning(png_ptr, "Out of place sRGB chunk");
  194228. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194229. {
  194230. png_warning(png_ptr, "Duplicate sRGB chunk");
  194231. png_crc_finish(png_ptr, length);
  194232. return;
  194233. }
  194234. if (length != 1)
  194235. {
  194236. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194237. png_crc_finish(png_ptr, length);
  194238. return;
  194239. }
  194240. png_crc_read(png_ptr, buf, 1);
  194241. if (png_crc_finish(png_ptr, 0))
  194242. return;
  194243. intent = buf[0];
  194244. /* check for bad intent */
  194245. if (intent >= PNG_sRGB_INTENT_LAST)
  194246. {
  194247. png_warning(png_ptr, "Unknown sRGB intent");
  194248. return;
  194249. }
  194250. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194251. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194252. {
  194253. png_fixed_point igamma;
  194254. #ifdef PNG_FIXED_POINT_SUPPORTED
  194255. igamma=info_ptr->int_gamma;
  194256. #else
  194257. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194258. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194259. # endif
  194260. #endif
  194261. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194262. {
  194263. png_warning(png_ptr,
  194264. "Ignoring incorrect gAMA value when sRGB is also present");
  194265. #ifndef PNG_NO_CONSOLE_IO
  194266. # ifdef PNG_FIXED_POINT_SUPPORTED
  194267. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194268. # else
  194269. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194270. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194271. # endif
  194272. # endif
  194273. #endif
  194274. }
  194275. }
  194276. #endif /* PNG_READ_gAMA_SUPPORTED */
  194277. #ifdef PNG_READ_cHRM_SUPPORTED
  194278. #ifdef PNG_FIXED_POINT_SUPPORTED
  194279. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194280. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194281. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194282. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194283. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194284. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194285. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194286. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194287. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194288. {
  194289. png_warning(png_ptr,
  194290. "Ignoring incorrect cHRM value when sRGB is also present");
  194291. }
  194292. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194293. #endif /* PNG_READ_cHRM_SUPPORTED */
  194294. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194295. }
  194296. #endif /* PNG_READ_sRGB_SUPPORTED */
  194297. #if defined(PNG_READ_iCCP_SUPPORTED)
  194298. void /* PRIVATE */
  194299. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194300. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194301. {
  194302. png_charp chunkdata;
  194303. png_byte compression_type;
  194304. png_bytep pC;
  194305. png_charp profile;
  194306. png_uint_32 skip = 0;
  194307. png_uint_32 profile_size, profile_length;
  194308. png_size_t slength, prefix_length, data_length;
  194309. png_debug(1, "in png_handle_iCCP\n");
  194310. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194311. png_error(png_ptr, "Missing IHDR before iCCP");
  194312. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194313. {
  194314. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194315. png_crc_finish(png_ptr, length);
  194316. return;
  194317. }
  194318. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194319. /* Should be an error, but we can cope with it */
  194320. png_warning(png_ptr, "Out of place iCCP chunk");
  194321. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194322. {
  194323. png_warning(png_ptr, "Duplicate iCCP chunk");
  194324. png_crc_finish(png_ptr, length);
  194325. return;
  194326. }
  194327. #ifdef PNG_MAX_MALLOC_64K
  194328. if (length > (png_uint_32)65535L)
  194329. {
  194330. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194331. skip = length - (png_uint_32)65535L;
  194332. length = (png_uint_32)65535L;
  194333. }
  194334. #endif
  194335. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194336. slength = (png_size_t)length;
  194337. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194338. if (png_crc_finish(png_ptr, skip))
  194339. {
  194340. png_free(png_ptr, chunkdata);
  194341. return;
  194342. }
  194343. chunkdata[slength] = 0x00;
  194344. for (profile = chunkdata; *profile; profile++)
  194345. /* empty loop to find end of name */ ;
  194346. ++profile;
  194347. /* there should be at least one zero (the compression type byte)
  194348. following the separator, and we should be on it */
  194349. if ( profile >= chunkdata + slength - 1)
  194350. {
  194351. png_free(png_ptr, chunkdata);
  194352. png_warning(png_ptr, "Malformed iCCP chunk");
  194353. return;
  194354. }
  194355. /* compression_type should always be zero */
  194356. compression_type = *profile++;
  194357. if (compression_type)
  194358. {
  194359. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194360. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194361. wrote nonzero) */
  194362. }
  194363. prefix_length = profile - chunkdata;
  194364. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194365. slength, prefix_length, &data_length);
  194366. profile_length = data_length - prefix_length;
  194367. if ( prefix_length > data_length || profile_length < 4)
  194368. {
  194369. png_free(png_ptr, chunkdata);
  194370. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194371. return;
  194372. }
  194373. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194374. pC = (png_bytep)(chunkdata+prefix_length);
  194375. profile_size = ((*(pC ))<<24) |
  194376. ((*(pC+1))<<16) |
  194377. ((*(pC+2))<< 8) |
  194378. ((*(pC+3)) );
  194379. if(profile_size < profile_length)
  194380. profile_length = profile_size;
  194381. if(profile_size > profile_length)
  194382. {
  194383. png_free(png_ptr, chunkdata);
  194384. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194385. return;
  194386. }
  194387. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194388. chunkdata + prefix_length, profile_length);
  194389. png_free(png_ptr, chunkdata);
  194390. }
  194391. #endif /* PNG_READ_iCCP_SUPPORTED */
  194392. #if defined(PNG_READ_sPLT_SUPPORTED)
  194393. void /* PRIVATE */
  194394. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194395. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194396. {
  194397. png_bytep chunkdata;
  194398. png_bytep entry_start;
  194399. png_sPLT_t new_palette;
  194400. #ifdef PNG_NO_POINTER_INDEXING
  194401. png_sPLT_entryp pp;
  194402. #endif
  194403. int data_length, entry_size, i;
  194404. png_uint_32 skip = 0;
  194405. png_size_t slength;
  194406. png_debug(1, "in png_handle_sPLT\n");
  194407. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194408. png_error(png_ptr, "Missing IHDR before sPLT");
  194409. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194410. {
  194411. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194412. png_crc_finish(png_ptr, length);
  194413. return;
  194414. }
  194415. #ifdef PNG_MAX_MALLOC_64K
  194416. if (length > (png_uint_32)65535L)
  194417. {
  194418. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194419. skip = length - (png_uint_32)65535L;
  194420. length = (png_uint_32)65535L;
  194421. }
  194422. #endif
  194423. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194424. slength = (png_size_t)length;
  194425. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194426. if (png_crc_finish(png_ptr, skip))
  194427. {
  194428. png_free(png_ptr, chunkdata);
  194429. return;
  194430. }
  194431. chunkdata[slength] = 0x00;
  194432. for (entry_start = chunkdata; *entry_start; entry_start++)
  194433. /* empty loop to find end of name */ ;
  194434. ++entry_start;
  194435. /* a sample depth should follow the separator, and we should be on it */
  194436. if (entry_start > chunkdata + slength - 2)
  194437. {
  194438. png_free(png_ptr, chunkdata);
  194439. png_warning(png_ptr, "malformed sPLT chunk");
  194440. return;
  194441. }
  194442. new_palette.depth = *entry_start++;
  194443. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194444. data_length = (slength - (entry_start - chunkdata));
  194445. /* integrity-check the data length */
  194446. if (data_length % entry_size)
  194447. {
  194448. png_free(png_ptr, chunkdata);
  194449. png_warning(png_ptr, "sPLT chunk has bad length");
  194450. return;
  194451. }
  194452. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194453. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194454. png_sizeof(png_sPLT_entry)))
  194455. {
  194456. png_warning(png_ptr, "sPLT chunk too long");
  194457. return;
  194458. }
  194459. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194460. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194461. if (new_palette.entries == NULL)
  194462. {
  194463. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194464. return;
  194465. }
  194466. #ifndef PNG_NO_POINTER_INDEXING
  194467. for (i = 0; i < new_palette.nentries; i++)
  194468. {
  194469. png_sPLT_entryp pp = new_palette.entries + i;
  194470. if (new_palette.depth == 8)
  194471. {
  194472. pp->red = *entry_start++;
  194473. pp->green = *entry_start++;
  194474. pp->blue = *entry_start++;
  194475. pp->alpha = *entry_start++;
  194476. }
  194477. else
  194478. {
  194479. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194480. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194481. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194482. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194483. }
  194484. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194485. }
  194486. #else
  194487. pp = new_palette.entries;
  194488. for (i = 0; i < new_palette.nentries; i++)
  194489. {
  194490. if (new_palette.depth == 8)
  194491. {
  194492. pp[i].red = *entry_start++;
  194493. pp[i].green = *entry_start++;
  194494. pp[i].blue = *entry_start++;
  194495. pp[i].alpha = *entry_start++;
  194496. }
  194497. else
  194498. {
  194499. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194500. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194501. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194502. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194503. }
  194504. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194505. }
  194506. #endif
  194507. /* discard all chunk data except the name and stash that */
  194508. new_palette.name = (png_charp)chunkdata;
  194509. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194510. png_free(png_ptr, chunkdata);
  194511. png_free(png_ptr, new_palette.entries);
  194512. }
  194513. #endif /* PNG_READ_sPLT_SUPPORTED */
  194514. #if defined(PNG_READ_tRNS_SUPPORTED)
  194515. void /* PRIVATE */
  194516. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194517. {
  194518. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194519. int bit_mask;
  194520. png_debug(1, "in png_handle_tRNS\n");
  194521. /* For non-indexed color, mask off any bits in the tRNS value that
  194522. * exceed the bit depth. Some creators were writing extra bits there.
  194523. * This is not needed for indexed color. */
  194524. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194525. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194526. png_error(png_ptr, "Missing IHDR before tRNS");
  194527. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194528. {
  194529. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194530. png_crc_finish(png_ptr, length);
  194531. return;
  194532. }
  194533. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194534. {
  194535. png_warning(png_ptr, "Duplicate tRNS chunk");
  194536. png_crc_finish(png_ptr, length);
  194537. return;
  194538. }
  194539. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194540. {
  194541. png_byte buf[2];
  194542. if (length != 2)
  194543. {
  194544. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194545. png_crc_finish(png_ptr, length);
  194546. return;
  194547. }
  194548. png_crc_read(png_ptr, buf, 2);
  194549. png_ptr->num_trans = 1;
  194550. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194551. }
  194552. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194553. {
  194554. png_byte buf[6];
  194555. if (length != 6)
  194556. {
  194557. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194558. png_crc_finish(png_ptr, length);
  194559. return;
  194560. }
  194561. png_crc_read(png_ptr, buf, (png_size_t)length);
  194562. png_ptr->num_trans = 1;
  194563. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194564. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194565. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194566. }
  194567. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194568. {
  194569. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194570. {
  194571. /* Should be an error, but we can cope with it. */
  194572. png_warning(png_ptr, "Missing PLTE before tRNS");
  194573. }
  194574. if (length > (png_uint_32)png_ptr->num_palette ||
  194575. length > PNG_MAX_PALETTE_LENGTH)
  194576. {
  194577. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194578. png_crc_finish(png_ptr, length);
  194579. return;
  194580. }
  194581. if (length == 0)
  194582. {
  194583. png_warning(png_ptr, "Zero length tRNS chunk");
  194584. png_crc_finish(png_ptr, length);
  194585. return;
  194586. }
  194587. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194588. png_ptr->num_trans = (png_uint_16)length;
  194589. }
  194590. else
  194591. {
  194592. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194593. png_crc_finish(png_ptr, length);
  194594. return;
  194595. }
  194596. if (png_crc_finish(png_ptr, 0))
  194597. {
  194598. png_ptr->num_trans = 0;
  194599. return;
  194600. }
  194601. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194602. &(png_ptr->trans_values));
  194603. }
  194604. #endif
  194605. #if defined(PNG_READ_bKGD_SUPPORTED)
  194606. void /* PRIVATE */
  194607. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194608. {
  194609. png_size_t truelen;
  194610. png_byte buf[6];
  194611. png_debug(1, "in png_handle_bKGD\n");
  194612. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194613. png_error(png_ptr, "Missing IHDR before bKGD");
  194614. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194615. {
  194616. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194617. png_crc_finish(png_ptr, length);
  194618. return;
  194619. }
  194620. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194621. !(png_ptr->mode & PNG_HAVE_PLTE))
  194622. {
  194623. png_warning(png_ptr, "Missing PLTE before bKGD");
  194624. png_crc_finish(png_ptr, length);
  194625. return;
  194626. }
  194627. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194628. {
  194629. png_warning(png_ptr, "Duplicate bKGD chunk");
  194630. png_crc_finish(png_ptr, length);
  194631. return;
  194632. }
  194633. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194634. truelen = 1;
  194635. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194636. truelen = 6;
  194637. else
  194638. truelen = 2;
  194639. if (length != truelen)
  194640. {
  194641. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194642. png_crc_finish(png_ptr, length);
  194643. return;
  194644. }
  194645. png_crc_read(png_ptr, buf, truelen);
  194646. if (png_crc_finish(png_ptr, 0))
  194647. return;
  194648. /* We convert the index value into RGB components so that we can allow
  194649. * arbitrary RGB values for background when we have transparency, and
  194650. * so it is easy to determine the RGB values of the background color
  194651. * from the info_ptr struct. */
  194652. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194653. {
  194654. png_ptr->background.index = buf[0];
  194655. if(info_ptr->num_palette)
  194656. {
  194657. if(buf[0] > info_ptr->num_palette)
  194658. {
  194659. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194660. return;
  194661. }
  194662. png_ptr->background.red =
  194663. (png_uint_16)png_ptr->palette[buf[0]].red;
  194664. png_ptr->background.green =
  194665. (png_uint_16)png_ptr->palette[buf[0]].green;
  194666. png_ptr->background.blue =
  194667. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194668. }
  194669. }
  194670. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194671. {
  194672. png_ptr->background.red =
  194673. png_ptr->background.green =
  194674. png_ptr->background.blue =
  194675. png_ptr->background.gray = png_get_uint_16(buf);
  194676. }
  194677. else
  194678. {
  194679. png_ptr->background.red = png_get_uint_16(buf);
  194680. png_ptr->background.green = png_get_uint_16(buf + 2);
  194681. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194682. }
  194683. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194684. }
  194685. #endif
  194686. #if defined(PNG_READ_hIST_SUPPORTED)
  194687. void /* PRIVATE */
  194688. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194689. {
  194690. unsigned int num, i;
  194691. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194692. png_debug(1, "in png_handle_hIST\n");
  194693. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194694. png_error(png_ptr, "Missing IHDR before hIST");
  194695. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194696. {
  194697. png_warning(png_ptr, "Invalid hIST after IDAT");
  194698. png_crc_finish(png_ptr, length);
  194699. return;
  194700. }
  194701. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194702. {
  194703. png_warning(png_ptr, "Missing PLTE before hIST");
  194704. png_crc_finish(png_ptr, length);
  194705. return;
  194706. }
  194707. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194708. {
  194709. png_warning(png_ptr, "Duplicate hIST chunk");
  194710. png_crc_finish(png_ptr, length);
  194711. return;
  194712. }
  194713. num = length / 2 ;
  194714. if (num != (unsigned int) png_ptr->num_palette || num >
  194715. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194716. {
  194717. png_warning(png_ptr, "Incorrect hIST chunk length");
  194718. png_crc_finish(png_ptr, length);
  194719. return;
  194720. }
  194721. for (i = 0; i < num; i++)
  194722. {
  194723. png_byte buf[2];
  194724. png_crc_read(png_ptr, buf, 2);
  194725. readbuf[i] = png_get_uint_16(buf);
  194726. }
  194727. if (png_crc_finish(png_ptr, 0))
  194728. return;
  194729. png_set_hIST(png_ptr, info_ptr, readbuf);
  194730. }
  194731. #endif
  194732. #if defined(PNG_READ_pHYs_SUPPORTED)
  194733. void /* PRIVATE */
  194734. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194735. {
  194736. png_byte buf[9];
  194737. png_uint_32 res_x, res_y;
  194738. int unit_type;
  194739. png_debug(1, "in png_handle_pHYs\n");
  194740. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194741. png_error(png_ptr, "Missing IHDR before pHYs");
  194742. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194743. {
  194744. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194745. png_crc_finish(png_ptr, length);
  194746. return;
  194747. }
  194748. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194749. {
  194750. png_warning(png_ptr, "Duplicate pHYs chunk");
  194751. png_crc_finish(png_ptr, length);
  194752. return;
  194753. }
  194754. if (length != 9)
  194755. {
  194756. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194757. png_crc_finish(png_ptr, length);
  194758. return;
  194759. }
  194760. png_crc_read(png_ptr, buf, 9);
  194761. if (png_crc_finish(png_ptr, 0))
  194762. return;
  194763. res_x = png_get_uint_32(buf);
  194764. res_y = png_get_uint_32(buf + 4);
  194765. unit_type = buf[8];
  194766. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194767. }
  194768. #endif
  194769. #if defined(PNG_READ_oFFs_SUPPORTED)
  194770. void /* PRIVATE */
  194771. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194772. {
  194773. png_byte buf[9];
  194774. png_int_32 offset_x, offset_y;
  194775. int unit_type;
  194776. png_debug(1, "in png_handle_oFFs\n");
  194777. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194778. png_error(png_ptr, "Missing IHDR before oFFs");
  194779. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194780. {
  194781. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194782. png_crc_finish(png_ptr, length);
  194783. return;
  194784. }
  194785. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194786. {
  194787. png_warning(png_ptr, "Duplicate oFFs chunk");
  194788. png_crc_finish(png_ptr, length);
  194789. return;
  194790. }
  194791. if (length != 9)
  194792. {
  194793. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194794. png_crc_finish(png_ptr, length);
  194795. return;
  194796. }
  194797. png_crc_read(png_ptr, buf, 9);
  194798. if (png_crc_finish(png_ptr, 0))
  194799. return;
  194800. offset_x = png_get_int_32(buf);
  194801. offset_y = png_get_int_32(buf + 4);
  194802. unit_type = buf[8];
  194803. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194804. }
  194805. #endif
  194806. #if defined(PNG_READ_pCAL_SUPPORTED)
  194807. /* read the pCAL chunk (described in the PNG Extensions document) */
  194808. void /* PRIVATE */
  194809. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194810. {
  194811. png_charp purpose;
  194812. png_int_32 X0, X1;
  194813. png_byte type, nparams;
  194814. png_charp buf, units, endptr;
  194815. png_charpp params;
  194816. png_size_t slength;
  194817. int i;
  194818. png_debug(1, "in png_handle_pCAL\n");
  194819. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194820. png_error(png_ptr, "Missing IHDR before pCAL");
  194821. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194822. {
  194823. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194824. png_crc_finish(png_ptr, length);
  194825. return;
  194826. }
  194827. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194828. {
  194829. png_warning(png_ptr, "Duplicate pCAL chunk");
  194830. png_crc_finish(png_ptr, length);
  194831. return;
  194832. }
  194833. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194834. length + 1);
  194835. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194836. if (purpose == NULL)
  194837. {
  194838. png_warning(png_ptr, "No memory for pCAL purpose.");
  194839. return;
  194840. }
  194841. slength = (png_size_t)length;
  194842. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194843. if (png_crc_finish(png_ptr, 0))
  194844. {
  194845. png_free(png_ptr, purpose);
  194846. return;
  194847. }
  194848. purpose[slength] = 0x00; /* null terminate the last string */
  194849. png_debug(3, "Finding end of pCAL purpose string\n");
  194850. for (buf = purpose; *buf; buf++)
  194851. /* empty loop */ ;
  194852. endptr = purpose + slength;
  194853. /* We need to have at least 12 bytes after the purpose string
  194854. in order to get the parameter information. */
  194855. if (endptr <= buf + 12)
  194856. {
  194857. png_warning(png_ptr, "Invalid pCAL data");
  194858. png_free(png_ptr, purpose);
  194859. return;
  194860. }
  194861. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194862. X0 = png_get_int_32((png_bytep)buf+1);
  194863. X1 = png_get_int_32((png_bytep)buf+5);
  194864. type = buf[9];
  194865. nparams = buf[10];
  194866. units = buf + 11;
  194867. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194868. /* Check that we have the right number of parameters for known
  194869. equation types. */
  194870. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194871. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194872. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194873. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194874. {
  194875. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194876. png_free(png_ptr, purpose);
  194877. return;
  194878. }
  194879. else if (type >= PNG_EQUATION_LAST)
  194880. {
  194881. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194882. }
  194883. for (buf = units; *buf; buf++)
  194884. /* Empty loop to move past the units string. */ ;
  194885. png_debug(3, "Allocating pCAL parameters array\n");
  194886. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194887. *png_sizeof(png_charp))) ;
  194888. if (params == NULL)
  194889. {
  194890. png_free(png_ptr, purpose);
  194891. png_warning(png_ptr, "No memory for pCAL params.");
  194892. return;
  194893. }
  194894. /* Get pointers to the start of each parameter string. */
  194895. for (i = 0; i < (int)nparams; i++)
  194896. {
  194897. buf++; /* Skip the null string terminator from previous parameter. */
  194898. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194899. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194900. /* Empty loop to move past each parameter string */ ;
  194901. /* Make sure we haven't run out of data yet */
  194902. if (buf > endptr)
  194903. {
  194904. png_warning(png_ptr, "Invalid pCAL data");
  194905. png_free(png_ptr, purpose);
  194906. png_free(png_ptr, params);
  194907. return;
  194908. }
  194909. }
  194910. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194911. units, params);
  194912. png_free(png_ptr, purpose);
  194913. png_free(png_ptr, params);
  194914. }
  194915. #endif
  194916. #if defined(PNG_READ_sCAL_SUPPORTED)
  194917. /* read the sCAL chunk */
  194918. void /* PRIVATE */
  194919. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194920. {
  194921. png_charp buffer, ep;
  194922. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194923. double width, height;
  194924. png_charp vp;
  194925. #else
  194926. #ifdef PNG_FIXED_POINT_SUPPORTED
  194927. png_charp swidth, sheight;
  194928. #endif
  194929. #endif
  194930. png_size_t slength;
  194931. png_debug(1, "in png_handle_sCAL\n");
  194932. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194933. png_error(png_ptr, "Missing IHDR before sCAL");
  194934. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194935. {
  194936. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194937. png_crc_finish(png_ptr, length);
  194938. return;
  194939. }
  194940. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194941. {
  194942. png_warning(png_ptr, "Duplicate sCAL chunk");
  194943. png_crc_finish(png_ptr, length);
  194944. return;
  194945. }
  194946. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194947. length + 1);
  194948. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194949. if (buffer == NULL)
  194950. {
  194951. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194952. return;
  194953. }
  194954. slength = (png_size_t)length;
  194955. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194956. if (png_crc_finish(png_ptr, 0))
  194957. {
  194958. png_free(png_ptr, buffer);
  194959. return;
  194960. }
  194961. buffer[slength] = 0x00; /* null terminate the last string */
  194962. ep = buffer + 1; /* skip unit byte */
  194963. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194964. width = png_strtod(png_ptr, ep, &vp);
  194965. if (*vp)
  194966. {
  194967. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194968. return;
  194969. }
  194970. #else
  194971. #ifdef PNG_FIXED_POINT_SUPPORTED
  194972. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194973. if (swidth == NULL)
  194974. {
  194975. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194976. return;
  194977. }
  194978. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194979. #endif
  194980. #endif
  194981. for (ep = buffer; *ep; ep++)
  194982. /* empty loop */ ;
  194983. ep++;
  194984. if (buffer + slength < ep)
  194985. {
  194986. png_warning(png_ptr, "Truncated sCAL chunk");
  194987. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194988. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194989. png_free(png_ptr, swidth);
  194990. #endif
  194991. png_free(png_ptr, buffer);
  194992. return;
  194993. }
  194994. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194995. height = png_strtod(png_ptr, ep, &vp);
  194996. if (*vp)
  194997. {
  194998. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194999. return;
  195000. }
  195001. #else
  195002. #ifdef PNG_FIXED_POINT_SUPPORTED
  195003. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195004. if (swidth == NULL)
  195005. {
  195006. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195007. return;
  195008. }
  195009. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195010. #endif
  195011. #endif
  195012. if (buffer + slength < ep
  195013. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195014. || width <= 0. || height <= 0.
  195015. #endif
  195016. )
  195017. {
  195018. png_warning(png_ptr, "Invalid sCAL data");
  195019. png_free(png_ptr, buffer);
  195020. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195021. png_free(png_ptr, swidth);
  195022. png_free(png_ptr, sheight);
  195023. #endif
  195024. return;
  195025. }
  195026. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195027. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195028. #else
  195029. #ifdef PNG_FIXED_POINT_SUPPORTED
  195030. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195031. #endif
  195032. #endif
  195033. png_free(png_ptr, buffer);
  195034. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195035. png_free(png_ptr, swidth);
  195036. png_free(png_ptr, sheight);
  195037. #endif
  195038. }
  195039. #endif
  195040. #if defined(PNG_READ_tIME_SUPPORTED)
  195041. void /* PRIVATE */
  195042. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195043. {
  195044. png_byte buf[7];
  195045. png_time mod_time;
  195046. png_debug(1, "in png_handle_tIME\n");
  195047. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195048. png_error(png_ptr, "Out of place tIME chunk");
  195049. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195050. {
  195051. png_warning(png_ptr, "Duplicate tIME chunk");
  195052. png_crc_finish(png_ptr, length);
  195053. return;
  195054. }
  195055. if (png_ptr->mode & PNG_HAVE_IDAT)
  195056. png_ptr->mode |= PNG_AFTER_IDAT;
  195057. if (length != 7)
  195058. {
  195059. png_warning(png_ptr, "Incorrect tIME chunk length");
  195060. png_crc_finish(png_ptr, length);
  195061. return;
  195062. }
  195063. png_crc_read(png_ptr, buf, 7);
  195064. if (png_crc_finish(png_ptr, 0))
  195065. return;
  195066. mod_time.second = buf[6];
  195067. mod_time.minute = buf[5];
  195068. mod_time.hour = buf[4];
  195069. mod_time.day = buf[3];
  195070. mod_time.month = buf[2];
  195071. mod_time.year = png_get_uint_16(buf);
  195072. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195073. }
  195074. #endif
  195075. #if defined(PNG_READ_tEXt_SUPPORTED)
  195076. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195077. void /* PRIVATE */
  195078. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195079. {
  195080. png_textp text_ptr;
  195081. png_charp key;
  195082. png_charp text;
  195083. png_uint_32 skip = 0;
  195084. png_size_t slength;
  195085. int ret;
  195086. png_debug(1, "in png_handle_tEXt\n");
  195087. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195088. png_error(png_ptr, "Missing IHDR before tEXt");
  195089. if (png_ptr->mode & PNG_HAVE_IDAT)
  195090. png_ptr->mode |= PNG_AFTER_IDAT;
  195091. #ifdef PNG_MAX_MALLOC_64K
  195092. if (length > (png_uint_32)65535L)
  195093. {
  195094. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195095. skip = length - (png_uint_32)65535L;
  195096. length = (png_uint_32)65535L;
  195097. }
  195098. #endif
  195099. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195100. if (key == NULL)
  195101. {
  195102. png_warning(png_ptr, "No memory to process text chunk.");
  195103. return;
  195104. }
  195105. slength = (png_size_t)length;
  195106. png_crc_read(png_ptr, (png_bytep)key, slength);
  195107. if (png_crc_finish(png_ptr, skip))
  195108. {
  195109. png_free(png_ptr, key);
  195110. return;
  195111. }
  195112. key[slength] = 0x00;
  195113. for (text = key; *text; text++)
  195114. /* empty loop to find end of key */ ;
  195115. if (text != key + slength)
  195116. text++;
  195117. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195118. (png_uint_32)png_sizeof(png_text));
  195119. if (text_ptr == NULL)
  195120. {
  195121. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195122. png_free(png_ptr, key);
  195123. return;
  195124. }
  195125. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195126. text_ptr->key = key;
  195127. #ifdef PNG_iTXt_SUPPORTED
  195128. text_ptr->lang = NULL;
  195129. text_ptr->lang_key = NULL;
  195130. text_ptr->itxt_length = 0;
  195131. #endif
  195132. text_ptr->text = text;
  195133. text_ptr->text_length = png_strlen(text);
  195134. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195135. png_free(png_ptr, key);
  195136. png_free(png_ptr, text_ptr);
  195137. if (ret)
  195138. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195139. }
  195140. #endif
  195141. #if defined(PNG_READ_zTXt_SUPPORTED)
  195142. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195143. void /* PRIVATE */
  195144. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195145. {
  195146. png_textp text_ptr;
  195147. png_charp chunkdata;
  195148. png_charp text;
  195149. int comp_type;
  195150. int ret;
  195151. png_size_t slength, prefix_len, data_len;
  195152. png_debug(1, "in png_handle_zTXt\n");
  195153. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195154. png_error(png_ptr, "Missing IHDR before zTXt");
  195155. if (png_ptr->mode & PNG_HAVE_IDAT)
  195156. png_ptr->mode |= PNG_AFTER_IDAT;
  195157. #ifdef PNG_MAX_MALLOC_64K
  195158. /* We will no doubt have problems with chunks even half this size, but
  195159. there is no hard and fast rule to tell us where to stop. */
  195160. if (length > (png_uint_32)65535L)
  195161. {
  195162. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195163. png_crc_finish(png_ptr, length);
  195164. return;
  195165. }
  195166. #endif
  195167. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195168. if (chunkdata == NULL)
  195169. {
  195170. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195171. return;
  195172. }
  195173. slength = (png_size_t)length;
  195174. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195175. if (png_crc_finish(png_ptr, 0))
  195176. {
  195177. png_free(png_ptr, chunkdata);
  195178. return;
  195179. }
  195180. chunkdata[slength] = 0x00;
  195181. for (text = chunkdata; *text; text++)
  195182. /* empty loop */ ;
  195183. /* zTXt must have some text after the chunkdataword */
  195184. if (text >= chunkdata + slength - 2)
  195185. {
  195186. png_warning(png_ptr, "Truncated zTXt chunk");
  195187. png_free(png_ptr, chunkdata);
  195188. return;
  195189. }
  195190. else
  195191. {
  195192. comp_type = *(++text);
  195193. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195194. {
  195195. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195196. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195197. }
  195198. text++; /* skip the compression_method byte */
  195199. }
  195200. prefix_len = text - chunkdata;
  195201. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195202. (png_size_t)length, prefix_len, &data_len);
  195203. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195204. (png_uint_32)png_sizeof(png_text));
  195205. if (text_ptr == NULL)
  195206. {
  195207. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195208. png_free(png_ptr, chunkdata);
  195209. return;
  195210. }
  195211. text_ptr->compression = comp_type;
  195212. text_ptr->key = chunkdata;
  195213. #ifdef PNG_iTXt_SUPPORTED
  195214. text_ptr->lang = NULL;
  195215. text_ptr->lang_key = NULL;
  195216. text_ptr->itxt_length = 0;
  195217. #endif
  195218. text_ptr->text = chunkdata + prefix_len;
  195219. text_ptr->text_length = data_len;
  195220. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195221. png_free(png_ptr, text_ptr);
  195222. png_free(png_ptr, chunkdata);
  195223. if (ret)
  195224. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195225. }
  195226. #endif
  195227. #if defined(PNG_READ_iTXt_SUPPORTED)
  195228. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195229. void /* PRIVATE */
  195230. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195231. {
  195232. png_textp text_ptr;
  195233. png_charp chunkdata;
  195234. png_charp key, lang, text, lang_key;
  195235. int comp_flag;
  195236. int comp_type = 0;
  195237. int ret;
  195238. png_size_t slength, prefix_len, data_len;
  195239. png_debug(1, "in png_handle_iTXt\n");
  195240. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195241. png_error(png_ptr, "Missing IHDR before iTXt");
  195242. if (png_ptr->mode & PNG_HAVE_IDAT)
  195243. png_ptr->mode |= PNG_AFTER_IDAT;
  195244. #ifdef PNG_MAX_MALLOC_64K
  195245. /* We will no doubt have problems with chunks even half this size, but
  195246. there is no hard and fast rule to tell us where to stop. */
  195247. if (length > (png_uint_32)65535L)
  195248. {
  195249. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195250. png_crc_finish(png_ptr, length);
  195251. return;
  195252. }
  195253. #endif
  195254. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195255. if (chunkdata == NULL)
  195256. {
  195257. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195258. return;
  195259. }
  195260. slength = (png_size_t)length;
  195261. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195262. if (png_crc_finish(png_ptr, 0))
  195263. {
  195264. png_free(png_ptr, chunkdata);
  195265. return;
  195266. }
  195267. chunkdata[slength] = 0x00;
  195268. for (lang = chunkdata; *lang; lang++)
  195269. /* empty loop */ ;
  195270. lang++; /* skip NUL separator */
  195271. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195272. translated keyword (possibly empty), and possibly some text after the
  195273. keyword */
  195274. if (lang >= chunkdata + slength - 3)
  195275. {
  195276. png_warning(png_ptr, "Truncated iTXt chunk");
  195277. png_free(png_ptr, chunkdata);
  195278. return;
  195279. }
  195280. else
  195281. {
  195282. comp_flag = *lang++;
  195283. comp_type = *lang++;
  195284. }
  195285. for (lang_key = lang; *lang_key; lang_key++)
  195286. /* empty loop */ ;
  195287. lang_key++; /* skip NUL separator */
  195288. if (lang_key >= chunkdata + slength)
  195289. {
  195290. png_warning(png_ptr, "Truncated iTXt chunk");
  195291. png_free(png_ptr, chunkdata);
  195292. return;
  195293. }
  195294. for (text = lang_key; *text; text++)
  195295. /* empty loop */ ;
  195296. text++; /* skip NUL separator */
  195297. if (text >= chunkdata + slength)
  195298. {
  195299. png_warning(png_ptr, "Malformed iTXt chunk");
  195300. png_free(png_ptr, chunkdata);
  195301. return;
  195302. }
  195303. prefix_len = text - chunkdata;
  195304. key=chunkdata;
  195305. if (comp_flag)
  195306. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195307. (size_t)length, prefix_len, &data_len);
  195308. else
  195309. data_len=png_strlen(chunkdata + prefix_len);
  195310. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195311. (png_uint_32)png_sizeof(png_text));
  195312. if (text_ptr == NULL)
  195313. {
  195314. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195315. png_free(png_ptr, chunkdata);
  195316. return;
  195317. }
  195318. text_ptr->compression = (int)comp_flag + 1;
  195319. text_ptr->lang_key = chunkdata+(lang_key-key);
  195320. text_ptr->lang = chunkdata+(lang-key);
  195321. text_ptr->itxt_length = data_len;
  195322. text_ptr->text_length = 0;
  195323. text_ptr->key = chunkdata;
  195324. text_ptr->text = chunkdata + prefix_len;
  195325. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195326. png_free(png_ptr, text_ptr);
  195327. png_free(png_ptr, chunkdata);
  195328. if (ret)
  195329. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195330. }
  195331. #endif
  195332. /* This function is called when we haven't found a handler for a
  195333. chunk. If there isn't a problem with the chunk itself (ie bad
  195334. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195335. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195336. case it will be saved away to be written out later. */
  195337. void /* PRIVATE */
  195338. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195339. {
  195340. png_uint_32 skip = 0;
  195341. png_debug(1, "in png_handle_unknown\n");
  195342. if (png_ptr->mode & PNG_HAVE_IDAT)
  195343. {
  195344. #ifdef PNG_USE_LOCAL_ARRAYS
  195345. PNG_CONST PNG_IDAT;
  195346. #endif
  195347. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195348. png_ptr->mode |= PNG_AFTER_IDAT;
  195349. }
  195350. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195351. if (!(png_ptr->chunk_name[0] & 0x20))
  195352. {
  195353. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195354. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195355. PNG_HANDLE_CHUNK_ALWAYS
  195356. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195357. && png_ptr->read_user_chunk_fn == NULL
  195358. #endif
  195359. )
  195360. #endif
  195361. png_chunk_error(png_ptr, "unknown critical chunk");
  195362. }
  195363. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195364. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195365. (png_ptr->read_user_chunk_fn != NULL))
  195366. {
  195367. #ifdef PNG_MAX_MALLOC_64K
  195368. if (length > (png_uint_32)65535L)
  195369. {
  195370. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195371. skip = length - (png_uint_32)65535L;
  195372. length = (png_uint_32)65535L;
  195373. }
  195374. #endif
  195375. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195376. (png_charp)png_ptr->chunk_name, 5);
  195377. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195378. png_ptr->unknown_chunk.size = (png_size_t)length;
  195379. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195380. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195381. if(png_ptr->read_user_chunk_fn != NULL)
  195382. {
  195383. /* callback to user unknown chunk handler */
  195384. int ret;
  195385. ret = (*(png_ptr->read_user_chunk_fn))
  195386. (png_ptr, &png_ptr->unknown_chunk);
  195387. if (ret < 0)
  195388. png_chunk_error(png_ptr, "error in user chunk");
  195389. if (ret == 0)
  195390. {
  195391. if (!(png_ptr->chunk_name[0] & 0x20))
  195392. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195393. PNG_HANDLE_CHUNK_ALWAYS)
  195394. png_chunk_error(png_ptr, "unknown critical chunk");
  195395. png_set_unknown_chunks(png_ptr, info_ptr,
  195396. &png_ptr->unknown_chunk, 1);
  195397. }
  195398. }
  195399. #else
  195400. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195401. #endif
  195402. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195403. png_ptr->unknown_chunk.data = NULL;
  195404. }
  195405. else
  195406. #endif
  195407. skip = length;
  195408. png_crc_finish(png_ptr, skip);
  195409. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195410. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195411. #endif
  195412. }
  195413. /* This function is called to verify that a chunk name is valid.
  195414. This function can't have the "critical chunk check" incorporated
  195415. into it, since in the future we will need to be able to call user
  195416. functions to handle unknown critical chunks after we check that
  195417. the chunk name itself is valid. */
  195418. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195419. void /* PRIVATE */
  195420. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195421. {
  195422. png_debug(1, "in png_check_chunk_name\n");
  195423. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195424. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195425. {
  195426. png_chunk_error(png_ptr, "invalid chunk type");
  195427. }
  195428. }
  195429. /* Combines the row recently read in with the existing pixels in the
  195430. row. This routine takes care of alpha and transparency if requested.
  195431. This routine also handles the two methods of progressive display
  195432. of interlaced images, depending on the mask value.
  195433. The mask value describes which pixels are to be combined with
  195434. the row. The pattern always repeats every 8 pixels, so just 8
  195435. bits are needed. A one indicates the pixel is to be combined,
  195436. a zero indicates the pixel is to be skipped. This is in addition
  195437. to any alpha or transparency value associated with the pixel. If
  195438. you want all pixels to be combined, pass 0xff (255) in mask. */
  195439. void /* PRIVATE */
  195440. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195441. {
  195442. png_debug(1,"in png_combine_row\n");
  195443. if (mask == 0xff)
  195444. {
  195445. png_memcpy(row, png_ptr->row_buf + 1,
  195446. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195447. }
  195448. else
  195449. {
  195450. switch (png_ptr->row_info.pixel_depth)
  195451. {
  195452. case 1:
  195453. {
  195454. png_bytep sp = png_ptr->row_buf + 1;
  195455. png_bytep dp = row;
  195456. int s_inc, s_start, s_end;
  195457. int m = 0x80;
  195458. int shift;
  195459. png_uint_32 i;
  195460. png_uint_32 row_width = png_ptr->width;
  195461. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195462. if (png_ptr->transformations & PNG_PACKSWAP)
  195463. {
  195464. s_start = 0;
  195465. s_end = 7;
  195466. s_inc = 1;
  195467. }
  195468. else
  195469. #endif
  195470. {
  195471. s_start = 7;
  195472. s_end = 0;
  195473. s_inc = -1;
  195474. }
  195475. shift = s_start;
  195476. for (i = 0; i < row_width; i++)
  195477. {
  195478. if (m & mask)
  195479. {
  195480. int value;
  195481. value = (*sp >> shift) & 0x01;
  195482. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195483. *dp |= (png_byte)(value << shift);
  195484. }
  195485. if (shift == s_end)
  195486. {
  195487. shift = s_start;
  195488. sp++;
  195489. dp++;
  195490. }
  195491. else
  195492. shift += s_inc;
  195493. if (m == 1)
  195494. m = 0x80;
  195495. else
  195496. m >>= 1;
  195497. }
  195498. break;
  195499. }
  195500. case 2:
  195501. {
  195502. png_bytep sp = png_ptr->row_buf + 1;
  195503. png_bytep dp = row;
  195504. int s_start, s_end, s_inc;
  195505. int m = 0x80;
  195506. int shift;
  195507. png_uint_32 i;
  195508. png_uint_32 row_width = png_ptr->width;
  195509. int value;
  195510. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195511. if (png_ptr->transformations & PNG_PACKSWAP)
  195512. {
  195513. s_start = 0;
  195514. s_end = 6;
  195515. s_inc = 2;
  195516. }
  195517. else
  195518. #endif
  195519. {
  195520. s_start = 6;
  195521. s_end = 0;
  195522. s_inc = -2;
  195523. }
  195524. shift = s_start;
  195525. for (i = 0; i < row_width; i++)
  195526. {
  195527. if (m & mask)
  195528. {
  195529. value = (*sp >> shift) & 0x03;
  195530. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195531. *dp |= (png_byte)(value << shift);
  195532. }
  195533. if (shift == s_end)
  195534. {
  195535. shift = s_start;
  195536. sp++;
  195537. dp++;
  195538. }
  195539. else
  195540. shift += s_inc;
  195541. if (m == 1)
  195542. m = 0x80;
  195543. else
  195544. m >>= 1;
  195545. }
  195546. break;
  195547. }
  195548. case 4:
  195549. {
  195550. png_bytep sp = png_ptr->row_buf + 1;
  195551. png_bytep dp = row;
  195552. int s_start, s_end, s_inc;
  195553. int m = 0x80;
  195554. int shift;
  195555. png_uint_32 i;
  195556. png_uint_32 row_width = png_ptr->width;
  195557. int value;
  195558. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195559. if (png_ptr->transformations & PNG_PACKSWAP)
  195560. {
  195561. s_start = 0;
  195562. s_end = 4;
  195563. s_inc = 4;
  195564. }
  195565. else
  195566. #endif
  195567. {
  195568. s_start = 4;
  195569. s_end = 0;
  195570. s_inc = -4;
  195571. }
  195572. shift = s_start;
  195573. for (i = 0; i < row_width; i++)
  195574. {
  195575. if (m & mask)
  195576. {
  195577. value = (*sp >> shift) & 0xf;
  195578. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195579. *dp |= (png_byte)(value << shift);
  195580. }
  195581. if (shift == s_end)
  195582. {
  195583. shift = s_start;
  195584. sp++;
  195585. dp++;
  195586. }
  195587. else
  195588. shift += s_inc;
  195589. if (m == 1)
  195590. m = 0x80;
  195591. else
  195592. m >>= 1;
  195593. }
  195594. break;
  195595. }
  195596. default:
  195597. {
  195598. png_bytep sp = png_ptr->row_buf + 1;
  195599. png_bytep dp = row;
  195600. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195601. png_uint_32 i;
  195602. png_uint_32 row_width = png_ptr->width;
  195603. png_byte m = 0x80;
  195604. for (i = 0; i < row_width; i++)
  195605. {
  195606. if (m & mask)
  195607. {
  195608. png_memcpy(dp, sp, pixel_bytes);
  195609. }
  195610. sp += pixel_bytes;
  195611. dp += pixel_bytes;
  195612. if (m == 1)
  195613. m = 0x80;
  195614. else
  195615. m >>= 1;
  195616. }
  195617. break;
  195618. }
  195619. }
  195620. }
  195621. }
  195622. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195623. /* OLD pre-1.0.9 interface:
  195624. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195625. png_uint_32 transformations)
  195626. */
  195627. void /* PRIVATE */
  195628. png_do_read_interlace(png_structp png_ptr)
  195629. {
  195630. png_row_infop row_info = &(png_ptr->row_info);
  195631. png_bytep row = png_ptr->row_buf + 1;
  195632. int pass = png_ptr->pass;
  195633. png_uint_32 transformations = png_ptr->transformations;
  195634. #ifdef PNG_USE_LOCAL_ARRAYS
  195635. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195636. /* offset to next interlace block */
  195637. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195638. #endif
  195639. png_debug(1,"in png_do_read_interlace\n");
  195640. if (row != NULL && row_info != NULL)
  195641. {
  195642. png_uint_32 final_width;
  195643. final_width = row_info->width * png_pass_inc[pass];
  195644. switch (row_info->pixel_depth)
  195645. {
  195646. case 1:
  195647. {
  195648. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195649. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195650. int sshift, dshift;
  195651. int s_start, s_end, s_inc;
  195652. int jstop = png_pass_inc[pass];
  195653. png_byte v;
  195654. png_uint_32 i;
  195655. int j;
  195656. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195657. if (transformations & PNG_PACKSWAP)
  195658. {
  195659. sshift = (int)((row_info->width + 7) & 0x07);
  195660. dshift = (int)((final_width + 7) & 0x07);
  195661. s_start = 7;
  195662. s_end = 0;
  195663. s_inc = -1;
  195664. }
  195665. else
  195666. #endif
  195667. {
  195668. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195669. dshift = 7 - (int)((final_width + 7) & 0x07);
  195670. s_start = 0;
  195671. s_end = 7;
  195672. s_inc = 1;
  195673. }
  195674. for (i = 0; i < row_info->width; i++)
  195675. {
  195676. v = (png_byte)((*sp >> sshift) & 0x01);
  195677. for (j = 0; j < jstop; j++)
  195678. {
  195679. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195680. *dp |= (png_byte)(v << dshift);
  195681. if (dshift == s_end)
  195682. {
  195683. dshift = s_start;
  195684. dp--;
  195685. }
  195686. else
  195687. dshift += s_inc;
  195688. }
  195689. if (sshift == s_end)
  195690. {
  195691. sshift = s_start;
  195692. sp--;
  195693. }
  195694. else
  195695. sshift += s_inc;
  195696. }
  195697. break;
  195698. }
  195699. case 2:
  195700. {
  195701. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195702. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195703. int sshift, dshift;
  195704. int s_start, s_end, s_inc;
  195705. int jstop = png_pass_inc[pass];
  195706. png_uint_32 i;
  195707. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195708. if (transformations & PNG_PACKSWAP)
  195709. {
  195710. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195711. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195712. s_start = 6;
  195713. s_end = 0;
  195714. s_inc = -2;
  195715. }
  195716. else
  195717. #endif
  195718. {
  195719. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195720. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195721. s_start = 0;
  195722. s_end = 6;
  195723. s_inc = 2;
  195724. }
  195725. for (i = 0; i < row_info->width; i++)
  195726. {
  195727. png_byte v;
  195728. int j;
  195729. v = (png_byte)((*sp >> sshift) & 0x03);
  195730. for (j = 0; j < jstop; j++)
  195731. {
  195732. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195733. *dp |= (png_byte)(v << dshift);
  195734. if (dshift == s_end)
  195735. {
  195736. dshift = s_start;
  195737. dp--;
  195738. }
  195739. else
  195740. dshift += s_inc;
  195741. }
  195742. if (sshift == s_end)
  195743. {
  195744. sshift = s_start;
  195745. sp--;
  195746. }
  195747. else
  195748. sshift += s_inc;
  195749. }
  195750. break;
  195751. }
  195752. case 4:
  195753. {
  195754. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195755. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195756. int sshift, dshift;
  195757. int s_start, s_end, s_inc;
  195758. png_uint_32 i;
  195759. int jstop = png_pass_inc[pass];
  195760. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195761. if (transformations & PNG_PACKSWAP)
  195762. {
  195763. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195764. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195765. s_start = 4;
  195766. s_end = 0;
  195767. s_inc = -4;
  195768. }
  195769. else
  195770. #endif
  195771. {
  195772. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195773. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195774. s_start = 0;
  195775. s_end = 4;
  195776. s_inc = 4;
  195777. }
  195778. for (i = 0; i < row_info->width; i++)
  195779. {
  195780. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195781. int j;
  195782. for (j = 0; j < jstop; j++)
  195783. {
  195784. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195785. *dp |= (png_byte)(v << dshift);
  195786. if (dshift == s_end)
  195787. {
  195788. dshift = s_start;
  195789. dp--;
  195790. }
  195791. else
  195792. dshift += s_inc;
  195793. }
  195794. if (sshift == s_end)
  195795. {
  195796. sshift = s_start;
  195797. sp--;
  195798. }
  195799. else
  195800. sshift += s_inc;
  195801. }
  195802. break;
  195803. }
  195804. default:
  195805. {
  195806. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195807. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195808. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195809. int jstop = png_pass_inc[pass];
  195810. png_uint_32 i;
  195811. for (i = 0; i < row_info->width; i++)
  195812. {
  195813. png_byte v[8];
  195814. int j;
  195815. png_memcpy(v, sp, pixel_bytes);
  195816. for (j = 0; j < jstop; j++)
  195817. {
  195818. png_memcpy(dp, v, pixel_bytes);
  195819. dp -= pixel_bytes;
  195820. }
  195821. sp -= pixel_bytes;
  195822. }
  195823. break;
  195824. }
  195825. }
  195826. row_info->width = final_width;
  195827. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195828. }
  195829. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195830. transformations = transformations; /* silence compiler warning */
  195831. #endif
  195832. }
  195833. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195834. void /* PRIVATE */
  195835. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195836. png_bytep prev_row, int filter)
  195837. {
  195838. png_debug(1, "in png_read_filter_row\n");
  195839. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195840. switch (filter)
  195841. {
  195842. case PNG_FILTER_VALUE_NONE:
  195843. break;
  195844. case PNG_FILTER_VALUE_SUB:
  195845. {
  195846. png_uint_32 i;
  195847. png_uint_32 istop = row_info->rowbytes;
  195848. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195849. png_bytep rp = row + bpp;
  195850. png_bytep lp = row;
  195851. for (i = bpp; i < istop; i++)
  195852. {
  195853. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195854. rp++;
  195855. }
  195856. break;
  195857. }
  195858. case PNG_FILTER_VALUE_UP:
  195859. {
  195860. png_uint_32 i;
  195861. png_uint_32 istop = row_info->rowbytes;
  195862. png_bytep rp = row;
  195863. png_bytep pp = prev_row;
  195864. for (i = 0; i < istop; i++)
  195865. {
  195866. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195867. rp++;
  195868. }
  195869. break;
  195870. }
  195871. case PNG_FILTER_VALUE_AVG:
  195872. {
  195873. png_uint_32 i;
  195874. png_bytep rp = row;
  195875. png_bytep pp = prev_row;
  195876. png_bytep lp = row;
  195877. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195878. png_uint_32 istop = row_info->rowbytes - bpp;
  195879. for (i = 0; i < bpp; i++)
  195880. {
  195881. *rp = (png_byte)(((int)(*rp) +
  195882. ((int)(*pp++) / 2 )) & 0xff);
  195883. rp++;
  195884. }
  195885. for (i = 0; i < istop; i++)
  195886. {
  195887. *rp = (png_byte)(((int)(*rp) +
  195888. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195889. rp++;
  195890. }
  195891. break;
  195892. }
  195893. case PNG_FILTER_VALUE_PAETH:
  195894. {
  195895. png_uint_32 i;
  195896. png_bytep rp = row;
  195897. png_bytep pp = prev_row;
  195898. png_bytep lp = row;
  195899. png_bytep cp = prev_row;
  195900. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195901. png_uint_32 istop=row_info->rowbytes - bpp;
  195902. for (i = 0; i < bpp; i++)
  195903. {
  195904. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195905. rp++;
  195906. }
  195907. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195908. {
  195909. int a, b, c, pa, pb, pc, p;
  195910. a = *lp++;
  195911. b = *pp++;
  195912. c = *cp++;
  195913. p = b - c;
  195914. pc = a - c;
  195915. #ifdef PNG_USE_ABS
  195916. pa = abs(p);
  195917. pb = abs(pc);
  195918. pc = abs(p + pc);
  195919. #else
  195920. pa = p < 0 ? -p : p;
  195921. pb = pc < 0 ? -pc : pc;
  195922. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195923. #endif
  195924. /*
  195925. if (pa <= pb && pa <= pc)
  195926. p = a;
  195927. else if (pb <= pc)
  195928. p = b;
  195929. else
  195930. p = c;
  195931. */
  195932. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195933. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195934. rp++;
  195935. }
  195936. break;
  195937. }
  195938. default:
  195939. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195940. *row=0;
  195941. break;
  195942. }
  195943. }
  195944. void /* PRIVATE */
  195945. png_read_finish_row(png_structp png_ptr)
  195946. {
  195947. #ifdef PNG_USE_LOCAL_ARRAYS
  195948. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195949. /* start of interlace block */
  195950. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195951. /* offset to next interlace block */
  195952. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195953. /* start of interlace block in the y direction */
  195954. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195955. /* offset to next interlace block in the y direction */
  195956. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195957. #endif
  195958. png_debug(1, "in png_read_finish_row\n");
  195959. png_ptr->row_number++;
  195960. if (png_ptr->row_number < png_ptr->num_rows)
  195961. return;
  195962. if (png_ptr->interlaced)
  195963. {
  195964. png_ptr->row_number = 0;
  195965. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195966. png_ptr->rowbytes + 1);
  195967. do
  195968. {
  195969. png_ptr->pass++;
  195970. if (png_ptr->pass >= 7)
  195971. break;
  195972. png_ptr->iwidth = (png_ptr->width +
  195973. png_pass_inc[png_ptr->pass] - 1 -
  195974. png_pass_start[png_ptr->pass]) /
  195975. png_pass_inc[png_ptr->pass];
  195976. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195977. png_ptr->iwidth) + 1;
  195978. if (!(png_ptr->transformations & PNG_INTERLACE))
  195979. {
  195980. png_ptr->num_rows = (png_ptr->height +
  195981. png_pass_yinc[png_ptr->pass] - 1 -
  195982. png_pass_ystart[png_ptr->pass]) /
  195983. png_pass_yinc[png_ptr->pass];
  195984. if (!(png_ptr->num_rows))
  195985. continue;
  195986. }
  195987. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195988. break;
  195989. } while (png_ptr->iwidth == 0);
  195990. if (png_ptr->pass < 7)
  195991. return;
  195992. }
  195993. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195994. {
  195995. #ifdef PNG_USE_LOCAL_ARRAYS
  195996. PNG_CONST PNG_IDAT;
  195997. #endif
  195998. char extra;
  195999. int ret;
  196000. png_ptr->zstream.next_out = (Bytef *)&extra;
  196001. png_ptr->zstream.avail_out = (uInt)1;
  196002. for(;;)
  196003. {
  196004. if (!(png_ptr->zstream.avail_in))
  196005. {
  196006. while (!png_ptr->idat_size)
  196007. {
  196008. png_byte chunk_length[4];
  196009. png_crc_finish(png_ptr, 0);
  196010. png_read_data(png_ptr, chunk_length, 4);
  196011. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196012. png_reset_crc(png_ptr);
  196013. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196014. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196015. png_error(png_ptr, "Not enough image data");
  196016. }
  196017. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196018. png_ptr->zstream.next_in = png_ptr->zbuf;
  196019. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196020. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196021. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196022. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196023. }
  196024. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196025. if (ret == Z_STREAM_END)
  196026. {
  196027. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196028. png_ptr->idat_size)
  196029. png_warning(png_ptr, "Extra compressed data");
  196030. png_ptr->mode |= PNG_AFTER_IDAT;
  196031. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196032. break;
  196033. }
  196034. if (ret != Z_OK)
  196035. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196036. "Decompression Error");
  196037. if (!(png_ptr->zstream.avail_out))
  196038. {
  196039. png_warning(png_ptr, "Extra compressed data.");
  196040. png_ptr->mode |= PNG_AFTER_IDAT;
  196041. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196042. break;
  196043. }
  196044. }
  196045. png_ptr->zstream.avail_out = 0;
  196046. }
  196047. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196048. png_warning(png_ptr, "Extra compression data");
  196049. inflateReset(&png_ptr->zstream);
  196050. png_ptr->mode |= PNG_AFTER_IDAT;
  196051. }
  196052. void /* PRIVATE */
  196053. png_read_start_row(png_structp png_ptr)
  196054. {
  196055. #ifdef PNG_USE_LOCAL_ARRAYS
  196056. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196057. /* start of interlace block */
  196058. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196059. /* offset to next interlace block */
  196060. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196061. /* start of interlace block in the y direction */
  196062. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196063. /* offset to next interlace block in the y direction */
  196064. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196065. #endif
  196066. int max_pixel_depth;
  196067. png_uint_32 row_bytes;
  196068. png_debug(1, "in png_read_start_row\n");
  196069. png_ptr->zstream.avail_in = 0;
  196070. png_init_read_transformations(png_ptr);
  196071. if (png_ptr->interlaced)
  196072. {
  196073. if (!(png_ptr->transformations & PNG_INTERLACE))
  196074. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196075. png_pass_ystart[0]) / png_pass_yinc[0];
  196076. else
  196077. png_ptr->num_rows = png_ptr->height;
  196078. png_ptr->iwidth = (png_ptr->width +
  196079. png_pass_inc[png_ptr->pass] - 1 -
  196080. png_pass_start[png_ptr->pass]) /
  196081. png_pass_inc[png_ptr->pass];
  196082. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196083. png_ptr->irowbytes = (png_size_t)row_bytes;
  196084. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196085. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196086. }
  196087. else
  196088. {
  196089. png_ptr->num_rows = png_ptr->height;
  196090. png_ptr->iwidth = png_ptr->width;
  196091. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196092. }
  196093. max_pixel_depth = png_ptr->pixel_depth;
  196094. #if defined(PNG_READ_PACK_SUPPORTED)
  196095. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196096. max_pixel_depth = 8;
  196097. #endif
  196098. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196099. if (png_ptr->transformations & PNG_EXPAND)
  196100. {
  196101. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196102. {
  196103. if (png_ptr->num_trans)
  196104. max_pixel_depth = 32;
  196105. else
  196106. max_pixel_depth = 24;
  196107. }
  196108. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196109. {
  196110. if (max_pixel_depth < 8)
  196111. max_pixel_depth = 8;
  196112. if (png_ptr->num_trans)
  196113. max_pixel_depth *= 2;
  196114. }
  196115. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196116. {
  196117. if (png_ptr->num_trans)
  196118. {
  196119. max_pixel_depth *= 4;
  196120. max_pixel_depth /= 3;
  196121. }
  196122. }
  196123. }
  196124. #endif
  196125. #if defined(PNG_READ_FILLER_SUPPORTED)
  196126. if (png_ptr->transformations & (PNG_FILLER))
  196127. {
  196128. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196129. max_pixel_depth = 32;
  196130. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196131. {
  196132. if (max_pixel_depth <= 8)
  196133. max_pixel_depth = 16;
  196134. else
  196135. max_pixel_depth = 32;
  196136. }
  196137. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196138. {
  196139. if (max_pixel_depth <= 32)
  196140. max_pixel_depth = 32;
  196141. else
  196142. max_pixel_depth = 64;
  196143. }
  196144. }
  196145. #endif
  196146. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196147. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196148. {
  196149. if (
  196150. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196151. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196152. #endif
  196153. #if defined(PNG_READ_FILLER_SUPPORTED)
  196154. (png_ptr->transformations & (PNG_FILLER)) ||
  196155. #endif
  196156. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196157. {
  196158. if (max_pixel_depth <= 16)
  196159. max_pixel_depth = 32;
  196160. else
  196161. max_pixel_depth = 64;
  196162. }
  196163. else
  196164. {
  196165. if (max_pixel_depth <= 8)
  196166. {
  196167. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196168. max_pixel_depth = 32;
  196169. else
  196170. max_pixel_depth = 24;
  196171. }
  196172. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196173. max_pixel_depth = 64;
  196174. else
  196175. max_pixel_depth = 48;
  196176. }
  196177. }
  196178. #endif
  196179. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196180. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196181. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196182. {
  196183. int user_pixel_depth=png_ptr->user_transform_depth*
  196184. png_ptr->user_transform_channels;
  196185. if(user_pixel_depth > max_pixel_depth)
  196186. max_pixel_depth=user_pixel_depth;
  196187. }
  196188. #endif
  196189. /* align the width on the next larger 8 pixels. Mainly used
  196190. for interlacing */
  196191. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196192. /* calculate the maximum bytes needed, adding a byte and a pixel
  196193. for safety's sake */
  196194. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196195. 1 + ((max_pixel_depth + 7) >> 3);
  196196. #ifdef PNG_MAX_MALLOC_64K
  196197. if (row_bytes > (png_uint_32)65536L)
  196198. png_error(png_ptr, "This image requires a row greater than 64KB");
  196199. #endif
  196200. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196201. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196202. #ifdef PNG_MAX_MALLOC_64K
  196203. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196204. png_error(png_ptr, "This image requires a row greater than 64KB");
  196205. #endif
  196206. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196207. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196208. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196209. png_ptr->rowbytes + 1));
  196210. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196211. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196212. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196213. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196214. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196215. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196216. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196217. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196218. }
  196219. #endif /* PNG_READ_SUPPORTED */
  196220. /*** End of inlined file: pngrutil.c ***/
  196221. /*** Start of inlined file: pngset.c ***/
  196222. /* pngset.c - storage of image information into info struct
  196223. *
  196224. * Last changed in libpng 1.2.21 [October 4, 2007]
  196225. * For conditions of distribution and use, see copyright notice in png.h
  196226. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196227. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196228. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196229. *
  196230. * The functions here are used during reads to store data from the file
  196231. * into the info struct, and during writes to store application data
  196232. * into the info struct for writing into the file. This abstracts the
  196233. * info struct and allows us to change the structure in the future.
  196234. */
  196235. #define PNG_INTERNAL
  196236. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196237. #if defined(PNG_bKGD_SUPPORTED)
  196238. void PNGAPI
  196239. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196240. {
  196241. png_debug1(1, "in %s storage function\n", "bKGD");
  196242. if (png_ptr == NULL || info_ptr == NULL)
  196243. return;
  196244. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196245. info_ptr->valid |= PNG_INFO_bKGD;
  196246. }
  196247. #endif
  196248. #if defined(PNG_cHRM_SUPPORTED)
  196249. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196250. void PNGAPI
  196251. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196252. double white_x, double white_y, double red_x, double red_y,
  196253. double green_x, double green_y, double blue_x, double blue_y)
  196254. {
  196255. png_debug1(1, "in %s storage function\n", "cHRM");
  196256. if (png_ptr == NULL || info_ptr == NULL)
  196257. return;
  196258. if (white_x < 0.0 || white_y < 0.0 ||
  196259. red_x < 0.0 || red_y < 0.0 ||
  196260. green_x < 0.0 || green_y < 0.0 ||
  196261. blue_x < 0.0 || blue_y < 0.0)
  196262. {
  196263. png_warning(png_ptr,
  196264. "Ignoring attempt to set negative chromaticity value");
  196265. return;
  196266. }
  196267. if (white_x > 21474.83 || white_y > 21474.83 ||
  196268. red_x > 21474.83 || red_y > 21474.83 ||
  196269. green_x > 21474.83 || green_y > 21474.83 ||
  196270. blue_x > 21474.83 || blue_y > 21474.83)
  196271. {
  196272. png_warning(png_ptr,
  196273. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196274. return;
  196275. }
  196276. info_ptr->x_white = (float)white_x;
  196277. info_ptr->y_white = (float)white_y;
  196278. info_ptr->x_red = (float)red_x;
  196279. info_ptr->y_red = (float)red_y;
  196280. info_ptr->x_green = (float)green_x;
  196281. info_ptr->y_green = (float)green_y;
  196282. info_ptr->x_blue = (float)blue_x;
  196283. info_ptr->y_blue = (float)blue_y;
  196284. #ifdef PNG_FIXED_POINT_SUPPORTED
  196285. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196286. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196287. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196288. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196289. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196290. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196291. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196292. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196293. #endif
  196294. info_ptr->valid |= PNG_INFO_cHRM;
  196295. }
  196296. #endif
  196297. #ifdef PNG_FIXED_POINT_SUPPORTED
  196298. void PNGAPI
  196299. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196300. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196301. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196302. png_fixed_point blue_x, png_fixed_point blue_y)
  196303. {
  196304. png_debug1(1, "in %s storage function\n", "cHRM");
  196305. if (png_ptr == NULL || info_ptr == NULL)
  196306. return;
  196307. if (white_x < 0 || white_y < 0 ||
  196308. red_x < 0 || red_y < 0 ||
  196309. green_x < 0 || green_y < 0 ||
  196310. blue_x < 0 || blue_y < 0)
  196311. {
  196312. png_warning(png_ptr,
  196313. "Ignoring attempt to set negative chromaticity value");
  196314. return;
  196315. }
  196316. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196317. if (white_x > (double) PNG_UINT_31_MAX ||
  196318. white_y > (double) PNG_UINT_31_MAX ||
  196319. red_x > (double) PNG_UINT_31_MAX ||
  196320. red_y > (double) PNG_UINT_31_MAX ||
  196321. green_x > (double) PNG_UINT_31_MAX ||
  196322. green_y > (double) PNG_UINT_31_MAX ||
  196323. blue_x > (double) PNG_UINT_31_MAX ||
  196324. blue_y > (double) PNG_UINT_31_MAX)
  196325. #else
  196326. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196327. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196328. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196329. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196330. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196331. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196332. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196333. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196334. #endif
  196335. {
  196336. png_warning(png_ptr,
  196337. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196338. return;
  196339. }
  196340. info_ptr->int_x_white = white_x;
  196341. info_ptr->int_y_white = white_y;
  196342. info_ptr->int_x_red = red_x;
  196343. info_ptr->int_y_red = red_y;
  196344. info_ptr->int_x_green = green_x;
  196345. info_ptr->int_y_green = green_y;
  196346. info_ptr->int_x_blue = blue_x;
  196347. info_ptr->int_y_blue = blue_y;
  196348. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196349. info_ptr->x_white = (float)(white_x/100000.);
  196350. info_ptr->y_white = (float)(white_y/100000.);
  196351. info_ptr->x_red = (float)( red_x/100000.);
  196352. info_ptr->y_red = (float)( red_y/100000.);
  196353. info_ptr->x_green = (float)(green_x/100000.);
  196354. info_ptr->y_green = (float)(green_y/100000.);
  196355. info_ptr->x_blue = (float)( blue_x/100000.);
  196356. info_ptr->y_blue = (float)( blue_y/100000.);
  196357. #endif
  196358. info_ptr->valid |= PNG_INFO_cHRM;
  196359. }
  196360. #endif
  196361. #endif
  196362. #if defined(PNG_gAMA_SUPPORTED)
  196363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196364. void PNGAPI
  196365. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196366. {
  196367. double gamma;
  196368. png_debug1(1, "in %s storage function\n", "gAMA");
  196369. if (png_ptr == NULL || info_ptr == NULL)
  196370. return;
  196371. /* Check for overflow */
  196372. if (file_gamma > 21474.83)
  196373. {
  196374. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196375. gamma=21474.83;
  196376. }
  196377. else
  196378. gamma=file_gamma;
  196379. info_ptr->gamma = (float)gamma;
  196380. #ifdef PNG_FIXED_POINT_SUPPORTED
  196381. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196382. #endif
  196383. info_ptr->valid |= PNG_INFO_gAMA;
  196384. if(gamma == 0.0)
  196385. png_warning(png_ptr, "Setting gamma=0");
  196386. }
  196387. #endif
  196388. void PNGAPI
  196389. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196390. int_gamma)
  196391. {
  196392. png_fixed_point gamma;
  196393. png_debug1(1, "in %s storage function\n", "gAMA");
  196394. if (png_ptr == NULL || info_ptr == NULL)
  196395. return;
  196396. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196397. {
  196398. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196399. gamma=PNG_UINT_31_MAX;
  196400. }
  196401. else
  196402. {
  196403. if (int_gamma < 0)
  196404. {
  196405. png_warning(png_ptr, "Setting negative gamma to zero");
  196406. gamma=0;
  196407. }
  196408. else
  196409. gamma=int_gamma;
  196410. }
  196411. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196412. info_ptr->gamma = (float)(gamma/100000.);
  196413. #endif
  196414. #ifdef PNG_FIXED_POINT_SUPPORTED
  196415. info_ptr->int_gamma = gamma;
  196416. #endif
  196417. info_ptr->valid |= PNG_INFO_gAMA;
  196418. if(gamma == 0)
  196419. png_warning(png_ptr, "Setting gamma=0");
  196420. }
  196421. #endif
  196422. #if defined(PNG_hIST_SUPPORTED)
  196423. void PNGAPI
  196424. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196425. {
  196426. int i;
  196427. png_debug1(1, "in %s storage function\n", "hIST");
  196428. if (png_ptr == NULL || info_ptr == NULL)
  196429. return;
  196430. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196431. > PNG_MAX_PALETTE_LENGTH)
  196432. {
  196433. png_warning(png_ptr,
  196434. "Invalid palette size, hIST allocation skipped.");
  196435. return;
  196436. }
  196437. #ifdef PNG_FREE_ME_SUPPORTED
  196438. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196439. #endif
  196440. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196441. 1.2.1 */
  196442. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196443. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196444. if (png_ptr->hist == NULL)
  196445. {
  196446. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196447. return;
  196448. }
  196449. for (i = 0; i < info_ptr->num_palette; i++)
  196450. png_ptr->hist[i] = hist[i];
  196451. info_ptr->hist = png_ptr->hist;
  196452. info_ptr->valid |= PNG_INFO_hIST;
  196453. #ifdef PNG_FREE_ME_SUPPORTED
  196454. info_ptr->free_me |= PNG_FREE_HIST;
  196455. #else
  196456. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196457. #endif
  196458. }
  196459. #endif
  196460. void PNGAPI
  196461. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196462. png_uint_32 width, png_uint_32 height, int bit_depth,
  196463. int color_type, int interlace_type, int compression_type,
  196464. int filter_type)
  196465. {
  196466. png_debug1(1, "in %s storage function\n", "IHDR");
  196467. if (png_ptr == NULL || info_ptr == NULL)
  196468. return;
  196469. /* check for width and height valid values */
  196470. if (width == 0 || height == 0)
  196471. png_error(png_ptr, "Image width or height is zero in IHDR");
  196472. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196473. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196474. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196475. #else
  196476. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196477. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196478. #endif
  196479. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196480. png_error(png_ptr, "Invalid image size in IHDR");
  196481. if ( width > (PNG_UINT_32_MAX
  196482. >> 3) /* 8-byte RGBA pixels */
  196483. - 64 /* bigrowbuf hack */
  196484. - 1 /* filter byte */
  196485. - 7*8 /* rounding of width to multiple of 8 pixels */
  196486. - 8) /* extra max_pixel_depth pad */
  196487. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196488. /* check other values */
  196489. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196490. bit_depth != 8 && bit_depth != 16)
  196491. png_error(png_ptr, "Invalid bit depth in IHDR");
  196492. if (color_type < 0 || color_type == 1 ||
  196493. color_type == 5 || color_type > 6)
  196494. png_error(png_ptr, "Invalid color type in IHDR");
  196495. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196496. ((color_type == PNG_COLOR_TYPE_RGB ||
  196497. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196498. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196499. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196500. if (interlace_type >= PNG_INTERLACE_LAST)
  196501. png_error(png_ptr, "Unknown interlace method in IHDR");
  196502. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196503. png_error(png_ptr, "Unknown compression method in IHDR");
  196504. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196505. /* Accept filter_method 64 (intrapixel differencing) only if
  196506. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196507. * 2. Libpng did not read a PNG signature (this filter_method is only
  196508. * used in PNG datastreams that are embedded in MNG datastreams) and
  196509. * 3. The application called png_permit_mng_features with a mask that
  196510. * included PNG_FLAG_MNG_FILTER_64 and
  196511. * 4. The filter_method is 64 and
  196512. * 5. The color_type is RGB or RGBA
  196513. */
  196514. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196515. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196516. if(filter_type != PNG_FILTER_TYPE_BASE)
  196517. {
  196518. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196519. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196520. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196521. (color_type == PNG_COLOR_TYPE_RGB ||
  196522. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196523. png_error(png_ptr, "Unknown filter method in IHDR");
  196524. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196525. png_warning(png_ptr, "Invalid filter method in IHDR");
  196526. }
  196527. #else
  196528. if(filter_type != PNG_FILTER_TYPE_BASE)
  196529. png_error(png_ptr, "Unknown filter method in IHDR");
  196530. #endif
  196531. info_ptr->width = width;
  196532. info_ptr->height = height;
  196533. info_ptr->bit_depth = (png_byte)bit_depth;
  196534. info_ptr->color_type =(png_byte) color_type;
  196535. info_ptr->compression_type = (png_byte)compression_type;
  196536. info_ptr->filter_type = (png_byte)filter_type;
  196537. info_ptr->interlace_type = (png_byte)interlace_type;
  196538. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196539. info_ptr->channels = 1;
  196540. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196541. info_ptr->channels = 3;
  196542. else
  196543. info_ptr->channels = 1;
  196544. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196545. info_ptr->channels++;
  196546. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196547. /* check for potential overflow */
  196548. if (width > (PNG_UINT_32_MAX
  196549. >> 3) /* 8-byte RGBA pixels */
  196550. - 64 /* bigrowbuf hack */
  196551. - 1 /* filter byte */
  196552. - 7*8 /* rounding of width to multiple of 8 pixels */
  196553. - 8) /* extra max_pixel_depth pad */
  196554. info_ptr->rowbytes = (png_size_t)0;
  196555. else
  196556. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196557. }
  196558. #if defined(PNG_oFFs_SUPPORTED)
  196559. void PNGAPI
  196560. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196561. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196562. {
  196563. png_debug1(1, "in %s storage function\n", "oFFs");
  196564. if (png_ptr == NULL || info_ptr == NULL)
  196565. return;
  196566. info_ptr->x_offset = offset_x;
  196567. info_ptr->y_offset = offset_y;
  196568. info_ptr->offset_unit_type = (png_byte)unit_type;
  196569. info_ptr->valid |= PNG_INFO_oFFs;
  196570. }
  196571. #endif
  196572. #if defined(PNG_pCAL_SUPPORTED)
  196573. void PNGAPI
  196574. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196575. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196576. png_charp units, png_charpp params)
  196577. {
  196578. png_uint_32 length;
  196579. int i;
  196580. png_debug1(1, "in %s storage function\n", "pCAL");
  196581. if (png_ptr == NULL || info_ptr == NULL)
  196582. return;
  196583. length = png_strlen(purpose) + 1;
  196584. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196585. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196586. if (info_ptr->pcal_purpose == NULL)
  196587. {
  196588. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196589. return;
  196590. }
  196591. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196592. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196593. info_ptr->pcal_X0 = X0;
  196594. info_ptr->pcal_X1 = X1;
  196595. info_ptr->pcal_type = (png_byte)type;
  196596. info_ptr->pcal_nparams = (png_byte)nparams;
  196597. length = png_strlen(units) + 1;
  196598. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196599. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196600. if (info_ptr->pcal_units == NULL)
  196601. {
  196602. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196603. return;
  196604. }
  196605. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196606. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196607. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196608. if (info_ptr->pcal_params == NULL)
  196609. {
  196610. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196611. return;
  196612. }
  196613. info_ptr->pcal_params[nparams] = NULL;
  196614. for (i = 0; i < nparams; i++)
  196615. {
  196616. length = png_strlen(params[i]) + 1;
  196617. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196618. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196619. if (info_ptr->pcal_params[i] == NULL)
  196620. {
  196621. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196622. return;
  196623. }
  196624. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196625. }
  196626. info_ptr->valid |= PNG_INFO_pCAL;
  196627. #ifdef PNG_FREE_ME_SUPPORTED
  196628. info_ptr->free_me |= PNG_FREE_PCAL;
  196629. #endif
  196630. }
  196631. #endif
  196632. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196633. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196634. void PNGAPI
  196635. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196636. int unit, double width, double height)
  196637. {
  196638. png_debug1(1, "in %s storage function\n", "sCAL");
  196639. if (png_ptr == NULL || info_ptr == NULL)
  196640. return;
  196641. info_ptr->scal_unit = (png_byte)unit;
  196642. info_ptr->scal_pixel_width = width;
  196643. info_ptr->scal_pixel_height = height;
  196644. info_ptr->valid |= PNG_INFO_sCAL;
  196645. }
  196646. #else
  196647. #ifdef PNG_FIXED_POINT_SUPPORTED
  196648. void PNGAPI
  196649. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196650. int unit, png_charp swidth, png_charp sheight)
  196651. {
  196652. png_uint_32 length;
  196653. png_debug1(1, "in %s storage function\n", "sCAL");
  196654. if (png_ptr == NULL || info_ptr == NULL)
  196655. return;
  196656. info_ptr->scal_unit = (png_byte)unit;
  196657. length = png_strlen(swidth) + 1;
  196658. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196659. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196660. if (info_ptr->scal_s_width == NULL)
  196661. {
  196662. png_warning(png_ptr,
  196663. "Memory allocation failed while processing sCAL.");
  196664. }
  196665. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196666. length = png_strlen(sheight) + 1;
  196667. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196668. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196669. if (info_ptr->scal_s_height == NULL)
  196670. {
  196671. png_free (png_ptr, info_ptr->scal_s_width);
  196672. png_warning(png_ptr,
  196673. "Memory allocation failed while processing sCAL.");
  196674. }
  196675. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196676. info_ptr->valid |= PNG_INFO_sCAL;
  196677. #ifdef PNG_FREE_ME_SUPPORTED
  196678. info_ptr->free_me |= PNG_FREE_SCAL;
  196679. #endif
  196680. }
  196681. #endif
  196682. #endif
  196683. #endif
  196684. #if defined(PNG_pHYs_SUPPORTED)
  196685. void PNGAPI
  196686. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196687. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196688. {
  196689. png_debug1(1, "in %s storage function\n", "pHYs");
  196690. if (png_ptr == NULL || info_ptr == NULL)
  196691. return;
  196692. info_ptr->x_pixels_per_unit = res_x;
  196693. info_ptr->y_pixels_per_unit = res_y;
  196694. info_ptr->phys_unit_type = (png_byte)unit_type;
  196695. info_ptr->valid |= PNG_INFO_pHYs;
  196696. }
  196697. #endif
  196698. void PNGAPI
  196699. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196700. png_colorp palette, int num_palette)
  196701. {
  196702. png_debug1(1, "in %s storage function\n", "PLTE");
  196703. if (png_ptr == NULL || info_ptr == NULL)
  196704. return;
  196705. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196706. {
  196707. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196708. png_error(png_ptr, "Invalid palette length");
  196709. else
  196710. {
  196711. png_warning(png_ptr, "Invalid palette length");
  196712. return;
  196713. }
  196714. }
  196715. /*
  196716. * It may not actually be necessary to set png_ptr->palette here;
  196717. * we do it for backward compatibility with the way the png_handle_tRNS
  196718. * function used to do the allocation.
  196719. */
  196720. #ifdef PNG_FREE_ME_SUPPORTED
  196721. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196722. #endif
  196723. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196724. of num_palette entries,
  196725. in case of an invalid PNG file that has too-large sample values. */
  196726. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196727. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196728. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196729. png_sizeof(png_color));
  196730. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196731. info_ptr->palette = png_ptr->palette;
  196732. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196733. #ifdef PNG_FREE_ME_SUPPORTED
  196734. info_ptr->free_me |= PNG_FREE_PLTE;
  196735. #else
  196736. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196737. #endif
  196738. info_ptr->valid |= PNG_INFO_PLTE;
  196739. }
  196740. #if defined(PNG_sBIT_SUPPORTED)
  196741. void PNGAPI
  196742. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196743. png_color_8p sig_bit)
  196744. {
  196745. png_debug1(1, "in %s storage function\n", "sBIT");
  196746. if (png_ptr == NULL || info_ptr == NULL)
  196747. return;
  196748. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196749. info_ptr->valid |= PNG_INFO_sBIT;
  196750. }
  196751. #endif
  196752. #if defined(PNG_sRGB_SUPPORTED)
  196753. void PNGAPI
  196754. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196755. {
  196756. png_debug1(1, "in %s storage function\n", "sRGB");
  196757. if (png_ptr == NULL || info_ptr == NULL)
  196758. return;
  196759. info_ptr->srgb_intent = (png_byte)intent;
  196760. info_ptr->valid |= PNG_INFO_sRGB;
  196761. }
  196762. void PNGAPI
  196763. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196764. int intent)
  196765. {
  196766. #if defined(PNG_gAMA_SUPPORTED)
  196767. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196768. float file_gamma;
  196769. #endif
  196770. #ifdef PNG_FIXED_POINT_SUPPORTED
  196771. png_fixed_point int_file_gamma;
  196772. #endif
  196773. #endif
  196774. #if defined(PNG_cHRM_SUPPORTED)
  196775. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196776. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196777. #endif
  196778. #ifdef PNG_FIXED_POINT_SUPPORTED
  196779. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196780. int_green_y, int_blue_x, int_blue_y;
  196781. #endif
  196782. #endif
  196783. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196784. if (png_ptr == NULL || info_ptr == NULL)
  196785. return;
  196786. png_set_sRGB(png_ptr, info_ptr, intent);
  196787. #if defined(PNG_gAMA_SUPPORTED)
  196788. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196789. file_gamma = (float).45455;
  196790. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196791. #endif
  196792. #ifdef PNG_FIXED_POINT_SUPPORTED
  196793. int_file_gamma = 45455L;
  196794. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196795. #endif
  196796. #endif
  196797. #if defined(PNG_cHRM_SUPPORTED)
  196798. #ifdef PNG_FIXED_POINT_SUPPORTED
  196799. int_white_x = 31270L;
  196800. int_white_y = 32900L;
  196801. int_red_x = 64000L;
  196802. int_red_y = 33000L;
  196803. int_green_x = 30000L;
  196804. int_green_y = 60000L;
  196805. int_blue_x = 15000L;
  196806. int_blue_y = 6000L;
  196807. png_set_cHRM_fixed(png_ptr, info_ptr,
  196808. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196809. int_blue_x, int_blue_y);
  196810. #endif
  196811. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196812. white_x = (float).3127;
  196813. white_y = (float).3290;
  196814. red_x = (float).64;
  196815. red_y = (float).33;
  196816. green_x = (float).30;
  196817. green_y = (float).60;
  196818. blue_x = (float).15;
  196819. blue_y = (float).06;
  196820. png_set_cHRM(png_ptr, info_ptr,
  196821. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196822. #endif
  196823. #endif
  196824. }
  196825. #endif
  196826. #if defined(PNG_iCCP_SUPPORTED)
  196827. void PNGAPI
  196828. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196829. png_charp name, int compression_type,
  196830. png_charp profile, png_uint_32 proflen)
  196831. {
  196832. png_charp new_iccp_name;
  196833. png_charp new_iccp_profile;
  196834. png_debug1(1, "in %s storage function\n", "iCCP");
  196835. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196836. return;
  196837. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196838. if (new_iccp_name == NULL)
  196839. {
  196840. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196841. return;
  196842. }
  196843. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196844. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196845. if (new_iccp_profile == NULL)
  196846. {
  196847. png_free (png_ptr, new_iccp_name);
  196848. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196849. return;
  196850. }
  196851. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196852. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196853. info_ptr->iccp_proflen = proflen;
  196854. info_ptr->iccp_name = new_iccp_name;
  196855. info_ptr->iccp_profile = new_iccp_profile;
  196856. /* Compression is always zero but is here so the API and info structure
  196857. * does not have to change if we introduce multiple compression types */
  196858. info_ptr->iccp_compression = (png_byte)compression_type;
  196859. #ifdef PNG_FREE_ME_SUPPORTED
  196860. info_ptr->free_me |= PNG_FREE_ICCP;
  196861. #endif
  196862. info_ptr->valid |= PNG_INFO_iCCP;
  196863. }
  196864. #endif
  196865. #if defined(PNG_TEXT_SUPPORTED)
  196866. void PNGAPI
  196867. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196868. int num_text)
  196869. {
  196870. int ret;
  196871. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196872. if (ret)
  196873. png_error(png_ptr, "Insufficient memory to store text");
  196874. }
  196875. int /* PRIVATE */
  196876. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196877. int num_text)
  196878. {
  196879. int i;
  196880. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196881. "text" : (png_const_charp)png_ptr->chunk_name));
  196882. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196883. return(0);
  196884. /* Make sure we have enough space in the "text" array in info_struct
  196885. * to hold all of the incoming text_ptr objects.
  196886. */
  196887. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196888. {
  196889. if (info_ptr->text != NULL)
  196890. {
  196891. png_textp old_text;
  196892. int old_max;
  196893. old_max = info_ptr->max_text;
  196894. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196895. old_text = info_ptr->text;
  196896. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196897. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196898. if (info_ptr->text == NULL)
  196899. {
  196900. png_free(png_ptr, old_text);
  196901. return(1);
  196902. }
  196903. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196904. png_sizeof(png_text)));
  196905. png_free(png_ptr, old_text);
  196906. }
  196907. else
  196908. {
  196909. info_ptr->max_text = num_text + 8;
  196910. info_ptr->num_text = 0;
  196911. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196912. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196913. if (info_ptr->text == NULL)
  196914. return(1);
  196915. #ifdef PNG_FREE_ME_SUPPORTED
  196916. info_ptr->free_me |= PNG_FREE_TEXT;
  196917. #endif
  196918. }
  196919. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196920. info_ptr->max_text);
  196921. }
  196922. for (i = 0; i < num_text; i++)
  196923. {
  196924. png_size_t text_length,key_len;
  196925. png_size_t lang_len,lang_key_len;
  196926. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196927. if (text_ptr[i].key == NULL)
  196928. continue;
  196929. key_len = png_strlen(text_ptr[i].key);
  196930. if(text_ptr[i].compression <= 0)
  196931. {
  196932. lang_len = 0;
  196933. lang_key_len = 0;
  196934. }
  196935. else
  196936. #ifdef PNG_iTXt_SUPPORTED
  196937. {
  196938. /* set iTXt data */
  196939. if (text_ptr[i].lang != NULL)
  196940. lang_len = png_strlen(text_ptr[i].lang);
  196941. else
  196942. lang_len = 0;
  196943. if (text_ptr[i].lang_key != NULL)
  196944. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196945. else
  196946. lang_key_len = 0;
  196947. }
  196948. #else
  196949. {
  196950. png_warning(png_ptr, "iTXt chunk not supported.");
  196951. continue;
  196952. }
  196953. #endif
  196954. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196955. {
  196956. text_length = 0;
  196957. #ifdef PNG_iTXt_SUPPORTED
  196958. if(text_ptr[i].compression > 0)
  196959. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196960. else
  196961. #endif
  196962. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196963. }
  196964. else
  196965. {
  196966. text_length = png_strlen(text_ptr[i].text);
  196967. textp->compression = text_ptr[i].compression;
  196968. }
  196969. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196970. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196971. if (textp->key == NULL)
  196972. return(1);
  196973. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196974. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196975. (int)textp->key);
  196976. png_memcpy(textp->key, text_ptr[i].key,
  196977. (png_size_t)(key_len));
  196978. *(textp->key+key_len) = '\0';
  196979. #ifdef PNG_iTXt_SUPPORTED
  196980. if (text_ptr[i].compression > 0)
  196981. {
  196982. textp->lang=textp->key + key_len + 1;
  196983. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196984. *(textp->lang+lang_len) = '\0';
  196985. textp->lang_key=textp->lang + lang_len + 1;
  196986. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196987. *(textp->lang_key+lang_key_len) = '\0';
  196988. textp->text=textp->lang_key + lang_key_len + 1;
  196989. }
  196990. else
  196991. #endif
  196992. {
  196993. #ifdef PNG_iTXt_SUPPORTED
  196994. textp->lang=NULL;
  196995. textp->lang_key=NULL;
  196996. #endif
  196997. textp->text=textp->key + key_len + 1;
  196998. }
  196999. if(text_length)
  197000. png_memcpy(textp->text, text_ptr[i].text,
  197001. (png_size_t)(text_length));
  197002. *(textp->text+text_length) = '\0';
  197003. #ifdef PNG_iTXt_SUPPORTED
  197004. if(textp->compression > 0)
  197005. {
  197006. textp->text_length = 0;
  197007. textp->itxt_length = text_length;
  197008. }
  197009. else
  197010. #endif
  197011. {
  197012. textp->text_length = text_length;
  197013. #ifdef PNG_iTXt_SUPPORTED
  197014. textp->itxt_length = 0;
  197015. #endif
  197016. }
  197017. info_ptr->num_text++;
  197018. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197019. }
  197020. return(0);
  197021. }
  197022. #endif
  197023. #if defined(PNG_tIME_SUPPORTED)
  197024. void PNGAPI
  197025. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197026. {
  197027. png_debug1(1, "in %s storage function\n", "tIME");
  197028. if (png_ptr == NULL || info_ptr == NULL ||
  197029. (png_ptr->mode & PNG_WROTE_tIME))
  197030. return;
  197031. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197032. info_ptr->valid |= PNG_INFO_tIME;
  197033. }
  197034. #endif
  197035. #if defined(PNG_tRNS_SUPPORTED)
  197036. void PNGAPI
  197037. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197038. png_bytep trans, int num_trans, png_color_16p trans_values)
  197039. {
  197040. png_debug1(1, "in %s storage function\n", "tRNS");
  197041. if (png_ptr == NULL || info_ptr == NULL)
  197042. return;
  197043. if (trans != NULL)
  197044. {
  197045. /*
  197046. * It may not actually be necessary to set png_ptr->trans here;
  197047. * we do it for backward compatibility with the way the png_handle_tRNS
  197048. * function used to do the allocation.
  197049. */
  197050. #ifdef PNG_FREE_ME_SUPPORTED
  197051. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197052. #endif
  197053. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197054. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197055. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197056. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197057. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197058. #ifdef PNG_FREE_ME_SUPPORTED
  197059. info_ptr->free_me |= PNG_FREE_TRNS;
  197060. #else
  197061. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197062. #endif
  197063. }
  197064. if (trans_values != NULL)
  197065. {
  197066. png_memcpy(&(info_ptr->trans_values), trans_values,
  197067. png_sizeof(png_color_16));
  197068. if (num_trans == 0)
  197069. num_trans = 1;
  197070. }
  197071. info_ptr->num_trans = (png_uint_16)num_trans;
  197072. info_ptr->valid |= PNG_INFO_tRNS;
  197073. }
  197074. #endif
  197075. #if defined(PNG_sPLT_SUPPORTED)
  197076. void PNGAPI
  197077. png_set_sPLT(png_structp png_ptr,
  197078. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197079. {
  197080. png_sPLT_tp np;
  197081. int i;
  197082. if (png_ptr == NULL || info_ptr == NULL)
  197083. return;
  197084. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197085. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197086. if (np == NULL)
  197087. {
  197088. png_warning(png_ptr, "No memory for sPLT palettes.");
  197089. return;
  197090. }
  197091. png_memcpy(np, info_ptr->splt_palettes,
  197092. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197093. png_free(png_ptr, info_ptr->splt_palettes);
  197094. info_ptr->splt_palettes=NULL;
  197095. for (i = 0; i < nentries; i++)
  197096. {
  197097. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197098. png_sPLT_tp from = entries + i;
  197099. to->name = (png_charp)png_malloc_warn(png_ptr,
  197100. png_strlen(from->name) + 1);
  197101. if (to->name == NULL)
  197102. {
  197103. png_warning(png_ptr,
  197104. "Out of memory while processing sPLT chunk");
  197105. }
  197106. /* TODO: use png_malloc_warn */
  197107. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197108. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197109. from->nentries * png_sizeof(png_sPLT_entry));
  197110. /* TODO: use png_malloc_warn */
  197111. png_memcpy(to->entries, from->entries,
  197112. from->nentries * png_sizeof(png_sPLT_entry));
  197113. if (to->entries == NULL)
  197114. {
  197115. png_warning(png_ptr,
  197116. "Out of memory while processing sPLT chunk");
  197117. png_free(png_ptr,to->name);
  197118. to->name = NULL;
  197119. }
  197120. to->nentries = from->nentries;
  197121. to->depth = from->depth;
  197122. }
  197123. info_ptr->splt_palettes = np;
  197124. info_ptr->splt_palettes_num += nentries;
  197125. info_ptr->valid |= PNG_INFO_sPLT;
  197126. #ifdef PNG_FREE_ME_SUPPORTED
  197127. info_ptr->free_me |= PNG_FREE_SPLT;
  197128. #endif
  197129. }
  197130. #endif /* PNG_sPLT_SUPPORTED */
  197131. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197132. void PNGAPI
  197133. png_set_unknown_chunks(png_structp png_ptr,
  197134. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197135. {
  197136. png_unknown_chunkp np;
  197137. int i;
  197138. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197139. return;
  197140. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197141. (info_ptr->unknown_chunks_num + num_unknowns) *
  197142. png_sizeof(png_unknown_chunk));
  197143. if (np == NULL)
  197144. {
  197145. png_warning(png_ptr,
  197146. "Out of memory while processing unknown chunk.");
  197147. return;
  197148. }
  197149. png_memcpy(np, info_ptr->unknown_chunks,
  197150. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197151. png_free(png_ptr, info_ptr->unknown_chunks);
  197152. info_ptr->unknown_chunks=NULL;
  197153. for (i = 0; i < num_unknowns; i++)
  197154. {
  197155. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197156. png_unknown_chunkp from = unknowns + i;
  197157. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197158. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197159. if (to->data == NULL)
  197160. {
  197161. png_warning(png_ptr,
  197162. "Out of memory while processing unknown chunk.");
  197163. }
  197164. else
  197165. {
  197166. png_memcpy(to->data, from->data, from->size);
  197167. to->size = from->size;
  197168. /* note our location in the read or write sequence */
  197169. to->location = (png_byte)(png_ptr->mode & 0xff);
  197170. }
  197171. }
  197172. info_ptr->unknown_chunks = np;
  197173. info_ptr->unknown_chunks_num += num_unknowns;
  197174. #ifdef PNG_FREE_ME_SUPPORTED
  197175. info_ptr->free_me |= PNG_FREE_UNKN;
  197176. #endif
  197177. }
  197178. void PNGAPI
  197179. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197180. int chunk, int location)
  197181. {
  197182. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197183. (int)info_ptr->unknown_chunks_num)
  197184. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197185. }
  197186. #endif
  197187. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197188. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197189. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197190. void PNGAPI
  197191. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197192. {
  197193. /* This function is deprecated in favor of png_permit_mng_features()
  197194. and will be removed from libpng-1.3.0 */
  197195. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197196. if (png_ptr == NULL)
  197197. return;
  197198. png_ptr->mng_features_permitted = (png_byte)
  197199. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197200. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197201. }
  197202. #endif
  197203. #endif
  197204. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197205. png_uint_32 PNGAPI
  197206. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197207. {
  197208. png_debug(1, "in png_permit_mng_features\n");
  197209. if (png_ptr == NULL)
  197210. return (png_uint_32)0;
  197211. png_ptr->mng_features_permitted =
  197212. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197213. return (png_uint_32)png_ptr->mng_features_permitted;
  197214. }
  197215. #endif
  197216. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197217. void PNGAPI
  197218. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197219. chunk_list, int num_chunks)
  197220. {
  197221. png_bytep new_list, p;
  197222. int i, old_num_chunks;
  197223. if (png_ptr == NULL)
  197224. return;
  197225. if (num_chunks == 0)
  197226. {
  197227. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197228. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197229. else
  197230. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197231. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197232. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197233. else
  197234. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197235. return;
  197236. }
  197237. if (chunk_list == NULL)
  197238. return;
  197239. old_num_chunks=png_ptr->num_chunk_list;
  197240. new_list=(png_bytep)png_malloc(png_ptr,
  197241. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197242. if(png_ptr->chunk_list != NULL)
  197243. {
  197244. png_memcpy(new_list, png_ptr->chunk_list,
  197245. (png_size_t)(5*old_num_chunks));
  197246. png_free(png_ptr, png_ptr->chunk_list);
  197247. png_ptr->chunk_list=NULL;
  197248. }
  197249. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197250. (png_size_t)(5*num_chunks));
  197251. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197252. *p=(png_byte)keep;
  197253. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197254. png_ptr->chunk_list=new_list;
  197255. #ifdef PNG_FREE_ME_SUPPORTED
  197256. png_ptr->free_me |= PNG_FREE_LIST;
  197257. #endif
  197258. }
  197259. #endif
  197260. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197261. void PNGAPI
  197262. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197263. png_user_chunk_ptr read_user_chunk_fn)
  197264. {
  197265. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197266. if (png_ptr == NULL)
  197267. return;
  197268. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197269. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197270. }
  197271. #endif
  197272. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197273. void PNGAPI
  197274. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197275. {
  197276. png_debug1(1, "in %s storage function\n", "rows");
  197277. if (png_ptr == NULL || info_ptr == NULL)
  197278. return;
  197279. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197280. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197281. info_ptr->row_pointers = row_pointers;
  197282. if(row_pointers)
  197283. info_ptr->valid |= PNG_INFO_IDAT;
  197284. }
  197285. #endif
  197286. #ifdef PNG_WRITE_SUPPORTED
  197287. void PNGAPI
  197288. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197289. {
  197290. if (png_ptr == NULL)
  197291. return;
  197292. if(png_ptr->zbuf)
  197293. png_free(png_ptr, png_ptr->zbuf);
  197294. png_ptr->zbuf_size = (png_size_t)size;
  197295. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197296. png_ptr->zstream.next_out = png_ptr->zbuf;
  197297. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197298. }
  197299. #endif
  197300. void PNGAPI
  197301. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197302. {
  197303. if (png_ptr && info_ptr)
  197304. info_ptr->valid &= ~(mask);
  197305. }
  197306. #ifndef PNG_1_0_X
  197307. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197308. /* function was added to libpng 1.2.0 and should always exist by default */
  197309. void PNGAPI
  197310. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197311. {
  197312. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197313. if (png_ptr != NULL)
  197314. png_ptr->asm_flags = 0;
  197315. }
  197316. /* this function was added to libpng 1.2.0 */
  197317. void PNGAPI
  197318. png_set_mmx_thresholds (png_structp png_ptr,
  197319. png_byte,
  197320. png_uint_32)
  197321. {
  197322. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197323. if (png_ptr == NULL)
  197324. return;
  197325. }
  197326. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197327. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197328. /* this function was added to libpng 1.2.6 */
  197329. void PNGAPI
  197330. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197331. png_uint_32 user_height_max)
  197332. {
  197333. /* Images with dimensions larger than these limits will be
  197334. * rejected by png_set_IHDR(). To accept any PNG datastream
  197335. * regardless of dimensions, set both limits to 0x7ffffffL.
  197336. */
  197337. if(png_ptr == NULL) return;
  197338. png_ptr->user_width_max = user_width_max;
  197339. png_ptr->user_height_max = user_height_max;
  197340. }
  197341. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197342. #endif /* ?PNG_1_0_X */
  197343. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197344. /*** End of inlined file: pngset.c ***/
  197345. /*** Start of inlined file: pngtrans.c ***/
  197346. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197347. *
  197348. * Last changed in libpng 1.2.17 May 15, 2007
  197349. * For conditions of distribution and use, see copyright notice in png.h
  197350. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197351. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197352. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197353. */
  197354. #define PNG_INTERNAL
  197355. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197356. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197357. /* turn on BGR-to-RGB mapping */
  197358. void PNGAPI
  197359. png_set_bgr(png_structp png_ptr)
  197360. {
  197361. png_debug(1, "in png_set_bgr\n");
  197362. if(png_ptr == NULL) return;
  197363. png_ptr->transformations |= PNG_BGR;
  197364. }
  197365. #endif
  197366. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197367. /* turn on 16 bit byte swapping */
  197368. void PNGAPI
  197369. png_set_swap(png_structp png_ptr)
  197370. {
  197371. png_debug(1, "in png_set_swap\n");
  197372. if(png_ptr == NULL) return;
  197373. if (png_ptr->bit_depth == 16)
  197374. png_ptr->transformations |= PNG_SWAP_BYTES;
  197375. }
  197376. #endif
  197377. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197378. /* turn on pixel packing */
  197379. void PNGAPI
  197380. png_set_packing(png_structp png_ptr)
  197381. {
  197382. png_debug(1, "in png_set_packing\n");
  197383. if(png_ptr == NULL) return;
  197384. if (png_ptr->bit_depth < 8)
  197385. {
  197386. png_ptr->transformations |= PNG_PACK;
  197387. png_ptr->usr_bit_depth = 8;
  197388. }
  197389. }
  197390. #endif
  197391. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197392. /* turn on packed pixel swapping */
  197393. void PNGAPI
  197394. png_set_packswap(png_structp png_ptr)
  197395. {
  197396. png_debug(1, "in png_set_packswap\n");
  197397. if(png_ptr == NULL) return;
  197398. if (png_ptr->bit_depth < 8)
  197399. png_ptr->transformations |= PNG_PACKSWAP;
  197400. }
  197401. #endif
  197402. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197403. void PNGAPI
  197404. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197405. {
  197406. png_debug(1, "in png_set_shift\n");
  197407. if(png_ptr == NULL) return;
  197408. png_ptr->transformations |= PNG_SHIFT;
  197409. png_ptr->shift = *true_bits;
  197410. }
  197411. #endif
  197412. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197413. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197414. int PNGAPI
  197415. png_set_interlace_handling(png_structp png_ptr)
  197416. {
  197417. png_debug(1, "in png_set_interlace handling\n");
  197418. if (png_ptr && png_ptr->interlaced)
  197419. {
  197420. png_ptr->transformations |= PNG_INTERLACE;
  197421. return (7);
  197422. }
  197423. return (1);
  197424. }
  197425. #endif
  197426. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197427. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197428. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197429. * for 48-bit input data, as well as to avoid problems with some compilers
  197430. * that don't like bytes as parameters.
  197431. */
  197432. void PNGAPI
  197433. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197434. {
  197435. png_debug(1, "in png_set_filler\n");
  197436. if(png_ptr == NULL) return;
  197437. png_ptr->transformations |= PNG_FILLER;
  197438. png_ptr->filler = (png_byte)filler;
  197439. if (filler_loc == PNG_FILLER_AFTER)
  197440. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197441. else
  197442. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197443. /* This should probably go in the "do_read_filler" routine.
  197444. * I attempted to do that in libpng-1.0.1a but that caused problems
  197445. * so I restored it in libpng-1.0.2a
  197446. */
  197447. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197448. {
  197449. png_ptr->usr_channels = 4;
  197450. }
  197451. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197452. * a less-than-8-bit grayscale to GA? */
  197453. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197454. {
  197455. png_ptr->usr_channels = 2;
  197456. }
  197457. }
  197458. #if !defined(PNG_1_0_X)
  197459. /* Added to libpng-1.2.7 */
  197460. void PNGAPI
  197461. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197462. {
  197463. png_debug(1, "in png_set_add_alpha\n");
  197464. if(png_ptr == NULL) return;
  197465. png_set_filler(png_ptr, filler, filler_loc);
  197466. png_ptr->transformations |= PNG_ADD_ALPHA;
  197467. }
  197468. #endif
  197469. #endif
  197470. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197471. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197472. void PNGAPI
  197473. png_set_swap_alpha(png_structp png_ptr)
  197474. {
  197475. png_debug(1, "in png_set_swap_alpha\n");
  197476. if(png_ptr == NULL) return;
  197477. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197478. }
  197479. #endif
  197480. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197481. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197482. void PNGAPI
  197483. png_set_invert_alpha(png_structp png_ptr)
  197484. {
  197485. png_debug(1, "in png_set_invert_alpha\n");
  197486. if(png_ptr == NULL) return;
  197487. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197488. }
  197489. #endif
  197490. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197491. void PNGAPI
  197492. png_set_invert_mono(png_structp png_ptr)
  197493. {
  197494. png_debug(1, "in png_set_invert_mono\n");
  197495. if(png_ptr == NULL) return;
  197496. png_ptr->transformations |= PNG_INVERT_MONO;
  197497. }
  197498. /* invert monochrome grayscale data */
  197499. void /* PRIVATE */
  197500. png_do_invert(png_row_infop row_info, png_bytep row)
  197501. {
  197502. png_debug(1, "in png_do_invert\n");
  197503. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197504. * if (row_info->bit_depth == 1 &&
  197505. */
  197506. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197507. if (row == NULL || row_info == NULL)
  197508. return;
  197509. #endif
  197510. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197511. {
  197512. png_bytep rp = row;
  197513. png_uint_32 i;
  197514. png_uint_32 istop = row_info->rowbytes;
  197515. for (i = 0; i < istop; i++)
  197516. {
  197517. *rp = (png_byte)(~(*rp));
  197518. rp++;
  197519. }
  197520. }
  197521. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197522. row_info->bit_depth == 8)
  197523. {
  197524. png_bytep rp = row;
  197525. png_uint_32 i;
  197526. png_uint_32 istop = row_info->rowbytes;
  197527. for (i = 0; i < istop; i+=2)
  197528. {
  197529. *rp = (png_byte)(~(*rp));
  197530. rp+=2;
  197531. }
  197532. }
  197533. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197534. row_info->bit_depth == 16)
  197535. {
  197536. png_bytep rp = row;
  197537. png_uint_32 i;
  197538. png_uint_32 istop = row_info->rowbytes;
  197539. for (i = 0; i < istop; i+=4)
  197540. {
  197541. *rp = (png_byte)(~(*rp));
  197542. *(rp+1) = (png_byte)(~(*(rp+1)));
  197543. rp+=4;
  197544. }
  197545. }
  197546. }
  197547. #endif
  197548. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197549. /* swaps byte order on 16 bit depth images */
  197550. void /* PRIVATE */
  197551. png_do_swap(png_row_infop row_info, png_bytep row)
  197552. {
  197553. png_debug(1, "in png_do_swap\n");
  197554. if (
  197555. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197556. row != NULL && row_info != NULL &&
  197557. #endif
  197558. row_info->bit_depth == 16)
  197559. {
  197560. png_bytep rp = row;
  197561. png_uint_32 i;
  197562. png_uint_32 istop= row_info->width * row_info->channels;
  197563. for (i = 0; i < istop; i++, rp += 2)
  197564. {
  197565. png_byte t = *rp;
  197566. *rp = *(rp + 1);
  197567. *(rp + 1) = t;
  197568. }
  197569. }
  197570. }
  197571. #endif
  197572. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197573. static PNG_CONST png_byte onebppswaptable[256] = {
  197574. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197575. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197576. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197577. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197578. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197579. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197580. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197581. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197582. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197583. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197584. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197585. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197586. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197587. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197588. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197589. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197590. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197591. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197592. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197593. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197594. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197595. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197596. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197597. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197598. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197599. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197600. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197601. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197602. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197603. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197604. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197605. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197606. };
  197607. static PNG_CONST png_byte twobppswaptable[256] = {
  197608. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197609. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197610. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197611. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197612. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197613. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197614. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197615. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197616. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197617. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197618. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197619. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197620. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197621. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197622. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197623. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197624. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197625. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197626. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197627. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197628. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197629. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197630. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197631. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197632. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197633. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197634. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197635. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197636. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197637. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197638. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197639. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197640. };
  197641. static PNG_CONST png_byte fourbppswaptable[256] = {
  197642. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197643. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197644. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197645. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197646. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197647. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197648. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197649. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197650. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197651. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197652. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197653. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197654. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197655. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197656. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197657. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197658. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197659. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197660. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197661. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197662. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197663. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197664. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197665. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197666. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197667. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197668. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197669. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197670. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197671. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197672. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197673. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197674. };
  197675. /* swaps pixel packing order within bytes */
  197676. void /* PRIVATE */
  197677. png_do_packswap(png_row_infop row_info, png_bytep row)
  197678. {
  197679. png_debug(1, "in png_do_packswap\n");
  197680. if (
  197681. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197682. row != NULL && row_info != NULL &&
  197683. #endif
  197684. row_info->bit_depth < 8)
  197685. {
  197686. png_bytep rp, end, table;
  197687. end = row + row_info->rowbytes;
  197688. if (row_info->bit_depth == 1)
  197689. table = (png_bytep)onebppswaptable;
  197690. else if (row_info->bit_depth == 2)
  197691. table = (png_bytep)twobppswaptable;
  197692. else if (row_info->bit_depth == 4)
  197693. table = (png_bytep)fourbppswaptable;
  197694. else
  197695. return;
  197696. for (rp = row; rp < end; rp++)
  197697. *rp = table[*rp];
  197698. }
  197699. }
  197700. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197701. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197702. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197703. /* remove filler or alpha byte(s) */
  197704. void /* PRIVATE */
  197705. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197706. {
  197707. png_debug(1, "in png_do_strip_filler\n");
  197708. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197709. if (row != NULL && row_info != NULL)
  197710. #endif
  197711. {
  197712. png_bytep sp=row;
  197713. png_bytep dp=row;
  197714. png_uint_32 row_width=row_info->width;
  197715. png_uint_32 i;
  197716. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197717. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197718. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197719. row_info->channels == 4)
  197720. {
  197721. if (row_info->bit_depth == 8)
  197722. {
  197723. /* This converts from RGBX or RGBA to RGB */
  197724. if (flags & PNG_FLAG_FILLER_AFTER)
  197725. {
  197726. dp+=3; sp+=4;
  197727. for (i = 1; i < row_width; i++)
  197728. {
  197729. *dp++ = *sp++;
  197730. *dp++ = *sp++;
  197731. *dp++ = *sp++;
  197732. sp++;
  197733. }
  197734. }
  197735. /* This converts from XRGB or ARGB to RGB */
  197736. else
  197737. {
  197738. for (i = 0; i < row_width; i++)
  197739. {
  197740. sp++;
  197741. *dp++ = *sp++;
  197742. *dp++ = *sp++;
  197743. *dp++ = *sp++;
  197744. }
  197745. }
  197746. row_info->pixel_depth = 24;
  197747. row_info->rowbytes = row_width * 3;
  197748. }
  197749. else /* if (row_info->bit_depth == 16) */
  197750. {
  197751. if (flags & PNG_FLAG_FILLER_AFTER)
  197752. {
  197753. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197754. sp += 8; dp += 6;
  197755. for (i = 1; i < row_width; i++)
  197756. {
  197757. /* This could be (although png_memcpy is probably slower):
  197758. png_memcpy(dp, sp, 6);
  197759. sp += 8;
  197760. dp += 6;
  197761. */
  197762. *dp++ = *sp++;
  197763. *dp++ = *sp++;
  197764. *dp++ = *sp++;
  197765. *dp++ = *sp++;
  197766. *dp++ = *sp++;
  197767. *dp++ = *sp++;
  197768. sp += 2;
  197769. }
  197770. }
  197771. else
  197772. {
  197773. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197774. for (i = 0; i < row_width; i++)
  197775. {
  197776. /* This could be (although png_memcpy is probably slower):
  197777. png_memcpy(dp, sp, 6);
  197778. sp += 8;
  197779. dp += 6;
  197780. */
  197781. sp+=2;
  197782. *dp++ = *sp++;
  197783. *dp++ = *sp++;
  197784. *dp++ = *sp++;
  197785. *dp++ = *sp++;
  197786. *dp++ = *sp++;
  197787. *dp++ = *sp++;
  197788. }
  197789. }
  197790. row_info->pixel_depth = 48;
  197791. row_info->rowbytes = row_width * 6;
  197792. }
  197793. row_info->channels = 3;
  197794. }
  197795. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197796. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197797. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197798. row_info->channels == 2)
  197799. {
  197800. if (row_info->bit_depth == 8)
  197801. {
  197802. /* This converts from GX or GA to G */
  197803. if (flags & PNG_FLAG_FILLER_AFTER)
  197804. {
  197805. for (i = 0; i < row_width; i++)
  197806. {
  197807. *dp++ = *sp++;
  197808. sp++;
  197809. }
  197810. }
  197811. /* This converts from XG or AG to G */
  197812. else
  197813. {
  197814. for (i = 0; i < row_width; i++)
  197815. {
  197816. sp++;
  197817. *dp++ = *sp++;
  197818. }
  197819. }
  197820. row_info->pixel_depth = 8;
  197821. row_info->rowbytes = row_width;
  197822. }
  197823. else /* if (row_info->bit_depth == 16) */
  197824. {
  197825. if (flags & PNG_FLAG_FILLER_AFTER)
  197826. {
  197827. /* This converts from GGXX or GGAA to GG */
  197828. sp += 4; dp += 2;
  197829. for (i = 1; i < row_width; i++)
  197830. {
  197831. *dp++ = *sp++;
  197832. *dp++ = *sp++;
  197833. sp += 2;
  197834. }
  197835. }
  197836. else
  197837. {
  197838. /* This converts from XXGG or AAGG to GG */
  197839. for (i = 0; i < row_width; i++)
  197840. {
  197841. sp += 2;
  197842. *dp++ = *sp++;
  197843. *dp++ = *sp++;
  197844. }
  197845. }
  197846. row_info->pixel_depth = 16;
  197847. row_info->rowbytes = row_width * 2;
  197848. }
  197849. row_info->channels = 1;
  197850. }
  197851. if (flags & PNG_FLAG_STRIP_ALPHA)
  197852. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197853. }
  197854. }
  197855. #endif
  197856. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197857. /* swaps red and blue bytes within a pixel */
  197858. void /* PRIVATE */
  197859. png_do_bgr(png_row_infop row_info, png_bytep row)
  197860. {
  197861. png_debug(1, "in png_do_bgr\n");
  197862. if (
  197863. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197864. row != NULL && row_info != NULL &&
  197865. #endif
  197866. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197867. {
  197868. png_uint_32 row_width = row_info->width;
  197869. if (row_info->bit_depth == 8)
  197870. {
  197871. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197872. {
  197873. png_bytep rp;
  197874. png_uint_32 i;
  197875. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197876. {
  197877. png_byte save = *rp;
  197878. *rp = *(rp + 2);
  197879. *(rp + 2) = save;
  197880. }
  197881. }
  197882. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197883. {
  197884. png_bytep rp;
  197885. png_uint_32 i;
  197886. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197887. {
  197888. png_byte save = *rp;
  197889. *rp = *(rp + 2);
  197890. *(rp + 2) = save;
  197891. }
  197892. }
  197893. }
  197894. else if (row_info->bit_depth == 16)
  197895. {
  197896. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197897. {
  197898. png_bytep rp;
  197899. png_uint_32 i;
  197900. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197901. {
  197902. png_byte save = *rp;
  197903. *rp = *(rp + 4);
  197904. *(rp + 4) = save;
  197905. save = *(rp + 1);
  197906. *(rp + 1) = *(rp + 5);
  197907. *(rp + 5) = save;
  197908. }
  197909. }
  197910. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197911. {
  197912. png_bytep rp;
  197913. png_uint_32 i;
  197914. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197915. {
  197916. png_byte save = *rp;
  197917. *rp = *(rp + 4);
  197918. *(rp + 4) = save;
  197919. save = *(rp + 1);
  197920. *(rp + 1) = *(rp + 5);
  197921. *(rp + 5) = save;
  197922. }
  197923. }
  197924. }
  197925. }
  197926. }
  197927. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197928. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197929. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197930. defined(PNG_LEGACY_SUPPORTED)
  197931. void PNGAPI
  197932. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197933. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197934. {
  197935. png_debug(1, "in png_set_user_transform_info\n");
  197936. if(png_ptr == NULL) return;
  197937. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197938. png_ptr->user_transform_ptr = user_transform_ptr;
  197939. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197940. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197941. #else
  197942. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197943. png_warning(png_ptr,
  197944. "This version of libpng does not support user transform info");
  197945. #endif
  197946. }
  197947. #endif
  197948. /* This function returns a pointer to the user_transform_ptr associated with
  197949. * the user transform functions. The application should free any memory
  197950. * associated with this pointer before png_write_destroy and png_read_destroy
  197951. * are called.
  197952. */
  197953. png_voidp PNGAPI
  197954. png_get_user_transform_ptr(png_structp png_ptr)
  197955. {
  197956. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197957. if (png_ptr == NULL) return (NULL);
  197958. return ((png_voidp)png_ptr->user_transform_ptr);
  197959. #else
  197960. return (NULL);
  197961. #endif
  197962. }
  197963. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197964. /*** End of inlined file: pngtrans.c ***/
  197965. /*** Start of inlined file: pngwio.c ***/
  197966. /* pngwio.c - functions for data output
  197967. *
  197968. * Last changed in libpng 1.2.13 November 13, 2006
  197969. * For conditions of distribution and use, see copyright notice in png.h
  197970. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197971. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197972. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197973. *
  197974. * This file provides a location for all output. Users who need
  197975. * special handling are expected to write functions that have the same
  197976. * arguments as these and perform similar functions, but that possibly
  197977. * use different output methods. Note that you shouldn't change these
  197978. * functions, but rather write replacement functions and then change
  197979. * them at run time with png_set_write_fn(...).
  197980. */
  197981. #define PNG_INTERNAL
  197982. #ifdef PNG_WRITE_SUPPORTED
  197983. /* Write the data to whatever output you are using. The default routine
  197984. writes to a file pointer. Note that this routine sometimes gets called
  197985. with very small lengths, so you should implement some kind of simple
  197986. buffering if you are using unbuffered writes. This should never be asked
  197987. to write more than 64K on a 16 bit machine. */
  197988. void /* PRIVATE */
  197989. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197990. {
  197991. if (png_ptr->write_data_fn != NULL )
  197992. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197993. else
  197994. png_error(png_ptr, "Call to NULL write function");
  197995. }
  197996. #if !defined(PNG_NO_STDIO)
  197997. /* This is the function that does the actual writing of data. If you are
  197998. not writing to a standard C stream, you should create a replacement
  197999. write_data function and use it at run time with png_set_write_fn(), rather
  198000. than changing the library. */
  198001. #ifndef USE_FAR_KEYWORD
  198002. void PNGAPI
  198003. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198004. {
  198005. png_uint_32 check;
  198006. if(png_ptr == NULL) return;
  198007. #if defined(_WIN32_WCE)
  198008. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198009. check = 0;
  198010. #else
  198011. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198012. #endif
  198013. if (check != length)
  198014. png_error(png_ptr, "Write Error");
  198015. }
  198016. #else
  198017. /* this is the model-independent version. Since the standard I/O library
  198018. can't handle far buffers in the medium and small models, we have to copy
  198019. the data.
  198020. */
  198021. #define NEAR_BUF_SIZE 1024
  198022. #define MIN(a,b) (a <= b ? a : b)
  198023. void PNGAPI
  198024. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198025. {
  198026. png_uint_32 check;
  198027. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198028. png_FILE_p io_ptr;
  198029. if(png_ptr == NULL) return;
  198030. /* Check if data really is near. If so, use usual code. */
  198031. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198032. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198033. if ((png_bytep)near_data == data)
  198034. {
  198035. #if defined(_WIN32_WCE)
  198036. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198037. check = 0;
  198038. #else
  198039. check = fwrite(near_data, 1, length, io_ptr);
  198040. #endif
  198041. }
  198042. else
  198043. {
  198044. png_byte buf[NEAR_BUF_SIZE];
  198045. png_size_t written, remaining, err;
  198046. check = 0;
  198047. remaining = length;
  198048. do
  198049. {
  198050. written = MIN(NEAR_BUF_SIZE, remaining);
  198051. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198052. #if defined(_WIN32_WCE)
  198053. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198054. err = 0;
  198055. #else
  198056. err = fwrite(buf, 1, written, io_ptr);
  198057. #endif
  198058. if (err != written)
  198059. break;
  198060. else
  198061. check += err;
  198062. data += written;
  198063. remaining -= written;
  198064. }
  198065. while (remaining != 0);
  198066. }
  198067. if (check != length)
  198068. png_error(png_ptr, "Write Error");
  198069. }
  198070. #endif
  198071. #endif
  198072. /* This function is called to output any data pending writing (normally
  198073. to disk). After png_flush is called, there should be no data pending
  198074. writing in any buffers. */
  198075. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198076. void /* PRIVATE */
  198077. png_flush(png_structp png_ptr)
  198078. {
  198079. if (png_ptr->output_flush_fn != NULL)
  198080. (*(png_ptr->output_flush_fn))(png_ptr);
  198081. }
  198082. #if !defined(PNG_NO_STDIO)
  198083. void PNGAPI
  198084. png_default_flush(png_structp png_ptr)
  198085. {
  198086. #if !defined(_WIN32_WCE)
  198087. png_FILE_p io_ptr;
  198088. #endif
  198089. if(png_ptr == NULL) return;
  198090. #if !defined(_WIN32_WCE)
  198091. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198092. if (io_ptr != NULL)
  198093. fflush(io_ptr);
  198094. #endif
  198095. }
  198096. #endif
  198097. #endif
  198098. /* This function allows the application to supply new output functions for
  198099. libpng if standard C streams aren't being used.
  198100. This function takes as its arguments:
  198101. png_ptr - pointer to a png output data structure
  198102. io_ptr - pointer to user supplied structure containing info about
  198103. the output functions. May be NULL.
  198104. write_data_fn - pointer to a new output function that takes as its
  198105. arguments a pointer to a png_struct, a pointer to
  198106. data to be written, and a 32-bit unsigned int that is
  198107. the number of bytes to be written. The new write
  198108. function should call png_error(png_ptr, "Error msg")
  198109. to exit and output any fatal error messages.
  198110. flush_data_fn - pointer to a new flush function that takes as its
  198111. arguments a pointer to a png_struct. After a call to
  198112. the flush function, there should be no data in any buffers
  198113. or pending transmission. If the output method doesn't do
  198114. any buffering of ouput, a function prototype must still be
  198115. supplied although it doesn't have to do anything. If
  198116. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198117. time, output_flush_fn will be ignored, although it must be
  198118. supplied for compatibility. */
  198119. void PNGAPI
  198120. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198121. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198122. {
  198123. if(png_ptr == NULL) return;
  198124. png_ptr->io_ptr = io_ptr;
  198125. #if !defined(PNG_NO_STDIO)
  198126. if (write_data_fn != NULL)
  198127. png_ptr->write_data_fn = write_data_fn;
  198128. else
  198129. png_ptr->write_data_fn = png_default_write_data;
  198130. #else
  198131. png_ptr->write_data_fn = write_data_fn;
  198132. #endif
  198133. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198134. #if !defined(PNG_NO_STDIO)
  198135. if (output_flush_fn != NULL)
  198136. png_ptr->output_flush_fn = output_flush_fn;
  198137. else
  198138. png_ptr->output_flush_fn = png_default_flush;
  198139. #else
  198140. png_ptr->output_flush_fn = output_flush_fn;
  198141. #endif
  198142. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198143. /* It is an error to read while writing a png file */
  198144. if (png_ptr->read_data_fn != NULL)
  198145. {
  198146. png_ptr->read_data_fn = NULL;
  198147. png_warning(png_ptr,
  198148. "Attempted to set both read_data_fn and write_data_fn in");
  198149. png_warning(png_ptr,
  198150. "the same structure. Resetting read_data_fn to NULL.");
  198151. }
  198152. }
  198153. #if defined(USE_FAR_KEYWORD)
  198154. #if defined(_MSC_VER)
  198155. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198156. {
  198157. void *near_ptr;
  198158. void FAR *far_ptr;
  198159. FP_OFF(near_ptr) = FP_OFF(ptr);
  198160. far_ptr = (void FAR *)near_ptr;
  198161. if(check != 0)
  198162. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198163. png_error(png_ptr,"segment lost in conversion");
  198164. return(near_ptr);
  198165. }
  198166. # else
  198167. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198168. {
  198169. void *near_ptr;
  198170. void FAR *far_ptr;
  198171. near_ptr = (void FAR *)ptr;
  198172. far_ptr = (void FAR *)near_ptr;
  198173. if(check != 0)
  198174. if(far_ptr != ptr)
  198175. png_error(png_ptr,"segment lost in conversion");
  198176. return(near_ptr);
  198177. }
  198178. # endif
  198179. # endif
  198180. #endif /* PNG_WRITE_SUPPORTED */
  198181. /*** End of inlined file: pngwio.c ***/
  198182. /*** Start of inlined file: pngwrite.c ***/
  198183. /* pngwrite.c - general routines to write a PNG file
  198184. *
  198185. * Last changed in libpng 1.2.15 January 5, 2007
  198186. * For conditions of distribution and use, see copyright notice in png.h
  198187. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198188. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198189. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198190. */
  198191. /* get internal access to png.h */
  198192. #define PNG_INTERNAL
  198193. #ifdef PNG_WRITE_SUPPORTED
  198194. /* Writes all the PNG information. This is the suggested way to use the
  198195. * library. If you have a new chunk to add, make a function to write it,
  198196. * and put it in the correct location here. If you want the chunk written
  198197. * after the image data, put it in png_write_end(). I strongly encourage
  198198. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198199. * the chunk, as that will keep the code from breaking if you want to just
  198200. * write a plain PNG file. If you have long comments, I suggest writing
  198201. * them in png_write_end(), and compressing them.
  198202. */
  198203. void PNGAPI
  198204. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198205. {
  198206. png_debug(1, "in png_write_info_before_PLTE\n");
  198207. if (png_ptr == NULL || info_ptr == NULL)
  198208. return;
  198209. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198210. {
  198211. png_write_sig(png_ptr); /* write PNG signature */
  198212. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198213. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198214. {
  198215. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198216. png_ptr->mng_features_permitted=0;
  198217. }
  198218. #endif
  198219. /* write IHDR information. */
  198220. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198221. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198222. info_ptr->filter_type,
  198223. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198224. info_ptr->interlace_type);
  198225. #else
  198226. 0);
  198227. #endif
  198228. /* the rest of these check to see if the valid field has the appropriate
  198229. flag set, and if it does, writes the chunk. */
  198230. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198231. if (info_ptr->valid & PNG_INFO_gAMA)
  198232. {
  198233. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198234. png_write_gAMA(png_ptr, info_ptr->gamma);
  198235. #else
  198236. #ifdef PNG_FIXED_POINT_SUPPORTED
  198237. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198238. # endif
  198239. #endif
  198240. }
  198241. #endif
  198242. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198243. if (info_ptr->valid & PNG_INFO_sRGB)
  198244. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198245. #endif
  198246. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198247. if (info_ptr->valid & PNG_INFO_iCCP)
  198248. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198249. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198250. #endif
  198251. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198252. if (info_ptr->valid & PNG_INFO_sBIT)
  198253. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198254. #endif
  198255. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198256. if (info_ptr->valid & PNG_INFO_cHRM)
  198257. {
  198258. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198259. png_write_cHRM(png_ptr,
  198260. info_ptr->x_white, info_ptr->y_white,
  198261. info_ptr->x_red, info_ptr->y_red,
  198262. info_ptr->x_green, info_ptr->y_green,
  198263. info_ptr->x_blue, info_ptr->y_blue);
  198264. #else
  198265. # ifdef PNG_FIXED_POINT_SUPPORTED
  198266. png_write_cHRM_fixed(png_ptr,
  198267. info_ptr->int_x_white, info_ptr->int_y_white,
  198268. info_ptr->int_x_red, info_ptr->int_y_red,
  198269. info_ptr->int_x_green, info_ptr->int_y_green,
  198270. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198271. # endif
  198272. #endif
  198273. }
  198274. #endif
  198275. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198276. if (info_ptr->unknown_chunks_num)
  198277. {
  198278. png_unknown_chunk *up;
  198279. png_debug(5, "writing extra chunks\n");
  198280. for (up = info_ptr->unknown_chunks;
  198281. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198282. up++)
  198283. {
  198284. int keep=png_handle_as_unknown(png_ptr, up->name);
  198285. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198286. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198287. !(up->location & PNG_HAVE_IDAT) &&
  198288. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198289. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198290. {
  198291. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198292. }
  198293. }
  198294. }
  198295. #endif
  198296. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198297. }
  198298. }
  198299. void PNGAPI
  198300. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198301. {
  198302. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198303. int i;
  198304. #endif
  198305. png_debug(1, "in png_write_info\n");
  198306. if (png_ptr == NULL || info_ptr == NULL)
  198307. return;
  198308. png_write_info_before_PLTE(png_ptr, info_ptr);
  198309. if (info_ptr->valid & PNG_INFO_PLTE)
  198310. png_write_PLTE(png_ptr, info_ptr->palette,
  198311. (png_uint_32)info_ptr->num_palette);
  198312. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198313. png_error(png_ptr, "Valid palette required for paletted images");
  198314. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198315. if (info_ptr->valid & PNG_INFO_tRNS)
  198316. {
  198317. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198318. /* invert the alpha channel (in tRNS) */
  198319. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198320. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198321. {
  198322. int j;
  198323. for (j=0; j<(int)info_ptr->num_trans; j++)
  198324. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198325. }
  198326. #endif
  198327. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198328. info_ptr->num_trans, info_ptr->color_type);
  198329. }
  198330. #endif
  198331. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198332. if (info_ptr->valid & PNG_INFO_bKGD)
  198333. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198334. #endif
  198335. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198336. if (info_ptr->valid & PNG_INFO_hIST)
  198337. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198338. #endif
  198339. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198340. if (info_ptr->valid & PNG_INFO_oFFs)
  198341. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198342. info_ptr->offset_unit_type);
  198343. #endif
  198344. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198345. if (info_ptr->valid & PNG_INFO_pCAL)
  198346. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198347. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198348. info_ptr->pcal_units, info_ptr->pcal_params);
  198349. #endif
  198350. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198351. if (info_ptr->valid & PNG_INFO_sCAL)
  198352. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198353. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198354. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198355. #else
  198356. #ifdef PNG_FIXED_POINT_SUPPORTED
  198357. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198358. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198359. #else
  198360. png_warning(png_ptr,
  198361. "png_write_sCAL not supported; sCAL chunk not written.");
  198362. #endif
  198363. #endif
  198364. #endif
  198365. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198366. if (info_ptr->valid & PNG_INFO_pHYs)
  198367. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198368. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198369. #endif
  198370. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198371. if (info_ptr->valid & PNG_INFO_tIME)
  198372. {
  198373. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198374. png_ptr->mode |= PNG_WROTE_tIME;
  198375. }
  198376. #endif
  198377. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198378. if (info_ptr->valid & PNG_INFO_sPLT)
  198379. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198380. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198381. #endif
  198382. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198383. /* Check to see if we need to write text chunks */
  198384. for (i = 0; i < info_ptr->num_text; i++)
  198385. {
  198386. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198387. info_ptr->text[i].compression);
  198388. /* an internationalized chunk? */
  198389. if (info_ptr->text[i].compression > 0)
  198390. {
  198391. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198392. /* write international chunk */
  198393. png_write_iTXt(png_ptr,
  198394. info_ptr->text[i].compression,
  198395. info_ptr->text[i].key,
  198396. info_ptr->text[i].lang,
  198397. info_ptr->text[i].lang_key,
  198398. info_ptr->text[i].text);
  198399. #else
  198400. png_warning(png_ptr, "Unable to write international text");
  198401. #endif
  198402. /* Mark this chunk as written */
  198403. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198404. }
  198405. /* If we want a compressed text chunk */
  198406. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198407. {
  198408. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198409. /* write compressed chunk */
  198410. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198411. info_ptr->text[i].text, 0,
  198412. info_ptr->text[i].compression);
  198413. #else
  198414. png_warning(png_ptr, "Unable to write compressed text");
  198415. #endif
  198416. /* Mark this chunk as written */
  198417. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198418. }
  198419. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198420. {
  198421. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198422. /* write uncompressed chunk */
  198423. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198424. info_ptr->text[i].text,
  198425. 0);
  198426. #else
  198427. png_warning(png_ptr, "Unable to write uncompressed text");
  198428. #endif
  198429. /* Mark this chunk as written */
  198430. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198431. }
  198432. }
  198433. #endif
  198434. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198435. if (info_ptr->unknown_chunks_num)
  198436. {
  198437. png_unknown_chunk *up;
  198438. png_debug(5, "writing extra chunks\n");
  198439. for (up = info_ptr->unknown_chunks;
  198440. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198441. up++)
  198442. {
  198443. int keep=png_handle_as_unknown(png_ptr, up->name);
  198444. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198445. up->location && (up->location & PNG_HAVE_PLTE) &&
  198446. !(up->location & PNG_HAVE_IDAT) &&
  198447. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198448. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198449. {
  198450. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198451. }
  198452. }
  198453. }
  198454. #endif
  198455. }
  198456. /* Writes the end of the PNG file. If you don't want to write comments or
  198457. * time information, you can pass NULL for info. If you already wrote these
  198458. * in png_write_info(), do not write them again here. If you have long
  198459. * comments, I suggest writing them here, and compressing them.
  198460. */
  198461. void PNGAPI
  198462. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198463. {
  198464. png_debug(1, "in png_write_end\n");
  198465. if (png_ptr == NULL)
  198466. return;
  198467. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198468. png_error(png_ptr, "No IDATs written into file");
  198469. /* see if user wants us to write information chunks */
  198470. if (info_ptr != NULL)
  198471. {
  198472. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198473. int i; /* local index variable */
  198474. #endif
  198475. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198476. /* check to see if user has supplied a time chunk */
  198477. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198478. !(png_ptr->mode & PNG_WROTE_tIME))
  198479. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198480. #endif
  198481. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198482. /* loop through comment chunks */
  198483. for (i = 0; i < info_ptr->num_text; i++)
  198484. {
  198485. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198486. info_ptr->text[i].compression);
  198487. /* an internationalized chunk? */
  198488. if (info_ptr->text[i].compression > 0)
  198489. {
  198490. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198491. /* write international chunk */
  198492. png_write_iTXt(png_ptr,
  198493. info_ptr->text[i].compression,
  198494. info_ptr->text[i].key,
  198495. info_ptr->text[i].lang,
  198496. info_ptr->text[i].lang_key,
  198497. info_ptr->text[i].text);
  198498. #else
  198499. png_warning(png_ptr, "Unable to write international text");
  198500. #endif
  198501. /* Mark this chunk as written */
  198502. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198503. }
  198504. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198505. {
  198506. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198507. /* write compressed chunk */
  198508. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198509. info_ptr->text[i].text, 0,
  198510. info_ptr->text[i].compression);
  198511. #else
  198512. png_warning(png_ptr, "Unable to write compressed text");
  198513. #endif
  198514. /* Mark this chunk as written */
  198515. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198516. }
  198517. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198518. {
  198519. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198520. /* write uncompressed chunk */
  198521. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198522. info_ptr->text[i].text, 0);
  198523. #else
  198524. png_warning(png_ptr, "Unable to write uncompressed text");
  198525. #endif
  198526. /* Mark this chunk as written */
  198527. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198528. }
  198529. }
  198530. #endif
  198531. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198532. if (info_ptr->unknown_chunks_num)
  198533. {
  198534. png_unknown_chunk *up;
  198535. png_debug(5, "writing extra chunks\n");
  198536. for (up = info_ptr->unknown_chunks;
  198537. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198538. up++)
  198539. {
  198540. int keep=png_handle_as_unknown(png_ptr, up->name);
  198541. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198542. up->location && (up->location & PNG_AFTER_IDAT) &&
  198543. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198544. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198545. {
  198546. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198547. }
  198548. }
  198549. }
  198550. #endif
  198551. }
  198552. png_ptr->mode |= PNG_AFTER_IDAT;
  198553. /* write end of PNG file */
  198554. png_write_IEND(png_ptr);
  198555. }
  198556. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198557. #if !defined(_WIN32_WCE)
  198558. /* "time.h" functions are not supported on WindowsCE */
  198559. void PNGAPI
  198560. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198561. {
  198562. png_debug(1, "in png_convert_from_struct_tm\n");
  198563. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198564. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198565. ptime->day = (png_byte)ttime->tm_mday;
  198566. ptime->hour = (png_byte)ttime->tm_hour;
  198567. ptime->minute = (png_byte)ttime->tm_min;
  198568. ptime->second = (png_byte)ttime->tm_sec;
  198569. }
  198570. void PNGAPI
  198571. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198572. {
  198573. struct tm *tbuf;
  198574. png_debug(1, "in png_convert_from_time_t\n");
  198575. tbuf = gmtime(&ttime);
  198576. png_convert_from_struct_tm(ptime, tbuf);
  198577. }
  198578. #endif
  198579. #endif
  198580. /* Initialize png_ptr structure, and allocate any memory needed */
  198581. png_structp PNGAPI
  198582. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198583. png_error_ptr error_fn, png_error_ptr warn_fn)
  198584. {
  198585. #ifdef PNG_USER_MEM_SUPPORTED
  198586. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198587. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198588. }
  198589. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198590. png_structp PNGAPI
  198591. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198592. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198593. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198594. {
  198595. #endif /* PNG_USER_MEM_SUPPORTED */
  198596. png_structp png_ptr;
  198597. #ifdef PNG_SETJMP_SUPPORTED
  198598. #ifdef USE_FAR_KEYWORD
  198599. jmp_buf jmpbuf;
  198600. #endif
  198601. #endif
  198602. int i;
  198603. png_debug(1, "in png_create_write_struct\n");
  198604. #ifdef PNG_USER_MEM_SUPPORTED
  198605. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198606. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198607. #else
  198608. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198609. #endif /* PNG_USER_MEM_SUPPORTED */
  198610. if (png_ptr == NULL)
  198611. return (NULL);
  198612. /* added at libpng-1.2.6 */
  198613. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198614. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198615. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198616. #endif
  198617. #ifdef PNG_SETJMP_SUPPORTED
  198618. #ifdef USE_FAR_KEYWORD
  198619. if (setjmp(jmpbuf))
  198620. #else
  198621. if (setjmp(png_ptr->jmpbuf))
  198622. #endif
  198623. {
  198624. png_free(png_ptr, png_ptr->zbuf);
  198625. png_ptr->zbuf=NULL;
  198626. png_destroy_struct(png_ptr);
  198627. return (NULL);
  198628. }
  198629. #ifdef USE_FAR_KEYWORD
  198630. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198631. #endif
  198632. #endif
  198633. #ifdef PNG_USER_MEM_SUPPORTED
  198634. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198635. #endif /* PNG_USER_MEM_SUPPORTED */
  198636. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198637. i=0;
  198638. do
  198639. {
  198640. if(user_png_ver[i] != png_libpng_ver[i])
  198641. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198642. } while (png_libpng_ver[i++]);
  198643. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198644. {
  198645. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198646. * we must recompile any applications that use any older library version.
  198647. * For versions after libpng 1.0, we will be compatible, so we need
  198648. * only check the first digit.
  198649. */
  198650. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198651. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198652. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198653. {
  198654. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198655. char msg[80];
  198656. if (user_png_ver)
  198657. {
  198658. png_snprintf(msg, 80,
  198659. "Application was compiled with png.h from libpng-%.20s",
  198660. user_png_ver);
  198661. png_warning(png_ptr, msg);
  198662. }
  198663. png_snprintf(msg, 80,
  198664. "Application is running with png.c from libpng-%.20s",
  198665. png_libpng_ver);
  198666. png_warning(png_ptr, msg);
  198667. #endif
  198668. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198669. png_ptr->flags=0;
  198670. #endif
  198671. png_error(png_ptr,
  198672. "Incompatible libpng version in application and library");
  198673. }
  198674. }
  198675. /* initialize zbuf - compression buffer */
  198676. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198677. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198678. (png_uint_32)png_ptr->zbuf_size);
  198679. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198680. png_flush_ptr_NULL);
  198681. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198682. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198683. 1, png_doublep_NULL, png_doublep_NULL);
  198684. #endif
  198685. #ifdef PNG_SETJMP_SUPPORTED
  198686. /* Applications that neglect to set up their own setjmp() and then encounter
  198687. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198688. abort instead of returning. */
  198689. #ifdef USE_FAR_KEYWORD
  198690. if (setjmp(jmpbuf))
  198691. PNG_ABORT();
  198692. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198693. #else
  198694. if (setjmp(png_ptr->jmpbuf))
  198695. PNG_ABORT();
  198696. #endif
  198697. #endif
  198698. return (png_ptr);
  198699. }
  198700. /* Initialize png_ptr structure, and allocate any memory needed */
  198701. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198702. /* Deprecated. */
  198703. #undef png_write_init
  198704. void PNGAPI
  198705. png_write_init(png_structp png_ptr)
  198706. {
  198707. /* We only come here via pre-1.0.7-compiled applications */
  198708. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198709. }
  198710. void PNGAPI
  198711. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198712. png_size_t png_struct_size, png_size_t png_info_size)
  198713. {
  198714. /* We only come here via pre-1.0.12-compiled applications */
  198715. if(png_ptr == NULL) return;
  198716. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198717. if(png_sizeof(png_struct) > png_struct_size ||
  198718. png_sizeof(png_info) > png_info_size)
  198719. {
  198720. char msg[80];
  198721. png_ptr->warning_fn=NULL;
  198722. if (user_png_ver)
  198723. {
  198724. png_snprintf(msg, 80,
  198725. "Application was compiled with png.h from libpng-%.20s",
  198726. user_png_ver);
  198727. png_warning(png_ptr, msg);
  198728. }
  198729. png_snprintf(msg, 80,
  198730. "Application is running with png.c from libpng-%.20s",
  198731. png_libpng_ver);
  198732. png_warning(png_ptr, msg);
  198733. }
  198734. #endif
  198735. if(png_sizeof(png_struct) > png_struct_size)
  198736. {
  198737. png_ptr->error_fn=NULL;
  198738. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198739. png_ptr->flags=0;
  198740. #endif
  198741. png_error(png_ptr,
  198742. "The png struct allocated by the application for writing is too small.");
  198743. }
  198744. if(png_sizeof(png_info) > png_info_size)
  198745. {
  198746. png_ptr->error_fn=NULL;
  198747. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198748. png_ptr->flags=0;
  198749. #endif
  198750. png_error(png_ptr,
  198751. "The info struct allocated by the application for writing is too small.");
  198752. }
  198753. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198754. }
  198755. #endif /* PNG_1_0_X || PNG_1_2_X */
  198756. void PNGAPI
  198757. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198758. png_size_t png_struct_size)
  198759. {
  198760. png_structp png_ptr=*ptr_ptr;
  198761. #ifdef PNG_SETJMP_SUPPORTED
  198762. jmp_buf tmp_jmp; /* to save current jump buffer */
  198763. #endif
  198764. int i = 0;
  198765. if (png_ptr == NULL)
  198766. return;
  198767. do
  198768. {
  198769. if (user_png_ver[i] != png_libpng_ver[i])
  198770. {
  198771. #ifdef PNG_LEGACY_SUPPORTED
  198772. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198773. #else
  198774. png_ptr->warning_fn=NULL;
  198775. png_warning(png_ptr,
  198776. "Application uses deprecated png_write_init() and should be recompiled.");
  198777. break;
  198778. #endif
  198779. }
  198780. } while (png_libpng_ver[i++]);
  198781. png_debug(1, "in png_write_init_3\n");
  198782. #ifdef PNG_SETJMP_SUPPORTED
  198783. /* save jump buffer and error functions */
  198784. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198785. #endif
  198786. if (png_sizeof(png_struct) > png_struct_size)
  198787. {
  198788. png_destroy_struct(png_ptr);
  198789. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198790. *ptr_ptr = png_ptr;
  198791. }
  198792. /* reset all variables to 0 */
  198793. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198794. /* added at libpng-1.2.6 */
  198795. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198796. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198797. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198798. #endif
  198799. #ifdef PNG_SETJMP_SUPPORTED
  198800. /* restore jump buffer */
  198801. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198802. #endif
  198803. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198804. png_flush_ptr_NULL);
  198805. /* initialize zbuf - compression buffer */
  198806. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198807. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198808. (png_uint_32)png_ptr->zbuf_size);
  198809. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198810. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198811. 1, png_doublep_NULL, png_doublep_NULL);
  198812. #endif
  198813. }
  198814. /* Write a few rows of image data. If the image is interlaced,
  198815. * either you will have to write the 7 sub images, or, if you
  198816. * have called png_set_interlace_handling(), you will have to
  198817. * "write" the image seven times.
  198818. */
  198819. void PNGAPI
  198820. png_write_rows(png_structp png_ptr, png_bytepp row,
  198821. png_uint_32 num_rows)
  198822. {
  198823. png_uint_32 i; /* row counter */
  198824. png_bytepp rp; /* row pointer */
  198825. png_debug(1, "in png_write_rows\n");
  198826. if (png_ptr == NULL)
  198827. return;
  198828. /* loop through the rows */
  198829. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198830. {
  198831. png_write_row(png_ptr, *rp);
  198832. }
  198833. }
  198834. /* Write the image. You only need to call this function once, even
  198835. * if you are writing an interlaced image.
  198836. */
  198837. void PNGAPI
  198838. png_write_image(png_structp png_ptr, png_bytepp image)
  198839. {
  198840. png_uint_32 i; /* row index */
  198841. int pass, num_pass; /* pass variables */
  198842. png_bytepp rp; /* points to current row */
  198843. if (png_ptr == NULL)
  198844. return;
  198845. png_debug(1, "in png_write_image\n");
  198846. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198847. /* intialize interlace handling. If image is not interlaced,
  198848. this will set pass to 1 */
  198849. num_pass = png_set_interlace_handling(png_ptr);
  198850. #else
  198851. num_pass = 1;
  198852. #endif
  198853. /* loop through passes */
  198854. for (pass = 0; pass < num_pass; pass++)
  198855. {
  198856. /* loop through image */
  198857. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198858. {
  198859. png_write_row(png_ptr, *rp);
  198860. }
  198861. }
  198862. }
  198863. /* called by user to write a row of image data */
  198864. void PNGAPI
  198865. png_write_row(png_structp png_ptr, png_bytep row)
  198866. {
  198867. if (png_ptr == NULL)
  198868. return;
  198869. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198870. png_ptr->row_number, png_ptr->pass);
  198871. /* initialize transformations and other stuff if first time */
  198872. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198873. {
  198874. /* make sure we wrote the header info */
  198875. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198876. png_error(png_ptr,
  198877. "png_write_info was never called before png_write_row.");
  198878. /* check for transforms that have been set but were defined out */
  198879. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198880. if (png_ptr->transformations & PNG_INVERT_MONO)
  198881. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198882. #endif
  198883. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198884. if (png_ptr->transformations & PNG_FILLER)
  198885. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198886. #endif
  198887. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198888. if (png_ptr->transformations & PNG_PACKSWAP)
  198889. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198890. #endif
  198891. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198892. if (png_ptr->transformations & PNG_PACK)
  198893. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198894. #endif
  198895. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198896. if (png_ptr->transformations & PNG_SHIFT)
  198897. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198898. #endif
  198899. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198900. if (png_ptr->transformations & PNG_BGR)
  198901. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198902. #endif
  198903. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198904. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198905. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198906. #endif
  198907. png_write_start_row(png_ptr);
  198908. }
  198909. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198910. /* if interlaced and not interested in row, return */
  198911. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198912. {
  198913. switch (png_ptr->pass)
  198914. {
  198915. case 0:
  198916. if (png_ptr->row_number & 0x07)
  198917. {
  198918. png_write_finish_row(png_ptr);
  198919. return;
  198920. }
  198921. break;
  198922. case 1:
  198923. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198924. {
  198925. png_write_finish_row(png_ptr);
  198926. return;
  198927. }
  198928. break;
  198929. case 2:
  198930. if ((png_ptr->row_number & 0x07) != 4)
  198931. {
  198932. png_write_finish_row(png_ptr);
  198933. return;
  198934. }
  198935. break;
  198936. case 3:
  198937. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198938. {
  198939. png_write_finish_row(png_ptr);
  198940. return;
  198941. }
  198942. break;
  198943. case 4:
  198944. if ((png_ptr->row_number & 0x03) != 2)
  198945. {
  198946. png_write_finish_row(png_ptr);
  198947. return;
  198948. }
  198949. break;
  198950. case 5:
  198951. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198952. {
  198953. png_write_finish_row(png_ptr);
  198954. return;
  198955. }
  198956. break;
  198957. case 6:
  198958. if (!(png_ptr->row_number & 0x01))
  198959. {
  198960. png_write_finish_row(png_ptr);
  198961. return;
  198962. }
  198963. break;
  198964. }
  198965. }
  198966. #endif
  198967. /* set up row info for transformations */
  198968. png_ptr->row_info.color_type = png_ptr->color_type;
  198969. png_ptr->row_info.width = png_ptr->usr_width;
  198970. png_ptr->row_info.channels = png_ptr->usr_channels;
  198971. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198972. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198973. png_ptr->row_info.channels);
  198974. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198975. png_ptr->row_info.width);
  198976. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198977. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198978. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198979. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198980. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198981. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198982. /* Copy user's row into buffer, leaving room for filter byte. */
  198983. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198984. png_ptr->row_info.rowbytes);
  198985. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198986. /* handle interlacing */
  198987. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198988. (png_ptr->transformations & PNG_INTERLACE))
  198989. {
  198990. png_do_write_interlace(&(png_ptr->row_info),
  198991. png_ptr->row_buf + 1, png_ptr->pass);
  198992. /* this should always get caught above, but still ... */
  198993. if (!(png_ptr->row_info.width))
  198994. {
  198995. png_write_finish_row(png_ptr);
  198996. return;
  198997. }
  198998. }
  198999. #endif
  199000. /* handle other transformations */
  199001. if (png_ptr->transformations)
  199002. png_do_write_transformations(png_ptr);
  199003. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199004. /* Write filter_method 64 (intrapixel differencing) only if
  199005. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199006. * 2. Libpng did not write a PNG signature (this filter_method is only
  199007. * used in PNG datastreams that are embedded in MNG datastreams) and
  199008. * 3. The application called png_permit_mng_features with a mask that
  199009. * included PNG_FLAG_MNG_FILTER_64 and
  199010. * 4. The filter_method is 64 and
  199011. * 5. The color_type is RGB or RGBA
  199012. */
  199013. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199014. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199015. {
  199016. /* Intrapixel differencing */
  199017. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199018. }
  199019. #endif
  199020. /* Find a filter if necessary, filter the row and write it out. */
  199021. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199022. if (png_ptr->write_row_fn != NULL)
  199023. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199024. }
  199025. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199026. /* Set the automatic flush interval or 0 to turn flushing off */
  199027. void PNGAPI
  199028. png_set_flush(png_structp png_ptr, int nrows)
  199029. {
  199030. png_debug(1, "in png_set_flush\n");
  199031. if (png_ptr == NULL)
  199032. return;
  199033. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199034. }
  199035. /* flush the current output buffers now */
  199036. void PNGAPI
  199037. png_write_flush(png_structp png_ptr)
  199038. {
  199039. int wrote_IDAT;
  199040. png_debug(1, "in png_write_flush\n");
  199041. if (png_ptr == NULL)
  199042. return;
  199043. /* We have already written out all of the data */
  199044. if (png_ptr->row_number >= png_ptr->num_rows)
  199045. return;
  199046. do
  199047. {
  199048. int ret;
  199049. /* compress the data */
  199050. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199051. wrote_IDAT = 0;
  199052. /* check for compression errors */
  199053. if (ret != Z_OK)
  199054. {
  199055. if (png_ptr->zstream.msg != NULL)
  199056. png_error(png_ptr, png_ptr->zstream.msg);
  199057. else
  199058. png_error(png_ptr, "zlib error");
  199059. }
  199060. if (!(png_ptr->zstream.avail_out))
  199061. {
  199062. /* write the IDAT and reset the zlib output buffer */
  199063. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199064. png_ptr->zbuf_size);
  199065. png_ptr->zstream.next_out = png_ptr->zbuf;
  199066. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199067. wrote_IDAT = 1;
  199068. }
  199069. } while(wrote_IDAT == 1);
  199070. /* If there is any data left to be output, write it into a new IDAT */
  199071. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199072. {
  199073. /* write the IDAT and reset the zlib output buffer */
  199074. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199075. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199076. png_ptr->zstream.next_out = png_ptr->zbuf;
  199077. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199078. }
  199079. png_ptr->flush_rows = 0;
  199080. png_flush(png_ptr);
  199081. }
  199082. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199083. /* free all memory used by the write */
  199084. void PNGAPI
  199085. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199086. {
  199087. png_structp png_ptr = NULL;
  199088. png_infop info_ptr = NULL;
  199089. #ifdef PNG_USER_MEM_SUPPORTED
  199090. png_free_ptr free_fn = NULL;
  199091. png_voidp mem_ptr = NULL;
  199092. #endif
  199093. png_debug(1, "in png_destroy_write_struct\n");
  199094. if (png_ptr_ptr != NULL)
  199095. {
  199096. png_ptr = *png_ptr_ptr;
  199097. #ifdef PNG_USER_MEM_SUPPORTED
  199098. free_fn = png_ptr->free_fn;
  199099. mem_ptr = png_ptr->mem_ptr;
  199100. #endif
  199101. }
  199102. if (info_ptr_ptr != NULL)
  199103. info_ptr = *info_ptr_ptr;
  199104. if (info_ptr != NULL)
  199105. {
  199106. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199107. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199108. if (png_ptr->num_chunk_list)
  199109. {
  199110. png_free(png_ptr, png_ptr->chunk_list);
  199111. png_ptr->chunk_list=NULL;
  199112. png_ptr->num_chunk_list=0;
  199113. }
  199114. #endif
  199115. #ifdef PNG_USER_MEM_SUPPORTED
  199116. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199117. (png_voidp)mem_ptr);
  199118. #else
  199119. png_destroy_struct((png_voidp)info_ptr);
  199120. #endif
  199121. *info_ptr_ptr = NULL;
  199122. }
  199123. if (png_ptr != NULL)
  199124. {
  199125. png_write_destroy(png_ptr);
  199126. #ifdef PNG_USER_MEM_SUPPORTED
  199127. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199128. (png_voidp)mem_ptr);
  199129. #else
  199130. png_destroy_struct((png_voidp)png_ptr);
  199131. #endif
  199132. *png_ptr_ptr = NULL;
  199133. }
  199134. }
  199135. /* Free any memory used in png_ptr struct (old method) */
  199136. void /* PRIVATE */
  199137. png_write_destroy(png_structp png_ptr)
  199138. {
  199139. #ifdef PNG_SETJMP_SUPPORTED
  199140. jmp_buf tmp_jmp; /* save jump buffer */
  199141. #endif
  199142. png_error_ptr error_fn;
  199143. png_error_ptr warning_fn;
  199144. png_voidp error_ptr;
  199145. #ifdef PNG_USER_MEM_SUPPORTED
  199146. png_free_ptr free_fn;
  199147. #endif
  199148. png_debug(1, "in png_write_destroy\n");
  199149. /* free any memory zlib uses */
  199150. deflateEnd(&png_ptr->zstream);
  199151. /* free our memory. png_free checks NULL for us. */
  199152. png_free(png_ptr, png_ptr->zbuf);
  199153. png_free(png_ptr, png_ptr->row_buf);
  199154. png_free(png_ptr, png_ptr->prev_row);
  199155. png_free(png_ptr, png_ptr->sub_row);
  199156. png_free(png_ptr, png_ptr->up_row);
  199157. png_free(png_ptr, png_ptr->avg_row);
  199158. png_free(png_ptr, png_ptr->paeth_row);
  199159. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199160. png_free(png_ptr, png_ptr->time_buffer);
  199161. #endif
  199162. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199163. png_free(png_ptr, png_ptr->prev_filters);
  199164. png_free(png_ptr, png_ptr->filter_weights);
  199165. png_free(png_ptr, png_ptr->inv_filter_weights);
  199166. png_free(png_ptr, png_ptr->filter_costs);
  199167. png_free(png_ptr, png_ptr->inv_filter_costs);
  199168. #endif
  199169. #ifdef PNG_SETJMP_SUPPORTED
  199170. /* reset structure */
  199171. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199172. #endif
  199173. error_fn = png_ptr->error_fn;
  199174. warning_fn = png_ptr->warning_fn;
  199175. error_ptr = png_ptr->error_ptr;
  199176. #ifdef PNG_USER_MEM_SUPPORTED
  199177. free_fn = png_ptr->free_fn;
  199178. #endif
  199179. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199180. png_ptr->error_fn = error_fn;
  199181. png_ptr->warning_fn = warning_fn;
  199182. png_ptr->error_ptr = error_ptr;
  199183. #ifdef PNG_USER_MEM_SUPPORTED
  199184. png_ptr->free_fn = free_fn;
  199185. #endif
  199186. #ifdef PNG_SETJMP_SUPPORTED
  199187. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199188. #endif
  199189. }
  199190. /* Allow the application to select one or more row filters to use. */
  199191. void PNGAPI
  199192. png_set_filter(png_structp png_ptr, int method, int filters)
  199193. {
  199194. png_debug(1, "in png_set_filter\n");
  199195. if (png_ptr == NULL)
  199196. return;
  199197. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199198. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199199. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199200. method = PNG_FILTER_TYPE_BASE;
  199201. #endif
  199202. if (method == PNG_FILTER_TYPE_BASE)
  199203. {
  199204. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199205. {
  199206. #ifndef PNG_NO_WRITE_FILTER
  199207. case 5:
  199208. case 6:
  199209. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199210. #endif /* PNG_NO_WRITE_FILTER */
  199211. case PNG_FILTER_VALUE_NONE:
  199212. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199213. #ifndef PNG_NO_WRITE_FILTER
  199214. case PNG_FILTER_VALUE_SUB:
  199215. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199216. case PNG_FILTER_VALUE_UP:
  199217. png_ptr->do_filter=PNG_FILTER_UP; break;
  199218. case PNG_FILTER_VALUE_AVG:
  199219. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199220. case PNG_FILTER_VALUE_PAETH:
  199221. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199222. default: png_ptr->do_filter = (png_byte)filters; break;
  199223. #else
  199224. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199225. #endif /* PNG_NO_WRITE_FILTER */
  199226. }
  199227. /* If we have allocated the row_buf, this means we have already started
  199228. * with the image and we should have allocated all of the filter buffers
  199229. * that have been selected. If prev_row isn't already allocated, then
  199230. * it is too late to start using the filters that need it, since we
  199231. * will be missing the data in the previous row. If an application
  199232. * wants to start and stop using particular filters during compression,
  199233. * it should start out with all of the filters, and then add and
  199234. * remove them after the start of compression.
  199235. */
  199236. if (png_ptr->row_buf != NULL)
  199237. {
  199238. #ifndef PNG_NO_WRITE_FILTER
  199239. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199240. {
  199241. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199242. (png_ptr->rowbytes + 1));
  199243. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199244. }
  199245. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199246. {
  199247. if (png_ptr->prev_row == NULL)
  199248. {
  199249. png_warning(png_ptr, "Can't add Up filter after starting");
  199250. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199251. }
  199252. else
  199253. {
  199254. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199255. (png_ptr->rowbytes + 1));
  199256. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199257. }
  199258. }
  199259. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199260. {
  199261. if (png_ptr->prev_row == NULL)
  199262. {
  199263. png_warning(png_ptr, "Can't add Average filter after starting");
  199264. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199265. }
  199266. else
  199267. {
  199268. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199269. (png_ptr->rowbytes + 1));
  199270. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199271. }
  199272. }
  199273. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199274. png_ptr->paeth_row == NULL)
  199275. {
  199276. if (png_ptr->prev_row == NULL)
  199277. {
  199278. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199279. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199280. }
  199281. else
  199282. {
  199283. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199284. (png_ptr->rowbytes + 1));
  199285. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199286. }
  199287. }
  199288. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199289. #endif /* PNG_NO_WRITE_FILTER */
  199290. png_ptr->do_filter = PNG_FILTER_NONE;
  199291. }
  199292. }
  199293. else
  199294. png_error(png_ptr, "Unknown custom filter method");
  199295. }
  199296. /* This allows us to influence the way in which libpng chooses the "best"
  199297. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199298. * differences metric is relatively fast and effective, there is some
  199299. * question as to whether it can be improved upon by trying to keep the
  199300. * filtered data going to zlib more consistent, hopefully resulting in
  199301. * better compression.
  199302. */
  199303. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199304. void PNGAPI
  199305. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199306. int num_weights, png_doublep filter_weights,
  199307. png_doublep filter_costs)
  199308. {
  199309. int i;
  199310. png_debug(1, "in png_set_filter_heuristics\n");
  199311. if (png_ptr == NULL)
  199312. return;
  199313. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199314. {
  199315. png_warning(png_ptr, "Unknown filter heuristic method");
  199316. return;
  199317. }
  199318. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199319. {
  199320. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199321. }
  199322. if (num_weights < 0 || filter_weights == NULL ||
  199323. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199324. {
  199325. num_weights = 0;
  199326. }
  199327. png_ptr->num_prev_filters = (png_byte)num_weights;
  199328. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199329. if (num_weights > 0)
  199330. {
  199331. if (png_ptr->prev_filters == NULL)
  199332. {
  199333. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199334. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199335. /* To make sure that the weighting starts out fairly */
  199336. for (i = 0; i < num_weights; i++)
  199337. {
  199338. png_ptr->prev_filters[i] = 255;
  199339. }
  199340. }
  199341. if (png_ptr->filter_weights == NULL)
  199342. {
  199343. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199344. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199345. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199346. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199347. for (i = 0; i < num_weights; i++)
  199348. {
  199349. png_ptr->inv_filter_weights[i] =
  199350. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199351. }
  199352. }
  199353. for (i = 0; i < num_weights; i++)
  199354. {
  199355. if (filter_weights[i] < 0.0)
  199356. {
  199357. png_ptr->inv_filter_weights[i] =
  199358. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199359. }
  199360. else
  199361. {
  199362. png_ptr->inv_filter_weights[i] =
  199363. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199364. png_ptr->filter_weights[i] =
  199365. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199366. }
  199367. }
  199368. }
  199369. /* If, in the future, there are other filter methods, this would
  199370. * need to be based on png_ptr->filter.
  199371. */
  199372. if (png_ptr->filter_costs == NULL)
  199373. {
  199374. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199375. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199376. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199377. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199378. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199379. {
  199380. png_ptr->inv_filter_costs[i] =
  199381. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199382. }
  199383. }
  199384. /* Here is where we set the relative costs of the different filters. We
  199385. * should take the desired compression level into account when setting
  199386. * the costs, so that Paeth, for instance, has a high relative cost at low
  199387. * compression levels, while it has a lower relative cost at higher
  199388. * compression settings. The filter types are in order of increasing
  199389. * relative cost, so it would be possible to do this with an algorithm.
  199390. */
  199391. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199392. {
  199393. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199394. {
  199395. png_ptr->inv_filter_costs[i] =
  199396. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199397. }
  199398. else if (filter_costs[i] >= 1.0)
  199399. {
  199400. png_ptr->inv_filter_costs[i] =
  199401. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199402. png_ptr->filter_costs[i] =
  199403. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199404. }
  199405. }
  199406. }
  199407. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199408. void PNGAPI
  199409. png_set_compression_level(png_structp png_ptr, int level)
  199410. {
  199411. png_debug(1, "in png_set_compression_level\n");
  199412. if (png_ptr == NULL)
  199413. return;
  199414. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199415. png_ptr->zlib_level = level;
  199416. }
  199417. void PNGAPI
  199418. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199419. {
  199420. png_debug(1, "in png_set_compression_mem_level\n");
  199421. if (png_ptr == NULL)
  199422. return;
  199423. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199424. png_ptr->zlib_mem_level = mem_level;
  199425. }
  199426. void PNGAPI
  199427. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199428. {
  199429. png_debug(1, "in png_set_compression_strategy\n");
  199430. if (png_ptr == NULL)
  199431. return;
  199432. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199433. png_ptr->zlib_strategy = strategy;
  199434. }
  199435. void PNGAPI
  199436. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199437. {
  199438. if (png_ptr == NULL)
  199439. return;
  199440. if (window_bits > 15)
  199441. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199442. else if (window_bits < 8)
  199443. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199444. #ifndef WBITS_8_OK
  199445. /* avoid libpng bug with 256-byte windows */
  199446. if (window_bits == 8)
  199447. {
  199448. png_warning(png_ptr, "Compression window is being reset to 512");
  199449. window_bits=9;
  199450. }
  199451. #endif
  199452. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199453. png_ptr->zlib_window_bits = window_bits;
  199454. }
  199455. void PNGAPI
  199456. png_set_compression_method(png_structp png_ptr, int method)
  199457. {
  199458. png_debug(1, "in png_set_compression_method\n");
  199459. if (png_ptr == NULL)
  199460. return;
  199461. if (method != 8)
  199462. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199463. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199464. png_ptr->zlib_method = method;
  199465. }
  199466. void PNGAPI
  199467. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199468. {
  199469. if (png_ptr == NULL)
  199470. return;
  199471. png_ptr->write_row_fn = write_row_fn;
  199472. }
  199473. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199474. void PNGAPI
  199475. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199476. write_user_transform_fn)
  199477. {
  199478. png_debug(1, "in png_set_write_user_transform_fn\n");
  199479. if (png_ptr == NULL)
  199480. return;
  199481. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199482. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199483. }
  199484. #endif
  199485. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199486. void PNGAPI
  199487. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199488. int transforms, voidp params)
  199489. {
  199490. if (png_ptr == NULL || info_ptr == NULL)
  199491. return;
  199492. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199493. /* invert the alpha channel from opacity to transparency */
  199494. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199495. png_set_invert_alpha(png_ptr);
  199496. #endif
  199497. /* Write the file header information. */
  199498. png_write_info(png_ptr, info_ptr);
  199499. /* ------ these transformations don't touch the info structure ------- */
  199500. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199501. /* invert monochrome pixels */
  199502. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199503. png_set_invert_mono(png_ptr);
  199504. #endif
  199505. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199506. /* Shift the pixels up to a legal bit depth and fill in
  199507. * as appropriate to correctly scale the image.
  199508. */
  199509. if ((transforms & PNG_TRANSFORM_SHIFT)
  199510. && (info_ptr->valid & PNG_INFO_sBIT))
  199511. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199512. #endif
  199513. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199514. /* pack pixels into bytes */
  199515. if (transforms & PNG_TRANSFORM_PACKING)
  199516. png_set_packing(png_ptr);
  199517. #endif
  199518. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199519. /* swap location of alpha bytes from ARGB to RGBA */
  199520. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199521. png_set_swap_alpha(png_ptr);
  199522. #endif
  199523. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199524. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199525. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199526. */
  199527. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199528. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199529. #endif
  199530. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199531. /* flip BGR pixels to RGB */
  199532. if (transforms & PNG_TRANSFORM_BGR)
  199533. png_set_bgr(png_ptr);
  199534. #endif
  199535. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199536. /* swap bytes of 16-bit files to most significant byte first */
  199537. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199538. png_set_swap(png_ptr);
  199539. #endif
  199540. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199541. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199542. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199543. png_set_packswap(png_ptr);
  199544. #endif
  199545. /* ----------------------- end of transformations ------------------- */
  199546. /* write the bits */
  199547. if (info_ptr->valid & PNG_INFO_IDAT)
  199548. png_write_image(png_ptr, info_ptr->row_pointers);
  199549. /* It is REQUIRED to call this to finish writing the rest of the file */
  199550. png_write_end(png_ptr, info_ptr);
  199551. transforms = transforms; /* quiet compiler warnings */
  199552. params = params;
  199553. }
  199554. #endif
  199555. #endif /* PNG_WRITE_SUPPORTED */
  199556. /*** End of inlined file: pngwrite.c ***/
  199557. /*** Start of inlined file: pngwtran.c ***/
  199558. /* pngwtran.c - transforms the data in a row for PNG writers
  199559. *
  199560. * Last changed in libpng 1.2.9 April 14, 2006
  199561. * For conditions of distribution and use, see copyright notice in png.h
  199562. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199563. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199564. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199565. */
  199566. #define PNG_INTERNAL
  199567. #ifdef PNG_WRITE_SUPPORTED
  199568. /* Transform the data according to the user's wishes. The order of
  199569. * transformations is significant.
  199570. */
  199571. void /* PRIVATE */
  199572. png_do_write_transformations(png_structp png_ptr)
  199573. {
  199574. png_debug(1, "in png_do_write_transformations\n");
  199575. if (png_ptr == NULL)
  199576. return;
  199577. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199578. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199579. if(png_ptr->write_user_transform_fn != NULL)
  199580. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199581. (png_ptr, /* png_ptr */
  199582. &(png_ptr->row_info), /* row_info: */
  199583. /* png_uint_32 width; width of row */
  199584. /* png_uint_32 rowbytes; number of bytes in row */
  199585. /* png_byte color_type; color type of pixels */
  199586. /* png_byte bit_depth; bit depth of samples */
  199587. /* png_byte channels; number of channels (1-4) */
  199588. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199589. png_ptr->row_buf + 1); /* start of pixel data for row */
  199590. #endif
  199591. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199592. if (png_ptr->transformations & PNG_FILLER)
  199593. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199594. png_ptr->flags);
  199595. #endif
  199596. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199597. if (png_ptr->transformations & PNG_PACKSWAP)
  199598. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199599. #endif
  199600. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199601. if (png_ptr->transformations & PNG_PACK)
  199602. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199603. (png_uint_32)png_ptr->bit_depth);
  199604. #endif
  199605. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199606. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199607. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199608. #endif
  199609. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199610. if (png_ptr->transformations & PNG_SHIFT)
  199611. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199612. &(png_ptr->shift));
  199613. #endif
  199614. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199615. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199616. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199617. #endif
  199618. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199619. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199620. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199621. #endif
  199622. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199623. if (png_ptr->transformations & PNG_BGR)
  199624. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199625. #endif
  199626. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199627. if (png_ptr->transformations & PNG_INVERT_MONO)
  199628. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199629. #endif
  199630. }
  199631. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199632. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199633. * row_info bit depth should be 8 (one pixel per byte). The channels
  199634. * should be 1 (this only happens on grayscale and paletted images).
  199635. */
  199636. void /* PRIVATE */
  199637. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199638. {
  199639. png_debug(1, "in png_do_pack\n");
  199640. if (row_info->bit_depth == 8 &&
  199641. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199642. row != NULL && row_info != NULL &&
  199643. #endif
  199644. row_info->channels == 1)
  199645. {
  199646. switch ((int)bit_depth)
  199647. {
  199648. case 1:
  199649. {
  199650. png_bytep sp, dp;
  199651. int mask, v;
  199652. png_uint_32 i;
  199653. png_uint_32 row_width = row_info->width;
  199654. sp = row;
  199655. dp = row;
  199656. mask = 0x80;
  199657. v = 0;
  199658. for (i = 0; i < row_width; i++)
  199659. {
  199660. if (*sp != 0)
  199661. v |= mask;
  199662. sp++;
  199663. if (mask > 1)
  199664. mask >>= 1;
  199665. else
  199666. {
  199667. mask = 0x80;
  199668. *dp = (png_byte)v;
  199669. dp++;
  199670. v = 0;
  199671. }
  199672. }
  199673. if (mask != 0x80)
  199674. *dp = (png_byte)v;
  199675. break;
  199676. }
  199677. case 2:
  199678. {
  199679. png_bytep sp, dp;
  199680. int shift, v;
  199681. png_uint_32 i;
  199682. png_uint_32 row_width = row_info->width;
  199683. sp = row;
  199684. dp = row;
  199685. shift = 6;
  199686. v = 0;
  199687. for (i = 0; i < row_width; i++)
  199688. {
  199689. png_byte value;
  199690. value = (png_byte)(*sp & 0x03);
  199691. v |= (value << shift);
  199692. if (shift == 0)
  199693. {
  199694. shift = 6;
  199695. *dp = (png_byte)v;
  199696. dp++;
  199697. v = 0;
  199698. }
  199699. else
  199700. shift -= 2;
  199701. sp++;
  199702. }
  199703. if (shift != 6)
  199704. *dp = (png_byte)v;
  199705. break;
  199706. }
  199707. case 4:
  199708. {
  199709. png_bytep sp, dp;
  199710. int shift, v;
  199711. png_uint_32 i;
  199712. png_uint_32 row_width = row_info->width;
  199713. sp = row;
  199714. dp = row;
  199715. shift = 4;
  199716. v = 0;
  199717. for (i = 0; i < row_width; i++)
  199718. {
  199719. png_byte value;
  199720. value = (png_byte)(*sp & 0x0f);
  199721. v |= (value << shift);
  199722. if (shift == 0)
  199723. {
  199724. shift = 4;
  199725. *dp = (png_byte)v;
  199726. dp++;
  199727. v = 0;
  199728. }
  199729. else
  199730. shift -= 4;
  199731. sp++;
  199732. }
  199733. if (shift != 4)
  199734. *dp = (png_byte)v;
  199735. break;
  199736. }
  199737. }
  199738. row_info->bit_depth = (png_byte)bit_depth;
  199739. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199740. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199741. row_info->width);
  199742. }
  199743. }
  199744. #endif
  199745. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199746. /* Shift pixel values to take advantage of whole range. Pass the
  199747. * true number of bits in bit_depth. The row should be packed
  199748. * according to row_info->bit_depth. Thus, if you had a row of
  199749. * bit depth 4, but the pixels only had values from 0 to 7, you
  199750. * would pass 3 as bit_depth, and this routine would translate the
  199751. * data to 0 to 15.
  199752. */
  199753. void /* PRIVATE */
  199754. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199755. {
  199756. png_debug(1, "in png_do_shift\n");
  199757. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199758. if (row != NULL && row_info != NULL &&
  199759. #else
  199760. if (
  199761. #endif
  199762. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199763. {
  199764. int shift_start[4], shift_dec[4];
  199765. int channels = 0;
  199766. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199767. {
  199768. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199769. shift_dec[channels] = bit_depth->red;
  199770. channels++;
  199771. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199772. shift_dec[channels] = bit_depth->green;
  199773. channels++;
  199774. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199775. shift_dec[channels] = bit_depth->blue;
  199776. channels++;
  199777. }
  199778. else
  199779. {
  199780. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199781. shift_dec[channels] = bit_depth->gray;
  199782. channels++;
  199783. }
  199784. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199785. {
  199786. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199787. shift_dec[channels] = bit_depth->alpha;
  199788. channels++;
  199789. }
  199790. /* with low row depths, could only be grayscale, so one channel */
  199791. if (row_info->bit_depth < 8)
  199792. {
  199793. png_bytep bp = row;
  199794. png_uint_32 i;
  199795. png_byte mask;
  199796. png_uint_32 row_bytes = row_info->rowbytes;
  199797. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199798. mask = 0x55;
  199799. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199800. mask = 0x11;
  199801. else
  199802. mask = 0xff;
  199803. for (i = 0; i < row_bytes; i++, bp++)
  199804. {
  199805. png_uint_16 v;
  199806. int j;
  199807. v = *bp;
  199808. *bp = 0;
  199809. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199810. {
  199811. if (j > 0)
  199812. *bp |= (png_byte)((v << j) & 0xff);
  199813. else
  199814. *bp |= (png_byte)((v >> (-j)) & mask);
  199815. }
  199816. }
  199817. }
  199818. else if (row_info->bit_depth == 8)
  199819. {
  199820. png_bytep bp = row;
  199821. png_uint_32 i;
  199822. png_uint_32 istop = channels * row_info->width;
  199823. for (i = 0; i < istop; i++, bp++)
  199824. {
  199825. png_uint_16 v;
  199826. int j;
  199827. int c = (int)(i%channels);
  199828. v = *bp;
  199829. *bp = 0;
  199830. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199831. {
  199832. if (j > 0)
  199833. *bp |= (png_byte)((v << j) & 0xff);
  199834. else
  199835. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199836. }
  199837. }
  199838. }
  199839. else
  199840. {
  199841. png_bytep bp;
  199842. png_uint_32 i;
  199843. png_uint_32 istop = channels * row_info->width;
  199844. for (bp = row, i = 0; i < istop; i++)
  199845. {
  199846. int c = (int)(i%channels);
  199847. png_uint_16 value, v;
  199848. int j;
  199849. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199850. value = 0;
  199851. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199852. {
  199853. if (j > 0)
  199854. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199855. else
  199856. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199857. }
  199858. *bp++ = (png_byte)(value >> 8);
  199859. *bp++ = (png_byte)(value & 0xff);
  199860. }
  199861. }
  199862. }
  199863. }
  199864. #endif
  199865. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199866. void /* PRIVATE */
  199867. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199868. {
  199869. png_debug(1, "in png_do_write_swap_alpha\n");
  199870. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199871. if (row != NULL && row_info != NULL)
  199872. #endif
  199873. {
  199874. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199875. {
  199876. /* This converts from ARGB to RGBA */
  199877. if (row_info->bit_depth == 8)
  199878. {
  199879. png_bytep sp, dp;
  199880. png_uint_32 i;
  199881. png_uint_32 row_width = row_info->width;
  199882. for (i = 0, sp = dp = row; i < row_width; i++)
  199883. {
  199884. png_byte save = *(sp++);
  199885. *(dp++) = *(sp++);
  199886. *(dp++) = *(sp++);
  199887. *(dp++) = *(sp++);
  199888. *(dp++) = save;
  199889. }
  199890. }
  199891. /* This converts from AARRGGBB to RRGGBBAA */
  199892. else
  199893. {
  199894. png_bytep sp, dp;
  199895. png_uint_32 i;
  199896. png_uint_32 row_width = row_info->width;
  199897. for (i = 0, sp = dp = row; i < row_width; i++)
  199898. {
  199899. png_byte save[2];
  199900. save[0] = *(sp++);
  199901. save[1] = *(sp++);
  199902. *(dp++) = *(sp++);
  199903. *(dp++) = *(sp++);
  199904. *(dp++) = *(sp++);
  199905. *(dp++) = *(sp++);
  199906. *(dp++) = *(sp++);
  199907. *(dp++) = *(sp++);
  199908. *(dp++) = save[0];
  199909. *(dp++) = save[1];
  199910. }
  199911. }
  199912. }
  199913. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199914. {
  199915. /* This converts from AG to GA */
  199916. if (row_info->bit_depth == 8)
  199917. {
  199918. png_bytep sp, dp;
  199919. png_uint_32 i;
  199920. png_uint_32 row_width = row_info->width;
  199921. for (i = 0, sp = dp = row; i < row_width; i++)
  199922. {
  199923. png_byte save = *(sp++);
  199924. *(dp++) = *(sp++);
  199925. *(dp++) = save;
  199926. }
  199927. }
  199928. /* This converts from AAGG to GGAA */
  199929. else
  199930. {
  199931. png_bytep sp, dp;
  199932. png_uint_32 i;
  199933. png_uint_32 row_width = row_info->width;
  199934. for (i = 0, sp = dp = row; i < row_width; i++)
  199935. {
  199936. png_byte save[2];
  199937. save[0] = *(sp++);
  199938. save[1] = *(sp++);
  199939. *(dp++) = *(sp++);
  199940. *(dp++) = *(sp++);
  199941. *(dp++) = save[0];
  199942. *(dp++) = save[1];
  199943. }
  199944. }
  199945. }
  199946. }
  199947. }
  199948. #endif
  199949. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199950. void /* PRIVATE */
  199951. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199952. {
  199953. png_debug(1, "in png_do_write_invert_alpha\n");
  199954. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199955. if (row != NULL && row_info != NULL)
  199956. #endif
  199957. {
  199958. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199959. {
  199960. /* This inverts the alpha channel in RGBA */
  199961. if (row_info->bit_depth == 8)
  199962. {
  199963. png_bytep sp, dp;
  199964. png_uint_32 i;
  199965. png_uint_32 row_width = row_info->width;
  199966. for (i = 0, sp = dp = row; i < row_width; i++)
  199967. {
  199968. /* does nothing
  199969. *(dp++) = *(sp++);
  199970. *(dp++) = *(sp++);
  199971. *(dp++) = *(sp++);
  199972. */
  199973. sp+=3; dp = sp;
  199974. *(dp++) = (png_byte)(255 - *(sp++));
  199975. }
  199976. }
  199977. /* This inverts the alpha channel in RRGGBBAA */
  199978. else
  199979. {
  199980. png_bytep sp, dp;
  199981. png_uint_32 i;
  199982. png_uint_32 row_width = row_info->width;
  199983. for (i = 0, sp = dp = row; i < row_width; i++)
  199984. {
  199985. /* does nothing
  199986. *(dp++) = *(sp++);
  199987. *(dp++) = *(sp++);
  199988. *(dp++) = *(sp++);
  199989. *(dp++) = *(sp++);
  199990. *(dp++) = *(sp++);
  199991. *(dp++) = *(sp++);
  199992. */
  199993. sp+=6; dp = sp;
  199994. *(dp++) = (png_byte)(255 - *(sp++));
  199995. *(dp++) = (png_byte)(255 - *(sp++));
  199996. }
  199997. }
  199998. }
  199999. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200000. {
  200001. /* This inverts the alpha channel in GA */
  200002. if (row_info->bit_depth == 8)
  200003. {
  200004. png_bytep sp, dp;
  200005. png_uint_32 i;
  200006. png_uint_32 row_width = row_info->width;
  200007. for (i = 0, sp = dp = row; i < row_width; i++)
  200008. {
  200009. *(dp++) = *(sp++);
  200010. *(dp++) = (png_byte)(255 - *(sp++));
  200011. }
  200012. }
  200013. /* This inverts the alpha channel in GGAA */
  200014. else
  200015. {
  200016. png_bytep sp, dp;
  200017. png_uint_32 i;
  200018. png_uint_32 row_width = row_info->width;
  200019. for (i = 0, sp = dp = row; i < row_width; i++)
  200020. {
  200021. /* does nothing
  200022. *(dp++) = *(sp++);
  200023. *(dp++) = *(sp++);
  200024. */
  200025. sp+=2; dp = sp;
  200026. *(dp++) = (png_byte)(255 - *(sp++));
  200027. *(dp++) = (png_byte)(255 - *(sp++));
  200028. }
  200029. }
  200030. }
  200031. }
  200032. }
  200033. #endif
  200034. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200035. /* undoes intrapixel differencing */
  200036. void /* PRIVATE */
  200037. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200038. {
  200039. png_debug(1, "in png_do_write_intrapixel\n");
  200040. if (
  200041. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200042. row != NULL && row_info != NULL &&
  200043. #endif
  200044. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200045. {
  200046. int bytes_per_pixel;
  200047. png_uint_32 row_width = row_info->width;
  200048. if (row_info->bit_depth == 8)
  200049. {
  200050. png_bytep rp;
  200051. png_uint_32 i;
  200052. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200053. bytes_per_pixel = 3;
  200054. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200055. bytes_per_pixel = 4;
  200056. else
  200057. return;
  200058. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200059. {
  200060. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200061. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200062. }
  200063. }
  200064. else if (row_info->bit_depth == 16)
  200065. {
  200066. png_bytep rp;
  200067. png_uint_32 i;
  200068. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200069. bytes_per_pixel = 6;
  200070. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200071. bytes_per_pixel = 8;
  200072. else
  200073. return;
  200074. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200075. {
  200076. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200077. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200078. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200079. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200080. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200081. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200082. *(rp+1) = (png_byte)(red & 0xff);
  200083. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200084. *(rp+5) = (png_byte)(blue & 0xff);
  200085. }
  200086. }
  200087. }
  200088. }
  200089. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200090. #endif /* PNG_WRITE_SUPPORTED */
  200091. /*** End of inlined file: pngwtran.c ***/
  200092. /*** Start of inlined file: pngwutil.c ***/
  200093. /* pngwutil.c - utilities to write a PNG file
  200094. *
  200095. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200096. * For conditions of distribution and use, see copyright notice in png.h
  200097. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200098. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200099. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200100. */
  200101. #define PNG_INTERNAL
  200102. #ifdef PNG_WRITE_SUPPORTED
  200103. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200104. * with unsigned numbers for convenience, although one supported
  200105. * ancillary chunk uses signed (two's complement) numbers.
  200106. */
  200107. void PNGAPI
  200108. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200109. {
  200110. buf[0] = (png_byte)((i >> 24) & 0xff);
  200111. buf[1] = (png_byte)((i >> 16) & 0xff);
  200112. buf[2] = (png_byte)((i >> 8) & 0xff);
  200113. buf[3] = (png_byte)(i & 0xff);
  200114. }
  200115. /* The png_save_int_32 function assumes integers are stored in two's
  200116. * complement format. If this isn't the case, then this routine needs to
  200117. * be modified to write data in two's complement format.
  200118. */
  200119. void PNGAPI
  200120. png_save_int_32(png_bytep buf, png_int_32 i)
  200121. {
  200122. buf[0] = (png_byte)((i >> 24) & 0xff);
  200123. buf[1] = (png_byte)((i >> 16) & 0xff);
  200124. buf[2] = (png_byte)((i >> 8) & 0xff);
  200125. buf[3] = (png_byte)(i & 0xff);
  200126. }
  200127. /* Place a 16-bit number into a buffer in PNG byte order.
  200128. * The parameter is declared unsigned int, not png_uint_16,
  200129. * just to avoid potential problems on pre-ANSI C compilers.
  200130. */
  200131. void PNGAPI
  200132. png_save_uint_16(png_bytep buf, unsigned int i)
  200133. {
  200134. buf[0] = (png_byte)((i >> 8) & 0xff);
  200135. buf[1] = (png_byte)(i & 0xff);
  200136. }
  200137. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200138. * representing the chunk name. The array must be at least 4 bytes in
  200139. * length, and does not need to be null terminated. To be safe, pass the
  200140. * pre-defined chunk names here, and if you need a new one, define it
  200141. * where the others are defined. The length is the length of the data.
  200142. * All the data must be present. If that is not possible, use the
  200143. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200144. * functions instead.
  200145. */
  200146. void PNGAPI
  200147. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200148. png_bytep data, png_size_t length)
  200149. {
  200150. if(png_ptr == NULL) return;
  200151. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200152. png_write_chunk_data(png_ptr, data, length);
  200153. png_write_chunk_end(png_ptr);
  200154. }
  200155. /* Write the start of a PNG chunk. The type is the chunk type.
  200156. * The total_length is the sum of the lengths of all the data you will be
  200157. * passing in png_write_chunk_data().
  200158. */
  200159. void PNGAPI
  200160. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200161. png_uint_32 length)
  200162. {
  200163. png_byte buf[4];
  200164. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200165. if(png_ptr == NULL) return;
  200166. /* write the length */
  200167. png_save_uint_32(buf, length);
  200168. png_write_data(png_ptr, buf, (png_size_t)4);
  200169. /* write the chunk name */
  200170. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200171. /* reset the crc and run it over the chunk name */
  200172. png_reset_crc(png_ptr);
  200173. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200174. }
  200175. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200176. * Note that multiple calls to this function are allowed, and that the
  200177. * sum of the lengths from these calls *must* add up to the total_length
  200178. * given to png_write_chunk_start().
  200179. */
  200180. void PNGAPI
  200181. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200182. {
  200183. /* write the data, and run the CRC over it */
  200184. if(png_ptr == NULL) return;
  200185. if (data != NULL && length > 0)
  200186. {
  200187. png_calculate_crc(png_ptr, data, length);
  200188. png_write_data(png_ptr, data, length);
  200189. }
  200190. }
  200191. /* Finish a chunk started with png_write_chunk_start(). */
  200192. void PNGAPI
  200193. png_write_chunk_end(png_structp png_ptr)
  200194. {
  200195. png_byte buf[4];
  200196. if(png_ptr == NULL) return;
  200197. /* write the crc */
  200198. png_save_uint_32(buf, png_ptr->crc);
  200199. png_write_data(png_ptr, buf, (png_size_t)4);
  200200. }
  200201. /* Simple function to write the signature. If we have already written
  200202. * the magic bytes of the signature, or more likely, the PNG stream is
  200203. * being embedded into another stream and doesn't need its own signature,
  200204. * we should call png_set_sig_bytes() to tell libpng how many of the
  200205. * bytes have already been written.
  200206. */
  200207. void /* PRIVATE */
  200208. png_write_sig(png_structp png_ptr)
  200209. {
  200210. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200211. /* write the rest of the 8 byte signature */
  200212. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200213. (png_size_t)8 - png_ptr->sig_bytes);
  200214. if(png_ptr->sig_bytes < 3)
  200215. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200216. }
  200217. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200218. /*
  200219. * This pair of functions encapsulates the operation of (a) compressing a
  200220. * text string, and (b) issuing it later as a series of chunk data writes.
  200221. * The compression_state structure is shared context for these functions
  200222. * set up by the caller in order to make the whole mess thread-safe.
  200223. */
  200224. typedef struct
  200225. {
  200226. char *input; /* the uncompressed input data */
  200227. int input_len; /* its length */
  200228. int num_output_ptr; /* number of output pointers used */
  200229. int max_output_ptr; /* size of output_ptr */
  200230. png_charpp output_ptr; /* array of pointers to output */
  200231. } compression_state;
  200232. /* compress given text into storage in the png_ptr structure */
  200233. static int /* PRIVATE */
  200234. png_text_compress(png_structp png_ptr,
  200235. png_charp text, png_size_t text_len, int compression,
  200236. compression_state *comp)
  200237. {
  200238. int ret;
  200239. comp->num_output_ptr = 0;
  200240. comp->max_output_ptr = 0;
  200241. comp->output_ptr = NULL;
  200242. comp->input = NULL;
  200243. comp->input_len = 0;
  200244. /* we may just want to pass the text right through */
  200245. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200246. {
  200247. comp->input = text;
  200248. comp->input_len = text_len;
  200249. return((int)text_len);
  200250. }
  200251. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200252. {
  200253. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200254. char msg[50];
  200255. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200256. png_warning(png_ptr, msg);
  200257. #else
  200258. png_warning(png_ptr, "Unknown compression type");
  200259. #endif
  200260. }
  200261. /* We can't write the chunk until we find out how much data we have,
  200262. * which means we need to run the compressor first and save the
  200263. * output. This shouldn't be a problem, as the vast majority of
  200264. * comments should be reasonable, but we will set up an array of
  200265. * malloc'd pointers to be sure.
  200266. *
  200267. * If we knew the application was well behaved, we could simplify this
  200268. * greatly by assuming we can always malloc an output buffer large
  200269. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200270. * and malloc this directly. The only time this would be a bad idea is
  200271. * if we can't malloc more than 64K and we have 64K of random input
  200272. * data, or if the input string is incredibly large (although this
  200273. * wouldn't cause a failure, just a slowdown due to swapping).
  200274. */
  200275. /* set up the compression buffers */
  200276. png_ptr->zstream.avail_in = (uInt)text_len;
  200277. png_ptr->zstream.next_in = (Bytef *)text;
  200278. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200279. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200280. /* this is the same compression loop as in png_write_row() */
  200281. do
  200282. {
  200283. /* compress the data */
  200284. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200285. if (ret != Z_OK)
  200286. {
  200287. /* error */
  200288. if (png_ptr->zstream.msg != NULL)
  200289. png_error(png_ptr, png_ptr->zstream.msg);
  200290. else
  200291. png_error(png_ptr, "zlib error");
  200292. }
  200293. /* check to see if we need more room */
  200294. if (!(png_ptr->zstream.avail_out))
  200295. {
  200296. /* make sure the output array has room */
  200297. if (comp->num_output_ptr >= comp->max_output_ptr)
  200298. {
  200299. int old_max;
  200300. old_max = comp->max_output_ptr;
  200301. comp->max_output_ptr = comp->num_output_ptr + 4;
  200302. if (comp->output_ptr != NULL)
  200303. {
  200304. png_charpp old_ptr;
  200305. old_ptr = comp->output_ptr;
  200306. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200307. (png_uint_32)(comp->max_output_ptr *
  200308. png_sizeof (png_charpp)));
  200309. png_memcpy(comp->output_ptr, old_ptr, old_max
  200310. * png_sizeof (png_charp));
  200311. png_free(png_ptr, old_ptr);
  200312. }
  200313. else
  200314. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200315. (png_uint_32)(comp->max_output_ptr *
  200316. png_sizeof (png_charp)));
  200317. }
  200318. /* save the data */
  200319. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200320. (png_uint_32)png_ptr->zbuf_size);
  200321. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200322. png_ptr->zbuf_size);
  200323. comp->num_output_ptr++;
  200324. /* and reset the buffer */
  200325. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200326. png_ptr->zstream.next_out = png_ptr->zbuf;
  200327. }
  200328. /* continue until we don't have any more to compress */
  200329. } while (png_ptr->zstream.avail_in);
  200330. /* finish the compression */
  200331. do
  200332. {
  200333. /* tell zlib we are finished */
  200334. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200335. if (ret == Z_OK)
  200336. {
  200337. /* check to see if we need more room */
  200338. if (!(png_ptr->zstream.avail_out))
  200339. {
  200340. /* check to make sure our output array has room */
  200341. if (comp->num_output_ptr >= comp->max_output_ptr)
  200342. {
  200343. int old_max;
  200344. old_max = comp->max_output_ptr;
  200345. comp->max_output_ptr = comp->num_output_ptr + 4;
  200346. if (comp->output_ptr != NULL)
  200347. {
  200348. png_charpp old_ptr;
  200349. old_ptr = comp->output_ptr;
  200350. /* This could be optimized to realloc() */
  200351. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200352. (png_uint_32)(comp->max_output_ptr *
  200353. png_sizeof (png_charpp)));
  200354. png_memcpy(comp->output_ptr, old_ptr,
  200355. old_max * png_sizeof (png_charp));
  200356. png_free(png_ptr, old_ptr);
  200357. }
  200358. else
  200359. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200360. (png_uint_32)(comp->max_output_ptr *
  200361. png_sizeof (png_charp)));
  200362. }
  200363. /* save off the data */
  200364. comp->output_ptr[comp->num_output_ptr] =
  200365. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200366. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200367. png_ptr->zbuf_size);
  200368. comp->num_output_ptr++;
  200369. /* and reset the buffer pointers */
  200370. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200371. png_ptr->zstream.next_out = png_ptr->zbuf;
  200372. }
  200373. }
  200374. else if (ret != Z_STREAM_END)
  200375. {
  200376. /* we got an error */
  200377. if (png_ptr->zstream.msg != NULL)
  200378. png_error(png_ptr, png_ptr->zstream.msg);
  200379. else
  200380. png_error(png_ptr, "zlib error");
  200381. }
  200382. } while (ret != Z_STREAM_END);
  200383. /* text length is number of buffers plus last buffer */
  200384. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200385. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200386. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200387. return((int)text_len);
  200388. }
  200389. /* ship the compressed text out via chunk writes */
  200390. static void /* PRIVATE */
  200391. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200392. {
  200393. int i;
  200394. /* handle the no-compression case */
  200395. if (comp->input)
  200396. {
  200397. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200398. (png_size_t)comp->input_len);
  200399. return;
  200400. }
  200401. /* write saved output buffers, if any */
  200402. for (i = 0; i < comp->num_output_ptr; i++)
  200403. {
  200404. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200405. png_ptr->zbuf_size);
  200406. png_free(png_ptr, comp->output_ptr[i]);
  200407. comp->output_ptr[i]=NULL;
  200408. }
  200409. if (comp->max_output_ptr != 0)
  200410. png_free(png_ptr, comp->output_ptr);
  200411. comp->output_ptr=NULL;
  200412. /* write anything left in zbuf */
  200413. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200414. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200415. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200416. /* reset zlib for another zTXt/iTXt or image data */
  200417. deflateReset(&png_ptr->zstream);
  200418. png_ptr->zstream.data_type = Z_BINARY;
  200419. }
  200420. #endif
  200421. /* Write the IHDR chunk, and update the png_struct with the necessary
  200422. * information. Note that the rest of this code depends upon this
  200423. * information being correct.
  200424. */
  200425. void /* PRIVATE */
  200426. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200427. int bit_depth, int color_type, int compression_type, int filter_type,
  200428. int interlace_type)
  200429. {
  200430. #ifdef PNG_USE_LOCAL_ARRAYS
  200431. PNG_IHDR;
  200432. #endif
  200433. png_byte buf[13]; /* buffer to store the IHDR info */
  200434. png_debug(1, "in png_write_IHDR\n");
  200435. /* Check that we have valid input data from the application info */
  200436. switch (color_type)
  200437. {
  200438. case PNG_COLOR_TYPE_GRAY:
  200439. switch (bit_depth)
  200440. {
  200441. case 1:
  200442. case 2:
  200443. case 4:
  200444. case 8:
  200445. case 16: png_ptr->channels = 1; break;
  200446. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200447. }
  200448. break;
  200449. case PNG_COLOR_TYPE_RGB:
  200450. if (bit_depth != 8 && bit_depth != 16)
  200451. png_error(png_ptr, "Invalid bit depth for RGB image");
  200452. png_ptr->channels = 3;
  200453. break;
  200454. case PNG_COLOR_TYPE_PALETTE:
  200455. switch (bit_depth)
  200456. {
  200457. case 1:
  200458. case 2:
  200459. case 4:
  200460. case 8: png_ptr->channels = 1; break;
  200461. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200462. }
  200463. break;
  200464. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200465. if (bit_depth != 8 && bit_depth != 16)
  200466. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200467. png_ptr->channels = 2;
  200468. break;
  200469. case PNG_COLOR_TYPE_RGB_ALPHA:
  200470. if (bit_depth != 8 && bit_depth != 16)
  200471. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200472. png_ptr->channels = 4;
  200473. break;
  200474. default:
  200475. png_error(png_ptr, "Invalid image color type specified");
  200476. }
  200477. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200478. {
  200479. png_warning(png_ptr, "Invalid compression type specified");
  200480. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200481. }
  200482. /* Write filter_method 64 (intrapixel differencing) only if
  200483. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200484. * 2. Libpng did not write a PNG signature (this filter_method is only
  200485. * used in PNG datastreams that are embedded in MNG datastreams) and
  200486. * 3. The application called png_permit_mng_features with a mask that
  200487. * included PNG_FLAG_MNG_FILTER_64 and
  200488. * 4. The filter_method is 64 and
  200489. * 5. The color_type is RGB or RGBA
  200490. */
  200491. if (
  200492. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200493. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200494. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200495. (color_type == PNG_COLOR_TYPE_RGB ||
  200496. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200497. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200498. #endif
  200499. filter_type != PNG_FILTER_TYPE_BASE)
  200500. {
  200501. png_warning(png_ptr, "Invalid filter type specified");
  200502. filter_type = PNG_FILTER_TYPE_BASE;
  200503. }
  200504. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200505. if (interlace_type != PNG_INTERLACE_NONE &&
  200506. interlace_type != PNG_INTERLACE_ADAM7)
  200507. {
  200508. png_warning(png_ptr, "Invalid interlace type specified");
  200509. interlace_type = PNG_INTERLACE_ADAM7;
  200510. }
  200511. #else
  200512. interlace_type=PNG_INTERLACE_NONE;
  200513. #endif
  200514. /* save off the relevent information */
  200515. png_ptr->bit_depth = (png_byte)bit_depth;
  200516. png_ptr->color_type = (png_byte)color_type;
  200517. png_ptr->interlaced = (png_byte)interlace_type;
  200518. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200519. png_ptr->filter_type = (png_byte)filter_type;
  200520. #endif
  200521. png_ptr->compression_type = (png_byte)compression_type;
  200522. png_ptr->width = width;
  200523. png_ptr->height = height;
  200524. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200525. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200526. /* set the usr info, so any transformations can modify it */
  200527. png_ptr->usr_width = png_ptr->width;
  200528. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200529. png_ptr->usr_channels = png_ptr->channels;
  200530. /* pack the header information into the buffer */
  200531. png_save_uint_32(buf, width);
  200532. png_save_uint_32(buf + 4, height);
  200533. buf[8] = (png_byte)bit_depth;
  200534. buf[9] = (png_byte)color_type;
  200535. buf[10] = (png_byte)compression_type;
  200536. buf[11] = (png_byte)filter_type;
  200537. buf[12] = (png_byte)interlace_type;
  200538. /* write the chunk */
  200539. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200540. /* initialize zlib with PNG info */
  200541. png_ptr->zstream.zalloc = png_zalloc;
  200542. png_ptr->zstream.zfree = png_zfree;
  200543. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200544. if (!(png_ptr->do_filter))
  200545. {
  200546. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200547. png_ptr->bit_depth < 8)
  200548. png_ptr->do_filter = PNG_FILTER_NONE;
  200549. else
  200550. png_ptr->do_filter = PNG_ALL_FILTERS;
  200551. }
  200552. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200553. {
  200554. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200555. png_ptr->zlib_strategy = Z_FILTERED;
  200556. else
  200557. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200558. }
  200559. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200560. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200561. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200562. png_ptr->zlib_mem_level = 8;
  200563. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200564. png_ptr->zlib_window_bits = 15;
  200565. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200566. png_ptr->zlib_method = 8;
  200567. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200568. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200569. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200570. png_error(png_ptr, "zlib failed to initialize compressor");
  200571. png_ptr->zstream.next_out = png_ptr->zbuf;
  200572. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200573. /* libpng is not interested in zstream.data_type */
  200574. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200575. png_ptr->zstream.data_type = Z_BINARY;
  200576. png_ptr->mode = PNG_HAVE_IHDR;
  200577. }
  200578. /* write the palette. We are careful not to trust png_color to be in the
  200579. * correct order for PNG, so people can redefine it to any convenient
  200580. * structure.
  200581. */
  200582. void /* PRIVATE */
  200583. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200584. {
  200585. #ifdef PNG_USE_LOCAL_ARRAYS
  200586. PNG_PLTE;
  200587. #endif
  200588. png_uint_32 i;
  200589. png_colorp pal_ptr;
  200590. png_byte buf[3];
  200591. png_debug(1, "in png_write_PLTE\n");
  200592. if ((
  200593. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200594. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200595. #endif
  200596. num_pal == 0) || num_pal > 256)
  200597. {
  200598. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200599. {
  200600. png_error(png_ptr, "Invalid number of colors in palette");
  200601. }
  200602. else
  200603. {
  200604. png_warning(png_ptr, "Invalid number of colors in palette");
  200605. return;
  200606. }
  200607. }
  200608. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200609. {
  200610. png_warning(png_ptr,
  200611. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200612. return;
  200613. }
  200614. png_ptr->num_palette = (png_uint_16)num_pal;
  200615. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200616. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200617. #ifndef PNG_NO_POINTER_INDEXING
  200618. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200619. {
  200620. buf[0] = pal_ptr->red;
  200621. buf[1] = pal_ptr->green;
  200622. buf[2] = pal_ptr->blue;
  200623. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200624. }
  200625. #else
  200626. /* This is a little slower but some buggy compilers need to do this instead */
  200627. pal_ptr=palette;
  200628. for (i = 0; i < num_pal; i++)
  200629. {
  200630. buf[0] = pal_ptr[i].red;
  200631. buf[1] = pal_ptr[i].green;
  200632. buf[2] = pal_ptr[i].blue;
  200633. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200634. }
  200635. #endif
  200636. png_write_chunk_end(png_ptr);
  200637. png_ptr->mode |= PNG_HAVE_PLTE;
  200638. }
  200639. /* write an IDAT chunk */
  200640. void /* PRIVATE */
  200641. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200642. {
  200643. #ifdef PNG_USE_LOCAL_ARRAYS
  200644. PNG_IDAT;
  200645. #endif
  200646. png_debug(1, "in png_write_IDAT\n");
  200647. /* Optimize the CMF field in the zlib stream. */
  200648. /* This hack of the zlib stream is compliant to the stream specification. */
  200649. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200650. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200651. {
  200652. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200653. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200654. {
  200655. /* Avoid memory underflows and multiplication overflows. */
  200656. /* The conditions below are practically always satisfied;
  200657. however, they still must be checked. */
  200658. if (length >= 2 &&
  200659. png_ptr->height < 16384 && png_ptr->width < 16384)
  200660. {
  200661. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200662. ((png_ptr->width *
  200663. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200664. unsigned int z_cinfo = z_cmf >> 4;
  200665. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200666. while (uncompressed_idat_size <= half_z_window_size &&
  200667. half_z_window_size >= 256)
  200668. {
  200669. z_cinfo--;
  200670. half_z_window_size >>= 1;
  200671. }
  200672. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200673. if (data[0] != (png_byte)z_cmf)
  200674. {
  200675. data[0] = (png_byte)z_cmf;
  200676. data[1] &= 0xe0;
  200677. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200678. }
  200679. }
  200680. }
  200681. else
  200682. png_error(png_ptr,
  200683. "Invalid zlib compression method or flags in IDAT");
  200684. }
  200685. png_write_chunk(png_ptr, png_IDAT, data, length);
  200686. png_ptr->mode |= PNG_HAVE_IDAT;
  200687. }
  200688. /* write an IEND chunk */
  200689. void /* PRIVATE */
  200690. png_write_IEND(png_structp png_ptr)
  200691. {
  200692. #ifdef PNG_USE_LOCAL_ARRAYS
  200693. PNG_IEND;
  200694. #endif
  200695. png_debug(1, "in png_write_IEND\n");
  200696. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200697. (png_size_t)0);
  200698. png_ptr->mode |= PNG_HAVE_IEND;
  200699. }
  200700. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200701. /* write a gAMA chunk */
  200702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200703. void /* PRIVATE */
  200704. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200705. {
  200706. #ifdef PNG_USE_LOCAL_ARRAYS
  200707. PNG_gAMA;
  200708. #endif
  200709. png_uint_32 igamma;
  200710. png_byte buf[4];
  200711. png_debug(1, "in png_write_gAMA\n");
  200712. /* file_gamma is saved in 1/100,000ths */
  200713. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200714. png_save_uint_32(buf, igamma);
  200715. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200716. }
  200717. #endif
  200718. #ifdef PNG_FIXED_POINT_SUPPORTED
  200719. void /* PRIVATE */
  200720. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200721. {
  200722. #ifdef PNG_USE_LOCAL_ARRAYS
  200723. PNG_gAMA;
  200724. #endif
  200725. png_byte buf[4];
  200726. png_debug(1, "in png_write_gAMA\n");
  200727. /* file_gamma is saved in 1/100,000ths */
  200728. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200729. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200730. }
  200731. #endif
  200732. #endif
  200733. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200734. /* write a sRGB chunk */
  200735. void /* PRIVATE */
  200736. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200737. {
  200738. #ifdef PNG_USE_LOCAL_ARRAYS
  200739. PNG_sRGB;
  200740. #endif
  200741. png_byte buf[1];
  200742. png_debug(1, "in png_write_sRGB\n");
  200743. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200744. png_warning(png_ptr,
  200745. "Invalid sRGB rendering intent specified");
  200746. buf[0]=(png_byte)srgb_intent;
  200747. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200748. }
  200749. #endif
  200750. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200751. /* write an iCCP chunk */
  200752. void /* PRIVATE */
  200753. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200754. png_charp profile, int profile_len)
  200755. {
  200756. #ifdef PNG_USE_LOCAL_ARRAYS
  200757. PNG_iCCP;
  200758. #endif
  200759. png_size_t name_len;
  200760. png_charp new_name;
  200761. compression_state comp;
  200762. int embedded_profile_len = 0;
  200763. png_debug(1, "in png_write_iCCP\n");
  200764. comp.num_output_ptr = 0;
  200765. comp.max_output_ptr = 0;
  200766. comp.output_ptr = NULL;
  200767. comp.input = NULL;
  200768. comp.input_len = 0;
  200769. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200770. &new_name)) == 0)
  200771. {
  200772. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200773. return;
  200774. }
  200775. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200776. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200777. if (profile == NULL)
  200778. profile_len = 0;
  200779. if (profile_len > 3)
  200780. embedded_profile_len =
  200781. ((*( (png_bytep)profile ))<<24) |
  200782. ((*( (png_bytep)profile+1))<<16) |
  200783. ((*( (png_bytep)profile+2))<< 8) |
  200784. ((*( (png_bytep)profile+3)) );
  200785. if (profile_len < embedded_profile_len)
  200786. {
  200787. png_warning(png_ptr,
  200788. "Embedded profile length too large in iCCP chunk");
  200789. return;
  200790. }
  200791. if (profile_len > embedded_profile_len)
  200792. {
  200793. png_warning(png_ptr,
  200794. "Truncating profile to actual length in iCCP chunk");
  200795. profile_len = embedded_profile_len;
  200796. }
  200797. if (profile_len)
  200798. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200799. PNG_COMPRESSION_TYPE_BASE, &comp);
  200800. /* make sure we include the NULL after the name and the compression type */
  200801. png_write_chunk_start(png_ptr, png_iCCP,
  200802. (png_uint_32)name_len+profile_len+2);
  200803. new_name[name_len+1]=0x00;
  200804. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200805. if (profile_len)
  200806. png_write_compressed_data_out(png_ptr, &comp);
  200807. png_write_chunk_end(png_ptr);
  200808. png_free(png_ptr, new_name);
  200809. }
  200810. #endif
  200811. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200812. /* write a sPLT chunk */
  200813. void /* PRIVATE */
  200814. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200815. {
  200816. #ifdef PNG_USE_LOCAL_ARRAYS
  200817. PNG_sPLT;
  200818. #endif
  200819. png_size_t name_len;
  200820. png_charp new_name;
  200821. png_byte entrybuf[10];
  200822. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200823. int palette_size = entry_size * spalette->nentries;
  200824. png_sPLT_entryp ep;
  200825. #ifdef PNG_NO_POINTER_INDEXING
  200826. int i;
  200827. #endif
  200828. png_debug(1, "in png_write_sPLT\n");
  200829. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200830. spalette->name, &new_name))==0)
  200831. {
  200832. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200833. return;
  200834. }
  200835. /* make sure we include the NULL after the name */
  200836. png_write_chunk_start(png_ptr, png_sPLT,
  200837. (png_uint_32)(name_len + 2 + palette_size));
  200838. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200839. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200840. /* loop through each palette entry, writing appropriately */
  200841. #ifndef PNG_NO_POINTER_INDEXING
  200842. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200843. {
  200844. if (spalette->depth == 8)
  200845. {
  200846. entrybuf[0] = (png_byte)ep->red;
  200847. entrybuf[1] = (png_byte)ep->green;
  200848. entrybuf[2] = (png_byte)ep->blue;
  200849. entrybuf[3] = (png_byte)ep->alpha;
  200850. png_save_uint_16(entrybuf + 4, ep->frequency);
  200851. }
  200852. else
  200853. {
  200854. png_save_uint_16(entrybuf + 0, ep->red);
  200855. png_save_uint_16(entrybuf + 2, ep->green);
  200856. png_save_uint_16(entrybuf + 4, ep->blue);
  200857. png_save_uint_16(entrybuf + 6, ep->alpha);
  200858. png_save_uint_16(entrybuf + 8, ep->frequency);
  200859. }
  200860. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200861. }
  200862. #else
  200863. ep=spalette->entries;
  200864. for (i=0; i>spalette->nentries; i++)
  200865. {
  200866. if (spalette->depth == 8)
  200867. {
  200868. entrybuf[0] = (png_byte)ep[i].red;
  200869. entrybuf[1] = (png_byte)ep[i].green;
  200870. entrybuf[2] = (png_byte)ep[i].blue;
  200871. entrybuf[3] = (png_byte)ep[i].alpha;
  200872. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200873. }
  200874. else
  200875. {
  200876. png_save_uint_16(entrybuf + 0, ep[i].red);
  200877. png_save_uint_16(entrybuf + 2, ep[i].green);
  200878. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200879. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200880. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200881. }
  200882. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200883. }
  200884. #endif
  200885. png_write_chunk_end(png_ptr);
  200886. png_free(png_ptr, new_name);
  200887. }
  200888. #endif
  200889. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200890. /* write the sBIT chunk */
  200891. void /* PRIVATE */
  200892. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200893. {
  200894. #ifdef PNG_USE_LOCAL_ARRAYS
  200895. PNG_sBIT;
  200896. #endif
  200897. png_byte buf[4];
  200898. png_size_t size;
  200899. png_debug(1, "in png_write_sBIT\n");
  200900. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200901. if (color_type & PNG_COLOR_MASK_COLOR)
  200902. {
  200903. png_byte maxbits;
  200904. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200905. png_ptr->usr_bit_depth);
  200906. if (sbit->red == 0 || sbit->red > maxbits ||
  200907. sbit->green == 0 || sbit->green > maxbits ||
  200908. sbit->blue == 0 || sbit->blue > maxbits)
  200909. {
  200910. png_warning(png_ptr, "Invalid sBIT depth specified");
  200911. return;
  200912. }
  200913. buf[0] = sbit->red;
  200914. buf[1] = sbit->green;
  200915. buf[2] = sbit->blue;
  200916. size = 3;
  200917. }
  200918. else
  200919. {
  200920. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200921. {
  200922. png_warning(png_ptr, "Invalid sBIT depth specified");
  200923. return;
  200924. }
  200925. buf[0] = sbit->gray;
  200926. size = 1;
  200927. }
  200928. if (color_type & PNG_COLOR_MASK_ALPHA)
  200929. {
  200930. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200931. {
  200932. png_warning(png_ptr, "Invalid sBIT depth specified");
  200933. return;
  200934. }
  200935. buf[size++] = sbit->alpha;
  200936. }
  200937. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200938. }
  200939. #endif
  200940. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200941. /* write the cHRM chunk */
  200942. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200943. void /* PRIVATE */
  200944. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200945. double red_x, double red_y, double green_x, double green_y,
  200946. double blue_x, double blue_y)
  200947. {
  200948. #ifdef PNG_USE_LOCAL_ARRAYS
  200949. PNG_cHRM;
  200950. #endif
  200951. png_byte buf[32];
  200952. png_uint_32 itemp;
  200953. png_debug(1, "in png_write_cHRM\n");
  200954. /* each value is saved in 1/100,000ths */
  200955. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200956. white_x + white_y > 1.0)
  200957. {
  200958. png_warning(png_ptr, "Invalid cHRM white point specified");
  200959. #if !defined(PNG_NO_CONSOLE_IO)
  200960. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200961. #endif
  200962. return;
  200963. }
  200964. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200965. png_save_uint_32(buf, itemp);
  200966. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200967. png_save_uint_32(buf + 4, itemp);
  200968. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200969. {
  200970. png_warning(png_ptr, "Invalid cHRM red point specified");
  200971. return;
  200972. }
  200973. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200974. png_save_uint_32(buf + 8, itemp);
  200975. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200976. png_save_uint_32(buf + 12, itemp);
  200977. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200978. {
  200979. png_warning(png_ptr, "Invalid cHRM green point specified");
  200980. return;
  200981. }
  200982. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200983. png_save_uint_32(buf + 16, itemp);
  200984. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200985. png_save_uint_32(buf + 20, itemp);
  200986. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200987. {
  200988. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200989. return;
  200990. }
  200991. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200992. png_save_uint_32(buf + 24, itemp);
  200993. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200994. png_save_uint_32(buf + 28, itemp);
  200995. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200996. }
  200997. #endif
  200998. #ifdef PNG_FIXED_POINT_SUPPORTED
  200999. void /* PRIVATE */
  201000. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201001. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201002. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201003. png_fixed_point blue_y)
  201004. {
  201005. #ifdef PNG_USE_LOCAL_ARRAYS
  201006. PNG_cHRM;
  201007. #endif
  201008. png_byte buf[32];
  201009. png_debug(1, "in png_write_cHRM\n");
  201010. /* each value is saved in 1/100,000ths */
  201011. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201012. {
  201013. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201014. #if !defined(PNG_NO_CONSOLE_IO)
  201015. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201016. #endif
  201017. return;
  201018. }
  201019. png_save_uint_32(buf, (png_uint_32)white_x);
  201020. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201021. if (red_x + red_y > 100000L)
  201022. {
  201023. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201024. return;
  201025. }
  201026. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201027. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201028. if (green_x + green_y > 100000L)
  201029. {
  201030. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201031. return;
  201032. }
  201033. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201034. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201035. if (blue_x + blue_y > 100000L)
  201036. {
  201037. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201038. return;
  201039. }
  201040. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201041. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201042. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201043. }
  201044. #endif
  201045. #endif
  201046. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201047. /* write the tRNS chunk */
  201048. void /* PRIVATE */
  201049. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201050. int num_trans, int color_type)
  201051. {
  201052. #ifdef PNG_USE_LOCAL_ARRAYS
  201053. PNG_tRNS;
  201054. #endif
  201055. png_byte buf[6];
  201056. png_debug(1, "in png_write_tRNS\n");
  201057. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201058. {
  201059. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201060. {
  201061. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201062. return;
  201063. }
  201064. /* write the chunk out as it is */
  201065. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201066. }
  201067. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201068. {
  201069. /* one 16 bit value */
  201070. if(tran->gray >= (1 << png_ptr->bit_depth))
  201071. {
  201072. png_warning(png_ptr,
  201073. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201074. return;
  201075. }
  201076. png_save_uint_16(buf, tran->gray);
  201077. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201078. }
  201079. else if (color_type == PNG_COLOR_TYPE_RGB)
  201080. {
  201081. /* three 16 bit values */
  201082. png_save_uint_16(buf, tran->red);
  201083. png_save_uint_16(buf + 2, tran->green);
  201084. png_save_uint_16(buf + 4, tran->blue);
  201085. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201086. {
  201087. png_warning(png_ptr,
  201088. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201089. return;
  201090. }
  201091. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201092. }
  201093. else
  201094. {
  201095. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201096. }
  201097. }
  201098. #endif
  201099. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201100. /* write the background chunk */
  201101. void /* PRIVATE */
  201102. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201103. {
  201104. #ifdef PNG_USE_LOCAL_ARRAYS
  201105. PNG_bKGD;
  201106. #endif
  201107. png_byte buf[6];
  201108. png_debug(1, "in png_write_bKGD\n");
  201109. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201110. {
  201111. if (
  201112. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201113. (png_ptr->num_palette ||
  201114. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201115. #endif
  201116. back->index > png_ptr->num_palette)
  201117. {
  201118. png_warning(png_ptr, "Invalid background palette index");
  201119. return;
  201120. }
  201121. buf[0] = back->index;
  201122. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201123. }
  201124. else if (color_type & PNG_COLOR_MASK_COLOR)
  201125. {
  201126. png_save_uint_16(buf, back->red);
  201127. png_save_uint_16(buf + 2, back->green);
  201128. png_save_uint_16(buf + 4, back->blue);
  201129. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201130. {
  201131. png_warning(png_ptr,
  201132. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201133. return;
  201134. }
  201135. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201136. }
  201137. else
  201138. {
  201139. if(back->gray >= (1 << png_ptr->bit_depth))
  201140. {
  201141. png_warning(png_ptr,
  201142. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201143. return;
  201144. }
  201145. png_save_uint_16(buf, back->gray);
  201146. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201147. }
  201148. }
  201149. #endif
  201150. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201151. /* write the histogram */
  201152. void /* PRIVATE */
  201153. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201154. {
  201155. #ifdef PNG_USE_LOCAL_ARRAYS
  201156. PNG_hIST;
  201157. #endif
  201158. int i;
  201159. png_byte buf[3];
  201160. png_debug(1, "in png_write_hIST\n");
  201161. if (num_hist > (int)png_ptr->num_palette)
  201162. {
  201163. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201164. png_ptr->num_palette);
  201165. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201166. return;
  201167. }
  201168. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201169. for (i = 0; i < num_hist; i++)
  201170. {
  201171. png_save_uint_16(buf, hist[i]);
  201172. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201173. }
  201174. png_write_chunk_end(png_ptr);
  201175. }
  201176. #endif
  201177. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201178. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201179. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201180. * and if invalid, correct the keyword rather than discarding the entire
  201181. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201182. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201183. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201184. *
  201185. * The new_key is allocated to hold the corrected keyword and must be freed
  201186. * by the calling routine. This avoids problems with trying to write to
  201187. * static keywords without having to have duplicate copies of the strings.
  201188. */
  201189. png_size_t /* PRIVATE */
  201190. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201191. {
  201192. png_size_t key_len;
  201193. png_charp kp, dp;
  201194. int kflag;
  201195. int kwarn=0;
  201196. png_debug(1, "in png_check_keyword\n");
  201197. *new_key = NULL;
  201198. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201199. {
  201200. png_warning(png_ptr, "zero length keyword");
  201201. return ((png_size_t)0);
  201202. }
  201203. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201204. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201205. if (*new_key == NULL)
  201206. {
  201207. png_warning(png_ptr, "Out of memory while procesing keyword");
  201208. return ((png_size_t)0);
  201209. }
  201210. /* Replace non-printing characters with a blank and print a warning */
  201211. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201212. {
  201213. if ((png_byte)*kp < 0x20 ||
  201214. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201215. {
  201216. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201217. char msg[40];
  201218. png_snprintf(msg, 40,
  201219. "invalid keyword character 0x%02X", (png_byte)*kp);
  201220. png_warning(png_ptr, msg);
  201221. #else
  201222. png_warning(png_ptr, "invalid character in keyword");
  201223. #endif
  201224. *dp = ' ';
  201225. }
  201226. else
  201227. {
  201228. *dp = *kp;
  201229. }
  201230. }
  201231. *dp = '\0';
  201232. /* Remove any trailing white space. */
  201233. kp = *new_key + key_len - 1;
  201234. if (*kp == ' ')
  201235. {
  201236. png_warning(png_ptr, "trailing spaces removed from keyword");
  201237. while (*kp == ' ')
  201238. {
  201239. *(kp--) = '\0';
  201240. key_len--;
  201241. }
  201242. }
  201243. /* Remove any leading white space. */
  201244. kp = *new_key;
  201245. if (*kp == ' ')
  201246. {
  201247. png_warning(png_ptr, "leading spaces removed from keyword");
  201248. while (*kp == ' ')
  201249. {
  201250. kp++;
  201251. key_len--;
  201252. }
  201253. }
  201254. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201255. /* Remove multiple internal spaces. */
  201256. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201257. {
  201258. if (*kp == ' ' && kflag == 0)
  201259. {
  201260. *(dp++) = *kp;
  201261. kflag = 1;
  201262. }
  201263. else if (*kp == ' ')
  201264. {
  201265. key_len--;
  201266. kwarn=1;
  201267. }
  201268. else
  201269. {
  201270. *(dp++) = *kp;
  201271. kflag = 0;
  201272. }
  201273. }
  201274. *dp = '\0';
  201275. if(kwarn)
  201276. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201277. if (key_len == 0)
  201278. {
  201279. png_free(png_ptr, *new_key);
  201280. *new_key=NULL;
  201281. png_warning(png_ptr, "Zero length keyword");
  201282. }
  201283. if (key_len > 79)
  201284. {
  201285. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201286. new_key[79] = '\0';
  201287. key_len = 79;
  201288. }
  201289. return (key_len);
  201290. }
  201291. #endif
  201292. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201293. /* write a tEXt chunk */
  201294. void /* PRIVATE */
  201295. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201296. png_size_t text_len)
  201297. {
  201298. #ifdef PNG_USE_LOCAL_ARRAYS
  201299. PNG_tEXt;
  201300. #endif
  201301. png_size_t key_len;
  201302. png_charp new_key;
  201303. png_debug(1, "in png_write_tEXt\n");
  201304. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201305. {
  201306. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201307. return;
  201308. }
  201309. if (text == NULL || *text == '\0')
  201310. text_len = 0;
  201311. else
  201312. text_len = png_strlen(text);
  201313. /* make sure we include the 0 after the key */
  201314. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201315. /*
  201316. * We leave it to the application to meet PNG-1.0 requirements on the
  201317. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201318. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201319. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201320. */
  201321. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201322. if (text_len)
  201323. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201324. png_write_chunk_end(png_ptr);
  201325. png_free(png_ptr, new_key);
  201326. }
  201327. #endif
  201328. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201329. /* write a compressed text chunk */
  201330. void /* PRIVATE */
  201331. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201332. png_size_t text_len, int compression)
  201333. {
  201334. #ifdef PNG_USE_LOCAL_ARRAYS
  201335. PNG_zTXt;
  201336. #endif
  201337. png_size_t key_len;
  201338. char buf[1];
  201339. png_charp new_key;
  201340. compression_state comp;
  201341. png_debug(1, "in png_write_zTXt\n");
  201342. comp.num_output_ptr = 0;
  201343. comp.max_output_ptr = 0;
  201344. comp.output_ptr = NULL;
  201345. comp.input = NULL;
  201346. comp.input_len = 0;
  201347. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201348. {
  201349. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201350. return;
  201351. }
  201352. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201353. {
  201354. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201355. png_free(png_ptr, new_key);
  201356. return;
  201357. }
  201358. text_len = png_strlen(text);
  201359. /* compute the compressed data; do it now for the length */
  201360. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201361. &comp);
  201362. /* write start of chunk */
  201363. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201364. (key_len+text_len+2));
  201365. /* write key */
  201366. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201367. png_free(png_ptr, new_key);
  201368. buf[0] = (png_byte)compression;
  201369. /* write compression */
  201370. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201371. /* write the compressed data */
  201372. png_write_compressed_data_out(png_ptr, &comp);
  201373. /* close the chunk */
  201374. png_write_chunk_end(png_ptr);
  201375. }
  201376. #endif
  201377. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201378. /* write an iTXt chunk */
  201379. void /* PRIVATE */
  201380. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201381. png_charp lang, png_charp lang_key, png_charp text)
  201382. {
  201383. #ifdef PNG_USE_LOCAL_ARRAYS
  201384. PNG_iTXt;
  201385. #endif
  201386. png_size_t lang_len, key_len, lang_key_len, text_len;
  201387. png_charp new_lang, new_key;
  201388. png_byte cbuf[2];
  201389. compression_state comp;
  201390. png_debug(1, "in png_write_iTXt\n");
  201391. comp.num_output_ptr = 0;
  201392. comp.max_output_ptr = 0;
  201393. comp.output_ptr = NULL;
  201394. comp.input = NULL;
  201395. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201396. {
  201397. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201398. return;
  201399. }
  201400. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201401. {
  201402. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201403. new_lang = NULL;
  201404. lang_len = 0;
  201405. }
  201406. if (lang_key == NULL)
  201407. lang_key_len = 0;
  201408. else
  201409. lang_key_len = png_strlen(lang_key);
  201410. if (text == NULL)
  201411. text_len = 0;
  201412. else
  201413. text_len = png_strlen(text);
  201414. /* compute the compressed data; do it now for the length */
  201415. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201416. &comp);
  201417. /* make sure we include the compression flag, the compression byte,
  201418. * and the NULs after the key, lang, and lang_key parts */
  201419. png_write_chunk_start(png_ptr, png_iTXt,
  201420. (png_uint_32)(
  201421. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201422. + key_len
  201423. + lang_len
  201424. + lang_key_len
  201425. + text_len));
  201426. /*
  201427. * We leave it to the application to meet PNG-1.0 requirements on the
  201428. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201429. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201430. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201431. */
  201432. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201433. /* set the compression flag */
  201434. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201435. compression == PNG_TEXT_COMPRESSION_NONE)
  201436. cbuf[0] = 0;
  201437. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201438. cbuf[0] = 1;
  201439. /* set the compression method */
  201440. cbuf[1] = 0;
  201441. png_write_chunk_data(png_ptr, cbuf, 2);
  201442. cbuf[0] = 0;
  201443. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201444. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201445. png_write_compressed_data_out(png_ptr, &comp);
  201446. png_write_chunk_end(png_ptr);
  201447. png_free(png_ptr, new_key);
  201448. if (new_lang)
  201449. png_free(png_ptr, new_lang);
  201450. }
  201451. #endif
  201452. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201453. /* write the oFFs chunk */
  201454. void /* PRIVATE */
  201455. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201456. int unit_type)
  201457. {
  201458. #ifdef PNG_USE_LOCAL_ARRAYS
  201459. PNG_oFFs;
  201460. #endif
  201461. png_byte buf[9];
  201462. png_debug(1, "in png_write_oFFs\n");
  201463. if (unit_type >= PNG_OFFSET_LAST)
  201464. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201465. png_save_int_32(buf, x_offset);
  201466. png_save_int_32(buf + 4, y_offset);
  201467. buf[8] = (png_byte)unit_type;
  201468. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201469. }
  201470. #endif
  201471. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201472. /* write the pCAL chunk (described in the PNG extensions document) */
  201473. void /* PRIVATE */
  201474. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201475. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201476. {
  201477. #ifdef PNG_USE_LOCAL_ARRAYS
  201478. PNG_pCAL;
  201479. #endif
  201480. png_size_t purpose_len, units_len, total_len;
  201481. png_uint_32p params_len;
  201482. png_byte buf[10];
  201483. png_charp new_purpose;
  201484. int i;
  201485. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201486. if (type >= PNG_EQUATION_LAST)
  201487. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201488. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201489. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201490. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201491. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201492. total_len = purpose_len + units_len + 10;
  201493. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201494. *png_sizeof(png_uint_32)));
  201495. /* Find the length of each parameter, making sure we don't count the
  201496. null terminator for the last parameter. */
  201497. for (i = 0; i < nparams; i++)
  201498. {
  201499. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201500. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201501. total_len += (png_size_t)params_len[i];
  201502. }
  201503. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201504. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201505. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201506. png_save_int_32(buf, X0);
  201507. png_save_int_32(buf + 4, X1);
  201508. buf[8] = (png_byte)type;
  201509. buf[9] = (png_byte)nparams;
  201510. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201511. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201512. png_free(png_ptr, new_purpose);
  201513. for (i = 0; i < nparams; i++)
  201514. {
  201515. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201516. (png_size_t)params_len[i]);
  201517. }
  201518. png_free(png_ptr, params_len);
  201519. png_write_chunk_end(png_ptr);
  201520. }
  201521. #endif
  201522. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201523. /* write the sCAL chunk */
  201524. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201525. void /* PRIVATE */
  201526. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201527. {
  201528. #ifdef PNG_USE_LOCAL_ARRAYS
  201529. PNG_sCAL;
  201530. #endif
  201531. char buf[64];
  201532. png_size_t total_len;
  201533. png_debug(1, "in png_write_sCAL\n");
  201534. buf[0] = (char)unit;
  201535. #if defined(_WIN32_WCE)
  201536. /* sprintf() function is not supported on WindowsCE */
  201537. {
  201538. wchar_t wc_buf[32];
  201539. size_t wc_len;
  201540. swprintf(wc_buf, TEXT("%12.12e"), width);
  201541. wc_len = wcslen(wc_buf);
  201542. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201543. total_len = wc_len + 2;
  201544. swprintf(wc_buf, TEXT("%12.12e"), height);
  201545. wc_len = wcslen(wc_buf);
  201546. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201547. NULL, NULL);
  201548. total_len += wc_len;
  201549. }
  201550. #else
  201551. png_snprintf(buf + 1, 63, "%12.12e", width);
  201552. total_len = 1 + png_strlen(buf + 1) + 1;
  201553. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201554. total_len += png_strlen(buf + total_len);
  201555. #endif
  201556. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201557. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201558. }
  201559. #else
  201560. #ifdef PNG_FIXED_POINT_SUPPORTED
  201561. void /* PRIVATE */
  201562. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201563. png_charp height)
  201564. {
  201565. #ifdef PNG_USE_LOCAL_ARRAYS
  201566. PNG_sCAL;
  201567. #endif
  201568. png_byte buf[64];
  201569. png_size_t wlen, hlen, total_len;
  201570. png_debug(1, "in png_write_sCAL_s\n");
  201571. wlen = png_strlen(width);
  201572. hlen = png_strlen(height);
  201573. total_len = wlen + hlen + 2;
  201574. if (total_len > 64)
  201575. {
  201576. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201577. return;
  201578. }
  201579. buf[0] = (png_byte)unit;
  201580. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201581. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201582. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201583. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201584. }
  201585. #endif
  201586. #endif
  201587. #endif
  201588. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201589. /* write the pHYs chunk */
  201590. void /* PRIVATE */
  201591. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201592. png_uint_32 y_pixels_per_unit,
  201593. int unit_type)
  201594. {
  201595. #ifdef PNG_USE_LOCAL_ARRAYS
  201596. PNG_pHYs;
  201597. #endif
  201598. png_byte buf[9];
  201599. png_debug(1, "in png_write_pHYs\n");
  201600. if (unit_type >= PNG_RESOLUTION_LAST)
  201601. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201602. png_save_uint_32(buf, x_pixels_per_unit);
  201603. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201604. buf[8] = (png_byte)unit_type;
  201605. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201606. }
  201607. #endif
  201608. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201609. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201610. * or png_convert_from_time_t(), or fill in the structure yourself.
  201611. */
  201612. void /* PRIVATE */
  201613. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201614. {
  201615. #ifdef PNG_USE_LOCAL_ARRAYS
  201616. PNG_tIME;
  201617. #endif
  201618. png_byte buf[7];
  201619. png_debug(1, "in png_write_tIME\n");
  201620. if (mod_time->month > 12 || mod_time->month < 1 ||
  201621. mod_time->day > 31 || mod_time->day < 1 ||
  201622. mod_time->hour > 23 || mod_time->second > 60)
  201623. {
  201624. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201625. return;
  201626. }
  201627. png_save_uint_16(buf, mod_time->year);
  201628. buf[2] = mod_time->month;
  201629. buf[3] = mod_time->day;
  201630. buf[4] = mod_time->hour;
  201631. buf[5] = mod_time->minute;
  201632. buf[6] = mod_time->second;
  201633. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201634. }
  201635. #endif
  201636. /* initializes the row writing capability of libpng */
  201637. void /* PRIVATE */
  201638. png_write_start_row(png_structp png_ptr)
  201639. {
  201640. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201641. #ifdef PNG_USE_LOCAL_ARRAYS
  201642. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201643. /* start of interlace block */
  201644. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201645. /* offset to next interlace block */
  201646. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201647. /* start of interlace block in the y direction */
  201648. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201649. /* offset to next interlace block in the y direction */
  201650. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201651. #endif
  201652. #endif
  201653. png_size_t buf_size;
  201654. png_debug(1, "in png_write_start_row\n");
  201655. buf_size = (png_size_t)(PNG_ROWBYTES(
  201656. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201657. /* set up row buffer */
  201658. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201659. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201660. #ifndef PNG_NO_WRITE_FILTERING
  201661. /* set up filtering buffer, if using this filter */
  201662. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201663. {
  201664. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201665. (png_ptr->rowbytes + 1));
  201666. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201667. }
  201668. /* We only need to keep the previous row if we are using one of these. */
  201669. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201670. {
  201671. /* set up previous row buffer */
  201672. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201673. png_memset(png_ptr->prev_row, 0, buf_size);
  201674. if (png_ptr->do_filter & PNG_FILTER_UP)
  201675. {
  201676. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201677. (png_ptr->rowbytes + 1));
  201678. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201679. }
  201680. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201681. {
  201682. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201683. (png_ptr->rowbytes + 1));
  201684. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201685. }
  201686. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201687. {
  201688. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201689. (png_ptr->rowbytes + 1));
  201690. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201691. }
  201692. #endif /* PNG_NO_WRITE_FILTERING */
  201693. }
  201694. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201695. /* if interlaced, we need to set up width and height of pass */
  201696. if (png_ptr->interlaced)
  201697. {
  201698. if (!(png_ptr->transformations & PNG_INTERLACE))
  201699. {
  201700. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201701. png_pass_ystart[0]) / png_pass_yinc[0];
  201702. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201703. png_pass_start[0]) / png_pass_inc[0];
  201704. }
  201705. else
  201706. {
  201707. png_ptr->num_rows = png_ptr->height;
  201708. png_ptr->usr_width = png_ptr->width;
  201709. }
  201710. }
  201711. else
  201712. #endif
  201713. {
  201714. png_ptr->num_rows = png_ptr->height;
  201715. png_ptr->usr_width = png_ptr->width;
  201716. }
  201717. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201718. png_ptr->zstream.next_out = png_ptr->zbuf;
  201719. }
  201720. /* Internal use only. Called when finished processing a row of data. */
  201721. void /* PRIVATE */
  201722. png_write_finish_row(png_structp png_ptr)
  201723. {
  201724. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201725. #ifdef PNG_USE_LOCAL_ARRAYS
  201726. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201727. /* start of interlace block */
  201728. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201729. /* offset to next interlace block */
  201730. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201731. /* start of interlace block in the y direction */
  201732. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201733. /* offset to next interlace block in the y direction */
  201734. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201735. #endif
  201736. #endif
  201737. int ret;
  201738. png_debug(1, "in png_write_finish_row\n");
  201739. /* next row */
  201740. png_ptr->row_number++;
  201741. /* see if we are done */
  201742. if (png_ptr->row_number < png_ptr->num_rows)
  201743. return;
  201744. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201745. /* if interlaced, go to next pass */
  201746. if (png_ptr->interlaced)
  201747. {
  201748. png_ptr->row_number = 0;
  201749. if (png_ptr->transformations & PNG_INTERLACE)
  201750. {
  201751. png_ptr->pass++;
  201752. }
  201753. else
  201754. {
  201755. /* loop until we find a non-zero width or height pass */
  201756. do
  201757. {
  201758. png_ptr->pass++;
  201759. if (png_ptr->pass >= 7)
  201760. break;
  201761. png_ptr->usr_width = (png_ptr->width +
  201762. png_pass_inc[png_ptr->pass] - 1 -
  201763. png_pass_start[png_ptr->pass]) /
  201764. png_pass_inc[png_ptr->pass];
  201765. png_ptr->num_rows = (png_ptr->height +
  201766. png_pass_yinc[png_ptr->pass] - 1 -
  201767. png_pass_ystart[png_ptr->pass]) /
  201768. png_pass_yinc[png_ptr->pass];
  201769. if (png_ptr->transformations & PNG_INTERLACE)
  201770. break;
  201771. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201772. }
  201773. /* reset the row above the image for the next pass */
  201774. if (png_ptr->pass < 7)
  201775. {
  201776. if (png_ptr->prev_row != NULL)
  201777. png_memset(png_ptr->prev_row, 0,
  201778. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201779. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201780. return;
  201781. }
  201782. }
  201783. #endif
  201784. /* if we get here, we've just written the last row, so we need
  201785. to flush the compressor */
  201786. do
  201787. {
  201788. /* tell the compressor we are done */
  201789. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201790. /* check for an error */
  201791. if (ret == Z_OK)
  201792. {
  201793. /* check to see if we need more room */
  201794. if (!(png_ptr->zstream.avail_out))
  201795. {
  201796. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201797. png_ptr->zstream.next_out = png_ptr->zbuf;
  201798. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201799. }
  201800. }
  201801. else if (ret != Z_STREAM_END)
  201802. {
  201803. if (png_ptr->zstream.msg != NULL)
  201804. png_error(png_ptr, png_ptr->zstream.msg);
  201805. else
  201806. png_error(png_ptr, "zlib error");
  201807. }
  201808. } while (ret != Z_STREAM_END);
  201809. /* write any extra space */
  201810. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201811. {
  201812. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201813. png_ptr->zstream.avail_out);
  201814. }
  201815. deflateReset(&png_ptr->zstream);
  201816. png_ptr->zstream.data_type = Z_BINARY;
  201817. }
  201818. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201819. /* Pick out the correct pixels for the interlace pass.
  201820. * The basic idea here is to go through the row with a source
  201821. * pointer and a destination pointer (sp and dp), and copy the
  201822. * correct pixels for the pass. As the row gets compacted,
  201823. * sp will always be >= dp, so we should never overwrite anything.
  201824. * See the default: case for the easiest code to understand.
  201825. */
  201826. void /* PRIVATE */
  201827. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201828. {
  201829. #ifdef PNG_USE_LOCAL_ARRAYS
  201830. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201831. /* start of interlace block */
  201832. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201833. /* offset to next interlace block */
  201834. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201835. #endif
  201836. png_debug(1, "in png_do_write_interlace\n");
  201837. /* we don't have to do anything on the last pass (6) */
  201838. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201839. if (row != NULL && row_info != NULL && pass < 6)
  201840. #else
  201841. if (pass < 6)
  201842. #endif
  201843. {
  201844. /* each pixel depth is handled separately */
  201845. switch (row_info->pixel_depth)
  201846. {
  201847. case 1:
  201848. {
  201849. png_bytep sp;
  201850. png_bytep dp;
  201851. int shift;
  201852. int d;
  201853. int value;
  201854. png_uint_32 i;
  201855. png_uint_32 row_width = row_info->width;
  201856. dp = row;
  201857. d = 0;
  201858. shift = 7;
  201859. for (i = png_pass_start[pass]; i < row_width;
  201860. i += png_pass_inc[pass])
  201861. {
  201862. sp = row + (png_size_t)(i >> 3);
  201863. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201864. d |= (value << shift);
  201865. if (shift == 0)
  201866. {
  201867. shift = 7;
  201868. *dp++ = (png_byte)d;
  201869. d = 0;
  201870. }
  201871. else
  201872. shift--;
  201873. }
  201874. if (shift != 7)
  201875. *dp = (png_byte)d;
  201876. break;
  201877. }
  201878. case 2:
  201879. {
  201880. png_bytep sp;
  201881. png_bytep dp;
  201882. int shift;
  201883. int d;
  201884. int value;
  201885. png_uint_32 i;
  201886. png_uint_32 row_width = row_info->width;
  201887. dp = row;
  201888. shift = 6;
  201889. d = 0;
  201890. for (i = png_pass_start[pass]; i < row_width;
  201891. i += png_pass_inc[pass])
  201892. {
  201893. sp = row + (png_size_t)(i >> 2);
  201894. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201895. d |= (value << shift);
  201896. if (shift == 0)
  201897. {
  201898. shift = 6;
  201899. *dp++ = (png_byte)d;
  201900. d = 0;
  201901. }
  201902. else
  201903. shift -= 2;
  201904. }
  201905. if (shift != 6)
  201906. *dp = (png_byte)d;
  201907. break;
  201908. }
  201909. case 4:
  201910. {
  201911. png_bytep sp;
  201912. png_bytep dp;
  201913. int shift;
  201914. int d;
  201915. int value;
  201916. png_uint_32 i;
  201917. png_uint_32 row_width = row_info->width;
  201918. dp = row;
  201919. shift = 4;
  201920. d = 0;
  201921. for (i = png_pass_start[pass]; i < row_width;
  201922. i += png_pass_inc[pass])
  201923. {
  201924. sp = row + (png_size_t)(i >> 1);
  201925. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201926. d |= (value << shift);
  201927. if (shift == 0)
  201928. {
  201929. shift = 4;
  201930. *dp++ = (png_byte)d;
  201931. d = 0;
  201932. }
  201933. else
  201934. shift -= 4;
  201935. }
  201936. if (shift != 4)
  201937. *dp = (png_byte)d;
  201938. break;
  201939. }
  201940. default:
  201941. {
  201942. png_bytep sp;
  201943. png_bytep dp;
  201944. png_uint_32 i;
  201945. png_uint_32 row_width = row_info->width;
  201946. png_size_t pixel_bytes;
  201947. /* start at the beginning */
  201948. dp = row;
  201949. /* find out how many bytes each pixel takes up */
  201950. pixel_bytes = (row_info->pixel_depth >> 3);
  201951. /* loop through the row, only looking at the pixels that
  201952. matter */
  201953. for (i = png_pass_start[pass]; i < row_width;
  201954. i += png_pass_inc[pass])
  201955. {
  201956. /* find out where the original pixel is */
  201957. sp = row + (png_size_t)i * pixel_bytes;
  201958. /* move the pixel */
  201959. if (dp != sp)
  201960. png_memcpy(dp, sp, pixel_bytes);
  201961. /* next pixel */
  201962. dp += pixel_bytes;
  201963. }
  201964. break;
  201965. }
  201966. }
  201967. /* set new row width */
  201968. row_info->width = (row_info->width +
  201969. png_pass_inc[pass] - 1 -
  201970. png_pass_start[pass]) /
  201971. png_pass_inc[pass];
  201972. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201973. row_info->width);
  201974. }
  201975. }
  201976. #endif
  201977. /* This filters the row, chooses which filter to use, if it has not already
  201978. * been specified by the application, and then writes the row out with the
  201979. * chosen filter.
  201980. */
  201981. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201982. #define PNG_HISHIFT 10
  201983. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201984. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201985. void /* PRIVATE */
  201986. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201987. {
  201988. png_bytep best_row;
  201989. #ifndef PNG_NO_WRITE_FILTER
  201990. png_bytep prev_row, row_buf;
  201991. png_uint_32 mins, bpp;
  201992. png_byte filter_to_do = png_ptr->do_filter;
  201993. png_uint_32 row_bytes = row_info->rowbytes;
  201994. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201995. int num_p_filters = (int)png_ptr->num_prev_filters;
  201996. #endif
  201997. png_debug(1, "in png_write_find_filter\n");
  201998. /* find out how many bytes offset each pixel is */
  201999. bpp = (row_info->pixel_depth + 7) >> 3;
  202000. prev_row = png_ptr->prev_row;
  202001. #endif
  202002. best_row = png_ptr->row_buf;
  202003. #ifndef PNG_NO_WRITE_FILTER
  202004. row_buf = best_row;
  202005. mins = PNG_MAXSUM;
  202006. /* The prediction method we use is to find which method provides the
  202007. * smallest value when summing the absolute values of the distances
  202008. * from zero, using anything >= 128 as negative numbers. This is known
  202009. * as the "minimum sum of absolute differences" heuristic. Other
  202010. * heuristics are the "weighted minimum sum of absolute differences"
  202011. * (experimental and can in theory improve compression), and the "zlib
  202012. * predictive" method (not implemented yet), which does test compressions
  202013. * of lines using different filter methods, and then chooses the
  202014. * (series of) filter(s) that give minimum compressed data size (VERY
  202015. * computationally expensive).
  202016. *
  202017. * GRR 980525: consider also
  202018. * (1) minimum sum of absolute differences from running average (i.e.,
  202019. * keep running sum of non-absolute differences & count of bytes)
  202020. * [track dispersion, too? restart average if dispersion too large?]
  202021. * (1b) minimum sum of absolute differences from sliding average, probably
  202022. * with window size <= deflate window (usually 32K)
  202023. * (2) minimum sum of squared differences from zero or running average
  202024. * (i.e., ~ root-mean-square approach)
  202025. */
  202026. /* We don't need to test the 'no filter' case if this is the only filter
  202027. * that has been chosen, as it doesn't actually do anything to the data.
  202028. */
  202029. if ((filter_to_do & PNG_FILTER_NONE) &&
  202030. filter_to_do != PNG_FILTER_NONE)
  202031. {
  202032. png_bytep rp;
  202033. png_uint_32 sum = 0;
  202034. png_uint_32 i;
  202035. int v;
  202036. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202037. {
  202038. v = *rp;
  202039. sum += (v < 128) ? v : 256 - v;
  202040. }
  202041. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202042. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202043. {
  202044. png_uint_32 sumhi, sumlo;
  202045. int j;
  202046. sumlo = sum & PNG_LOMASK;
  202047. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202048. /* Reduce the sum if we match any of the previous rows */
  202049. for (j = 0; j < num_p_filters; j++)
  202050. {
  202051. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202052. {
  202053. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202054. PNG_WEIGHT_SHIFT;
  202055. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202056. PNG_WEIGHT_SHIFT;
  202057. }
  202058. }
  202059. /* Factor in the cost of this filter (this is here for completeness,
  202060. * but it makes no sense to have a "cost" for the NONE filter, as
  202061. * it has the minimum possible computational cost - none).
  202062. */
  202063. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202064. PNG_COST_SHIFT;
  202065. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202066. PNG_COST_SHIFT;
  202067. if (sumhi > PNG_HIMASK)
  202068. sum = PNG_MAXSUM;
  202069. else
  202070. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202071. }
  202072. #endif
  202073. mins = sum;
  202074. }
  202075. /* sub filter */
  202076. if (filter_to_do == PNG_FILTER_SUB)
  202077. /* it's the only filter so no testing is needed */
  202078. {
  202079. png_bytep rp, lp, dp;
  202080. png_uint_32 i;
  202081. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202082. i++, rp++, dp++)
  202083. {
  202084. *dp = *rp;
  202085. }
  202086. for (lp = row_buf + 1; i < row_bytes;
  202087. i++, rp++, lp++, dp++)
  202088. {
  202089. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202090. }
  202091. best_row = png_ptr->sub_row;
  202092. }
  202093. else if (filter_to_do & PNG_FILTER_SUB)
  202094. {
  202095. png_bytep rp, dp, lp;
  202096. png_uint_32 sum = 0, lmins = mins;
  202097. png_uint_32 i;
  202098. int v;
  202099. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202100. /* We temporarily increase the "minimum sum" by the factor we
  202101. * would reduce the sum of this filter, so that we can do the
  202102. * early exit comparison without scaling the sum each time.
  202103. */
  202104. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202105. {
  202106. int j;
  202107. png_uint_32 lmhi, lmlo;
  202108. lmlo = lmins & PNG_LOMASK;
  202109. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202110. for (j = 0; j < num_p_filters; j++)
  202111. {
  202112. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202113. {
  202114. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202115. PNG_WEIGHT_SHIFT;
  202116. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202117. PNG_WEIGHT_SHIFT;
  202118. }
  202119. }
  202120. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202121. PNG_COST_SHIFT;
  202122. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202123. PNG_COST_SHIFT;
  202124. if (lmhi > PNG_HIMASK)
  202125. lmins = PNG_MAXSUM;
  202126. else
  202127. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202128. }
  202129. #endif
  202130. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202131. i++, rp++, dp++)
  202132. {
  202133. v = *dp = *rp;
  202134. sum += (v < 128) ? v : 256 - v;
  202135. }
  202136. for (lp = row_buf + 1; i < row_bytes;
  202137. i++, rp++, lp++, dp++)
  202138. {
  202139. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202140. sum += (v < 128) ? v : 256 - v;
  202141. if (sum > lmins) /* We are already worse, don't continue. */
  202142. break;
  202143. }
  202144. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202145. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202146. {
  202147. int j;
  202148. png_uint_32 sumhi, sumlo;
  202149. sumlo = sum & PNG_LOMASK;
  202150. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202151. for (j = 0; j < num_p_filters; j++)
  202152. {
  202153. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202154. {
  202155. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202156. PNG_WEIGHT_SHIFT;
  202157. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202158. PNG_WEIGHT_SHIFT;
  202159. }
  202160. }
  202161. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202162. PNG_COST_SHIFT;
  202163. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202164. PNG_COST_SHIFT;
  202165. if (sumhi > PNG_HIMASK)
  202166. sum = PNG_MAXSUM;
  202167. else
  202168. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202169. }
  202170. #endif
  202171. if (sum < mins)
  202172. {
  202173. mins = sum;
  202174. best_row = png_ptr->sub_row;
  202175. }
  202176. }
  202177. /* up filter */
  202178. if (filter_to_do == PNG_FILTER_UP)
  202179. {
  202180. png_bytep rp, dp, pp;
  202181. png_uint_32 i;
  202182. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202183. pp = prev_row + 1; i < row_bytes;
  202184. i++, rp++, pp++, dp++)
  202185. {
  202186. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202187. }
  202188. best_row = png_ptr->up_row;
  202189. }
  202190. else if (filter_to_do & PNG_FILTER_UP)
  202191. {
  202192. png_bytep rp, dp, pp;
  202193. png_uint_32 sum = 0, lmins = mins;
  202194. png_uint_32 i;
  202195. int v;
  202196. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202197. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202198. {
  202199. int j;
  202200. png_uint_32 lmhi, lmlo;
  202201. lmlo = lmins & PNG_LOMASK;
  202202. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202203. for (j = 0; j < num_p_filters; j++)
  202204. {
  202205. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202206. {
  202207. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202208. PNG_WEIGHT_SHIFT;
  202209. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202210. PNG_WEIGHT_SHIFT;
  202211. }
  202212. }
  202213. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202214. PNG_COST_SHIFT;
  202215. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202216. PNG_COST_SHIFT;
  202217. if (lmhi > PNG_HIMASK)
  202218. lmins = PNG_MAXSUM;
  202219. else
  202220. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202221. }
  202222. #endif
  202223. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202224. pp = prev_row + 1; i < row_bytes; i++)
  202225. {
  202226. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202227. sum += (v < 128) ? v : 256 - v;
  202228. if (sum > lmins) /* We are already worse, don't continue. */
  202229. break;
  202230. }
  202231. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202232. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202233. {
  202234. int j;
  202235. png_uint_32 sumhi, sumlo;
  202236. sumlo = sum & PNG_LOMASK;
  202237. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202238. for (j = 0; j < num_p_filters; j++)
  202239. {
  202240. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202241. {
  202242. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202243. PNG_WEIGHT_SHIFT;
  202244. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202245. PNG_WEIGHT_SHIFT;
  202246. }
  202247. }
  202248. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202249. PNG_COST_SHIFT;
  202250. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202251. PNG_COST_SHIFT;
  202252. if (sumhi > PNG_HIMASK)
  202253. sum = PNG_MAXSUM;
  202254. else
  202255. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202256. }
  202257. #endif
  202258. if (sum < mins)
  202259. {
  202260. mins = sum;
  202261. best_row = png_ptr->up_row;
  202262. }
  202263. }
  202264. /* avg filter */
  202265. if (filter_to_do == PNG_FILTER_AVG)
  202266. {
  202267. png_bytep rp, dp, pp, lp;
  202268. png_uint_32 i;
  202269. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202270. pp = prev_row + 1; i < bpp; i++)
  202271. {
  202272. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202273. }
  202274. for (lp = row_buf + 1; i < row_bytes; i++)
  202275. {
  202276. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202277. & 0xff);
  202278. }
  202279. best_row = png_ptr->avg_row;
  202280. }
  202281. else if (filter_to_do & PNG_FILTER_AVG)
  202282. {
  202283. png_bytep rp, dp, pp, lp;
  202284. png_uint_32 sum = 0, lmins = mins;
  202285. png_uint_32 i;
  202286. int v;
  202287. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202288. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202289. {
  202290. int j;
  202291. png_uint_32 lmhi, lmlo;
  202292. lmlo = lmins & PNG_LOMASK;
  202293. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202294. for (j = 0; j < num_p_filters; j++)
  202295. {
  202296. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202297. {
  202298. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202299. PNG_WEIGHT_SHIFT;
  202300. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202301. PNG_WEIGHT_SHIFT;
  202302. }
  202303. }
  202304. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202305. PNG_COST_SHIFT;
  202306. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202307. PNG_COST_SHIFT;
  202308. if (lmhi > PNG_HIMASK)
  202309. lmins = PNG_MAXSUM;
  202310. else
  202311. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202312. }
  202313. #endif
  202314. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202315. pp = prev_row + 1; i < bpp; i++)
  202316. {
  202317. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202318. sum += (v < 128) ? v : 256 - v;
  202319. }
  202320. for (lp = row_buf + 1; i < row_bytes; i++)
  202321. {
  202322. v = *dp++ =
  202323. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202324. sum += (v < 128) ? v : 256 - v;
  202325. if (sum > lmins) /* We are already worse, don't continue. */
  202326. break;
  202327. }
  202328. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202329. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202330. {
  202331. int j;
  202332. png_uint_32 sumhi, sumlo;
  202333. sumlo = sum & PNG_LOMASK;
  202334. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202335. for (j = 0; j < num_p_filters; j++)
  202336. {
  202337. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202338. {
  202339. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202340. PNG_WEIGHT_SHIFT;
  202341. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202342. PNG_WEIGHT_SHIFT;
  202343. }
  202344. }
  202345. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202346. PNG_COST_SHIFT;
  202347. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202348. PNG_COST_SHIFT;
  202349. if (sumhi > PNG_HIMASK)
  202350. sum = PNG_MAXSUM;
  202351. else
  202352. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202353. }
  202354. #endif
  202355. if (sum < mins)
  202356. {
  202357. mins = sum;
  202358. best_row = png_ptr->avg_row;
  202359. }
  202360. }
  202361. /* Paeth filter */
  202362. if (filter_to_do == PNG_FILTER_PAETH)
  202363. {
  202364. png_bytep rp, dp, pp, cp, lp;
  202365. png_uint_32 i;
  202366. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202367. pp = prev_row + 1; i < bpp; i++)
  202368. {
  202369. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202370. }
  202371. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202372. {
  202373. int a, b, c, pa, pb, pc, p;
  202374. b = *pp++;
  202375. c = *cp++;
  202376. a = *lp++;
  202377. p = b - c;
  202378. pc = a - c;
  202379. #ifdef PNG_USE_ABS
  202380. pa = abs(p);
  202381. pb = abs(pc);
  202382. pc = abs(p + pc);
  202383. #else
  202384. pa = p < 0 ? -p : p;
  202385. pb = pc < 0 ? -pc : pc;
  202386. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202387. #endif
  202388. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202389. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202390. }
  202391. best_row = png_ptr->paeth_row;
  202392. }
  202393. else if (filter_to_do & PNG_FILTER_PAETH)
  202394. {
  202395. png_bytep rp, dp, pp, cp, lp;
  202396. png_uint_32 sum = 0, lmins = mins;
  202397. png_uint_32 i;
  202398. int v;
  202399. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202400. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202401. {
  202402. int j;
  202403. png_uint_32 lmhi, lmlo;
  202404. lmlo = lmins & PNG_LOMASK;
  202405. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202406. for (j = 0; j < num_p_filters; j++)
  202407. {
  202408. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202409. {
  202410. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202411. PNG_WEIGHT_SHIFT;
  202412. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202413. PNG_WEIGHT_SHIFT;
  202414. }
  202415. }
  202416. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202417. PNG_COST_SHIFT;
  202418. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202419. PNG_COST_SHIFT;
  202420. if (lmhi > PNG_HIMASK)
  202421. lmins = PNG_MAXSUM;
  202422. else
  202423. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202424. }
  202425. #endif
  202426. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202427. pp = prev_row + 1; i < bpp; i++)
  202428. {
  202429. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202430. sum += (v < 128) ? v : 256 - v;
  202431. }
  202432. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202433. {
  202434. int a, b, c, pa, pb, pc, p;
  202435. b = *pp++;
  202436. c = *cp++;
  202437. a = *lp++;
  202438. #ifndef PNG_SLOW_PAETH
  202439. p = b - c;
  202440. pc = a - c;
  202441. #ifdef PNG_USE_ABS
  202442. pa = abs(p);
  202443. pb = abs(pc);
  202444. pc = abs(p + pc);
  202445. #else
  202446. pa = p < 0 ? -p : p;
  202447. pb = pc < 0 ? -pc : pc;
  202448. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202449. #endif
  202450. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202451. #else /* PNG_SLOW_PAETH */
  202452. p = a + b - c;
  202453. pa = abs(p - a);
  202454. pb = abs(p - b);
  202455. pc = abs(p - c);
  202456. if (pa <= pb && pa <= pc)
  202457. p = a;
  202458. else if (pb <= pc)
  202459. p = b;
  202460. else
  202461. p = c;
  202462. #endif /* PNG_SLOW_PAETH */
  202463. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202464. sum += (v < 128) ? v : 256 - v;
  202465. if (sum > lmins) /* We are already worse, don't continue. */
  202466. break;
  202467. }
  202468. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202469. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202470. {
  202471. int j;
  202472. png_uint_32 sumhi, sumlo;
  202473. sumlo = sum & PNG_LOMASK;
  202474. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202475. for (j = 0; j < num_p_filters; j++)
  202476. {
  202477. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202478. {
  202479. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202480. PNG_WEIGHT_SHIFT;
  202481. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202482. PNG_WEIGHT_SHIFT;
  202483. }
  202484. }
  202485. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202486. PNG_COST_SHIFT;
  202487. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202488. PNG_COST_SHIFT;
  202489. if (sumhi > PNG_HIMASK)
  202490. sum = PNG_MAXSUM;
  202491. else
  202492. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202493. }
  202494. #endif
  202495. if (sum < mins)
  202496. {
  202497. best_row = png_ptr->paeth_row;
  202498. }
  202499. }
  202500. #endif /* PNG_NO_WRITE_FILTER */
  202501. /* Do the actual writing of the filtered row data from the chosen filter. */
  202502. png_write_filtered_row(png_ptr, best_row);
  202503. #ifndef PNG_NO_WRITE_FILTER
  202504. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202505. /* Save the type of filter we picked this time for future calculations */
  202506. if (png_ptr->num_prev_filters > 0)
  202507. {
  202508. int j;
  202509. for (j = 1; j < num_p_filters; j++)
  202510. {
  202511. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202512. }
  202513. png_ptr->prev_filters[j] = best_row[0];
  202514. }
  202515. #endif
  202516. #endif /* PNG_NO_WRITE_FILTER */
  202517. }
  202518. /* Do the actual writing of a previously filtered row. */
  202519. void /* PRIVATE */
  202520. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202521. {
  202522. png_debug(1, "in png_write_filtered_row\n");
  202523. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202524. /* set up the zlib input buffer */
  202525. png_ptr->zstream.next_in = filtered_row;
  202526. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202527. /* repeat until we have compressed all the data */
  202528. do
  202529. {
  202530. int ret; /* return of zlib */
  202531. /* compress the data */
  202532. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202533. /* check for compression errors */
  202534. if (ret != Z_OK)
  202535. {
  202536. if (png_ptr->zstream.msg != NULL)
  202537. png_error(png_ptr, png_ptr->zstream.msg);
  202538. else
  202539. png_error(png_ptr, "zlib error");
  202540. }
  202541. /* see if it is time to write another IDAT */
  202542. if (!(png_ptr->zstream.avail_out))
  202543. {
  202544. /* write the IDAT and reset the zlib output buffer */
  202545. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202546. png_ptr->zstream.next_out = png_ptr->zbuf;
  202547. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202548. }
  202549. /* repeat until all data has been compressed */
  202550. } while (png_ptr->zstream.avail_in);
  202551. /* swap the current and previous rows */
  202552. if (png_ptr->prev_row != NULL)
  202553. {
  202554. png_bytep tptr;
  202555. tptr = png_ptr->prev_row;
  202556. png_ptr->prev_row = png_ptr->row_buf;
  202557. png_ptr->row_buf = tptr;
  202558. }
  202559. /* finish row - updates counters and flushes zlib if last row */
  202560. png_write_finish_row(png_ptr);
  202561. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202562. png_ptr->flush_rows++;
  202563. if (png_ptr->flush_dist > 0 &&
  202564. png_ptr->flush_rows >= png_ptr->flush_dist)
  202565. {
  202566. png_write_flush(png_ptr);
  202567. }
  202568. #endif
  202569. }
  202570. #endif /* PNG_WRITE_SUPPORTED */
  202571. /*** End of inlined file: pngwutil.c ***/
  202572. #else
  202573. extern "C"
  202574. {
  202575. #include <png.h>
  202576. #include <pngconf.h>
  202577. }
  202578. #endif
  202579. }
  202580. #undef max
  202581. #undef min
  202582. #if JUCE_MSVC
  202583. #pragma warning (pop)
  202584. #endif
  202585. BEGIN_JUCE_NAMESPACE
  202586. using ::calloc;
  202587. using ::malloc;
  202588. using ::free;
  202589. namespace PNGHelpers
  202590. {
  202591. using namespace pnglibNamespace;
  202592. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202593. {
  202594. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202595. }
  202596. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202597. {
  202598. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202599. }
  202600. struct PNGErrorStruct {};
  202601. static void errorCallback (png_structp, png_const_charp)
  202602. {
  202603. throw PNGErrorStruct();
  202604. }
  202605. }
  202606. PNGImageFormat::PNGImageFormat() {}
  202607. PNGImageFormat::~PNGImageFormat() {}
  202608. const String PNGImageFormat::getFormatName()
  202609. {
  202610. return "PNG";
  202611. }
  202612. bool PNGImageFormat::canUnderstand (InputStream& in)
  202613. {
  202614. const int bytesNeeded = 4;
  202615. char header [bytesNeeded];
  202616. return in.read (header, bytesNeeded) == bytesNeeded
  202617. && header[1] == 'P'
  202618. && header[2] == 'N'
  202619. && header[3] == 'G';
  202620. }
  202621. const Image PNGImageFormat::decodeImage (InputStream& in)
  202622. {
  202623. using namespace pnglibNamespace;
  202624. Image image;
  202625. png_structp pngReadStruct;
  202626. png_infop pngInfoStruct;
  202627. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202628. if (pngReadStruct != 0)
  202629. {
  202630. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202631. if (pngInfoStruct == 0)
  202632. {
  202633. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202634. return Image::null;
  202635. }
  202636. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202637. // read the header..
  202638. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202639. png_uint_32 width, height;
  202640. int bitDepth, colorType, interlaceType;
  202641. png_read_info (pngReadStruct, pngInfoStruct);
  202642. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202643. &width, &height,
  202644. &bitDepth, &colorType,
  202645. &interlaceType, 0, 0);
  202646. if (bitDepth == 16)
  202647. png_set_strip_16 (pngReadStruct);
  202648. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202649. png_set_expand (pngReadStruct);
  202650. if (bitDepth < 8)
  202651. png_set_expand (pngReadStruct);
  202652. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202653. png_set_expand (pngReadStruct);
  202654. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202655. png_set_gray_to_rgb (pngReadStruct);
  202656. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202657. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202658. || pngInfoStruct->num_trans > 0;
  202659. // Load the image into a temp buffer in the pnglib format..
  202660. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202661. {
  202662. HeapBlock <png_bytep> rows (height);
  202663. for (int y = (int) height; --y >= 0;)
  202664. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202665. png_read_image (pngReadStruct, rows);
  202666. png_read_end (pngReadStruct, pngInfoStruct);
  202667. }
  202668. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202669. // now convert the data to a juce image format..
  202670. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202671. (int) width, (int) height, hasAlphaChan);
  202672. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202673. const Image::BitmapData destData (image, true);
  202674. uint8* srcRow = tempBuffer;
  202675. uint8* destRow = destData.data;
  202676. for (int y = 0; y < (int) height; ++y)
  202677. {
  202678. const uint8* src = srcRow;
  202679. srcRow += (width << 2);
  202680. uint8* dest = destRow;
  202681. destRow += destData.lineStride;
  202682. if (hasAlphaChan)
  202683. {
  202684. for (int i = (int) width; --i >= 0;)
  202685. {
  202686. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202687. ((PixelARGB*) dest)->premultiply();
  202688. dest += destData.pixelStride;
  202689. src += 4;
  202690. }
  202691. }
  202692. else
  202693. {
  202694. for (int i = (int) width; --i >= 0;)
  202695. {
  202696. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202697. dest += destData.pixelStride;
  202698. src += 4;
  202699. }
  202700. }
  202701. }
  202702. }
  202703. return image;
  202704. }
  202705. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202706. {
  202707. using namespace pnglibNamespace;
  202708. const int width = image.getWidth();
  202709. const int height = image.getHeight();
  202710. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202711. if (pngWriteStruct == 0)
  202712. return false;
  202713. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202714. if (pngInfoStruct == 0)
  202715. {
  202716. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202717. return false;
  202718. }
  202719. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202720. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202721. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202722. : PNG_COLOR_TYPE_RGB,
  202723. PNG_INTERLACE_NONE,
  202724. PNG_COMPRESSION_TYPE_BASE,
  202725. PNG_FILTER_TYPE_BASE);
  202726. HeapBlock <uint8> rowData (width * 4);
  202727. png_color_8 sig_bit;
  202728. sig_bit.red = 8;
  202729. sig_bit.green = 8;
  202730. sig_bit.blue = 8;
  202731. sig_bit.alpha = 8;
  202732. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202733. png_write_info (pngWriteStruct, pngInfoStruct);
  202734. png_set_shift (pngWriteStruct, &sig_bit);
  202735. png_set_packing (pngWriteStruct);
  202736. const Image::BitmapData srcData (image, false);
  202737. for (int y = 0; y < height; ++y)
  202738. {
  202739. uint8* dst = rowData;
  202740. const uint8* src = srcData.getLinePointer (y);
  202741. if (image.hasAlphaChannel())
  202742. {
  202743. for (int i = width; --i >= 0;)
  202744. {
  202745. PixelARGB p (*(const PixelARGB*) src);
  202746. p.unpremultiply();
  202747. *dst++ = p.getRed();
  202748. *dst++ = p.getGreen();
  202749. *dst++ = p.getBlue();
  202750. *dst++ = p.getAlpha();
  202751. src += srcData.pixelStride;
  202752. }
  202753. }
  202754. else
  202755. {
  202756. for (int i = width; --i >= 0;)
  202757. {
  202758. *dst++ = ((const PixelRGB*) src)->getRed();
  202759. *dst++ = ((const PixelRGB*) src)->getGreen();
  202760. *dst++ = ((const PixelRGB*) src)->getBlue();
  202761. src += srcData.pixelStride;
  202762. }
  202763. }
  202764. png_write_rows (pngWriteStruct, &rowData, 1);
  202765. }
  202766. png_write_end (pngWriteStruct, pngInfoStruct);
  202767. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202768. out.flush();
  202769. return true;
  202770. }
  202771. END_JUCE_NAMESPACE
  202772. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202773. #endif
  202774. //==============================================================================
  202775. #if JUCE_BUILD_NATIVE
  202776. #if JUCE_WINDOWS
  202777. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202778. /*
  202779. This file wraps together all the win32-specific code, so that
  202780. we can include all the native headers just once, and compile all our
  202781. platform-specific stuff in one big lump, keeping it out of the way of
  202782. the rest of the codebase.
  202783. */
  202784. #if JUCE_WINDOWS
  202785. BEGIN_JUCE_NAMESPACE
  202786. #define JUCE_INCLUDED_FILE 1
  202787. // Now include the actual code files..
  202788. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202789. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202790. // compiled on its own).
  202791. #if JUCE_INCLUDED_FILE
  202792. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202793. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202794. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202795. #ifndef DOXYGEN
  202796. // use with DynamicLibraryLoader to simplify importing functions
  202797. //
  202798. // functionName: function to import
  202799. // localFunctionName: name you want to use to actually call it (must be different)
  202800. // returnType: the return type
  202801. // object: the DynamicLibraryLoader to use
  202802. // params: list of params (bracketed)
  202803. //
  202804. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202805. typedef returnType (WINAPI *type##localFunctionName) params; \
  202806. type##localFunctionName localFunctionName \
  202807. = (type##localFunctionName)object.findProcAddress (#functionName);
  202808. // loads and unloads a DLL automatically
  202809. class JUCE_API DynamicLibraryLoader
  202810. {
  202811. public:
  202812. DynamicLibraryLoader (const String& name);
  202813. ~DynamicLibraryLoader();
  202814. void* findProcAddress (const String& functionName);
  202815. private:
  202816. void* libHandle;
  202817. };
  202818. #endif
  202819. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202820. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202821. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202822. {
  202823. libHandle = LoadLibrary (name);
  202824. }
  202825. DynamicLibraryLoader::~DynamicLibraryLoader()
  202826. {
  202827. FreeLibrary ((HMODULE) libHandle);
  202828. }
  202829. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202830. {
  202831. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202832. }
  202833. #endif
  202834. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202835. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202836. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202837. // compiled on its own).
  202838. #if JUCE_INCLUDED_FILE
  202839. extern void juce_initialiseThreadEvents();
  202840. void Logger::outputDebugString (const String& text)
  202841. {
  202842. OutputDebugString (text + "\n");
  202843. }
  202844. static int64 hiResTicksPerSecond;
  202845. static double hiResTicksScaleFactor;
  202846. #if JUCE_USE_INTRINSICS
  202847. // CPU info functions using intrinsics...
  202848. #pragma intrinsic (__cpuid)
  202849. #pragma intrinsic (__rdtsc)
  202850. const String SystemStats::getCpuVendor()
  202851. {
  202852. int info [4];
  202853. __cpuid (info, 0);
  202854. char v [12];
  202855. memcpy (v, info + 1, 4);
  202856. memcpy (v + 4, info + 3, 4);
  202857. memcpy (v + 8, info + 2, 4);
  202858. return String (v, 12);
  202859. }
  202860. #else
  202861. // CPU info functions using old fashioned inline asm...
  202862. static void juce_getCpuVendor (char* const v)
  202863. {
  202864. int vendor[4];
  202865. zeromem (vendor, 16);
  202866. #ifdef JUCE_64BIT
  202867. #else
  202868. #ifndef __MINGW32__
  202869. __try
  202870. #endif
  202871. {
  202872. #if JUCE_GCC
  202873. unsigned int dummy = 0;
  202874. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202875. #else
  202876. __asm
  202877. {
  202878. mov eax, 0
  202879. cpuid
  202880. mov [vendor], ebx
  202881. mov [vendor + 4], edx
  202882. mov [vendor + 8], ecx
  202883. }
  202884. #endif
  202885. }
  202886. #ifndef __MINGW32__
  202887. __except (EXCEPTION_EXECUTE_HANDLER)
  202888. {
  202889. *v = 0;
  202890. }
  202891. #endif
  202892. #endif
  202893. memcpy (v, vendor, 16);
  202894. }
  202895. const String SystemStats::getCpuVendor()
  202896. {
  202897. char v [16];
  202898. juce_getCpuVendor (v);
  202899. return String (v, 16);
  202900. }
  202901. #endif
  202902. void SystemStats::initialiseStats()
  202903. {
  202904. juce_initialiseThreadEvents();
  202905. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202906. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202907. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202908. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202909. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202910. #else
  202911. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202912. #endif
  202913. {
  202914. SYSTEM_INFO systemInfo;
  202915. GetSystemInfo (&systemInfo);
  202916. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  202917. }
  202918. LARGE_INTEGER f;
  202919. QueryPerformanceFrequency (&f);
  202920. hiResTicksPerSecond = f.QuadPart;
  202921. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202922. String s (SystemStats::getJUCEVersion());
  202923. const MMRESULT res = timeBeginPeriod (1);
  202924. (void) res;
  202925. jassert (res == TIMERR_NOERROR);
  202926. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202927. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202928. #endif
  202929. }
  202930. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202931. {
  202932. OSVERSIONINFO info;
  202933. info.dwOSVersionInfoSize = sizeof (info);
  202934. GetVersionEx (&info);
  202935. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202936. {
  202937. switch (info.dwMajorVersion)
  202938. {
  202939. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202940. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202941. default: jassertfalse; break; // !! not a supported OS!
  202942. }
  202943. }
  202944. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202945. {
  202946. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202947. return Win98;
  202948. }
  202949. return UnknownOS;
  202950. }
  202951. const String SystemStats::getOperatingSystemName()
  202952. {
  202953. const char* name = "Unknown OS";
  202954. switch (getOperatingSystemType())
  202955. {
  202956. case Windows7: name = "Windows 7"; break;
  202957. case WinVista: name = "Windows Vista"; break;
  202958. case WinXP: name = "Windows XP"; break;
  202959. case Win2000: name = "Windows 2000"; break;
  202960. case Win98: name = "Windows 98"; break;
  202961. default: jassertfalse; break; // !! new type of OS?
  202962. }
  202963. return name;
  202964. }
  202965. bool SystemStats::isOperatingSystem64Bit()
  202966. {
  202967. #ifdef _WIN64
  202968. return true;
  202969. #else
  202970. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202971. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202972. BOOL isWow64 = FALSE;
  202973. return (fnIsWow64Process != 0)
  202974. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202975. && (isWow64 != FALSE);
  202976. #endif
  202977. }
  202978. int SystemStats::getMemorySizeInMegabytes()
  202979. {
  202980. MEMORYSTATUSEX mem;
  202981. mem.dwLength = sizeof (mem);
  202982. GlobalMemoryStatusEx (&mem);
  202983. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202984. }
  202985. uint32 juce_millisecondsSinceStartup() throw()
  202986. {
  202987. return (uint32) GetTickCount();
  202988. }
  202989. int64 Time::getHighResolutionTicks() throw()
  202990. {
  202991. LARGE_INTEGER ticks;
  202992. QueryPerformanceCounter (&ticks);
  202993. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202994. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202995. // fix for a very obscure PCI hardware bug that can make the counter
  202996. // sometimes jump forwards by a few seconds..
  202997. static int64 hiResTicksOffset = 0;
  202998. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202999. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203000. hiResTicksOffset = newOffset;
  203001. return ticks.QuadPart + hiResTicksOffset;
  203002. }
  203003. double Time::getMillisecondCounterHiRes() throw()
  203004. {
  203005. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203006. }
  203007. int64 Time::getHighResolutionTicksPerSecond() throw()
  203008. {
  203009. return hiResTicksPerSecond;
  203010. }
  203011. static int64 juce_getClockCycleCounter() throw()
  203012. {
  203013. #if JUCE_USE_INTRINSICS
  203014. // MS intrinsics version...
  203015. return __rdtsc();
  203016. #elif JUCE_GCC
  203017. // GNU inline asm version...
  203018. unsigned int hi = 0, lo = 0;
  203019. __asm__ __volatile__ (
  203020. "xor %%eax, %%eax \n\
  203021. xor %%edx, %%edx \n\
  203022. rdtsc \n\
  203023. movl %%eax, %[lo] \n\
  203024. movl %%edx, %[hi]"
  203025. :
  203026. : [hi] "m" (hi),
  203027. [lo] "m" (lo)
  203028. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203029. return (int64) ((((uint64) hi) << 32) | lo);
  203030. #else
  203031. // MSVC inline asm version...
  203032. unsigned int hi = 0, lo = 0;
  203033. __asm
  203034. {
  203035. xor eax, eax
  203036. xor edx, edx
  203037. rdtsc
  203038. mov lo, eax
  203039. mov hi, edx
  203040. }
  203041. return (int64) ((((uint64) hi) << 32) | lo);
  203042. #endif
  203043. }
  203044. int SystemStats::getCpuSpeedInMegaherz()
  203045. {
  203046. const int64 cycles = juce_getClockCycleCounter();
  203047. const uint32 millis = Time::getMillisecondCounter();
  203048. int lastResult = 0;
  203049. for (;;)
  203050. {
  203051. int n = 1000000;
  203052. while (--n > 0) {}
  203053. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203054. const int64 cyclesNow = juce_getClockCycleCounter();
  203055. if (millisElapsed > 80)
  203056. {
  203057. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203058. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203059. return newResult;
  203060. lastResult = newResult;
  203061. }
  203062. }
  203063. }
  203064. bool Time::setSystemTimeToThisTime() const
  203065. {
  203066. SYSTEMTIME st;
  203067. st.wDayOfWeek = 0;
  203068. st.wYear = (WORD) getYear();
  203069. st.wMonth = (WORD) (getMonth() + 1);
  203070. st.wDay = (WORD) getDayOfMonth();
  203071. st.wHour = (WORD) getHours();
  203072. st.wMinute = (WORD) getMinutes();
  203073. st.wSecond = (WORD) getSeconds();
  203074. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203075. // do this twice because of daylight saving conversion problems - the
  203076. // first one sets it up, the second one kicks it in.
  203077. return SetLocalTime (&st) != 0
  203078. && SetLocalTime (&st) != 0;
  203079. }
  203080. int SystemStats::getPageSize()
  203081. {
  203082. SYSTEM_INFO systemInfo;
  203083. GetSystemInfo (&systemInfo);
  203084. return systemInfo.dwPageSize;
  203085. }
  203086. const String SystemStats::getLogonName()
  203087. {
  203088. TCHAR text [256];
  203089. DWORD len = numElementsInArray (text) - 2;
  203090. zerostruct (text);
  203091. GetUserName (text, &len);
  203092. return String (text, len);
  203093. }
  203094. const String SystemStats::getFullUserName()
  203095. {
  203096. return getLogonName();
  203097. }
  203098. #endif
  203099. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203100. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203101. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203102. // compiled on its own).
  203103. #if JUCE_INCLUDED_FILE
  203104. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203105. extern HWND juce_messageWindowHandle;
  203106. #endif
  203107. #if ! JUCE_USE_INTRINSICS
  203108. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203109. // older ones we have to actually call the ops as win32 functions..
  203110. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203111. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203112. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203113. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203114. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203115. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203116. {
  203117. jassertfalse; // This operation isn't available in old MS compiler versions!
  203118. __int64 oldValue = *value;
  203119. if (oldValue == valueToCompare)
  203120. *value = newValue;
  203121. return oldValue;
  203122. }
  203123. #endif
  203124. CriticalSection::CriticalSection() throw()
  203125. {
  203126. // (just to check the MS haven't changed this structure and broken things...)
  203127. #if _MSC_VER >= 1400
  203128. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203129. #else
  203130. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203131. #endif
  203132. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203133. }
  203134. CriticalSection::~CriticalSection() throw()
  203135. {
  203136. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203137. }
  203138. void CriticalSection::enter() const throw()
  203139. {
  203140. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203141. }
  203142. bool CriticalSection::tryEnter() const throw()
  203143. {
  203144. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203145. }
  203146. void CriticalSection::exit() const throw()
  203147. {
  203148. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203149. }
  203150. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203151. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203152. {
  203153. }
  203154. WaitableEvent::~WaitableEvent() throw()
  203155. {
  203156. CloseHandle (internal);
  203157. }
  203158. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203159. {
  203160. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203161. }
  203162. void WaitableEvent::signal() const throw()
  203163. {
  203164. SetEvent (internal);
  203165. }
  203166. void WaitableEvent::reset() const throw()
  203167. {
  203168. ResetEvent (internal);
  203169. }
  203170. void JUCE_API juce_threadEntryPoint (void*);
  203171. static unsigned int __stdcall threadEntryProc (void* userData)
  203172. {
  203173. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203174. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203175. GetCurrentThreadId(), TRUE);
  203176. #endif
  203177. juce_threadEntryPoint (userData);
  203178. _endthreadex (0);
  203179. return 0;
  203180. }
  203181. void juce_CloseThreadHandle (void* handle)
  203182. {
  203183. CloseHandle ((HANDLE) handle);
  203184. }
  203185. void* juce_createThread (void* userData)
  203186. {
  203187. unsigned int threadId;
  203188. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203189. }
  203190. void juce_killThread (void* handle)
  203191. {
  203192. if (handle != 0)
  203193. {
  203194. #if JUCE_DEBUG
  203195. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203196. #endif
  203197. TerminateThread (handle, 0);
  203198. }
  203199. }
  203200. void juce_setCurrentThreadName (const String& name)
  203201. {
  203202. #if JUCE_DEBUG && JUCE_MSVC
  203203. struct
  203204. {
  203205. DWORD dwType;
  203206. LPCSTR szName;
  203207. DWORD dwThreadID;
  203208. DWORD dwFlags;
  203209. } info;
  203210. info.dwType = 0x1000;
  203211. info.szName = name.toCString();
  203212. info.dwThreadID = GetCurrentThreadId();
  203213. info.dwFlags = 0;
  203214. __try
  203215. {
  203216. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203217. }
  203218. __except (EXCEPTION_CONTINUE_EXECUTION)
  203219. {}
  203220. #else
  203221. (void) name;
  203222. #endif
  203223. }
  203224. Thread::ThreadID Thread::getCurrentThreadId()
  203225. {
  203226. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203227. }
  203228. // priority 1 to 10 where 5=normal, 1=low
  203229. bool juce_setThreadPriority (void* threadHandle, int priority)
  203230. {
  203231. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203232. if (priority < 1)
  203233. pri = THREAD_PRIORITY_IDLE;
  203234. else if (priority < 2)
  203235. pri = THREAD_PRIORITY_LOWEST;
  203236. else if (priority < 5)
  203237. pri = THREAD_PRIORITY_BELOW_NORMAL;
  203238. else if (priority < 7)
  203239. pri = THREAD_PRIORITY_NORMAL;
  203240. else if (priority < 9)
  203241. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203242. else if (priority < 10)
  203243. pri = THREAD_PRIORITY_HIGHEST;
  203244. if (threadHandle == 0)
  203245. threadHandle = GetCurrentThread();
  203246. return SetThreadPriority (threadHandle, pri) != FALSE;
  203247. }
  203248. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203249. {
  203250. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203251. }
  203252. static HANDLE sleepEvent = 0;
  203253. void juce_initialiseThreadEvents()
  203254. {
  203255. if (sleepEvent == 0)
  203256. #if JUCE_DEBUG
  203257. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203258. #else
  203259. sleepEvent = CreateEvent (0, 0, 0, 0);
  203260. #endif
  203261. }
  203262. void Thread::yield()
  203263. {
  203264. Sleep (0);
  203265. }
  203266. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203267. {
  203268. if (millisecs >= 10)
  203269. {
  203270. Sleep (millisecs);
  203271. }
  203272. else
  203273. {
  203274. jassert (sleepEvent != 0);
  203275. // unlike Sleep() this is guaranteed to return to the current thread after
  203276. // the time expires, so we'll use this for short waits, which are more likely
  203277. // to need to be accurate
  203278. WaitForSingleObject (sleepEvent, millisecs);
  203279. }
  203280. }
  203281. static int lastProcessPriority = -1;
  203282. // called by WindowDriver because Windows does wierd things to process priority
  203283. // when you swap apps, and this forces an update when the app is brought to the front.
  203284. void juce_repeatLastProcessPriority()
  203285. {
  203286. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203287. {
  203288. DWORD p;
  203289. switch (lastProcessPriority)
  203290. {
  203291. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203292. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203293. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203294. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203295. default: jassertfalse; return; // bad priority value
  203296. }
  203297. SetPriorityClass (GetCurrentProcess(), p);
  203298. }
  203299. }
  203300. void Process::setPriority (ProcessPriority prior)
  203301. {
  203302. if (lastProcessPriority != (int) prior)
  203303. {
  203304. lastProcessPriority = (int) prior;
  203305. juce_repeatLastProcessPriority();
  203306. }
  203307. }
  203308. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203309. {
  203310. return IsDebuggerPresent() != FALSE;
  203311. }
  203312. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203313. {
  203314. return juce_isRunningUnderDebugger();
  203315. }
  203316. void Process::raisePrivilege()
  203317. {
  203318. jassertfalse; // xxx not implemented
  203319. }
  203320. void Process::lowerPrivilege()
  203321. {
  203322. jassertfalse; // xxx not implemented
  203323. }
  203324. void Process::terminate()
  203325. {
  203326. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203327. _CrtDumpMemoryLeaks();
  203328. #endif
  203329. // bullet in the head in case there's a problem shutting down..
  203330. ExitProcess (0);
  203331. }
  203332. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203333. {
  203334. void* result = 0;
  203335. JUCE_TRY
  203336. {
  203337. result = LoadLibrary (name);
  203338. }
  203339. JUCE_CATCH_ALL
  203340. return result;
  203341. }
  203342. void PlatformUtilities::freeDynamicLibrary (void* h)
  203343. {
  203344. JUCE_TRY
  203345. {
  203346. if (h != 0)
  203347. FreeLibrary ((HMODULE) h);
  203348. }
  203349. JUCE_CATCH_ALL
  203350. }
  203351. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203352. {
  203353. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203354. }
  203355. class InterProcessLock::Pimpl
  203356. {
  203357. public:
  203358. Pimpl (const String& name, const int timeOutMillisecs)
  203359. : handle (0), refCount (1)
  203360. {
  203361. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203362. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203363. {
  203364. if (timeOutMillisecs == 0)
  203365. {
  203366. close();
  203367. return;
  203368. }
  203369. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203370. {
  203371. case WAIT_OBJECT_0:
  203372. case WAIT_ABANDONED:
  203373. break;
  203374. case WAIT_TIMEOUT:
  203375. default:
  203376. close();
  203377. break;
  203378. }
  203379. }
  203380. }
  203381. ~Pimpl()
  203382. {
  203383. close();
  203384. }
  203385. void close()
  203386. {
  203387. if (handle != 0)
  203388. {
  203389. ReleaseMutex (handle);
  203390. CloseHandle (handle);
  203391. handle = 0;
  203392. }
  203393. }
  203394. HANDLE handle;
  203395. int refCount;
  203396. };
  203397. InterProcessLock::InterProcessLock (const String& name_)
  203398. : name (name_)
  203399. {
  203400. }
  203401. InterProcessLock::~InterProcessLock()
  203402. {
  203403. }
  203404. bool InterProcessLock::enter (const int timeOutMillisecs)
  203405. {
  203406. const ScopedLock sl (lock);
  203407. if (pimpl == 0)
  203408. {
  203409. pimpl = new Pimpl (name, timeOutMillisecs);
  203410. if (pimpl->handle == 0)
  203411. pimpl = 0;
  203412. }
  203413. else
  203414. {
  203415. pimpl->refCount++;
  203416. }
  203417. return pimpl != 0;
  203418. }
  203419. void InterProcessLock::exit()
  203420. {
  203421. const ScopedLock sl (lock);
  203422. // Trying to release the lock too many times!
  203423. jassert (pimpl != 0);
  203424. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203425. pimpl = 0;
  203426. }
  203427. #endif
  203428. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203429. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203430. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203431. // compiled on its own).
  203432. #if JUCE_INCLUDED_FILE
  203433. #ifndef CSIDL_MYMUSIC
  203434. #define CSIDL_MYMUSIC 0x000d
  203435. #endif
  203436. #ifndef CSIDL_MYVIDEO
  203437. #define CSIDL_MYVIDEO 0x000e
  203438. #endif
  203439. #ifndef INVALID_FILE_ATTRIBUTES
  203440. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203441. #endif
  203442. const juce_wchar File::separator = '\\';
  203443. const String File::separatorString ("\\");
  203444. bool File::exists() const
  203445. {
  203446. return fullPath.isNotEmpty()
  203447. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203448. }
  203449. bool File::existsAsFile() const
  203450. {
  203451. return fullPath.isNotEmpty()
  203452. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203453. }
  203454. bool File::isDirectory() const
  203455. {
  203456. const DWORD attr = GetFileAttributes (fullPath);
  203457. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203458. }
  203459. bool File::hasWriteAccess() const
  203460. {
  203461. if (exists())
  203462. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203463. // on windows, it seems that even read-only directories can still be written into,
  203464. // so checking the parent directory's permissions would return the wrong result..
  203465. return true;
  203466. }
  203467. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203468. {
  203469. DWORD attr = GetFileAttributes (fullPath);
  203470. if (attr == INVALID_FILE_ATTRIBUTES)
  203471. return false;
  203472. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203473. return true;
  203474. if (shouldBeReadOnly)
  203475. attr |= FILE_ATTRIBUTE_READONLY;
  203476. else
  203477. attr &= ~FILE_ATTRIBUTE_READONLY;
  203478. return SetFileAttributes (fullPath, attr) != FALSE;
  203479. }
  203480. bool File::isHidden() const
  203481. {
  203482. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203483. }
  203484. bool File::deleteFile() const
  203485. {
  203486. if (! exists())
  203487. return true;
  203488. else if (isDirectory())
  203489. return RemoveDirectory (fullPath) != 0;
  203490. else
  203491. return DeleteFile (fullPath) != 0;
  203492. }
  203493. bool File::moveToTrash() const
  203494. {
  203495. if (! exists())
  203496. return true;
  203497. SHFILEOPSTRUCT fos;
  203498. zerostruct (fos);
  203499. // The string we pass in must be double null terminated..
  203500. String doubleNullTermPath (getFullPathName() + " ");
  203501. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203502. p [getFullPathName().length()] = 0;
  203503. fos.wFunc = FO_DELETE;
  203504. fos.pFrom = p;
  203505. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203506. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203507. return SHFileOperation (&fos) == 0;
  203508. }
  203509. bool File::copyInternal (const File& dest) const
  203510. {
  203511. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203512. }
  203513. bool File::moveInternal (const File& dest) const
  203514. {
  203515. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203516. }
  203517. void File::createDirectoryInternal (const String& fileName) const
  203518. {
  203519. CreateDirectory (fileName, 0);
  203520. }
  203521. // return 0 if not possible
  203522. void* juce_fileOpen (const File& file, bool forWriting)
  203523. {
  203524. HANDLE h;
  203525. if (forWriting)
  203526. {
  203527. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203528. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203529. if (h != INVALID_HANDLE_VALUE)
  203530. SetFilePointer (h, 0, 0, FILE_END);
  203531. else
  203532. h = 0;
  203533. }
  203534. else
  203535. {
  203536. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203537. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203538. if (h == INVALID_HANDLE_VALUE)
  203539. h = 0;
  203540. }
  203541. return h;
  203542. }
  203543. void juce_fileClose (void* handle)
  203544. {
  203545. CloseHandle (handle);
  203546. }
  203547. int juce_fileRead (void* handle, void* buffer, int size)
  203548. {
  203549. DWORD num = 0;
  203550. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203551. return (int) num;
  203552. }
  203553. int juce_fileWrite (void* handle, const void* buffer, int size)
  203554. {
  203555. DWORD num;
  203556. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203557. return (int) num;
  203558. }
  203559. int64 juce_fileSetPosition (void* handle, int64 pos)
  203560. {
  203561. LARGE_INTEGER li;
  203562. li.QuadPart = pos;
  203563. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203564. return li.QuadPart;
  203565. }
  203566. int64 FileOutputStream::getPositionInternal() const
  203567. {
  203568. if (fileHandle == 0)
  203569. return -1;
  203570. LARGE_INTEGER li;
  203571. li.QuadPart = 0;
  203572. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203573. return jmax ((int64) 0, li.QuadPart);
  203574. }
  203575. void FileOutputStream::flushInternal()
  203576. {
  203577. if (fileHandle != 0)
  203578. FlushFileBuffers ((HANDLE) fileHandle);
  203579. }
  203580. int64 File::getSize() const
  203581. {
  203582. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203583. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203584. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203585. return 0;
  203586. }
  203587. static int64 fileTimeToTime (const FILETIME* const ft)
  203588. {
  203589. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203590. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203591. }
  203592. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203593. {
  203594. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203595. }
  203596. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203597. {
  203598. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203599. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203600. {
  203601. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203602. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203603. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203604. }
  203605. else
  203606. {
  203607. creationTime = accessTime = modificationTime = 0;
  203608. }
  203609. }
  203610. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203611. {
  203612. void* const h = juce_fileOpen (fullPath, true);
  203613. bool ok = false;
  203614. if (h != 0)
  203615. {
  203616. FILETIME m, a, c;
  203617. timeToFileTime (modificationTime, &m);
  203618. timeToFileTime (accessTime, &a);
  203619. timeToFileTime (creationTime, &c);
  203620. ok = SetFileTime ((HANDLE) h,
  203621. creationTime > 0 ? &c : 0,
  203622. accessTime > 0 ? &a : 0,
  203623. modificationTime > 0 ? &m : 0) != 0;
  203624. juce_fileClose (h);
  203625. }
  203626. return ok;
  203627. }
  203628. void File::findFileSystemRoots (Array<File>& destArray)
  203629. {
  203630. TCHAR buffer [2048];
  203631. buffer[0] = 0;
  203632. buffer[1] = 0;
  203633. GetLogicalDriveStrings (2048, buffer);
  203634. const TCHAR* n = buffer;
  203635. StringArray roots;
  203636. while (*n != 0)
  203637. {
  203638. roots.add (String (n));
  203639. while (*n++ != 0)
  203640. {}
  203641. }
  203642. roots.sort (true);
  203643. for (int i = 0; i < roots.size(); ++i)
  203644. destArray.add (roots [i]);
  203645. }
  203646. static const String getDriveFromPath (const String& path)
  203647. {
  203648. if (path.isNotEmpty() && path[1] == ':')
  203649. return path.substring (0, 2) + '\\';
  203650. return path;
  203651. }
  203652. const String File::getVolumeLabel() const
  203653. {
  203654. TCHAR dest[64];
  203655. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203656. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203657. dest[0] = 0;
  203658. return dest;
  203659. }
  203660. int File::getVolumeSerialNumber() const
  203661. {
  203662. TCHAR dest[64];
  203663. DWORD serialNum;
  203664. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203665. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203666. return 0;
  203667. return (int) serialNum;
  203668. }
  203669. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203670. {
  203671. ULARGE_INTEGER spc, tot, totFree;
  203672. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203673. return total ? (int64) tot.QuadPart
  203674. : (int64) spc.QuadPart;
  203675. return 0;
  203676. }
  203677. int64 File::getBytesFreeOnVolume() const
  203678. {
  203679. return getDiskSpaceInfo (getFullPathName(), false);
  203680. }
  203681. int64 File::getVolumeTotalSize() const
  203682. {
  203683. return getDiskSpaceInfo (getFullPathName(), true);
  203684. }
  203685. static unsigned int getWindowsDriveType (const String& path)
  203686. {
  203687. return GetDriveType (getDriveFromPath (path));
  203688. }
  203689. bool File::isOnCDRomDrive() const
  203690. {
  203691. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203692. }
  203693. bool File::isOnHardDisk() const
  203694. {
  203695. if (fullPath.isEmpty())
  203696. return false;
  203697. const unsigned int n = getWindowsDriveType (getFullPathName());
  203698. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203699. return n != DRIVE_REMOVABLE;
  203700. else
  203701. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203702. }
  203703. bool File::isOnRemovableDrive() const
  203704. {
  203705. if (fullPath.isEmpty())
  203706. return false;
  203707. const unsigned int n = getWindowsDriveType (getFullPathName());
  203708. return n == DRIVE_CDROM
  203709. || n == DRIVE_REMOTE
  203710. || n == DRIVE_REMOVABLE
  203711. || n == DRIVE_RAMDISK;
  203712. }
  203713. static const File juce_getSpecialFolderPath (int type)
  203714. {
  203715. WCHAR path [MAX_PATH + 256];
  203716. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203717. return File (String (path));
  203718. return File::nonexistent;
  203719. }
  203720. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203721. {
  203722. int csidlType = 0;
  203723. switch (type)
  203724. {
  203725. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203726. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203727. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203728. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203729. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203730. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203731. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203732. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203733. case tempDirectory:
  203734. {
  203735. WCHAR dest [2048];
  203736. dest[0] = 0;
  203737. GetTempPath (numElementsInArray (dest), dest);
  203738. return File (String (dest));
  203739. }
  203740. case invokedExecutableFile:
  203741. case currentExecutableFile:
  203742. case currentApplicationFile:
  203743. {
  203744. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203745. WCHAR dest [MAX_PATH + 256];
  203746. dest[0] = 0;
  203747. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203748. return File (String (dest));
  203749. }
  203750. case hostApplicationPath:
  203751. {
  203752. WCHAR dest [MAX_PATH + 256];
  203753. dest[0] = 0;
  203754. GetModuleFileName (0, dest, numElementsInArray (dest));
  203755. return File (String (dest));
  203756. }
  203757. default:
  203758. jassertfalse; // unknown type?
  203759. return File::nonexistent;
  203760. }
  203761. return juce_getSpecialFolderPath (csidlType);
  203762. }
  203763. const File File::getCurrentWorkingDirectory()
  203764. {
  203765. WCHAR dest [MAX_PATH + 256];
  203766. dest[0] = 0;
  203767. GetCurrentDirectory (numElementsInArray (dest), dest);
  203768. return File (String (dest));
  203769. }
  203770. bool File::setAsCurrentWorkingDirectory() const
  203771. {
  203772. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203773. }
  203774. const String File::getVersion() const
  203775. {
  203776. String result;
  203777. DWORD handle = 0;
  203778. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203779. HeapBlock<char> buffer;
  203780. buffer.calloc (bufferSize);
  203781. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203782. {
  203783. VS_FIXEDFILEINFO* vffi;
  203784. UINT len = 0;
  203785. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203786. {
  203787. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203788. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203789. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203790. << (int) LOWORD (vffi->dwFileVersionLS);
  203791. }
  203792. }
  203793. return result;
  203794. }
  203795. const File File::getLinkedTarget() const
  203796. {
  203797. File result (*this);
  203798. String p (getFullPathName());
  203799. if (! exists())
  203800. p += ".lnk";
  203801. else if (getFileExtension() != ".lnk")
  203802. return result;
  203803. ComSmartPtr <IShellLink> shellLink;
  203804. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203805. {
  203806. ComSmartPtr <IPersistFile> persistFile;
  203807. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203808. {
  203809. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203810. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203811. {
  203812. WIN32_FIND_DATA winFindData;
  203813. WCHAR resolvedPath [MAX_PATH];
  203814. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203815. result = File (resolvedPath);
  203816. }
  203817. }
  203818. }
  203819. return result;
  203820. }
  203821. class DirectoryIterator::NativeIterator::Pimpl
  203822. {
  203823. public:
  203824. Pimpl (const File& directory, const String& wildCard)
  203825. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203826. handle (INVALID_HANDLE_VALUE)
  203827. {
  203828. }
  203829. ~Pimpl()
  203830. {
  203831. if (handle != INVALID_HANDLE_VALUE)
  203832. FindClose (handle);
  203833. }
  203834. bool next (String& filenameFound,
  203835. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203836. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203837. {
  203838. WIN32_FIND_DATA findData;
  203839. if (handle == INVALID_HANDLE_VALUE)
  203840. {
  203841. handle = FindFirstFile (directoryWithWildCard, &findData);
  203842. if (handle == INVALID_HANDLE_VALUE)
  203843. return false;
  203844. }
  203845. else
  203846. {
  203847. if (FindNextFile (handle, &findData) == 0)
  203848. return false;
  203849. }
  203850. filenameFound = findData.cFileName;
  203851. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203852. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203853. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203854. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203855. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203856. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203857. return true;
  203858. }
  203859. juce_UseDebuggingNewOperator
  203860. private:
  203861. const String directoryWithWildCard;
  203862. HANDLE handle;
  203863. Pimpl (const Pimpl&);
  203864. Pimpl& operator= (const Pimpl&);
  203865. };
  203866. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203867. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203868. {
  203869. }
  203870. DirectoryIterator::NativeIterator::~NativeIterator()
  203871. {
  203872. }
  203873. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203874. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203875. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203876. {
  203877. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203878. }
  203879. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203880. {
  203881. HINSTANCE hInstance = 0;
  203882. JUCE_TRY
  203883. {
  203884. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203885. }
  203886. JUCE_CATCH_ALL
  203887. return hInstance > (HINSTANCE) 32;
  203888. }
  203889. void File::revealToUser() const
  203890. {
  203891. if (isDirectory())
  203892. startAsProcess();
  203893. else if (getParentDirectory().exists())
  203894. getParentDirectory().startAsProcess();
  203895. }
  203896. class NamedPipeInternal
  203897. {
  203898. public:
  203899. NamedPipeInternal (const String& file, const bool isPipe_)
  203900. : pipeH (0),
  203901. cancelEvent (0),
  203902. connected (false),
  203903. isPipe (isPipe_)
  203904. {
  203905. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203906. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203907. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203908. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203909. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203910. }
  203911. ~NamedPipeInternal()
  203912. {
  203913. disconnectPipe();
  203914. if (pipeH != 0)
  203915. CloseHandle (pipeH);
  203916. CloseHandle (cancelEvent);
  203917. }
  203918. bool connect (const int timeOutMs)
  203919. {
  203920. if (! isPipe)
  203921. return true;
  203922. if (! connected)
  203923. {
  203924. OVERLAPPED over;
  203925. zerostruct (over);
  203926. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203927. if (ConnectNamedPipe (pipeH, &over))
  203928. {
  203929. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203930. }
  203931. else
  203932. {
  203933. const int err = GetLastError();
  203934. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203935. {
  203936. HANDLE handles[] = { over.hEvent, cancelEvent };
  203937. if (WaitForMultipleObjects (2, handles, FALSE,
  203938. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203939. connected = true;
  203940. }
  203941. else if (err == ERROR_PIPE_CONNECTED)
  203942. {
  203943. connected = true;
  203944. }
  203945. }
  203946. CloseHandle (over.hEvent);
  203947. }
  203948. return connected;
  203949. }
  203950. void disconnectPipe()
  203951. {
  203952. if (connected)
  203953. {
  203954. DisconnectNamedPipe (pipeH);
  203955. connected = false;
  203956. }
  203957. }
  203958. HANDLE pipeH;
  203959. HANDLE cancelEvent;
  203960. bool connected, isPipe;
  203961. };
  203962. void NamedPipe::close()
  203963. {
  203964. cancelPendingReads();
  203965. const ScopedLock sl (lock);
  203966. delete static_cast<NamedPipeInternal*> (internal);
  203967. internal = 0;
  203968. }
  203969. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203970. {
  203971. close();
  203972. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203973. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203974. {
  203975. internal = intern.release();
  203976. return true;
  203977. }
  203978. return false;
  203979. }
  203980. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203981. {
  203982. const ScopedLock sl (lock);
  203983. int bytesRead = -1;
  203984. bool waitAgain = true;
  203985. while (waitAgain && internal != 0)
  203986. {
  203987. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203988. waitAgain = false;
  203989. if (! intern->connect (timeOutMilliseconds))
  203990. break;
  203991. if (maxBytesToRead <= 0)
  203992. return 0;
  203993. OVERLAPPED over;
  203994. zerostruct (over);
  203995. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203996. unsigned long numRead;
  203997. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203998. {
  203999. bytesRead = (int) numRead;
  204000. }
  204001. else if (GetLastError() == ERROR_IO_PENDING)
  204002. {
  204003. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204004. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204005. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204006. : INFINITE);
  204007. if (waitResult != WAIT_OBJECT_0)
  204008. {
  204009. // if the operation timed out, let's cancel it...
  204010. CancelIo (intern->pipeH);
  204011. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204012. }
  204013. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204014. {
  204015. bytesRead = (int) numRead;
  204016. }
  204017. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204018. {
  204019. intern->disconnectPipe();
  204020. waitAgain = true;
  204021. }
  204022. }
  204023. else
  204024. {
  204025. waitAgain = internal != 0;
  204026. Sleep (5);
  204027. }
  204028. CloseHandle (over.hEvent);
  204029. }
  204030. return bytesRead;
  204031. }
  204032. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204033. {
  204034. int bytesWritten = -1;
  204035. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204036. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204037. {
  204038. if (numBytesToWrite <= 0)
  204039. return 0;
  204040. OVERLAPPED over;
  204041. zerostruct (over);
  204042. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204043. unsigned long numWritten;
  204044. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204045. {
  204046. bytesWritten = (int) numWritten;
  204047. }
  204048. else if (GetLastError() == ERROR_IO_PENDING)
  204049. {
  204050. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204051. DWORD waitResult;
  204052. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204053. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204054. : INFINITE);
  204055. if (waitResult != WAIT_OBJECT_0)
  204056. {
  204057. CancelIo (intern->pipeH);
  204058. WaitForSingleObject (over.hEvent, INFINITE);
  204059. }
  204060. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204061. {
  204062. bytesWritten = (int) numWritten;
  204063. }
  204064. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204065. {
  204066. intern->disconnectPipe();
  204067. }
  204068. }
  204069. CloseHandle (over.hEvent);
  204070. }
  204071. return bytesWritten;
  204072. }
  204073. void NamedPipe::cancelPendingReads()
  204074. {
  204075. if (internal != 0)
  204076. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204077. }
  204078. #endif
  204079. /*** End of inlined file: juce_win32_Files.cpp ***/
  204080. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204081. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204082. // compiled on its own).
  204083. #if JUCE_INCLUDED_FILE
  204084. #ifndef INTERNET_FLAG_NEED_FILE
  204085. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204086. #endif
  204087. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204088. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204089. #endif
  204090. struct ConnectionAndRequestStruct
  204091. {
  204092. HINTERNET connection, request;
  204093. };
  204094. static HINTERNET sessionHandle = 0;
  204095. #ifndef WORKAROUND_TIMEOUT_BUG
  204096. //#define WORKAROUND_TIMEOUT_BUG 1
  204097. #endif
  204098. #if WORKAROUND_TIMEOUT_BUG
  204099. // Required because of a Microsoft bug in setting a timeout
  204100. class InternetConnectThread : public Thread
  204101. {
  204102. public:
  204103. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204104. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204105. {
  204106. startThread();
  204107. }
  204108. ~InternetConnectThread()
  204109. {
  204110. stopThread (60000);
  204111. }
  204112. void run()
  204113. {
  204114. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204115. uc.nPort, _T(""), _T(""),
  204116. isFtp ? INTERNET_SERVICE_FTP
  204117. : INTERNET_SERVICE_HTTP,
  204118. 0, 0);
  204119. notify();
  204120. }
  204121. juce_UseDebuggingNewOperator
  204122. private:
  204123. URL_COMPONENTS& uc;
  204124. HINTERNET& connection;
  204125. const bool isFtp;
  204126. InternetConnectThread (const InternetConnectThread&);
  204127. InternetConnectThread& operator= (const InternetConnectThread&);
  204128. };
  204129. #endif
  204130. void* juce_openInternetFile (const String& url,
  204131. const String& headers,
  204132. const MemoryBlock& postData,
  204133. const bool isPost,
  204134. URL::OpenStreamProgressCallback* callback,
  204135. void* callbackContext,
  204136. int timeOutMs)
  204137. {
  204138. if (sessionHandle == 0)
  204139. sessionHandle = InternetOpen (_T("juce"),
  204140. INTERNET_OPEN_TYPE_PRECONFIG,
  204141. 0, 0, 0);
  204142. if (sessionHandle != 0)
  204143. {
  204144. // break up the url..
  204145. TCHAR file[1024], server[1024];
  204146. URL_COMPONENTS uc;
  204147. zerostruct (uc);
  204148. uc.dwStructSize = sizeof (uc);
  204149. uc.dwUrlPathLength = sizeof (file);
  204150. uc.dwHostNameLength = sizeof (server);
  204151. uc.lpszUrlPath = file;
  204152. uc.lpszHostName = server;
  204153. if (InternetCrackUrl (url, 0, 0, &uc))
  204154. {
  204155. int disable = 1;
  204156. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204157. if (timeOutMs == 0)
  204158. timeOutMs = 30000;
  204159. else if (timeOutMs < 0)
  204160. timeOutMs = -1;
  204161. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204162. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204163. #if WORKAROUND_TIMEOUT_BUG
  204164. HINTERNET connection = 0;
  204165. {
  204166. InternetConnectThread connectThread (uc, connection, isFtp);
  204167. connectThread.wait (timeOutMs);
  204168. if (connection == 0)
  204169. {
  204170. InternetCloseHandle (sessionHandle);
  204171. sessionHandle = 0;
  204172. }
  204173. }
  204174. #else
  204175. HINTERNET connection = InternetConnect (sessionHandle,
  204176. uc.lpszHostName,
  204177. uc.nPort,
  204178. _T(""), _T(""),
  204179. isFtp ? INTERNET_SERVICE_FTP
  204180. : INTERNET_SERVICE_HTTP,
  204181. 0, 0);
  204182. #endif
  204183. if (connection != 0)
  204184. {
  204185. if (isFtp)
  204186. {
  204187. HINTERNET request = FtpOpenFile (connection,
  204188. uc.lpszUrlPath,
  204189. GENERIC_READ,
  204190. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204191. 0);
  204192. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204193. result->connection = connection;
  204194. result->request = request;
  204195. return result;
  204196. }
  204197. else
  204198. {
  204199. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204200. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204201. if (url.startsWithIgnoreCase ("https:"))
  204202. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204203. // IE7 seems to automatically work out when it's https)
  204204. HINTERNET request = HttpOpenRequest (connection,
  204205. isPost ? _T("POST")
  204206. : _T("GET"),
  204207. uc.lpszUrlPath,
  204208. 0, 0, mimeTypes, flags, 0);
  204209. if (request != 0)
  204210. {
  204211. INTERNET_BUFFERS buffers;
  204212. zerostruct (buffers);
  204213. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204214. buffers.lpcszHeader = (LPCTSTR) headers;
  204215. buffers.dwHeadersLength = headers.length();
  204216. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204217. ConnectionAndRequestStruct* result = 0;
  204218. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204219. {
  204220. int bytesSent = 0;
  204221. for (;;)
  204222. {
  204223. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204224. DWORD bytesDone = 0;
  204225. if (bytesToDo > 0
  204226. && ! InternetWriteFile (request,
  204227. static_cast <const char*> (postData.getData()) + bytesSent,
  204228. bytesToDo, &bytesDone))
  204229. {
  204230. break;
  204231. }
  204232. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204233. {
  204234. result = new ConnectionAndRequestStruct();
  204235. result->connection = connection;
  204236. result->request = request;
  204237. if (! HttpEndRequest (request, 0, 0, 0))
  204238. break;
  204239. return result;
  204240. }
  204241. bytesSent += bytesDone;
  204242. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204243. break;
  204244. }
  204245. }
  204246. InternetCloseHandle (request);
  204247. }
  204248. InternetCloseHandle (connection);
  204249. }
  204250. }
  204251. }
  204252. }
  204253. return 0;
  204254. }
  204255. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204256. {
  204257. DWORD bytesRead = 0;
  204258. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204259. if (crs != 0)
  204260. InternetReadFile (crs->request,
  204261. buffer, bytesToRead,
  204262. &bytesRead);
  204263. return bytesRead;
  204264. }
  204265. int juce_seekInInternetFile (void* handle, int newPosition)
  204266. {
  204267. if (handle != 0)
  204268. {
  204269. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204270. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204271. }
  204272. return -1;
  204273. }
  204274. int64 juce_getInternetFileContentLength (void* handle)
  204275. {
  204276. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204277. if (crs != 0)
  204278. {
  204279. DWORD index = 0, result = 0, size = sizeof (result);
  204280. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204281. return (int64) result;
  204282. }
  204283. return -1;
  204284. }
  204285. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204286. {
  204287. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204288. if (crs != 0)
  204289. {
  204290. DWORD bufferSizeBytes = 4096;
  204291. for (;;)
  204292. {
  204293. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204294. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204295. {
  204296. StringArray headersArray;
  204297. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204298. for (int i = 0; i < headersArray.size(); ++i)
  204299. {
  204300. const String& header = headersArray[i];
  204301. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204302. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204303. const String previousValue (headers [key]);
  204304. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204305. }
  204306. break;
  204307. }
  204308. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204309. break;
  204310. }
  204311. }
  204312. }
  204313. void juce_closeInternetFile (void* handle)
  204314. {
  204315. if (handle != 0)
  204316. {
  204317. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204318. InternetCloseHandle (crs->request);
  204319. InternetCloseHandle (crs->connection);
  204320. }
  204321. }
  204322. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204323. {
  204324. int numFound = 0;
  204325. DynamicLibraryLoader dll ("iphlpapi.dll");
  204326. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204327. if (getAdaptersInfo != 0)
  204328. {
  204329. ULONG len = sizeof (IP_ADAPTER_INFO);
  204330. MemoryBlock mb;
  204331. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204332. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204333. {
  204334. mb.setSize (len);
  204335. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204336. }
  204337. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204338. {
  204339. PIP_ADAPTER_INFO adapter = adapterInfo;
  204340. while (adapter != 0)
  204341. {
  204342. int64 mac = 0;
  204343. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204344. mac = (mac << 8) | adapter->Address[i];
  204345. if (littleEndian)
  204346. mac = (int64) ByteOrder::swap ((uint64) mac);
  204347. if (numFound < maxNum && mac != 0)
  204348. addresses [numFound++] = mac;
  204349. adapter = adapter->Next;
  204350. }
  204351. }
  204352. }
  204353. return numFound;
  204354. }
  204355. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204356. {
  204357. int numFound = 0;
  204358. DynamicLibraryLoader dll ("netapi32.dll");
  204359. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204360. if (NetbiosCall != 0)
  204361. {
  204362. NCB ncb;
  204363. zerostruct (ncb);
  204364. struct ASTAT
  204365. {
  204366. ADAPTER_STATUS adapt;
  204367. NAME_BUFFER NameBuff [30];
  204368. };
  204369. ASTAT astat;
  204370. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204371. LANA_ENUM enums;
  204372. zerostruct (enums);
  204373. ncb.ncb_command = NCBENUM;
  204374. ncb.ncb_buffer = (unsigned char*) &enums;
  204375. ncb.ncb_length = sizeof (LANA_ENUM);
  204376. NetbiosCall (&ncb);
  204377. for (int i = 0; i < enums.length; ++i)
  204378. {
  204379. zerostruct (ncb);
  204380. ncb.ncb_command = NCBRESET;
  204381. ncb.ncb_lana_num = enums.lana[i];
  204382. if (NetbiosCall (&ncb) == 0)
  204383. {
  204384. zerostruct (ncb);
  204385. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204386. ncb.ncb_command = NCBASTAT;
  204387. ncb.ncb_lana_num = enums.lana[i];
  204388. ncb.ncb_buffer = (unsigned char*) &astat;
  204389. ncb.ncb_length = sizeof (ASTAT);
  204390. if (NetbiosCall (&ncb) == 0)
  204391. {
  204392. if (astat.adapt.adapter_type == 0xfe)
  204393. {
  204394. uint64 mac = 0;
  204395. for (int i = 6; --i >= 0;)
  204396. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204397. if (numFound < maxNum && mac != 0)
  204398. addresses [numFound++] = mac;
  204399. }
  204400. }
  204401. }
  204402. }
  204403. }
  204404. return numFound;
  204405. }
  204406. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204407. {
  204408. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204409. if (numFound == 0)
  204410. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204411. return numFound;
  204412. }
  204413. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204414. const String& emailSubject,
  204415. const String& bodyText,
  204416. const StringArray& filesToAttach)
  204417. {
  204418. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204419. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204420. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204421. bool ok = false;
  204422. if (mapiSendMail != 0)
  204423. {
  204424. MapiMessage message;
  204425. zerostruct (message);
  204426. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204427. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204428. MapiRecipDesc recip;
  204429. zerostruct (recip);
  204430. recip.ulRecipClass = MAPI_TO;
  204431. String targetEmailAddress_ (targetEmailAddress);
  204432. if (targetEmailAddress_.isEmpty())
  204433. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204434. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204435. message.nRecipCount = 1;
  204436. message.lpRecips = &recip;
  204437. HeapBlock <MapiFileDesc> files;
  204438. files.calloc (filesToAttach.size());
  204439. message.nFileCount = filesToAttach.size();
  204440. message.lpFiles = files;
  204441. for (int i = 0; i < filesToAttach.size(); ++i)
  204442. {
  204443. files[i].nPosition = (ULONG) -1;
  204444. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204445. }
  204446. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204447. }
  204448. FreeLibrary (h);
  204449. return ok;
  204450. }
  204451. #endif
  204452. /*** End of inlined file: juce_win32_Network.cpp ***/
  204453. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204454. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204455. // compiled on its own).
  204456. #if JUCE_INCLUDED_FILE
  204457. static HKEY findKeyForPath (String name,
  204458. const bool createForWriting,
  204459. String& valueName)
  204460. {
  204461. HKEY rootKey = 0;
  204462. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204463. rootKey = HKEY_CURRENT_USER;
  204464. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204465. rootKey = HKEY_LOCAL_MACHINE;
  204466. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204467. rootKey = HKEY_CLASSES_ROOT;
  204468. if (rootKey != 0)
  204469. {
  204470. name = name.substring (name.indexOfChar ('\\') + 1);
  204471. const int lastSlash = name.lastIndexOfChar ('\\');
  204472. valueName = name.substring (lastSlash + 1);
  204473. name = name.substring (0, lastSlash);
  204474. HKEY key;
  204475. DWORD result;
  204476. if (createForWriting)
  204477. {
  204478. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204479. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204480. return key;
  204481. }
  204482. else
  204483. {
  204484. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204485. return key;
  204486. }
  204487. }
  204488. return 0;
  204489. }
  204490. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204491. const String& defaultValue)
  204492. {
  204493. String valueName, result (defaultValue);
  204494. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204495. if (k != 0)
  204496. {
  204497. WCHAR buffer [2048];
  204498. unsigned long bufferSize = sizeof (buffer);
  204499. DWORD type = REG_SZ;
  204500. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204501. {
  204502. if (type == REG_SZ)
  204503. result = buffer;
  204504. else if (type == REG_DWORD)
  204505. result = String ((int) *(DWORD*) buffer);
  204506. }
  204507. RegCloseKey (k);
  204508. }
  204509. return result;
  204510. }
  204511. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204512. const String& value)
  204513. {
  204514. String valueName;
  204515. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204516. if (k != 0)
  204517. {
  204518. RegSetValueEx (k, valueName, 0, REG_SZ,
  204519. (const BYTE*) (const WCHAR*) value,
  204520. sizeof (WCHAR) * (value.length() + 1));
  204521. RegCloseKey (k);
  204522. }
  204523. }
  204524. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204525. {
  204526. bool exists = false;
  204527. String valueName;
  204528. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204529. if (k != 0)
  204530. {
  204531. unsigned char buffer [2048];
  204532. unsigned long bufferSize = sizeof (buffer);
  204533. DWORD type = 0;
  204534. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204535. exists = true;
  204536. RegCloseKey (k);
  204537. }
  204538. return exists;
  204539. }
  204540. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204541. {
  204542. String valueName;
  204543. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204544. if (k != 0)
  204545. {
  204546. RegDeleteValue (k, valueName);
  204547. RegCloseKey (k);
  204548. }
  204549. }
  204550. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204551. {
  204552. String valueName;
  204553. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204554. if (k != 0)
  204555. {
  204556. RegDeleteKey (k, valueName);
  204557. RegCloseKey (k);
  204558. }
  204559. }
  204560. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204561. const String& symbolicDescription,
  204562. const String& fullDescription,
  204563. const File& targetExecutable,
  204564. int iconResourceNumber)
  204565. {
  204566. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204567. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204568. if (iconResourceNumber != 0)
  204569. setRegistryValue (key + "\\DefaultIcon\\",
  204570. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204571. setRegistryValue (key + "\\", fullDescription);
  204572. setRegistryValue (key + "\\shell\\open\\command\\",
  204573. targetExecutable.getFullPathName() + " %1");
  204574. }
  204575. bool juce_IsRunningInWine()
  204576. {
  204577. HKEY key;
  204578. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204579. {
  204580. RegCloseKey (key);
  204581. return true;
  204582. }
  204583. return false;
  204584. }
  204585. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204586. {
  204587. String s (::GetCommandLineW());
  204588. StringArray tokens;
  204589. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204590. return tokens.joinIntoString (" ", 1);
  204591. }
  204592. static void* currentModuleHandle = 0;
  204593. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204594. {
  204595. if (currentModuleHandle == 0)
  204596. currentModuleHandle = GetModuleHandle (0);
  204597. return currentModuleHandle;
  204598. }
  204599. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204600. {
  204601. currentModuleHandle = newHandle;
  204602. }
  204603. void PlatformUtilities::fpuReset()
  204604. {
  204605. #if JUCE_MSVC
  204606. _clearfp();
  204607. #endif
  204608. }
  204609. void PlatformUtilities::beep()
  204610. {
  204611. MessageBeep (MB_OK);
  204612. }
  204613. #endif
  204614. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204615. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204616. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204617. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204618. // compiled on its own).
  204619. #if JUCE_INCLUDED_FILE
  204620. static const unsigned int specialId = WM_APP + 0x4400;
  204621. static const unsigned int broadcastId = WM_APP + 0x4403;
  204622. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204623. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204624. HWND juce_messageWindowHandle = 0;
  204625. extern long improbableWindowNumber; // defined in windowing.cpp
  204626. #ifndef WM_APPCOMMAND
  204627. #define WM_APPCOMMAND 0x0319
  204628. #endif
  204629. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204630. const UINT message,
  204631. const WPARAM wParam,
  204632. const LPARAM lParam) throw()
  204633. {
  204634. JUCE_TRY
  204635. {
  204636. if (h == juce_messageWindowHandle)
  204637. {
  204638. if (message == specialCallbackId)
  204639. {
  204640. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204641. return (LRESULT) (*func) ((void*) lParam);
  204642. }
  204643. else if (message == specialId)
  204644. {
  204645. // these are trapped early in the dispatch call, but must also be checked
  204646. // here in case there are windows modal dialog boxes doing their own
  204647. // dispatch loop and not calling our version
  204648. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  204649. return 0;
  204650. }
  204651. else if (message == broadcastId)
  204652. {
  204653. const ScopedPointer <String> messageString ((String*) lParam);
  204654. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204655. return 0;
  204656. }
  204657. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204658. {
  204659. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204660. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204661. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204662. return 0;
  204663. }
  204664. }
  204665. }
  204666. JUCE_CATCH_EXCEPTION
  204667. return DefWindowProc (h, message, wParam, lParam);
  204668. }
  204669. static bool isEventBlockedByModalComps (MSG& m)
  204670. {
  204671. if (Component::getNumCurrentlyModalComponents() == 0
  204672. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204673. return false;
  204674. switch (m.message)
  204675. {
  204676. case WM_MOUSEMOVE:
  204677. case WM_NCMOUSEMOVE:
  204678. case 0x020A: /* WM_MOUSEWHEEL */
  204679. case 0x020E: /* WM_MOUSEHWHEEL */
  204680. case WM_KEYUP:
  204681. case WM_SYSKEYUP:
  204682. case WM_CHAR:
  204683. case WM_APPCOMMAND:
  204684. case WM_LBUTTONUP:
  204685. case WM_MBUTTONUP:
  204686. case WM_RBUTTONUP:
  204687. case WM_MOUSEACTIVATE:
  204688. case WM_NCMOUSEHOVER:
  204689. case WM_MOUSEHOVER:
  204690. return true;
  204691. case WM_NCLBUTTONDOWN:
  204692. case WM_NCLBUTTONDBLCLK:
  204693. case WM_NCRBUTTONDOWN:
  204694. case WM_NCRBUTTONDBLCLK:
  204695. case WM_NCMBUTTONDOWN:
  204696. case WM_NCMBUTTONDBLCLK:
  204697. case WM_LBUTTONDOWN:
  204698. case WM_LBUTTONDBLCLK:
  204699. case WM_MBUTTONDOWN:
  204700. case WM_MBUTTONDBLCLK:
  204701. case WM_RBUTTONDOWN:
  204702. case WM_RBUTTONDBLCLK:
  204703. case WM_KEYDOWN:
  204704. case WM_SYSKEYDOWN:
  204705. {
  204706. Component* const modal = Component::getCurrentlyModalComponent (0);
  204707. if (modal != 0)
  204708. modal->inputAttemptWhenModal();
  204709. return true;
  204710. }
  204711. default:
  204712. break;
  204713. }
  204714. return false;
  204715. }
  204716. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204717. {
  204718. MSG m;
  204719. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204720. return false;
  204721. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204722. {
  204723. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204724. {
  204725. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  204726. }
  204727. else if (m.message == WM_QUIT)
  204728. {
  204729. if (JUCEApplication::getInstance() != 0)
  204730. JUCEApplication::getInstance()->systemRequestedQuit();
  204731. }
  204732. else if (! isEventBlockedByModalComps (m))
  204733. {
  204734. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204735. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204736. {
  204737. // if it's someone else's window being clicked on, and the focus is
  204738. // currently on a juce window, pass the kb focus over..
  204739. HWND currentFocus = GetFocus();
  204740. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204741. SetFocus (m.hwnd);
  204742. }
  204743. TranslateMessage (&m);
  204744. DispatchMessage (&m);
  204745. }
  204746. }
  204747. return true;
  204748. }
  204749. bool juce_postMessageToSystemQueue (Message* message)
  204750. {
  204751. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204752. }
  204753. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204754. void* userData)
  204755. {
  204756. if (MessageManager::getInstance()->isThisTheMessageThread())
  204757. {
  204758. return (*callback) (userData);
  204759. }
  204760. else
  204761. {
  204762. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204763. // deadlock because the message manager is blocked from running, and can't
  204764. // call your function..
  204765. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204766. return (void*) SendMessage (juce_messageWindowHandle,
  204767. specialCallbackId,
  204768. (WPARAM) callback,
  204769. (LPARAM) userData);
  204770. }
  204771. }
  204772. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204773. {
  204774. if (hwnd != juce_messageWindowHandle)
  204775. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204776. return TRUE;
  204777. }
  204778. void MessageManager::broadcastMessage (const String& value) throw()
  204779. {
  204780. Array<void*> windows;
  204781. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204782. const String localCopy (value);
  204783. COPYDATASTRUCT data;
  204784. data.dwData = broadcastId;
  204785. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204786. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204787. for (int i = windows.size(); --i >= 0;)
  204788. {
  204789. HWND hwnd = (HWND) windows.getUnchecked(i);
  204790. TCHAR windowName [64]; // no need to read longer strings than this
  204791. GetWindowText (hwnd, windowName, 64);
  204792. windowName [63] = 0;
  204793. if (String (windowName) == messageWindowName)
  204794. {
  204795. DWORD_PTR result;
  204796. SendMessageTimeout (hwnd, WM_COPYDATA,
  204797. (WPARAM) juce_messageWindowHandle,
  204798. (LPARAM) &data,
  204799. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204800. 8000,
  204801. &result);
  204802. }
  204803. }
  204804. }
  204805. static const String getMessageWindowClassName()
  204806. {
  204807. // this name has to be different for each app/dll instance because otherwise
  204808. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204809. // window class).
  204810. static int number = 0;
  204811. if (number == 0)
  204812. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204813. return "JUCEcs_" + String (number);
  204814. }
  204815. void MessageManager::doPlatformSpecificInitialisation()
  204816. {
  204817. OleInitialize (0);
  204818. const String className (getMessageWindowClassName());
  204819. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204820. WNDCLASSEX wc;
  204821. zerostruct (wc);
  204822. wc.cbSize = sizeof (wc);
  204823. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204824. wc.cbWndExtra = 4;
  204825. wc.hInstance = hmod;
  204826. wc.lpszClassName = className;
  204827. RegisterClassEx (&wc);
  204828. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204829. messageWindowName,
  204830. 0, 0, 0, 0, 0, 0, 0,
  204831. hmod, 0);
  204832. }
  204833. void MessageManager::doPlatformSpecificShutdown()
  204834. {
  204835. DestroyWindow (juce_messageWindowHandle);
  204836. UnregisterClass (getMessageWindowClassName(), 0);
  204837. OleUninitialize();
  204838. }
  204839. #endif
  204840. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204841. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204842. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204843. // compiled on its own).
  204844. #if JUCE_INCLUDED_FILE
  204845. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204846. // these are in the windows SDK, but need to be repeated here for GCC..
  204847. #ifndef GET_APPCOMMAND_LPARAM
  204848. #define FAPPCOMMAND_MASK 0xF000
  204849. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204850. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204851. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204852. #define APPCOMMAND_MEDIA_STOP 13
  204853. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204854. #define WM_APPCOMMAND 0x0319
  204855. #endif
  204856. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204857. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204858. extern bool juce_IsRunningInWine();
  204859. #ifndef ULW_ALPHA
  204860. #define ULW_ALPHA 0x00000002
  204861. #endif
  204862. #ifndef AC_SRC_ALPHA
  204863. #define AC_SRC_ALPHA 0x01
  204864. #endif
  204865. static HPALETTE palette = 0;
  204866. static bool createPaletteIfNeeded = true;
  204867. static bool shouldDeactivateTitleBar = true;
  204868. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  204869. #define WM_TRAYNOTIFY WM_USER + 100
  204870. using ::abs;
  204871. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204872. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204873. bool Desktop::canUseSemiTransparentWindows() throw()
  204874. {
  204875. if (updateLayeredWindow == 0)
  204876. {
  204877. if (! juce_IsRunningInWine())
  204878. {
  204879. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204880. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204881. }
  204882. }
  204883. return updateLayeredWindow != 0;
  204884. }
  204885. const int extendedKeyModifier = 0x10000;
  204886. const int KeyPress::spaceKey = VK_SPACE;
  204887. const int KeyPress::returnKey = VK_RETURN;
  204888. const int KeyPress::escapeKey = VK_ESCAPE;
  204889. const int KeyPress::backspaceKey = VK_BACK;
  204890. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204891. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204892. const int KeyPress::tabKey = VK_TAB;
  204893. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204894. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204895. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204896. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204897. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204898. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204899. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204900. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204901. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204902. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204903. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204904. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204905. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204906. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204907. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204908. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204909. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204910. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204911. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204912. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204913. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204914. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204915. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204916. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204917. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204918. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204919. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204920. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204921. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204922. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204923. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204924. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204925. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204926. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204927. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204928. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204929. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204930. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204931. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204932. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204933. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204934. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204935. const int KeyPress::playKey = 0x30000;
  204936. const int KeyPress::stopKey = 0x30001;
  204937. const int KeyPress::fastForwardKey = 0x30002;
  204938. const int KeyPress::rewindKey = 0x30003;
  204939. class WindowsBitmapImage : public Image::SharedImage
  204940. {
  204941. public:
  204942. HBITMAP hBitmap;
  204943. BITMAPV4HEADER bitmapInfo;
  204944. HDC hdc;
  204945. unsigned char* bitmapData;
  204946. WindowsBitmapImage (const Image::PixelFormat format_,
  204947. const int w, const int h, const bool clearImage)
  204948. : Image::SharedImage (format_, w, h)
  204949. {
  204950. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204951. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204952. zerostruct (bitmapInfo);
  204953. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204954. bitmapInfo.bV4Width = w;
  204955. bitmapInfo.bV4Height = h;
  204956. bitmapInfo.bV4Planes = 1;
  204957. bitmapInfo.bV4CSType = 1;
  204958. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204959. if (format_ == Image::ARGB)
  204960. {
  204961. bitmapInfo.bV4AlphaMask = 0xff000000;
  204962. bitmapInfo.bV4RedMask = 0xff0000;
  204963. bitmapInfo.bV4GreenMask = 0xff00;
  204964. bitmapInfo.bV4BlueMask = 0xff;
  204965. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204966. }
  204967. else
  204968. {
  204969. bitmapInfo.bV4V4Compression = BI_RGB;
  204970. }
  204971. lineStride = -((w * pixelStride + 3) & ~3);
  204972. HDC dc = GetDC (0);
  204973. hdc = CreateCompatibleDC (dc);
  204974. ReleaseDC (0, dc);
  204975. SetMapMode (hdc, MM_TEXT);
  204976. hBitmap = CreateDIBSection (hdc,
  204977. (BITMAPINFO*) &(bitmapInfo),
  204978. DIB_RGB_COLORS,
  204979. (void**) &bitmapData,
  204980. 0, 0);
  204981. SelectObject (hdc, hBitmap);
  204982. if (format_ == Image::ARGB && clearImage)
  204983. zeromem (bitmapData, abs (h * lineStride));
  204984. imageData = bitmapData - (lineStride * (h - 1));
  204985. }
  204986. ~WindowsBitmapImage()
  204987. {
  204988. DeleteDC (hdc);
  204989. DeleteObject (hBitmap);
  204990. }
  204991. Image::ImageType getType() const { return Image::NativeImage; }
  204992. LowLevelGraphicsContext* createLowLevelContext()
  204993. {
  204994. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204995. }
  204996. SharedImage* clone()
  204997. {
  204998. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204999. for (int i = 0; i < height; ++i)
  205000. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  205001. return im;
  205002. }
  205003. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  205004. const int x, const int y,
  205005. const RectangleList& maskedRegion) throw()
  205006. {
  205007. static HDRAWDIB hdd = 0;
  205008. static bool needToCreateDrawDib = true;
  205009. if (needToCreateDrawDib)
  205010. {
  205011. needToCreateDrawDib = false;
  205012. HDC dc = GetDC (0);
  205013. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205014. ReleaseDC (0, dc);
  205015. // only open if we're not palettised
  205016. if (n > 8)
  205017. hdd = DrawDibOpen();
  205018. }
  205019. if (createPaletteIfNeeded)
  205020. {
  205021. HDC dc = GetDC (0);
  205022. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205023. ReleaseDC (0, dc);
  205024. if (n <= 8)
  205025. palette = CreateHalftonePalette (dc);
  205026. createPaletteIfNeeded = false;
  205027. }
  205028. if (palette != 0)
  205029. {
  205030. SelectPalette (dc, palette, FALSE);
  205031. RealizePalette (dc);
  205032. SetStretchBltMode (dc, HALFTONE);
  205033. }
  205034. SetMapMode (dc, MM_TEXT);
  205035. if (transparent)
  205036. {
  205037. POINT p, pos;
  205038. SIZE size;
  205039. RECT windowBounds;
  205040. GetWindowRect (hwnd, &windowBounds);
  205041. p.x = -x;
  205042. p.y = -y;
  205043. pos.x = windowBounds.left;
  205044. pos.y = windowBounds.top;
  205045. size.cx = windowBounds.right - windowBounds.left;
  205046. size.cy = windowBounds.bottom - windowBounds.top;
  205047. BLENDFUNCTION bf;
  205048. bf.AlphaFormat = AC_SRC_ALPHA;
  205049. bf.BlendFlags = 0;
  205050. bf.BlendOp = AC_SRC_OVER;
  205051. bf.SourceConstantAlpha = 0xff;
  205052. if (! maskedRegion.isEmpty())
  205053. {
  205054. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205055. {
  205056. const Rectangle<int>& r = *i.getRectangle();
  205057. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205058. }
  205059. }
  205060. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205061. }
  205062. else
  205063. {
  205064. int savedDC = 0;
  205065. if (! maskedRegion.isEmpty())
  205066. {
  205067. savedDC = SaveDC (dc);
  205068. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205069. {
  205070. const Rectangle<int>& r = *i.getRectangle();
  205071. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205072. }
  205073. }
  205074. if (hdd == 0)
  205075. {
  205076. StretchDIBits (dc,
  205077. x, y, width, height,
  205078. 0, 0, width, height,
  205079. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205080. DIB_RGB_COLORS, SRCCOPY);
  205081. }
  205082. else
  205083. {
  205084. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205085. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205086. 0, 0, width, height, 0);
  205087. }
  205088. if (! maskedRegion.isEmpty())
  205089. RestoreDC (dc, savedDC);
  205090. }
  205091. }
  205092. juce_UseDebuggingNewOperator
  205093. private:
  205094. WindowsBitmapImage (const WindowsBitmapImage&);
  205095. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205096. };
  205097. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205098. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  205099. {
  205100. SHORT k = (SHORT) keyCode;
  205101. if ((keyCode & extendedKeyModifier) == 0
  205102. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  205103. k += (SHORT) 'A' - (SHORT) 'a';
  205104. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205105. (SHORT) '+', VK_OEM_PLUS,
  205106. (SHORT) '-', VK_OEM_MINUS,
  205107. (SHORT) '.', VK_OEM_PERIOD,
  205108. (SHORT) ';', VK_OEM_1,
  205109. (SHORT) ':', VK_OEM_1,
  205110. (SHORT) '/', VK_OEM_2,
  205111. (SHORT) '?', VK_OEM_2,
  205112. (SHORT) '[', VK_OEM_4,
  205113. (SHORT) ']', VK_OEM_6 };
  205114. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205115. if (k == translatedValues [i])
  205116. k = translatedValues [i + 1];
  205117. return (GetKeyState (k) & 0x8000) != 0;
  205118. }
  205119. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  205120. {
  205121. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  205122. return callback (userData);
  205123. else
  205124. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  205125. }
  205126. class Win32ComponentPeer : public ComponentPeer
  205127. {
  205128. public:
  205129. Win32ComponentPeer (Component* const component,
  205130. const int windowStyleFlags)
  205131. : ComponentPeer (component, windowStyleFlags),
  205132. dontRepaint (false),
  205133. fullScreen (false),
  205134. isDragging (false),
  205135. isMouseOver (false),
  205136. hasCreatedCaret (false),
  205137. currentWindowIcon (0),
  205138. taskBarIcon (0),
  205139. dropTarget (0)
  205140. {
  205141. callFunctionIfNotLocked (&createWindowCallback, this);
  205142. setTitle (component->getName());
  205143. if ((windowStyleFlags & windowHasDropShadow) != 0
  205144. && Desktop::canUseSemiTransparentWindows())
  205145. {
  205146. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205147. if (shadower != 0)
  205148. shadower->setOwner (component);
  205149. }
  205150. else
  205151. {
  205152. shadower = 0;
  205153. }
  205154. }
  205155. ~Win32ComponentPeer()
  205156. {
  205157. setTaskBarIcon (Image());
  205158. deleteAndZero (shadower);
  205159. // do this before the next bit to avoid messages arriving for this window
  205160. // before it's destroyed
  205161. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205162. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  205163. if (currentWindowIcon != 0)
  205164. DestroyIcon (currentWindowIcon);
  205165. if (dropTarget != 0)
  205166. {
  205167. dropTarget->Release();
  205168. dropTarget = 0;
  205169. }
  205170. }
  205171. void* getNativeHandle() const
  205172. {
  205173. return hwnd;
  205174. }
  205175. void setVisible (bool shouldBeVisible)
  205176. {
  205177. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205178. if (shouldBeVisible)
  205179. InvalidateRect (hwnd, 0, 0);
  205180. else
  205181. lastPaintTime = 0;
  205182. }
  205183. void setTitle (const String& title)
  205184. {
  205185. SetWindowText (hwnd, title);
  205186. }
  205187. void setPosition (int x, int y)
  205188. {
  205189. offsetWithinParent (x, y);
  205190. SetWindowPos (hwnd, 0,
  205191. x - windowBorder.getLeft(),
  205192. y - windowBorder.getTop(),
  205193. 0, 0,
  205194. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205195. }
  205196. void repaintNowIfTransparent()
  205197. {
  205198. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205199. handlePaintMessage();
  205200. }
  205201. void updateBorderSize()
  205202. {
  205203. WINDOWINFO info;
  205204. info.cbSize = sizeof (info);
  205205. if (GetWindowInfo (hwnd, &info))
  205206. {
  205207. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205208. info.rcClient.left - info.rcWindow.left,
  205209. info.rcWindow.bottom - info.rcClient.bottom,
  205210. info.rcWindow.right - info.rcClient.right);
  205211. }
  205212. }
  205213. void setSize (int w, int h)
  205214. {
  205215. SetWindowPos (hwnd, 0, 0, 0,
  205216. w + windowBorder.getLeftAndRight(),
  205217. h + windowBorder.getTopAndBottom(),
  205218. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205219. updateBorderSize();
  205220. repaintNowIfTransparent();
  205221. }
  205222. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  205223. {
  205224. fullScreen = isNowFullScreen;
  205225. offsetWithinParent (x, y);
  205226. SetWindowPos (hwnd, 0,
  205227. x - windowBorder.getLeft(),
  205228. y - windowBorder.getTop(),
  205229. w + windowBorder.getLeftAndRight(),
  205230. h + windowBorder.getTopAndBottom(),
  205231. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205232. updateBorderSize();
  205233. repaintNowIfTransparent();
  205234. }
  205235. const Rectangle<int> getBounds() const
  205236. {
  205237. RECT r;
  205238. GetWindowRect (hwnd, &r);
  205239. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  205240. HWND parentH = GetParent (hwnd);
  205241. if (parentH != 0)
  205242. {
  205243. GetWindowRect (parentH, &r);
  205244. bounds.translate (-r.left, -r.top);
  205245. }
  205246. return windowBorder.subtractedFrom (bounds);
  205247. }
  205248. const Point<int> getScreenPosition() const
  205249. {
  205250. RECT r;
  205251. GetWindowRect (hwnd, &r);
  205252. return Point<int> (r.left + windowBorder.getLeft(),
  205253. r.top + windowBorder.getTop());
  205254. }
  205255. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  205256. {
  205257. return relativePosition + getScreenPosition();
  205258. }
  205259. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  205260. {
  205261. return screenPosition - getScreenPosition();
  205262. }
  205263. void setMinimised (bool shouldBeMinimised)
  205264. {
  205265. if (shouldBeMinimised != isMinimised())
  205266. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205267. }
  205268. bool isMinimised() const
  205269. {
  205270. WINDOWPLACEMENT wp;
  205271. wp.length = sizeof (WINDOWPLACEMENT);
  205272. GetWindowPlacement (hwnd, &wp);
  205273. return wp.showCmd == SW_SHOWMINIMIZED;
  205274. }
  205275. void setFullScreen (bool shouldBeFullScreen)
  205276. {
  205277. setMinimised (false);
  205278. if (fullScreen != shouldBeFullScreen)
  205279. {
  205280. fullScreen = shouldBeFullScreen;
  205281. const Component::SafePointer<Component> deletionChecker (component);
  205282. if (! fullScreen)
  205283. {
  205284. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  205285. if (hasTitleBar())
  205286. ShowWindow (hwnd, SW_SHOWNORMAL);
  205287. if (! boundsCopy.isEmpty())
  205288. {
  205289. setBounds (boundsCopy.getX(),
  205290. boundsCopy.getY(),
  205291. boundsCopy.getWidth(),
  205292. boundsCopy.getHeight(),
  205293. false);
  205294. }
  205295. }
  205296. else
  205297. {
  205298. if (hasTitleBar())
  205299. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  205300. else
  205301. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  205302. }
  205303. if (deletionChecker != 0)
  205304. handleMovedOrResized();
  205305. }
  205306. }
  205307. bool isFullScreen() const
  205308. {
  205309. if (! hasTitleBar())
  205310. return fullScreen;
  205311. WINDOWPLACEMENT wp;
  205312. wp.length = sizeof (wp);
  205313. GetWindowPlacement (hwnd, &wp);
  205314. return wp.showCmd == SW_SHOWMAXIMIZED;
  205315. }
  205316. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  205317. {
  205318. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  205319. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  205320. return false;
  205321. RECT r;
  205322. GetWindowRect (hwnd, &r);
  205323. POINT p;
  205324. p.x = position.getX() + r.left + windowBorder.getLeft();
  205325. p.y = position.getY() + r.top + windowBorder.getTop();
  205326. HWND w = WindowFromPoint (p);
  205327. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  205328. }
  205329. const BorderSize getFrameSize() const
  205330. {
  205331. return windowBorder;
  205332. }
  205333. bool setAlwaysOnTop (bool alwaysOnTop)
  205334. {
  205335. const bool oldDeactivate = shouldDeactivateTitleBar;
  205336. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205337. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  205338. 0, 0, 0, 0,
  205339. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205340. shouldDeactivateTitleBar = oldDeactivate;
  205341. if (shadower != 0)
  205342. shadower->componentBroughtToFront (*component);
  205343. return true;
  205344. }
  205345. void toFront (bool makeActive)
  205346. {
  205347. setMinimised (false);
  205348. const bool oldDeactivate = shouldDeactivateTitleBar;
  205349. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205350. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  205351. shouldDeactivateTitleBar = oldDeactivate;
  205352. if (! makeActive)
  205353. {
  205354. // in this case a broughttofront call won't have occured, so do it now..
  205355. handleBroughtToFront();
  205356. }
  205357. }
  205358. void toBehind (ComponentPeer* other)
  205359. {
  205360. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205361. jassert (otherPeer != 0); // wrong type of window?
  205362. if (otherPeer != 0)
  205363. {
  205364. setMinimised (false);
  205365. // must be careful not to try to put a topmost window behind a normal one, or win32
  205366. // promotes the normal one to be topmost!
  205367. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  205368. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205369. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205370. else if (otherPeer->getComponent()->isAlwaysOnTop())
  205371. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  205372. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205373. }
  205374. }
  205375. bool isFocused() const
  205376. {
  205377. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  205378. }
  205379. void grabFocus()
  205380. {
  205381. const bool oldDeactivate = shouldDeactivateTitleBar;
  205382. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205383. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  205384. shouldDeactivateTitleBar = oldDeactivate;
  205385. }
  205386. void textInputRequired (const Point<int>&)
  205387. {
  205388. if (! hasCreatedCaret)
  205389. {
  205390. hasCreatedCaret = true;
  205391. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  205392. }
  205393. ShowCaret (hwnd);
  205394. SetCaretPos (0, 0);
  205395. }
  205396. void repaint (const Rectangle<int>& area)
  205397. {
  205398. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  205399. InvalidateRect (hwnd, &r, FALSE);
  205400. }
  205401. void performAnyPendingRepaintsNow()
  205402. {
  205403. MSG m;
  205404. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205405. DispatchMessage (&m);
  205406. }
  205407. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205408. {
  205409. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205410. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  205411. return 0;
  205412. }
  205413. void setTaskBarIcon (const Image& image)
  205414. {
  205415. if (image.isValid())
  205416. {
  205417. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  205418. if (taskBarIcon == 0)
  205419. {
  205420. taskBarIcon = new NOTIFYICONDATA();
  205421. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205422. taskBarIcon->hWnd = (HWND) hwnd;
  205423. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205424. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205425. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205426. taskBarIcon->hIcon = hicon;
  205427. taskBarIcon->szTip[0] = 0;
  205428. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205429. }
  205430. else
  205431. {
  205432. HICON oldIcon = taskBarIcon->hIcon;
  205433. taskBarIcon->hIcon = hicon;
  205434. taskBarIcon->uFlags = NIF_ICON;
  205435. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205436. DestroyIcon (oldIcon);
  205437. }
  205438. DestroyIcon (hicon);
  205439. }
  205440. else if (taskBarIcon != 0)
  205441. {
  205442. taskBarIcon->uFlags = 0;
  205443. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205444. DestroyIcon (taskBarIcon->hIcon);
  205445. deleteAndZero (taskBarIcon);
  205446. }
  205447. }
  205448. void setTaskBarIconToolTip (const String& toolTip) const
  205449. {
  205450. if (taskBarIcon != 0)
  205451. {
  205452. taskBarIcon->uFlags = NIF_TIP;
  205453. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205454. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205455. }
  205456. }
  205457. bool isInside (HWND h) const
  205458. {
  205459. return GetAncestor (hwnd, GA_ROOT) == h;
  205460. }
  205461. static void updateKeyModifiers() throw()
  205462. {
  205463. int keyMods = 0;
  205464. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  205465. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  205466. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  205467. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205468. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205469. }
  205470. static void updateModifiersFromWParam (const WPARAM wParam)
  205471. {
  205472. int mouseMods = 0;
  205473. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  205474. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  205475. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  205476. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  205477. updateKeyModifiers();
  205478. }
  205479. static int64 getMouseEventTime()
  205480. {
  205481. static int64 eventTimeOffset = 0;
  205482. static DWORD lastMessageTime = 0;
  205483. const DWORD thisMessageTime = GetMessageTime();
  205484. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205485. {
  205486. lastMessageTime = thisMessageTime;
  205487. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205488. }
  205489. return eventTimeOffset + thisMessageTime;
  205490. }
  205491. juce_UseDebuggingNewOperator
  205492. bool dontRepaint;
  205493. static ModifierKeys currentModifiers;
  205494. static ModifierKeys modifiersAtLastCallback;
  205495. private:
  205496. HWND hwnd;
  205497. DropShadower* shadower;
  205498. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205499. BorderSize windowBorder;
  205500. HICON currentWindowIcon;
  205501. NOTIFYICONDATA* taskBarIcon;
  205502. IDropTarget* dropTarget;
  205503. class TemporaryImage : public Timer
  205504. {
  205505. public:
  205506. TemporaryImage() {}
  205507. ~TemporaryImage() {}
  205508. const Image& getImage (const bool transparent, const int w, const int h)
  205509. {
  205510. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205511. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205512. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205513. startTimer (3000);
  205514. return image;
  205515. }
  205516. void timerCallback()
  205517. {
  205518. stopTimer();
  205519. image = Image::null;
  205520. }
  205521. private:
  205522. Image image;
  205523. TemporaryImage (const TemporaryImage&);
  205524. TemporaryImage& operator= (const TemporaryImage&);
  205525. };
  205526. TemporaryImage offscreenImageGenerator;
  205527. class WindowClassHolder : public DeletedAtShutdown
  205528. {
  205529. public:
  205530. WindowClassHolder()
  205531. : windowClassName ("JUCE_")
  205532. {
  205533. // this name has to be different for each app/dll instance because otherwise
  205534. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205535. // window class).
  205536. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205537. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205538. TCHAR moduleFile [1024];
  205539. moduleFile[0] = 0;
  205540. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205541. WORD iconNum = 0;
  205542. WNDCLASSEX wcex;
  205543. wcex.cbSize = sizeof (wcex);
  205544. wcex.style = CS_OWNDC;
  205545. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205546. wcex.lpszClassName = windowClassName;
  205547. wcex.cbClsExtra = 0;
  205548. wcex.cbWndExtra = 32;
  205549. wcex.hInstance = moduleHandle;
  205550. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205551. iconNum = 1;
  205552. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205553. wcex.hCursor = 0;
  205554. wcex.hbrBackground = 0;
  205555. wcex.lpszMenuName = 0;
  205556. RegisterClassEx (&wcex);
  205557. }
  205558. ~WindowClassHolder()
  205559. {
  205560. if (ComponentPeer::getNumPeers() == 0)
  205561. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205562. clearSingletonInstance();
  205563. }
  205564. String windowClassName;
  205565. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205566. };
  205567. static void* createWindowCallback (void* userData)
  205568. {
  205569. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205570. return 0;
  205571. }
  205572. void createWindow()
  205573. {
  205574. DWORD exstyle = WS_EX_ACCEPTFILES;
  205575. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205576. if (hasTitleBar())
  205577. {
  205578. type |= WS_OVERLAPPED;
  205579. if ((styleFlags & windowHasCloseButton) != 0)
  205580. {
  205581. type |= WS_SYSMENU;
  205582. }
  205583. else
  205584. {
  205585. // annoyingly, windows won't let you have a min/max button without a close button
  205586. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205587. }
  205588. if ((styleFlags & windowIsResizable) != 0)
  205589. type |= WS_THICKFRAME;
  205590. }
  205591. else
  205592. {
  205593. type |= WS_POPUP | WS_SYSMENU;
  205594. }
  205595. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205596. exstyle |= WS_EX_TOOLWINDOW;
  205597. else
  205598. exstyle |= WS_EX_APPWINDOW;
  205599. if ((styleFlags & windowHasMinimiseButton) != 0)
  205600. type |= WS_MINIMIZEBOX;
  205601. if ((styleFlags & windowHasMaximiseButton) != 0)
  205602. type |= WS_MAXIMIZEBOX;
  205603. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205604. exstyle |= WS_EX_TRANSPARENT;
  205605. if ((styleFlags & windowIsSemiTransparent) != 0
  205606. && Desktop::canUseSemiTransparentWindows())
  205607. exstyle |= WS_EX_LAYERED;
  205608. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205609. if (hwnd != 0)
  205610. {
  205611. SetWindowLongPtr (hwnd, 0, 0);
  205612. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205613. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205614. if (dropTarget == 0)
  205615. dropTarget = new JuceDropTarget (this);
  205616. RegisterDragDrop (hwnd, dropTarget);
  205617. updateBorderSize();
  205618. // Calling this function here is (for some reason) necessary to make Windows
  205619. // correctly enable the menu items that we specify in the wm_initmenu message.
  205620. GetSystemMenu (hwnd, false);
  205621. }
  205622. else
  205623. {
  205624. jassertfalse;
  205625. }
  205626. }
  205627. static void* destroyWindowCallback (void* handle)
  205628. {
  205629. RevokeDragDrop ((HWND) handle);
  205630. DestroyWindow ((HWND) handle);
  205631. return 0;
  205632. }
  205633. static void* toFrontCallback1 (void* h)
  205634. {
  205635. SetForegroundWindow ((HWND) h);
  205636. return 0;
  205637. }
  205638. static void* toFrontCallback2 (void* h)
  205639. {
  205640. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205641. return 0;
  205642. }
  205643. static void* setFocusCallback (void* h)
  205644. {
  205645. SetFocus ((HWND) h);
  205646. return 0;
  205647. }
  205648. static void* getFocusCallback (void*)
  205649. {
  205650. return GetFocus();
  205651. }
  205652. void offsetWithinParent (int& x, int& y) const
  205653. {
  205654. if (isTransparent())
  205655. {
  205656. HWND parentHwnd = GetParent (hwnd);
  205657. if (parentHwnd != 0)
  205658. {
  205659. RECT parentRect;
  205660. GetWindowRect (parentHwnd, &parentRect);
  205661. x += parentRect.left;
  205662. y += parentRect.top;
  205663. }
  205664. }
  205665. }
  205666. bool isTransparent() const
  205667. {
  205668. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205669. }
  205670. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205671. void setIcon (const Image& newIcon)
  205672. {
  205673. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205674. if (hicon != 0)
  205675. {
  205676. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205677. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205678. if (currentWindowIcon != 0)
  205679. DestroyIcon (currentWindowIcon);
  205680. currentWindowIcon = hicon;
  205681. }
  205682. }
  205683. void handlePaintMessage()
  205684. {
  205685. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205686. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205687. PAINTSTRUCT paintStruct;
  205688. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205689. // message and become re-entrant, but that's OK
  205690. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205691. // corrupt the image it's using to paint into, so do a check here.
  205692. static bool reentrant = false;
  205693. if (reentrant)
  205694. {
  205695. DeleteObject (rgn);
  205696. EndPaint (hwnd, &paintStruct);
  205697. return;
  205698. }
  205699. reentrant = true;
  205700. // this is the rectangle to update..
  205701. int x = paintStruct.rcPaint.left;
  205702. int y = paintStruct.rcPaint.top;
  205703. int w = paintStruct.rcPaint.right - x;
  205704. int h = paintStruct.rcPaint.bottom - y;
  205705. const bool transparent = isTransparent();
  205706. if (transparent)
  205707. {
  205708. // it's not possible to have a transparent window with a title bar at the moment!
  205709. jassert (! hasTitleBar());
  205710. RECT r;
  205711. GetWindowRect (hwnd, &r);
  205712. x = y = 0;
  205713. w = r.right - r.left;
  205714. h = r.bottom - r.top;
  205715. }
  205716. if (w > 0 && h > 0)
  205717. {
  205718. clearMaskedRegion();
  205719. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205720. RectangleList contextClip;
  205721. const Rectangle<int> clipBounds (0, 0, w, h);
  205722. bool needToPaintAll = true;
  205723. if (regionType == COMPLEXREGION && ! transparent)
  205724. {
  205725. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205726. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205727. DeleteObject (clipRgn);
  205728. char rgnData [8192];
  205729. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205730. if (res > 0 && res <= sizeof (rgnData))
  205731. {
  205732. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205733. if (hdr->iType == RDH_RECTANGLES
  205734. && hdr->rcBound.right - hdr->rcBound.left >= w
  205735. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205736. {
  205737. needToPaintAll = false;
  205738. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205739. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205740. while (--num >= 0)
  205741. {
  205742. if (rects->right <= x + w && rects->bottom <= y + h)
  205743. {
  205744. // (need to move this one pixel to the left because of a win32 bug)
  205745. const int cx = jmax (x, (int) rects->left - 1);
  205746. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205747. .getIntersection (clipBounds));
  205748. }
  205749. else
  205750. {
  205751. needToPaintAll = true;
  205752. break;
  205753. }
  205754. ++rects;
  205755. }
  205756. }
  205757. }
  205758. }
  205759. if (needToPaintAll)
  205760. {
  205761. contextClip.clear();
  205762. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  205763. }
  205764. if (transparent)
  205765. {
  205766. RectangleList::Iterator i (contextClip);
  205767. while (i.next())
  205768. offscreenImage.clear (*i.getRectangle());
  205769. }
  205770. // if the component's not opaque, this won't draw properly unless the platform can support this
  205771. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205772. updateCurrentModifiers();
  205773. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205774. handlePaint (context);
  205775. if (! dontRepaint)
  205776. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205777. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205778. }
  205779. DeleteObject (rgn);
  205780. EndPaint (hwnd, &paintStruct);
  205781. reentrant = false;
  205782. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205783. _fpreset(); // because some graphics cards can unmask FP exceptions
  205784. #endif
  205785. lastPaintTime = Time::getMillisecondCounter();
  205786. }
  205787. void doMouseEvent (const Point<int>& position)
  205788. {
  205789. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205790. }
  205791. void doMouseMove (const Point<int>& position)
  205792. {
  205793. if (! isMouseOver)
  205794. {
  205795. isMouseOver = true;
  205796. updateKeyModifiers();
  205797. TRACKMOUSEEVENT tme;
  205798. tme.cbSize = sizeof (tme);
  205799. tme.dwFlags = TME_LEAVE;
  205800. tme.hwndTrack = hwnd;
  205801. tme.dwHoverTime = 0;
  205802. if (! TrackMouseEvent (&tme))
  205803. jassertfalse;
  205804. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205805. }
  205806. else if (! isDragging)
  205807. {
  205808. if (! contains (position, false))
  205809. return;
  205810. }
  205811. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205812. static uint32 lastMouseTime = 0;
  205813. const uint32 now = Time::getMillisecondCounter();
  205814. const int maxMouseMovesPerSecond = 60;
  205815. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205816. {
  205817. lastMouseTime = now;
  205818. doMouseEvent (position);
  205819. }
  205820. }
  205821. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205822. {
  205823. if (GetCapture() != hwnd)
  205824. SetCapture (hwnd);
  205825. doMouseMove (position);
  205826. updateModifiersFromWParam (wParam);
  205827. isDragging = true;
  205828. doMouseEvent (position);
  205829. }
  205830. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205831. {
  205832. updateModifiersFromWParam (wParam);
  205833. isDragging = false;
  205834. // release the mouse capture if the user has released all buttons
  205835. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205836. ReleaseCapture();
  205837. doMouseEvent (position);
  205838. }
  205839. void doCaptureChanged()
  205840. {
  205841. if (isDragging)
  205842. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205843. }
  205844. void doMouseExit()
  205845. {
  205846. isMouseOver = false;
  205847. doMouseEvent (getCurrentMousePos());
  205848. }
  205849. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205850. {
  205851. updateKeyModifiers();
  205852. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205853. handleMouseWheel (0, position, getMouseEventTime(),
  205854. isVertical ? 0.0f : amount,
  205855. isVertical ? amount : 0.0f);
  205856. }
  205857. void sendModifierKeyChangeIfNeeded()
  205858. {
  205859. if (modifiersAtLastCallback != currentModifiers)
  205860. {
  205861. modifiersAtLastCallback = currentModifiers;
  205862. handleModifierKeysChange();
  205863. }
  205864. }
  205865. bool doKeyUp (const WPARAM key)
  205866. {
  205867. updateKeyModifiers();
  205868. switch (key)
  205869. {
  205870. case VK_SHIFT:
  205871. case VK_CONTROL:
  205872. case VK_MENU:
  205873. case VK_CAPITAL:
  205874. case VK_LWIN:
  205875. case VK_RWIN:
  205876. case VK_APPS:
  205877. case VK_NUMLOCK:
  205878. case VK_SCROLL:
  205879. case VK_LSHIFT:
  205880. case VK_RSHIFT:
  205881. case VK_LCONTROL:
  205882. case VK_LMENU:
  205883. case VK_RCONTROL:
  205884. case VK_RMENU:
  205885. sendModifierKeyChangeIfNeeded();
  205886. }
  205887. return handleKeyUpOrDown (false)
  205888. || Component::getCurrentlyModalComponent() != 0;
  205889. }
  205890. bool doKeyDown (const WPARAM key)
  205891. {
  205892. updateKeyModifiers();
  205893. bool used = false;
  205894. switch (key)
  205895. {
  205896. case VK_SHIFT:
  205897. case VK_LSHIFT:
  205898. case VK_RSHIFT:
  205899. case VK_CONTROL:
  205900. case VK_LCONTROL:
  205901. case VK_RCONTROL:
  205902. case VK_MENU:
  205903. case VK_LMENU:
  205904. case VK_RMENU:
  205905. case VK_LWIN:
  205906. case VK_RWIN:
  205907. case VK_CAPITAL:
  205908. case VK_NUMLOCK:
  205909. case VK_SCROLL:
  205910. case VK_APPS:
  205911. sendModifierKeyChangeIfNeeded();
  205912. break;
  205913. case VK_LEFT:
  205914. case VK_RIGHT:
  205915. case VK_UP:
  205916. case VK_DOWN:
  205917. case VK_PRIOR:
  205918. case VK_NEXT:
  205919. case VK_HOME:
  205920. case VK_END:
  205921. case VK_DELETE:
  205922. case VK_INSERT:
  205923. case VK_F1:
  205924. case VK_F2:
  205925. case VK_F3:
  205926. case VK_F4:
  205927. case VK_F5:
  205928. case VK_F6:
  205929. case VK_F7:
  205930. case VK_F8:
  205931. case VK_F9:
  205932. case VK_F10:
  205933. case VK_F11:
  205934. case VK_F12:
  205935. case VK_F13:
  205936. case VK_F14:
  205937. case VK_F15:
  205938. case VK_F16:
  205939. used = handleKeyUpOrDown (true);
  205940. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205941. break;
  205942. case VK_ADD:
  205943. case VK_SUBTRACT:
  205944. case VK_MULTIPLY:
  205945. case VK_DIVIDE:
  205946. case VK_SEPARATOR:
  205947. case VK_DECIMAL:
  205948. used = handleKeyUpOrDown (true);
  205949. break;
  205950. default:
  205951. used = handleKeyUpOrDown (true);
  205952. {
  205953. MSG msg;
  205954. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205955. {
  205956. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205957. // manually generate the key-press event that matches this key-down.
  205958. const UINT keyChar = MapVirtualKey (key, 2);
  205959. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205960. }
  205961. }
  205962. break;
  205963. }
  205964. if (Component::getCurrentlyModalComponent() != 0)
  205965. used = true;
  205966. return used;
  205967. }
  205968. bool doKeyChar (int key, const LPARAM flags)
  205969. {
  205970. updateKeyModifiers();
  205971. juce_wchar textChar = (juce_wchar) key;
  205972. const int virtualScanCode = (flags >> 16) & 0xff;
  205973. if (key >= '0' && key <= '9')
  205974. {
  205975. switch (virtualScanCode) // check for a numeric keypad scan-code
  205976. {
  205977. case 0x52:
  205978. case 0x4f:
  205979. case 0x50:
  205980. case 0x51:
  205981. case 0x4b:
  205982. case 0x4c:
  205983. case 0x4d:
  205984. case 0x47:
  205985. case 0x48:
  205986. case 0x49:
  205987. key = (key - '0') + KeyPress::numberPad0;
  205988. break;
  205989. default:
  205990. break;
  205991. }
  205992. }
  205993. else
  205994. {
  205995. // convert the scan code to an unmodified character code..
  205996. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205997. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205998. keyChar = LOWORD (keyChar);
  205999. if (keyChar != 0)
  206000. key = (int) keyChar;
  206001. // avoid sending junk text characters for some control-key combinations
  206002. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  206003. textChar = 0;
  206004. }
  206005. return handleKeyPress (key, textChar);
  206006. }
  206007. bool doAppCommand (const LPARAM lParam)
  206008. {
  206009. int key = 0;
  206010. switch (GET_APPCOMMAND_LPARAM (lParam))
  206011. {
  206012. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  206013. key = KeyPress::playKey;
  206014. break;
  206015. case APPCOMMAND_MEDIA_STOP:
  206016. key = KeyPress::stopKey;
  206017. break;
  206018. case APPCOMMAND_MEDIA_NEXTTRACK:
  206019. key = KeyPress::fastForwardKey;
  206020. break;
  206021. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  206022. key = KeyPress::rewindKey;
  206023. break;
  206024. }
  206025. if (key != 0)
  206026. {
  206027. updateKeyModifiers();
  206028. if (hwnd == GetActiveWindow())
  206029. {
  206030. handleKeyPress (key, 0);
  206031. return true;
  206032. }
  206033. }
  206034. return false;
  206035. }
  206036. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  206037. {
  206038. public:
  206039. JuceDropTarget (Win32ComponentPeer* const owner_)
  206040. : owner (owner_)
  206041. {
  206042. }
  206043. ~JuceDropTarget() {}
  206044. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206045. {
  206046. updateFileList (pDataObject);
  206047. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206048. *pdwEffect = DROPEFFECT_COPY;
  206049. return S_OK;
  206050. }
  206051. HRESULT __stdcall DragLeave()
  206052. {
  206053. owner->handleFileDragExit (files);
  206054. return S_OK;
  206055. }
  206056. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206057. {
  206058. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206059. *pdwEffect = DROPEFFECT_COPY;
  206060. return S_OK;
  206061. }
  206062. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206063. {
  206064. updateFileList (pDataObject);
  206065. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206066. *pdwEffect = DROPEFFECT_COPY;
  206067. return S_OK;
  206068. }
  206069. private:
  206070. Win32ComponentPeer* const owner;
  206071. StringArray files;
  206072. void updateFileList (IDataObject* const pDataObject)
  206073. {
  206074. files.clear();
  206075. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206076. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206077. if (pDataObject->GetData (&format, &medium) == S_OK)
  206078. {
  206079. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206080. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206081. unsigned int i = 0;
  206082. if (pDropFiles->fWide)
  206083. {
  206084. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206085. for (;;)
  206086. {
  206087. unsigned int len = 0;
  206088. while (i + len < totalLen && fname [i + len] != 0)
  206089. ++len;
  206090. if (len == 0)
  206091. break;
  206092. files.add (String (fname + i, len));
  206093. i += len + 1;
  206094. }
  206095. }
  206096. else
  206097. {
  206098. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206099. for (;;)
  206100. {
  206101. unsigned int len = 0;
  206102. while (i + len < totalLen && fname [i + len] != 0)
  206103. ++len;
  206104. if (len == 0)
  206105. break;
  206106. files.add (String (fname + i, len));
  206107. i += len + 1;
  206108. }
  206109. }
  206110. GlobalUnlock (medium.hGlobal);
  206111. }
  206112. }
  206113. JuceDropTarget (const JuceDropTarget&);
  206114. JuceDropTarget& operator= (const JuceDropTarget&);
  206115. };
  206116. void doSettingChange()
  206117. {
  206118. Desktop::getInstance().refreshMonitorSizes();
  206119. if (fullScreen && ! isMinimised())
  206120. {
  206121. const Rectangle<int> r (component->getParentMonitorArea());
  206122. SetWindowPos (hwnd, 0,
  206123. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206124. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206125. }
  206126. }
  206127. public:
  206128. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206129. {
  206130. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206131. if (peer != 0)
  206132. return peer->peerWindowProc (h, message, wParam, lParam);
  206133. return DefWindowProcW (h, message, wParam, lParam);
  206134. }
  206135. private:
  206136. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  206137. {
  206138. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206139. }
  206140. const Point<int> getCurrentMousePos() throw()
  206141. {
  206142. RECT wr;
  206143. GetWindowRect (hwnd, &wr);
  206144. const DWORD mp = GetMessagePos();
  206145. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206146. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  206147. }
  206148. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206149. {
  206150. if (isValidPeer (this))
  206151. {
  206152. switch (message)
  206153. {
  206154. case WM_NCHITTEST:
  206155. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206156. return HTTRANSPARENT;
  206157. if (hasTitleBar())
  206158. break;
  206159. return HTCLIENT;
  206160. case WM_PAINT:
  206161. handlePaintMessage();
  206162. return 0;
  206163. case WM_NCPAINT:
  206164. if (wParam != 1)
  206165. handlePaintMessage();
  206166. if (hasTitleBar())
  206167. break;
  206168. return 0;
  206169. case WM_ERASEBKGND:
  206170. case WM_NCCALCSIZE:
  206171. if (hasTitleBar())
  206172. break;
  206173. return 1;
  206174. case WM_MOUSEMOVE:
  206175. doMouseMove (getPointFromLParam (lParam));
  206176. return 0;
  206177. case WM_MOUSELEAVE:
  206178. doMouseExit();
  206179. return 0;
  206180. case WM_LBUTTONDOWN:
  206181. case WM_MBUTTONDOWN:
  206182. case WM_RBUTTONDOWN:
  206183. doMouseDown (getPointFromLParam (lParam), wParam);
  206184. return 0;
  206185. case WM_LBUTTONUP:
  206186. case WM_MBUTTONUP:
  206187. case WM_RBUTTONUP:
  206188. doMouseUp (getPointFromLParam (lParam), wParam);
  206189. return 0;
  206190. case WM_CAPTURECHANGED:
  206191. doCaptureChanged();
  206192. return 0;
  206193. case WM_NCMOUSEMOVE:
  206194. if (hasTitleBar())
  206195. break;
  206196. return 0;
  206197. case 0x020A: /* WM_MOUSEWHEEL */
  206198. doMouseWheel (getCurrentMousePos(), wParam, true);
  206199. return 0;
  206200. case 0x020E: /* WM_MOUSEHWHEEL */
  206201. doMouseWheel (getCurrentMousePos(), wParam, false);
  206202. return 0;
  206203. case WM_WINDOWPOSCHANGING:
  206204. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206205. {
  206206. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206207. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  206208. {
  206209. if (constrainer != 0)
  206210. {
  206211. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  206212. component->getY() - windowBorder.getTop(),
  206213. component->getWidth() + windowBorder.getLeftAndRight(),
  206214. component->getHeight() + windowBorder.getTopAndBottom());
  206215. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  206216. constrainer->checkBounds (pos, current,
  206217. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206218. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  206219. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  206220. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  206221. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  206222. wp->x = pos.getX();
  206223. wp->y = pos.getY();
  206224. wp->cx = pos.getWidth();
  206225. wp->cy = pos.getHeight();
  206226. }
  206227. }
  206228. }
  206229. return 0;
  206230. case WM_WINDOWPOSCHANGED:
  206231. handleMovedOrResized();
  206232. if (dontRepaint)
  206233. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  206234. return 0;
  206235. case WM_KEYDOWN:
  206236. case WM_SYSKEYDOWN:
  206237. if (doKeyDown (wParam))
  206238. return 0;
  206239. break;
  206240. case WM_KEYUP:
  206241. case WM_SYSKEYUP:
  206242. if (doKeyUp (wParam))
  206243. return 0;
  206244. break;
  206245. case WM_CHAR:
  206246. if (doKeyChar ((int) wParam, lParam))
  206247. return 0;
  206248. break;
  206249. case WM_APPCOMMAND:
  206250. if (doAppCommand (lParam))
  206251. return TRUE;
  206252. break;
  206253. case WM_SETFOCUS:
  206254. updateKeyModifiers();
  206255. handleFocusGain();
  206256. break;
  206257. case WM_KILLFOCUS:
  206258. if (hasCreatedCaret)
  206259. {
  206260. hasCreatedCaret = false;
  206261. DestroyCaret();
  206262. }
  206263. handleFocusLoss();
  206264. break;
  206265. case WM_ACTIVATEAPP:
  206266. // Windows does weird things to process priority when you swap apps,
  206267. // so this forces an update when the app is brought to the front
  206268. if (wParam != FALSE)
  206269. juce_repeatLastProcessPriority();
  206270. else
  206271. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  206272. juce_CheckCurrentlyFocusedTopLevelWindow();
  206273. modifiersAtLastCallback = -1;
  206274. return 0;
  206275. case WM_ACTIVATE:
  206276. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  206277. {
  206278. modifiersAtLastCallback = -1;
  206279. updateKeyModifiers();
  206280. if (isMinimised())
  206281. {
  206282. component->repaint();
  206283. handleMovedOrResized();
  206284. if (! ComponentPeer::isValidPeer (this))
  206285. return 0;
  206286. }
  206287. if (LOWORD (wParam) == WA_CLICKACTIVE
  206288. && component->isCurrentlyBlockedByAnotherModalComponent())
  206289. {
  206290. const Point<int> mousePos (component->getMouseXYRelative());
  206291. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  206292. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  206293. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  206294. return 0;
  206295. }
  206296. handleBroughtToFront();
  206297. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206298. Component::getCurrentlyModalComponent()->toFront (true);
  206299. return 0;
  206300. }
  206301. break;
  206302. case WM_NCACTIVATE:
  206303. // while a temporary window is being shown, prevent Windows from deactivating the
  206304. // title bars of our main windows.
  206305. if (wParam == 0 && ! shouldDeactivateTitleBar)
  206306. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  206307. break;
  206308. case WM_MOUSEACTIVATE:
  206309. if (! component->getMouseClickGrabsKeyboardFocus())
  206310. return MA_NOACTIVATE;
  206311. break;
  206312. case WM_SHOWWINDOW:
  206313. if (wParam != 0)
  206314. handleBroughtToFront();
  206315. break;
  206316. case WM_CLOSE:
  206317. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  206318. handleUserClosingWindow();
  206319. return 0;
  206320. case WM_QUERYENDSESSION:
  206321. if (JUCEApplication::getInstance() != 0)
  206322. {
  206323. JUCEApplication::getInstance()->systemRequestedQuit();
  206324. return MessageManager::getInstance()->hasStopMessageBeenSent();
  206325. }
  206326. return TRUE;
  206327. case WM_TRAYNOTIFY:
  206328. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206329. {
  206330. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206331. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206332. {
  206333. Component* const current = Component::getCurrentlyModalComponent();
  206334. if (current != 0)
  206335. current->inputAttemptWhenModal();
  206336. }
  206337. }
  206338. else
  206339. {
  206340. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206341. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206342. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206343. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206344. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206345. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206346. eventMods = eventMods.withoutMouseButtons();
  206347. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206348. Point<int>(), eventMods, component, component, getMouseEventTime(),
  206349. Point<int>(), getMouseEventTime(), 1, false);
  206350. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206351. {
  206352. SetFocus (hwnd);
  206353. SetForegroundWindow (hwnd);
  206354. component->mouseDown (e);
  206355. }
  206356. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206357. {
  206358. component->mouseUp (e);
  206359. }
  206360. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206361. {
  206362. component->mouseDoubleClick (e);
  206363. }
  206364. else if (lParam == WM_MOUSEMOVE)
  206365. {
  206366. component->mouseMove (e);
  206367. }
  206368. }
  206369. break;
  206370. case WM_SYNCPAINT:
  206371. return 0;
  206372. case WM_PALETTECHANGED:
  206373. InvalidateRect (h, 0, 0);
  206374. break;
  206375. case WM_DISPLAYCHANGE:
  206376. InvalidateRect (h, 0, 0);
  206377. createPaletteIfNeeded = true;
  206378. // intentional fall-through...
  206379. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206380. doSettingChange();
  206381. break;
  206382. case WM_INITMENU:
  206383. if (! hasTitleBar())
  206384. {
  206385. if (isFullScreen())
  206386. {
  206387. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206388. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206389. }
  206390. else if (! isMinimised())
  206391. {
  206392. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206393. }
  206394. }
  206395. break;
  206396. case WM_SYSCOMMAND:
  206397. switch (wParam & 0xfff0)
  206398. {
  206399. case SC_CLOSE:
  206400. if (sendInputAttemptWhenModalMessage())
  206401. return 0;
  206402. if (hasTitleBar())
  206403. {
  206404. PostMessage (h, WM_CLOSE, 0, 0);
  206405. return 0;
  206406. }
  206407. break;
  206408. case SC_KEYMENU:
  206409. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  206410. // obscure situations that can arise if a modal loop is started from an alt-key
  206411. // keypress).
  206412. if (hasTitleBar() && h == GetCapture())
  206413. ReleaseCapture();
  206414. break;
  206415. case SC_MAXIMIZE:
  206416. if (sendInputAttemptWhenModalMessage())
  206417. return 0;
  206418. setFullScreen (true);
  206419. return 0;
  206420. case SC_MINIMIZE:
  206421. if (sendInputAttemptWhenModalMessage())
  206422. return 0;
  206423. if (! hasTitleBar())
  206424. {
  206425. setMinimised (true);
  206426. return 0;
  206427. }
  206428. break;
  206429. case SC_RESTORE:
  206430. if (sendInputAttemptWhenModalMessage())
  206431. return 0;
  206432. if (hasTitleBar())
  206433. {
  206434. if (isFullScreen())
  206435. {
  206436. setFullScreen (false);
  206437. return 0;
  206438. }
  206439. }
  206440. else
  206441. {
  206442. if (isMinimised())
  206443. setMinimised (false);
  206444. else if (isFullScreen())
  206445. setFullScreen (false);
  206446. return 0;
  206447. }
  206448. break;
  206449. }
  206450. break;
  206451. case WM_NCLBUTTONDOWN:
  206452. case WM_NCRBUTTONDOWN:
  206453. case WM_NCMBUTTONDOWN:
  206454. sendInputAttemptWhenModalMessage();
  206455. break;
  206456. //case WM_IME_STARTCOMPOSITION;
  206457. // return 0;
  206458. case WM_GETDLGCODE:
  206459. return DLGC_WANTALLKEYS;
  206460. default:
  206461. break;
  206462. }
  206463. }
  206464. return DefWindowProcW (h, message, wParam, lParam);
  206465. }
  206466. bool sendInputAttemptWhenModalMessage()
  206467. {
  206468. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206469. {
  206470. Component* const current = Component::getCurrentlyModalComponent();
  206471. if (current != 0)
  206472. current->inputAttemptWhenModal();
  206473. return true;
  206474. }
  206475. return false;
  206476. }
  206477. Win32ComponentPeer (const Win32ComponentPeer&);
  206478. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206479. };
  206480. ModifierKeys Win32ComponentPeer::currentModifiers;
  206481. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206482. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206483. {
  206484. return new Win32ComponentPeer (this, styleFlags);
  206485. }
  206486. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206487. void ModifierKeys::updateCurrentModifiers() throw()
  206488. {
  206489. currentModifiers = Win32ComponentPeer::currentModifiers;
  206490. }
  206491. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206492. {
  206493. Win32ComponentPeer::updateKeyModifiers();
  206494. int keyMods = 0;
  206495. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206496. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206497. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206498. Win32ComponentPeer::currentModifiers
  206499. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206500. return Win32ComponentPeer::currentModifiers;
  206501. }
  206502. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206503. {
  206504. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206505. if (wp != 0)
  206506. wp->setTaskBarIcon (newImage);
  206507. }
  206508. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206509. {
  206510. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206511. if (wp != 0)
  206512. wp->setTaskBarIconToolTip (tooltip);
  206513. }
  206514. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206515. {
  206516. DWORD val = GetWindowLong (h, styleType);
  206517. if (bitIsSet)
  206518. val |= feature;
  206519. else
  206520. val &= ~feature;
  206521. SetWindowLongPtr (h, styleType, val);
  206522. SetWindowPos (h, 0, 0, 0, 0, 0,
  206523. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206524. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206525. }
  206526. bool Process::isForegroundProcess()
  206527. {
  206528. HWND fg = GetForegroundWindow();
  206529. if (fg == 0)
  206530. return true;
  206531. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206532. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206533. // have to see if any of our windows are children of the foreground window
  206534. fg = GetAncestor (fg, GA_ROOT);
  206535. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206536. {
  206537. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206538. if (wp != 0 && wp->isInside (fg))
  206539. return true;
  206540. }
  206541. return false;
  206542. }
  206543. bool AlertWindow::showNativeDialogBox (const String& title,
  206544. const String& bodyText,
  206545. bool isOkCancel)
  206546. {
  206547. return MessageBox (0, bodyText, title,
  206548. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206549. : MB_OK)) == IDOK;
  206550. }
  206551. void Desktop::createMouseInputSources()
  206552. {
  206553. mouseSources.add (new MouseInputSource (0, true));
  206554. }
  206555. const Point<int> Desktop::getMousePosition()
  206556. {
  206557. POINT mousePos;
  206558. GetCursorPos (&mousePos);
  206559. return Point<int> (mousePos.x, mousePos.y);
  206560. }
  206561. void Desktop::setMousePosition (const Point<int>& newPosition)
  206562. {
  206563. SetCursorPos (newPosition.getX(), newPosition.getY());
  206564. }
  206565. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206566. {
  206567. return createSoftwareImage (format, width, height, clearImage);
  206568. }
  206569. class ScreenSaverDefeater : public Timer,
  206570. public DeletedAtShutdown
  206571. {
  206572. public:
  206573. ScreenSaverDefeater()
  206574. {
  206575. startTimer (10000);
  206576. timerCallback();
  206577. }
  206578. ~ScreenSaverDefeater() {}
  206579. void timerCallback()
  206580. {
  206581. if (Process::isForegroundProcess())
  206582. {
  206583. // simulate a shift key getting pressed..
  206584. INPUT input[2];
  206585. input[0].type = INPUT_KEYBOARD;
  206586. input[0].ki.wVk = VK_SHIFT;
  206587. input[0].ki.dwFlags = 0;
  206588. input[0].ki.dwExtraInfo = 0;
  206589. input[1].type = INPUT_KEYBOARD;
  206590. input[1].ki.wVk = VK_SHIFT;
  206591. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206592. input[1].ki.dwExtraInfo = 0;
  206593. SendInput (2, input, sizeof (INPUT));
  206594. }
  206595. }
  206596. };
  206597. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206598. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206599. {
  206600. if (isEnabled)
  206601. deleteAndZero (screenSaverDefeater);
  206602. else if (screenSaverDefeater == 0)
  206603. screenSaverDefeater = new ScreenSaverDefeater();
  206604. }
  206605. bool Desktop::isScreenSaverEnabled()
  206606. {
  206607. return screenSaverDefeater == 0;
  206608. }
  206609. /* (The code below is the "correct" way to disable the screen saver, but it
  206610. completely fails on winXP when the saver is password-protected...)
  206611. static bool juce_screenSaverEnabled = true;
  206612. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206613. {
  206614. juce_screenSaverEnabled = isEnabled;
  206615. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206616. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206617. }
  206618. bool Desktop::isScreenSaverEnabled() throw()
  206619. {
  206620. return juce_screenSaverEnabled;
  206621. }
  206622. */
  206623. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206624. {
  206625. if (enableOrDisable)
  206626. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206627. }
  206628. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206629. {
  206630. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206631. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206632. return TRUE;
  206633. }
  206634. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206635. {
  206636. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206637. // make sure the first in the list is the main monitor
  206638. for (int i = 1; i < monitorCoords.size(); ++i)
  206639. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206640. monitorCoords.swap (i, 0);
  206641. if (monitorCoords.size() == 0)
  206642. {
  206643. RECT r;
  206644. GetWindowRect (GetDesktopWindow(), &r);
  206645. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206646. }
  206647. if (clipToWorkArea)
  206648. {
  206649. // clip the main monitor to the active non-taskbar area
  206650. RECT r;
  206651. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206652. Rectangle<int>& screen = monitorCoords.getReference (0);
  206653. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206654. jmax (screen.getY(), (int) r.top));
  206655. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206656. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206657. }
  206658. }
  206659. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  206660. {
  206661. Image im;
  206662. if (bitmap != 0)
  206663. {
  206664. BITMAP bm;
  206665. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206666. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206667. {
  206668. HDC tempDC = GetDC (0);
  206669. HDC dc = CreateCompatibleDC (tempDC);
  206670. ReleaseDC (0, tempDC);
  206671. SelectObject (dc, bitmap);
  206672. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206673. Image::BitmapData imageData (im, true);
  206674. for (int y = bm.bmHeight; --y >= 0;)
  206675. {
  206676. for (int x = bm.bmWidth; --x >= 0;)
  206677. {
  206678. COLORREF col = GetPixel (dc, x, y);
  206679. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206680. (uint8) GetGValue (col),
  206681. (uint8) GetBValue (col)));
  206682. }
  206683. }
  206684. DeleteDC (dc);
  206685. }
  206686. }
  206687. return im;
  206688. }
  206689. static const Image createImageFromHICON (HICON icon)
  206690. {
  206691. ICONINFO info;
  206692. if (GetIconInfo (icon, &info))
  206693. {
  206694. Image mask (createImageFromHBITMAP (info.hbmMask));
  206695. Image image (createImageFromHBITMAP (info.hbmColor));
  206696. if (mask.isValid() && image.isValid())
  206697. {
  206698. for (int y = image.getHeight(); --y >= 0;)
  206699. {
  206700. for (int x = image.getWidth(); --x >= 0;)
  206701. {
  206702. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206703. if (brightness > 0.0f)
  206704. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206705. }
  206706. }
  206707. return image;
  206708. }
  206709. }
  206710. return Image::null;
  206711. }
  206712. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206713. {
  206714. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206715. Image bitmap (nativeBitmap);
  206716. {
  206717. Graphics g (bitmap);
  206718. g.drawImageAt (image, 0, 0);
  206719. }
  206720. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206721. ICONINFO info;
  206722. info.fIcon = isIcon;
  206723. info.xHotspot = hotspotX;
  206724. info.yHotspot = hotspotY;
  206725. info.hbmMask = mask;
  206726. info.hbmColor = nativeBitmap->hBitmap;
  206727. HICON hi = CreateIconIndirect (&info);
  206728. DeleteObject (mask);
  206729. return hi;
  206730. }
  206731. const Image juce_createIconForFile (const File& file)
  206732. {
  206733. Image image;
  206734. WCHAR filename [1024];
  206735. file.getFullPathName().copyToUnicode (filename, 1023);
  206736. WORD iconNum = 0;
  206737. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206738. filename, &iconNum);
  206739. if (icon != 0)
  206740. {
  206741. image = createImageFromHICON (icon);
  206742. DestroyIcon (icon);
  206743. }
  206744. return image;
  206745. }
  206746. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206747. {
  206748. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206749. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206750. Image im (image);
  206751. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206752. {
  206753. im = im.rescaled (maxW, maxH);
  206754. hotspotX = (hotspotX * maxW) / image.getWidth();
  206755. hotspotY = (hotspotY * maxH) / image.getHeight();
  206756. }
  206757. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206758. }
  206759. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206760. {
  206761. if (cursorHandle != 0 && ! isStandard)
  206762. DestroyCursor ((HCURSOR) cursorHandle);
  206763. }
  206764. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206765. {
  206766. LPCTSTR cursorName = IDC_ARROW;
  206767. switch (type)
  206768. {
  206769. case NormalCursor: break;
  206770. case NoCursor: return 0;
  206771. case WaitCursor: cursorName = IDC_WAIT; break;
  206772. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206773. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206774. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206775. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206776. case LeftRightResizeCursor:
  206777. case LeftEdgeResizeCursor:
  206778. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206779. case UpDownResizeCursor:
  206780. case TopEdgeResizeCursor:
  206781. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206782. case TopLeftCornerResizeCursor:
  206783. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206784. case TopRightCornerResizeCursor:
  206785. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206786. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206787. case DraggingHandCursor:
  206788. {
  206789. static void* dragHandCursor = 0;
  206790. if (dragHandCursor == 0)
  206791. {
  206792. static const unsigned char dragHandData[] =
  206793. { 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,
  206794. 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,
  206795. 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 };
  206796. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206797. }
  206798. return dragHandCursor;
  206799. }
  206800. default:
  206801. jassertfalse; break;
  206802. }
  206803. HCURSOR cursorH = LoadCursor (0, cursorName);
  206804. if (cursorH == 0)
  206805. cursorH = LoadCursor (0, IDC_ARROW);
  206806. return cursorH;
  206807. }
  206808. void MouseCursor::showInWindow (ComponentPeer*) const
  206809. {
  206810. SetCursor ((HCURSOR) getHandle());
  206811. }
  206812. void MouseCursor::showInAllWindows() const
  206813. {
  206814. showInWindow (0);
  206815. }
  206816. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206817. {
  206818. public:
  206819. JuceDropSource() {}
  206820. ~JuceDropSource() {}
  206821. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206822. {
  206823. if (escapePressed)
  206824. return DRAGDROP_S_CANCEL;
  206825. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206826. return DRAGDROP_S_DROP;
  206827. return S_OK;
  206828. }
  206829. HRESULT __stdcall GiveFeedback (DWORD)
  206830. {
  206831. return DRAGDROP_S_USEDEFAULTCURSORS;
  206832. }
  206833. };
  206834. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206835. {
  206836. public:
  206837. JuceEnumFormatEtc (const FORMATETC* const format_)
  206838. : format (format_),
  206839. index (0)
  206840. {
  206841. }
  206842. ~JuceEnumFormatEtc() {}
  206843. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206844. {
  206845. if (result == 0)
  206846. return E_POINTER;
  206847. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206848. newOne->index = index;
  206849. *result = newOne;
  206850. return S_OK;
  206851. }
  206852. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206853. {
  206854. if (pceltFetched != 0)
  206855. *pceltFetched = 0;
  206856. else if (celt != 1)
  206857. return S_FALSE;
  206858. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206859. {
  206860. copyFormatEtc (lpFormatEtc [0], *format);
  206861. ++index;
  206862. if (pceltFetched != 0)
  206863. *pceltFetched = 1;
  206864. return S_OK;
  206865. }
  206866. return S_FALSE;
  206867. }
  206868. HRESULT __stdcall Skip (ULONG celt)
  206869. {
  206870. if (index + (int) celt >= 1)
  206871. return S_FALSE;
  206872. index += celt;
  206873. return S_OK;
  206874. }
  206875. HRESULT __stdcall Reset()
  206876. {
  206877. index = 0;
  206878. return S_OK;
  206879. }
  206880. private:
  206881. const FORMATETC* const format;
  206882. int index;
  206883. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206884. {
  206885. dest = source;
  206886. if (source.ptd != 0)
  206887. {
  206888. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206889. *(dest.ptd) = *(source.ptd);
  206890. }
  206891. }
  206892. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206893. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206894. };
  206895. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206896. {
  206897. public:
  206898. JuceDataObject (JuceDropSource* const dropSource_,
  206899. const FORMATETC* const format_,
  206900. const STGMEDIUM* const medium_)
  206901. : dropSource (dropSource_),
  206902. format (format_),
  206903. medium (medium_)
  206904. {
  206905. }
  206906. virtual ~JuceDataObject()
  206907. {
  206908. jassert (refCount == 0);
  206909. }
  206910. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206911. {
  206912. if ((pFormatEtc->tymed & format->tymed) != 0
  206913. && pFormatEtc->cfFormat == format->cfFormat
  206914. && pFormatEtc->dwAspect == format->dwAspect)
  206915. {
  206916. pMedium->tymed = format->tymed;
  206917. pMedium->pUnkForRelease = 0;
  206918. if (format->tymed == TYMED_HGLOBAL)
  206919. {
  206920. const SIZE_T len = GlobalSize (medium->hGlobal);
  206921. void* const src = GlobalLock (medium->hGlobal);
  206922. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206923. memcpy (dst, src, len);
  206924. GlobalUnlock (medium->hGlobal);
  206925. pMedium->hGlobal = dst;
  206926. return S_OK;
  206927. }
  206928. }
  206929. return DV_E_FORMATETC;
  206930. }
  206931. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206932. {
  206933. if (f == 0)
  206934. return E_INVALIDARG;
  206935. if (f->tymed == format->tymed
  206936. && f->cfFormat == format->cfFormat
  206937. && f->dwAspect == format->dwAspect)
  206938. return S_OK;
  206939. return DV_E_FORMATETC;
  206940. }
  206941. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206942. {
  206943. pFormatEtcOut->ptd = 0;
  206944. return E_NOTIMPL;
  206945. }
  206946. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206947. {
  206948. if (result == 0)
  206949. return E_POINTER;
  206950. if (direction == DATADIR_GET)
  206951. {
  206952. *result = new JuceEnumFormatEtc (format);
  206953. return S_OK;
  206954. }
  206955. *result = 0;
  206956. return E_NOTIMPL;
  206957. }
  206958. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206959. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206960. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206961. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206962. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206963. private:
  206964. JuceDropSource* const dropSource;
  206965. const FORMATETC* const format;
  206966. const STGMEDIUM* const medium;
  206967. JuceDataObject (const JuceDataObject&);
  206968. JuceDataObject& operator= (const JuceDataObject&);
  206969. };
  206970. static HDROP createHDrop (const StringArray& fileNames)
  206971. {
  206972. int totalChars = 0;
  206973. for (int i = fileNames.size(); --i >= 0;)
  206974. totalChars += fileNames[i].length() + 1;
  206975. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206976. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  206977. if (hDrop != 0)
  206978. {
  206979. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206980. pDropFiles->pFiles = sizeof (DROPFILES);
  206981. pDropFiles->fWide = true;
  206982. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206983. for (int i = 0; i < fileNames.size(); ++i)
  206984. {
  206985. fileNames[i].copyToUnicode (fname, 2048);
  206986. fname += fileNames[i].length() + 1;
  206987. }
  206988. *fname = 0;
  206989. GlobalUnlock (hDrop);
  206990. }
  206991. return hDrop;
  206992. }
  206993. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  206994. {
  206995. JuceDropSource* const source = new JuceDropSource();
  206996. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206997. DWORD effect;
  206998. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206999. data->Release();
  207000. source->Release();
  207001. return res == DRAGDROP_S_DROP;
  207002. }
  207003. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  207004. {
  207005. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207006. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207007. medium.hGlobal = createHDrop (files);
  207008. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  207009. : DROPEFFECT_COPY);
  207010. }
  207011. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  207012. {
  207013. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207014. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207015. const int numChars = text.length();
  207016. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  207017. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  207018. text.copyToUnicode (data, numChars + 1);
  207019. format.cfFormat = CF_UNICODETEXT;
  207020. GlobalUnlock (medium.hGlobal);
  207021. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  207022. }
  207023. #endif
  207024. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  207025. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  207026. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207027. // compiled on its own).
  207028. #if JUCE_INCLUDED_FILE
  207029. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  207030. NEWTEXTMETRICEXW*,
  207031. int type,
  207032. LPARAM lParam)
  207033. {
  207034. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  207035. {
  207036. const String fontName (lpelfe->elfLogFont.lfFaceName);
  207037. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  207038. }
  207039. return 1;
  207040. }
  207041. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  207042. NEWTEXTMETRICEXW*,
  207043. int type,
  207044. LPARAM lParam)
  207045. {
  207046. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  207047. {
  207048. LOGFONTW lf;
  207049. zerostruct (lf);
  207050. lf.lfWeight = FW_DONTCARE;
  207051. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207052. lf.lfQuality = DEFAULT_QUALITY;
  207053. lf.lfCharSet = DEFAULT_CHARSET;
  207054. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207055. lf.lfPitchAndFamily = FF_DONTCARE;
  207056. const String fontName (lpelfe->elfLogFont.lfFaceName);
  207057. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  207058. HDC dc = CreateCompatibleDC (0);
  207059. EnumFontFamiliesEx (dc, &lf,
  207060. (FONTENUMPROCW) &wfontEnum2,
  207061. lParam, 0);
  207062. DeleteDC (dc);
  207063. }
  207064. return 1;
  207065. }
  207066. const StringArray Font::findAllTypefaceNames()
  207067. {
  207068. StringArray results;
  207069. HDC dc = CreateCompatibleDC (0);
  207070. {
  207071. LOGFONTW lf;
  207072. zerostruct (lf);
  207073. lf.lfWeight = FW_DONTCARE;
  207074. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207075. lf.lfQuality = DEFAULT_QUALITY;
  207076. lf.lfCharSet = DEFAULT_CHARSET;
  207077. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207078. lf.lfPitchAndFamily = FF_DONTCARE;
  207079. lf.lfFaceName[0] = 0;
  207080. EnumFontFamiliesEx (dc, &lf,
  207081. (FONTENUMPROCW) &wfontEnum1,
  207082. (LPARAM) &results, 0);
  207083. }
  207084. DeleteDC (dc);
  207085. results.sort (true);
  207086. return results;
  207087. }
  207088. extern bool juce_IsRunningInWine();
  207089. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  207090. {
  207091. if (juce_IsRunningInWine())
  207092. {
  207093. // If we're running in Wine, then use fonts that might be available on Linux..
  207094. defaultSans = "Bitstream Vera Sans";
  207095. defaultSerif = "Bitstream Vera Serif";
  207096. defaultFixed = "Bitstream Vera Sans Mono";
  207097. }
  207098. else
  207099. {
  207100. defaultSans = "Verdana";
  207101. defaultSerif = "Times";
  207102. defaultFixed = "Lucida Console";
  207103. }
  207104. }
  207105. class FontDCHolder : private DeletedAtShutdown
  207106. {
  207107. public:
  207108. FontDCHolder()
  207109. : dc (0), numKPs (0), size (0),
  207110. bold (false), italic (false)
  207111. {
  207112. }
  207113. ~FontDCHolder()
  207114. {
  207115. if (dc != 0)
  207116. {
  207117. DeleteDC (dc);
  207118. DeleteObject (fontH);
  207119. }
  207120. clearSingletonInstance();
  207121. }
  207122. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  207123. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  207124. {
  207125. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  207126. {
  207127. fontName = fontName_;
  207128. bold = bold_;
  207129. italic = italic_;
  207130. size = size_;
  207131. if (dc != 0)
  207132. {
  207133. DeleteDC (dc);
  207134. DeleteObject (fontH);
  207135. kps.free();
  207136. }
  207137. fontH = 0;
  207138. dc = CreateCompatibleDC (0);
  207139. SetMapperFlags (dc, 0);
  207140. SetMapMode (dc, MM_TEXT);
  207141. LOGFONTW lfw;
  207142. zerostruct (lfw);
  207143. lfw.lfCharSet = DEFAULT_CHARSET;
  207144. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207145. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207146. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  207147. lfw.lfQuality = PROOF_QUALITY;
  207148. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  207149. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  207150. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  207151. lfw.lfHeight = size > 0 ? size : -256;
  207152. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  207153. if (standardSizedFont != 0)
  207154. {
  207155. if (SelectObject (dc, standardSizedFont) != 0)
  207156. {
  207157. fontH = standardSizedFont;
  207158. if (size == 0)
  207159. {
  207160. OUTLINETEXTMETRIC otm;
  207161. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  207162. {
  207163. lfw.lfHeight = -(int) otm.otmEMSquare;
  207164. fontH = CreateFontIndirect (&lfw);
  207165. SelectObject (dc, fontH);
  207166. DeleteObject (standardSizedFont);
  207167. }
  207168. }
  207169. }
  207170. else
  207171. {
  207172. jassertfalse;
  207173. }
  207174. }
  207175. else
  207176. {
  207177. jassertfalse;
  207178. }
  207179. }
  207180. return dc;
  207181. }
  207182. KERNINGPAIR* getKerningPairs (int& numKPs_)
  207183. {
  207184. if (kps == 0)
  207185. {
  207186. numKPs = GetKerningPairs (dc, 0, 0);
  207187. kps.calloc (numKPs);
  207188. GetKerningPairs (dc, numKPs, kps);
  207189. }
  207190. numKPs_ = numKPs;
  207191. return kps;
  207192. }
  207193. private:
  207194. HFONT fontH;
  207195. HDC dc;
  207196. String fontName;
  207197. HeapBlock <KERNINGPAIR> kps;
  207198. int numKPs, size;
  207199. bool bold, italic;
  207200. FontDCHolder (const FontDCHolder&);
  207201. FontDCHolder& operator= (const FontDCHolder&);
  207202. };
  207203. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  207204. class WindowsTypeface : public CustomTypeface
  207205. {
  207206. public:
  207207. WindowsTypeface (const Font& font)
  207208. {
  207209. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  207210. font.isBold(), font.isItalic(), 0);
  207211. TEXTMETRIC tm;
  207212. tm.tmAscent = tm.tmHeight = 1;
  207213. tm.tmDefaultChar = 0;
  207214. GetTextMetrics (dc, &tm);
  207215. setCharacteristics (font.getTypefaceName(),
  207216. tm.tmAscent / (float) tm.tmHeight,
  207217. font.isBold(), font.isItalic(),
  207218. tm.tmDefaultChar);
  207219. }
  207220. bool loadGlyphIfPossible (juce_wchar character)
  207221. {
  207222. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  207223. GLYPHMETRICS gm;
  207224. {
  207225. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  207226. WORD index = 0;
  207227. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  207228. && index == 0xffff)
  207229. {
  207230. return false;
  207231. }
  207232. }
  207233. Path glyphPath;
  207234. TEXTMETRIC tm;
  207235. if (! GetTextMetrics (dc, &tm))
  207236. {
  207237. addGlyph (character, glyphPath, 0);
  207238. return true;
  207239. }
  207240. const float height = (float) tm.tmHeight;
  207241. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  207242. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  207243. &gm, 0, 0, &identityMatrix);
  207244. if (bufSize > 0)
  207245. {
  207246. HeapBlock<char> data (bufSize);
  207247. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  207248. bufSize, data, &identityMatrix);
  207249. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  207250. const float scaleX = 1.0f / height;
  207251. const float scaleY = -1.0f / height;
  207252. while ((char*) pheader < data + bufSize)
  207253. {
  207254. float x = scaleX * pheader->pfxStart.x.value;
  207255. float y = scaleY * pheader->pfxStart.y.value;
  207256. glyphPath.startNewSubPath (x, y);
  207257. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  207258. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  207259. while ((const char*) curve < curveEnd)
  207260. {
  207261. if (curve->wType == TT_PRIM_LINE)
  207262. {
  207263. for (int i = 0; i < curve->cpfx; ++i)
  207264. {
  207265. x = scaleX * curve->apfx[i].x.value;
  207266. y = scaleY * curve->apfx[i].y.value;
  207267. glyphPath.lineTo (x, y);
  207268. }
  207269. }
  207270. else if (curve->wType == TT_PRIM_QSPLINE)
  207271. {
  207272. for (int i = 0; i < curve->cpfx - 1; ++i)
  207273. {
  207274. const float x2 = scaleX * curve->apfx[i].x.value;
  207275. const float y2 = scaleY * curve->apfx[i].y.value;
  207276. float x3, y3;
  207277. if (i < curve->cpfx - 2)
  207278. {
  207279. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  207280. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  207281. }
  207282. else
  207283. {
  207284. x3 = scaleX * curve->apfx[i + 1].x.value;
  207285. y3 = scaleY * curve->apfx[i + 1].y.value;
  207286. }
  207287. glyphPath.quadraticTo (x2, y2, x3, y3);
  207288. x = x3;
  207289. y = y3;
  207290. }
  207291. }
  207292. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  207293. }
  207294. pheader = (const TTPOLYGONHEADER*) curve;
  207295. glyphPath.closeSubPath();
  207296. }
  207297. }
  207298. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  207299. int numKPs;
  207300. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  207301. for (int i = 0; i < numKPs; ++i)
  207302. {
  207303. if (kps[i].wFirst == character)
  207304. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  207305. kps[i].iKernAmount / height);
  207306. }
  207307. return true;
  207308. }
  207309. juce_UseDebuggingNewOperator
  207310. };
  207311. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  207312. {
  207313. return new WindowsTypeface (font);
  207314. }
  207315. #endif
  207316. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  207317. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  207318. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207319. // compiled on its own).
  207320. #if JUCE_INCLUDED_FILE
  207321. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  207322. namespace FileChooserHelpers
  207323. {
  207324. static const void* defaultDirPath = 0;
  207325. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  207326. static Component* currentExtraFileWin = 0;
  207327. static bool areThereAnyAlwaysOnTopWindows()
  207328. {
  207329. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  207330. {
  207331. Component* c = Desktop::getInstance().getComponent (i);
  207332. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  207333. return true;
  207334. }
  207335. return false;
  207336. }
  207337. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  207338. {
  207339. if (msg == BFFM_INITIALIZED)
  207340. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  207341. else if (msg == BFFM_VALIDATEFAILEDW)
  207342. returnedString = (LPCWSTR) lParam;
  207343. else if (msg == BFFM_VALIDATEFAILEDA)
  207344. returnedString = (const char*) lParam;
  207345. return 0;
  207346. }
  207347. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  207348. {
  207349. if (currentExtraFileWin != 0)
  207350. {
  207351. if (uiMsg == WM_INITDIALOG)
  207352. {
  207353. HWND dialogH = GetParent (hdlg);
  207354. jassert (dialogH != 0);
  207355. if (dialogH == 0)
  207356. dialogH = hdlg;
  207357. RECT r, cr;
  207358. GetWindowRect (dialogH, &r);
  207359. GetClientRect (dialogH, &cr);
  207360. SetWindowPos (dialogH, 0,
  207361. r.left, r.top,
  207362. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  207363. jmax (150, (int) (r.bottom - r.top)),
  207364. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  207365. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  207366. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  207367. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  207368. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  207369. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  207370. }
  207371. else if (uiMsg == WM_NOTIFY)
  207372. {
  207373. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  207374. if (ofn->hdr.code == CDN_SELCHANGE)
  207375. {
  207376. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  207377. if (comp != 0)
  207378. {
  207379. TCHAR path [MAX_PATH * 2];
  207380. path[0] = 0;
  207381. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  207382. const String fn ((const WCHAR*) path);
  207383. comp->selectedFileChanged (File (fn));
  207384. }
  207385. }
  207386. }
  207387. }
  207388. return 0;
  207389. }
  207390. class FPComponentHolder : public Component
  207391. {
  207392. public:
  207393. FPComponentHolder()
  207394. {
  207395. setVisible (true);
  207396. setOpaque (true);
  207397. }
  207398. ~FPComponentHolder()
  207399. {
  207400. }
  207401. void paint (Graphics& g)
  207402. {
  207403. g.fillAll (Colours::lightgrey);
  207404. }
  207405. private:
  207406. FPComponentHolder (const FPComponentHolder&);
  207407. FPComponentHolder& operator= (const FPComponentHolder&);
  207408. };
  207409. }
  207410. void FileChooser::showPlatformDialog (Array<File>& results,
  207411. const String& title,
  207412. const File& currentFileOrDirectory,
  207413. const String& filter,
  207414. bool selectsDirectory,
  207415. bool /*selectsFiles*/,
  207416. bool isSaveDialogue,
  207417. bool warnAboutOverwritingExistingFiles,
  207418. bool selectMultipleFiles,
  207419. FilePreviewComponent* extraInfoComponent)
  207420. {
  207421. using namespace FileChooserHelpers;
  207422. const int numCharsAvailable = 32768;
  207423. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  207424. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  207425. int fnameIdx = 0;
  207426. JUCE_TRY
  207427. {
  207428. // use a modal window as the parent for this dialog box
  207429. // to block input from other app windows
  207430. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  207431. Component w (String::empty);
  207432. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  207433. mainMon.getY() + mainMon.getHeight() / 4,
  207434. 0, 0);
  207435. w.setOpaque (true);
  207436. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  207437. w.addToDesktop (0);
  207438. if (extraInfoComponent == 0)
  207439. w.enterModalState();
  207440. String initialDir;
  207441. if (currentFileOrDirectory.isDirectory())
  207442. {
  207443. initialDir = currentFileOrDirectory.getFullPathName();
  207444. }
  207445. else
  207446. {
  207447. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  207448. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  207449. }
  207450. if (currentExtraFileWin->isValidComponent())
  207451. {
  207452. jassertfalse;
  207453. return;
  207454. }
  207455. if (selectsDirectory)
  207456. {
  207457. LPITEMIDLIST list = 0;
  207458. filenameSpace.fillWith (0);
  207459. {
  207460. BROWSEINFO bi;
  207461. zerostruct (bi);
  207462. bi.hwndOwner = (HWND) w.getWindowHandle();
  207463. bi.pszDisplayName = fname;
  207464. bi.lpszTitle = title;
  207465. bi.lpfn = browseCallbackProc;
  207466. #ifdef BIF_USENEWUI
  207467. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  207468. #else
  207469. bi.ulFlags = 0x50;
  207470. #endif
  207471. defaultDirPath = (const WCHAR*) initialDir;
  207472. list = SHBrowseForFolder (&bi);
  207473. if (! SHGetPathFromIDListW (list, fname))
  207474. {
  207475. fname[0] = 0;
  207476. returnedString = String::empty;
  207477. }
  207478. }
  207479. LPMALLOC al;
  207480. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207481. al->Free (list);
  207482. defaultDirPath = 0;
  207483. if (returnedString.isNotEmpty())
  207484. {
  207485. const String stringFName (fname);
  207486. results.add (File (stringFName).getSiblingFile (returnedString));
  207487. returnedString = String::empty;
  207488. return;
  207489. }
  207490. }
  207491. else
  207492. {
  207493. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207494. if (warnAboutOverwritingExistingFiles)
  207495. flags |= OFN_OVERWRITEPROMPT;
  207496. if (selectMultipleFiles)
  207497. flags |= OFN_ALLOWMULTISELECT;
  207498. if (extraInfoComponent != 0)
  207499. {
  207500. flags |= OFN_ENABLEHOOK;
  207501. currentExtraFileWin = new FPComponentHolder();
  207502. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207503. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207504. extraInfoComponent->getHeight());
  207505. currentExtraFileWin->addToDesktop (0);
  207506. currentExtraFileWin->enterModalState();
  207507. }
  207508. {
  207509. WCHAR filters [1024];
  207510. zeromem (filters, sizeof (filters));
  207511. filter.copyToUnicode (filters, 1024);
  207512. filter.copyToUnicode (filters + filter.length() + 1,
  207513. 1022 - filter.length());
  207514. OPENFILENAMEW of;
  207515. zerostruct (of);
  207516. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207517. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207518. #else
  207519. of.lStructSize = sizeof (of);
  207520. #endif
  207521. of.hwndOwner = (HWND) w.getWindowHandle();
  207522. of.lpstrFilter = filters;
  207523. of.nFilterIndex = 1;
  207524. of.lpstrFile = fname;
  207525. of.nMaxFile = numCharsAvailable;
  207526. of.lpstrInitialDir = initialDir;
  207527. of.lpstrTitle = title;
  207528. of.Flags = flags;
  207529. if (extraInfoComponent != 0)
  207530. of.lpfnHook = &openCallback;
  207531. if (isSaveDialogue)
  207532. {
  207533. if (! GetSaveFileName (&of))
  207534. fname[0] = 0;
  207535. else
  207536. fnameIdx = of.nFileOffset;
  207537. }
  207538. else
  207539. {
  207540. if (! GetOpenFileName (&of))
  207541. fname[0] = 0;
  207542. else
  207543. fnameIdx = of.nFileOffset;
  207544. }
  207545. }
  207546. }
  207547. }
  207548. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207549. catch (...)
  207550. {
  207551. fname[0] = 0;
  207552. }
  207553. #endif
  207554. deleteAndZero (currentExtraFileWin);
  207555. const WCHAR* const files = fname;
  207556. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207557. {
  207558. const WCHAR* filename = files + fnameIdx;
  207559. while (*filename != 0)
  207560. {
  207561. const String filepath (String (files) + "\\" + String (filename));
  207562. results.add (File (filepath));
  207563. filename += CharacterFunctions::length (filename) + 1;
  207564. }
  207565. }
  207566. else if (files[0] != 0)
  207567. {
  207568. results.add (File (files));
  207569. }
  207570. }
  207571. #endif
  207572. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207573. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207574. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207575. // compiled on its own).
  207576. #if JUCE_INCLUDED_FILE
  207577. void SystemClipboard::copyTextToClipboard (const String& text)
  207578. {
  207579. if (OpenClipboard (0) != 0)
  207580. {
  207581. if (EmptyClipboard() != 0)
  207582. {
  207583. const int len = text.length();
  207584. if (len > 0)
  207585. {
  207586. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207587. (len + 1) * sizeof (wchar_t));
  207588. if (bufH != 0)
  207589. {
  207590. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207591. text.copyToUnicode (data, len);
  207592. GlobalUnlock (bufH);
  207593. SetClipboardData (CF_UNICODETEXT, bufH);
  207594. }
  207595. }
  207596. }
  207597. CloseClipboard();
  207598. }
  207599. }
  207600. const String SystemClipboard::getTextFromClipboard()
  207601. {
  207602. String result;
  207603. if (OpenClipboard (0) != 0)
  207604. {
  207605. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207606. if (bufH != 0)
  207607. {
  207608. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207609. if (data != 0)
  207610. {
  207611. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207612. GlobalUnlock (bufH);
  207613. }
  207614. }
  207615. CloseClipboard();
  207616. }
  207617. return result;
  207618. }
  207619. #endif
  207620. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207621. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207622. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207623. // compiled on its own).
  207624. #if JUCE_INCLUDED_FILE
  207625. namespace ActiveXHelpers
  207626. {
  207627. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207628. {
  207629. public:
  207630. JuceIStorage() {}
  207631. ~JuceIStorage() {}
  207632. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207633. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207634. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207635. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207636. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207637. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207638. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207639. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207640. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207641. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207642. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207643. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207644. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207645. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207646. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207647. juce_UseDebuggingNewOperator
  207648. };
  207649. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207650. {
  207651. HWND window;
  207652. public:
  207653. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207654. ~JuceOleInPlaceFrame() {}
  207655. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207656. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207657. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207658. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207659. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207660. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207661. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207662. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207663. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207664. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207665. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207666. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207667. juce_UseDebuggingNewOperator
  207668. };
  207669. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207670. {
  207671. HWND window;
  207672. JuceOleInPlaceFrame* frame;
  207673. public:
  207674. JuceIOleInPlaceSite (HWND window_)
  207675. : window (window_),
  207676. frame (new JuceOleInPlaceFrame (window))
  207677. {}
  207678. ~JuceIOleInPlaceSite()
  207679. {
  207680. frame->Release();
  207681. }
  207682. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207683. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207684. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207685. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207686. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207687. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207688. {
  207689. *lplpFrame = frame;
  207690. *lplpDoc = 0;
  207691. lpFrameInfo->fMDIApp = FALSE;
  207692. lpFrameInfo->hwndFrame = window;
  207693. lpFrameInfo->haccel = 0;
  207694. lpFrameInfo->cAccelEntries = 0;
  207695. return S_OK;
  207696. }
  207697. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207698. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207699. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207700. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207701. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207702. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207703. juce_UseDebuggingNewOperator
  207704. };
  207705. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207706. {
  207707. JuceIOleInPlaceSite* inplaceSite;
  207708. public:
  207709. JuceIOleClientSite (HWND window)
  207710. : inplaceSite (new JuceIOleInPlaceSite (window))
  207711. {}
  207712. ~JuceIOleClientSite()
  207713. {
  207714. inplaceSite->Release();
  207715. }
  207716. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207717. {
  207718. if (type == IID_IOleInPlaceSite)
  207719. {
  207720. inplaceSite->AddRef();
  207721. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207722. return S_OK;
  207723. }
  207724. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207725. }
  207726. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207727. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207728. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207729. HRESULT __stdcall ShowObject() { return S_OK; }
  207730. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207731. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207732. juce_UseDebuggingNewOperator
  207733. };
  207734. static Array<ActiveXControlComponent*> activeXComps;
  207735. static HWND getHWND (const ActiveXControlComponent* const component)
  207736. {
  207737. HWND hwnd = 0;
  207738. const IID iid = IID_IOleWindow;
  207739. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207740. if (window != 0)
  207741. {
  207742. window->GetWindow (&hwnd);
  207743. window->Release();
  207744. }
  207745. return hwnd;
  207746. }
  207747. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207748. {
  207749. RECT activeXRect, peerRect;
  207750. GetWindowRect (hwnd, &activeXRect);
  207751. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207752. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207753. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207754. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207755. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207756. switch (message)
  207757. {
  207758. case WM_MOUSEMOVE:
  207759. case WM_LBUTTONDOWN:
  207760. case WM_MBUTTONDOWN:
  207761. case WM_RBUTTONDOWN:
  207762. case WM_LBUTTONUP:
  207763. case WM_MBUTTONUP:
  207764. case WM_RBUTTONUP:
  207765. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207766. break;
  207767. default:
  207768. break;
  207769. }
  207770. }
  207771. }
  207772. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207773. {
  207774. ActiveXControlComponent* const owner;
  207775. bool wasShowing;
  207776. public:
  207777. HWND controlHWND;
  207778. IStorage* storage;
  207779. IOleClientSite* clientSite;
  207780. IOleObject* control;
  207781. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207782. : ComponentMovementWatcher (owner_),
  207783. owner (owner_),
  207784. wasShowing (owner_ != 0 && owner_->isShowing()),
  207785. controlHWND (0),
  207786. storage (new ActiveXHelpers::JuceIStorage()),
  207787. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207788. control (0)
  207789. {
  207790. }
  207791. ~Pimpl()
  207792. {
  207793. if (control != 0)
  207794. {
  207795. control->Close (OLECLOSE_NOSAVE);
  207796. control->Release();
  207797. }
  207798. clientSite->Release();
  207799. storage->Release();
  207800. }
  207801. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207802. {
  207803. Component* const topComp = owner->getTopLevelComponent();
  207804. if (topComp->getPeer() != 0)
  207805. {
  207806. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207807. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207808. }
  207809. }
  207810. void componentPeerChanged()
  207811. {
  207812. const bool isShowingNow = owner->isShowing();
  207813. if (wasShowing != isShowingNow)
  207814. {
  207815. wasShowing = isShowingNow;
  207816. owner->setControlVisible (isShowingNow);
  207817. }
  207818. componentMovedOrResized (true, true);
  207819. }
  207820. void componentVisibilityChanged (Component&)
  207821. {
  207822. componentPeerChanged();
  207823. }
  207824. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207825. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207826. {
  207827. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207828. {
  207829. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207830. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207831. {
  207832. switch (message)
  207833. {
  207834. case WM_MOUSEMOVE:
  207835. case WM_LBUTTONDOWN:
  207836. case WM_MBUTTONDOWN:
  207837. case WM_RBUTTONDOWN:
  207838. case WM_LBUTTONUP:
  207839. case WM_MBUTTONUP:
  207840. case WM_RBUTTONUP:
  207841. case WM_LBUTTONDBLCLK:
  207842. case WM_MBUTTONDBLCLK:
  207843. case WM_RBUTTONDBLCLK:
  207844. if (ax->isShowing())
  207845. {
  207846. ComponentPeer* const peer = ax->getPeer();
  207847. if (peer != 0)
  207848. {
  207849. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207850. if (! ax->areMouseEventsAllowed())
  207851. return 0;
  207852. }
  207853. }
  207854. break;
  207855. default:
  207856. break;
  207857. }
  207858. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207859. }
  207860. }
  207861. return DefWindowProc (hwnd, message, wParam, lParam);
  207862. }
  207863. };
  207864. ActiveXControlComponent::ActiveXControlComponent()
  207865. : originalWndProc (0),
  207866. mouseEventsAllowed (true)
  207867. {
  207868. ActiveXHelpers::activeXComps.add (this);
  207869. }
  207870. ActiveXControlComponent::~ActiveXControlComponent()
  207871. {
  207872. deleteControl();
  207873. ActiveXHelpers::activeXComps.removeValue (this);
  207874. }
  207875. void ActiveXControlComponent::paint (Graphics& g)
  207876. {
  207877. if (control == 0)
  207878. g.fillAll (Colours::lightgrey);
  207879. }
  207880. bool ActiveXControlComponent::createControl (const void* controlIID)
  207881. {
  207882. deleteControl();
  207883. ComponentPeer* const peer = getPeer();
  207884. // the component must have already been added to a real window when you call this!
  207885. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207886. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207887. {
  207888. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207889. HWND hwnd = (HWND) peer->getNativeHandle();
  207890. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207891. HRESULT hr;
  207892. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207893. newControl->clientSite, newControl->storage,
  207894. (void**) &(newControl->control))) == S_OK)
  207895. {
  207896. newControl->control->SetHostNames (L"Juce", 0);
  207897. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207898. {
  207899. RECT rect;
  207900. rect.left = pos.getX();
  207901. rect.top = pos.getY();
  207902. rect.right = pos.getX() + getWidth();
  207903. rect.bottom = pos.getY() + getHeight();
  207904. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207905. {
  207906. control = newControl;
  207907. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207908. control->controlHWND = ActiveXHelpers::getHWND (this);
  207909. if (control->controlHWND != 0)
  207910. {
  207911. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207912. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207913. }
  207914. return true;
  207915. }
  207916. }
  207917. }
  207918. }
  207919. return false;
  207920. }
  207921. void ActiveXControlComponent::deleteControl()
  207922. {
  207923. control = 0;
  207924. originalWndProc = 0;
  207925. }
  207926. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207927. {
  207928. void* result = 0;
  207929. if (control != 0 && control->control != 0
  207930. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207931. return result;
  207932. return 0;
  207933. }
  207934. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207935. {
  207936. if (control->controlHWND != 0)
  207937. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207938. }
  207939. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207940. {
  207941. if (control->controlHWND != 0)
  207942. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207943. }
  207944. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207945. {
  207946. mouseEventsAllowed = eventsCanReachControl;
  207947. }
  207948. #endif
  207949. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207950. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207951. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207952. // compiled on its own).
  207953. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207954. using namespace QTOLibrary;
  207955. using namespace QTOControlLib;
  207956. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207957. static bool isQTAvailable = false;
  207958. class QuickTimeMovieComponent::Pimpl
  207959. {
  207960. public:
  207961. Pimpl() : dataHandle (0)
  207962. {
  207963. }
  207964. ~Pimpl()
  207965. {
  207966. clearHandle();
  207967. }
  207968. void clearHandle()
  207969. {
  207970. if (dataHandle != 0)
  207971. {
  207972. DisposeHandle (dataHandle);
  207973. dataHandle = 0;
  207974. }
  207975. }
  207976. IQTControlPtr qtControl;
  207977. IQTMoviePtr qtMovie;
  207978. Handle dataHandle;
  207979. };
  207980. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207981. : movieLoaded (false),
  207982. controllerVisible (true)
  207983. {
  207984. pimpl = new Pimpl();
  207985. setMouseEventsAllowed (false);
  207986. }
  207987. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207988. {
  207989. closeMovie();
  207990. pimpl->qtControl = 0;
  207991. deleteControl();
  207992. pimpl = 0;
  207993. }
  207994. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207995. {
  207996. if (! isQTAvailable)
  207997. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207998. return isQTAvailable;
  207999. }
  208000. void QuickTimeMovieComponent::createControlIfNeeded()
  208001. {
  208002. if (isShowing() && ! isControlCreated())
  208003. {
  208004. const IID qtIID = __uuidof (QTControl);
  208005. if (createControl (&qtIID))
  208006. {
  208007. const IID qtInterfaceIID = __uuidof (IQTControl);
  208008. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  208009. if (pimpl->qtControl != 0)
  208010. {
  208011. pimpl->qtControl->Release(); // it has one ref too many at this point
  208012. pimpl->qtControl->QuickTimeInitialize();
  208013. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  208014. if (movieFile != File::nonexistent)
  208015. loadMovie (movieFile, controllerVisible);
  208016. }
  208017. }
  208018. }
  208019. }
  208020. bool QuickTimeMovieComponent::isControlCreated() const
  208021. {
  208022. return isControlOpen();
  208023. }
  208024. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  208025. const bool isControllerVisible)
  208026. {
  208027. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  208028. movieFile = File::nonexistent;
  208029. movieLoaded = false;
  208030. pimpl->qtMovie = 0;
  208031. controllerVisible = isControllerVisible;
  208032. createControlIfNeeded();
  208033. if (isControlCreated())
  208034. {
  208035. if (pimpl->qtControl != 0)
  208036. {
  208037. pimpl->qtControl->Put_MovieHandle (0);
  208038. pimpl->clearHandle();
  208039. Movie movie;
  208040. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  208041. {
  208042. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  208043. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  208044. if (pimpl->qtMovie != 0)
  208045. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  208046. : qtMovieControllerTypeNone);
  208047. }
  208048. if (movie == 0)
  208049. pimpl->clearHandle();
  208050. }
  208051. movieLoaded = (pimpl->qtMovie != 0);
  208052. }
  208053. else
  208054. {
  208055. // You're trying to open a movie when the control hasn't yet been created, probably because
  208056. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  208057. jassertfalse;
  208058. }
  208059. return movieLoaded;
  208060. }
  208061. void QuickTimeMovieComponent::closeMovie()
  208062. {
  208063. stop();
  208064. movieFile = File::nonexistent;
  208065. movieLoaded = false;
  208066. pimpl->qtMovie = 0;
  208067. if (pimpl->qtControl != 0)
  208068. pimpl->qtControl->Put_MovieHandle (0);
  208069. pimpl->clearHandle();
  208070. }
  208071. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  208072. {
  208073. return movieFile;
  208074. }
  208075. bool QuickTimeMovieComponent::isMovieOpen() const
  208076. {
  208077. return movieLoaded;
  208078. }
  208079. double QuickTimeMovieComponent::getMovieDuration() const
  208080. {
  208081. if (pimpl->qtMovie != 0)
  208082. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  208083. return 0.0;
  208084. }
  208085. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  208086. {
  208087. if (pimpl->qtMovie != 0)
  208088. {
  208089. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  208090. width = r.right - r.left;
  208091. height = r.bottom - r.top;
  208092. }
  208093. else
  208094. {
  208095. width = height = 0;
  208096. }
  208097. }
  208098. void QuickTimeMovieComponent::play()
  208099. {
  208100. if (pimpl->qtMovie != 0)
  208101. pimpl->qtMovie->Play();
  208102. }
  208103. void QuickTimeMovieComponent::stop()
  208104. {
  208105. if (pimpl->qtMovie != 0)
  208106. pimpl->qtMovie->Stop();
  208107. }
  208108. bool QuickTimeMovieComponent::isPlaying() const
  208109. {
  208110. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  208111. }
  208112. void QuickTimeMovieComponent::setPosition (const double seconds)
  208113. {
  208114. if (pimpl->qtMovie != 0)
  208115. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  208116. }
  208117. double QuickTimeMovieComponent::getPosition() const
  208118. {
  208119. if (pimpl->qtMovie != 0)
  208120. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  208121. return 0.0;
  208122. }
  208123. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  208124. {
  208125. if (pimpl->qtMovie != 0)
  208126. pimpl->qtMovie->PutRate (newSpeed);
  208127. }
  208128. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  208129. {
  208130. if (pimpl->qtMovie != 0)
  208131. {
  208132. pimpl->qtMovie->PutAudioVolume (newVolume);
  208133. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  208134. }
  208135. }
  208136. float QuickTimeMovieComponent::getMovieVolume() const
  208137. {
  208138. if (pimpl->qtMovie != 0)
  208139. return pimpl->qtMovie->GetAudioVolume();
  208140. return 0.0f;
  208141. }
  208142. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  208143. {
  208144. if (pimpl->qtMovie != 0)
  208145. pimpl->qtMovie->PutLoop (shouldLoop);
  208146. }
  208147. bool QuickTimeMovieComponent::isLooping() const
  208148. {
  208149. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  208150. }
  208151. bool QuickTimeMovieComponent::isControllerVisible() const
  208152. {
  208153. return controllerVisible;
  208154. }
  208155. void QuickTimeMovieComponent::parentHierarchyChanged()
  208156. {
  208157. createControlIfNeeded();
  208158. QTCompBaseClass::parentHierarchyChanged();
  208159. }
  208160. void QuickTimeMovieComponent::visibilityChanged()
  208161. {
  208162. createControlIfNeeded();
  208163. QTCompBaseClass::visibilityChanged();
  208164. }
  208165. void QuickTimeMovieComponent::paint (Graphics& g)
  208166. {
  208167. if (! isControlCreated())
  208168. g.fillAll (Colours::black);
  208169. }
  208170. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  208171. {
  208172. Handle dataRef = 0;
  208173. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  208174. if (err == noErr)
  208175. {
  208176. Str255 suffix;
  208177. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  208178. StringPtr name = suffix;
  208179. err = PtrAndHand (name, dataRef, name[0] + 1);
  208180. if (err == noErr)
  208181. {
  208182. long atoms[3];
  208183. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  208184. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  208185. atoms[2] = EndianU32_NtoB (MovieFileType);
  208186. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  208187. if (err == noErr)
  208188. return dataRef;
  208189. }
  208190. DisposeHandle (dataRef);
  208191. }
  208192. return 0;
  208193. }
  208194. static CFStringRef juceStringToCFString (const String& s)
  208195. {
  208196. const int len = s.length();
  208197. const juce_wchar* const t = s;
  208198. HeapBlock <UniChar> temp (len + 2);
  208199. for (int i = 0; i <= len; ++i)
  208200. temp[i] = t[i];
  208201. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  208202. }
  208203. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  208204. {
  208205. Boolean trueBool = true;
  208206. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  208207. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  208208. props[prop].propValueSize = sizeof (trueBool);
  208209. props[prop].propValueAddress = &trueBool;
  208210. ++prop;
  208211. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  208212. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  208213. props[prop].propValueSize = sizeof (trueBool);
  208214. props[prop].propValueAddress = &trueBool;
  208215. ++prop;
  208216. Boolean isActive = true;
  208217. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  208218. props[prop].propID = kQTNewMoviePropertyID_Active;
  208219. props[prop].propValueSize = sizeof (isActive);
  208220. props[prop].propValueAddress = &isActive;
  208221. ++prop;
  208222. MacSetPort (0);
  208223. jassert (prop <= 5);
  208224. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  208225. return err == noErr;
  208226. }
  208227. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  208228. {
  208229. if (input == 0)
  208230. return false;
  208231. dataHandle = 0;
  208232. bool ok = false;
  208233. QTNewMoviePropertyElement props[5];
  208234. zeromem (props, sizeof (props));
  208235. int prop = 0;
  208236. DataReferenceRecord dr;
  208237. props[prop].propClass = kQTPropertyClass_DataLocation;
  208238. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  208239. props[prop].propValueSize = sizeof (dr);
  208240. props[prop].propValueAddress = &dr;
  208241. ++prop;
  208242. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  208243. if (fin != 0)
  208244. {
  208245. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  208246. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  208247. &dr.dataRef, &dr.dataRefType);
  208248. ok = openMovie (props, prop, movie);
  208249. DisposeHandle (dr.dataRef);
  208250. CFRelease (filePath);
  208251. }
  208252. else
  208253. {
  208254. // sanity-check because this currently needs to load the whole stream into memory..
  208255. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  208256. dataHandle = NewHandle ((Size) input->getTotalLength());
  208257. HLock (dataHandle);
  208258. // read the entire stream into memory - this is a pain, but can't get it to work
  208259. // properly using a custom callback to supply the data.
  208260. input->read (*dataHandle, (int) input->getTotalLength());
  208261. HUnlock (dataHandle);
  208262. // different types to get QT to try. (We should really be a bit smarter here by
  208263. // working out in advance which one the stream contains, rather than just trying
  208264. // each one)
  208265. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  208266. "\04.avi", "\04.m4a" };
  208267. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  208268. {
  208269. /* // this fails for some bizarre reason - it can be bodged to work with
  208270. // movies, but can't seem to do it for other file types..
  208271. QTNewMovieUserProcRecord procInfo;
  208272. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  208273. procInfo.getMovieUserProcRefcon = this;
  208274. procInfo.defaultDataRef.dataRef = dataRef;
  208275. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  208276. props[prop].propClass = kQTPropertyClass_DataLocation;
  208277. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  208278. props[prop].propValueSize = sizeof (procInfo);
  208279. props[prop].propValueAddress = (void*) &procInfo;
  208280. ++prop; */
  208281. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  208282. dr.dataRefType = HandleDataHandlerSubType;
  208283. ok = openMovie (props, prop, movie);
  208284. DisposeHandle (dr.dataRef);
  208285. }
  208286. }
  208287. return ok;
  208288. }
  208289. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  208290. const bool isControllerVisible)
  208291. {
  208292. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  208293. movieFile = movieFile_;
  208294. return ok;
  208295. }
  208296. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  208297. const bool isControllerVisible)
  208298. {
  208299. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  208300. }
  208301. void QuickTimeMovieComponent::goToStart()
  208302. {
  208303. setPosition (0.0);
  208304. }
  208305. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  208306. const RectanglePlacement& placement)
  208307. {
  208308. int normalWidth, normalHeight;
  208309. getMovieNormalSize (normalWidth, normalHeight);
  208310. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  208311. {
  208312. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  208313. placement.applyTo (x, y, w, h,
  208314. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  208315. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  208316. if (w > 0 && h > 0)
  208317. {
  208318. setBounds (roundToInt (x), roundToInt (y),
  208319. roundToInt (w), roundToInt (h));
  208320. }
  208321. }
  208322. else
  208323. {
  208324. setBounds (spaceToFitWithin);
  208325. }
  208326. }
  208327. #endif
  208328. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  208329. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208330. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208331. // compiled on its own).
  208332. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  208333. class WebBrowserComponentInternal : public ActiveXControlComponent
  208334. {
  208335. public:
  208336. WebBrowserComponentInternal()
  208337. : browser (0),
  208338. connectionPoint (0),
  208339. adviseCookie (0)
  208340. {
  208341. }
  208342. ~WebBrowserComponentInternal()
  208343. {
  208344. if (connectionPoint != 0)
  208345. connectionPoint->Unadvise (adviseCookie);
  208346. if (browser != 0)
  208347. browser->Release();
  208348. }
  208349. void createBrowser()
  208350. {
  208351. createControl (&CLSID_WebBrowser);
  208352. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  208353. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  208354. if (connectionPointContainer != 0)
  208355. {
  208356. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  208357. &connectionPoint);
  208358. if (connectionPoint != 0)
  208359. {
  208360. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  208361. jassert (owner != 0);
  208362. EventHandler* handler = new EventHandler (owner);
  208363. connectionPoint->Advise (handler, &adviseCookie);
  208364. handler->Release();
  208365. }
  208366. }
  208367. }
  208368. void goToURL (const String& url,
  208369. const StringArray* headers,
  208370. const MemoryBlock* postData)
  208371. {
  208372. if (browser != 0)
  208373. {
  208374. LPSAFEARRAY sa = 0;
  208375. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  208376. VariantInit (&flags);
  208377. VariantInit (&frame);
  208378. VariantInit (&postDataVar);
  208379. VariantInit (&headersVar);
  208380. if (headers != 0)
  208381. {
  208382. V_VT (&headersVar) = VT_BSTR;
  208383. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  208384. }
  208385. if (postData != 0 && postData->getSize() > 0)
  208386. {
  208387. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  208388. if (sa != 0)
  208389. {
  208390. void* data = 0;
  208391. SafeArrayAccessData (sa, &data);
  208392. jassert (data != 0);
  208393. if (data != 0)
  208394. {
  208395. postData->copyTo (data, 0, postData->getSize());
  208396. SafeArrayUnaccessData (sa);
  208397. VARIANT postDataVar2;
  208398. VariantInit (&postDataVar2);
  208399. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  208400. V_ARRAY (&postDataVar2) = sa;
  208401. postDataVar = postDataVar2;
  208402. }
  208403. }
  208404. }
  208405. browser->Navigate ((BSTR) (const OLECHAR*) url,
  208406. &flags, &frame,
  208407. &postDataVar, &headersVar);
  208408. if (sa != 0)
  208409. SafeArrayDestroy (sa);
  208410. VariantClear (&flags);
  208411. VariantClear (&frame);
  208412. VariantClear (&postDataVar);
  208413. VariantClear (&headersVar);
  208414. }
  208415. }
  208416. IWebBrowser2* browser;
  208417. juce_UseDebuggingNewOperator
  208418. private:
  208419. IConnectionPoint* connectionPoint;
  208420. DWORD adviseCookie;
  208421. class EventHandler : public ComBaseClassHelper <IDispatch>,
  208422. public ComponentMovementWatcher
  208423. {
  208424. public:
  208425. EventHandler (WebBrowserComponent* owner_)
  208426. : ComponentMovementWatcher (owner_),
  208427. owner (owner_)
  208428. {
  208429. }
  208430. ~EventHandler()
  208431. {
  208432. }
  208433. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  208434. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  208435. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  208436. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  208437. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  208438. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  208439. UINT __RPC_FAR* /*puArgErr*/)
  208440. {
  208441. switch (dispIdMember)
  208442. {
  208443. case DISPID_BEFORENAVIGATE2:
  208444. {
  208445. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  208446. String url;
  208447. if ((vurl->vt & VT_BYREF) != 0)
  208448. url = *vurl->pbstrVal;
  208449. else
  208450. url = vurl->bstrVal;
  208451. *pDispParams->rgvarg->pboolVal
  208452. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  208453. : VARIANT_TRUE;
  208454. return S_OK;
  208455. }
  208456. default:
  208457. break;
  208458. }
  208459. return E_NOTIMPL;
  208460. }
  208461. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  208462. void componentPeerChanged() {}
  208463. void componentVisibilityChanged (Component&)
  208464. {
  208465. owner->visibilityChanged();
  208466. }
  208467. juce_UseDebuggingNewOperator
  208468. private:
  208469. WebBrowserComponent* const owner;
  208470. EventHandler (const EventHandler&);
  208471. EventHandler& operator= (const EventHandler&);
  208472. };
  208473. };
  208474. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  208475. : browser (0),
  208476. blankPageShown (false),
  208477. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  208478. {
  208479. setOpaque (true);
  208480. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208481. }
  208482. WebBrowserComponent::~WebBrowserComponent()
  208483. {
  208484. delete browser;
  208485. }
  208486. void WebBrowserComponent::goToURL (const String& url,
  208487. const StringArray* headers,
  208488. const MemoryBlock* postData)
  208489. {
  208490. lastURL = url;
  208491. lastHeaders.clear();
  208492. if (headers != 0)
  208493. lastHeaders = *headers;
  208494. lastPostData.setSize (0);
  208495. if (postData != 0)
  208496. lastPostData = *postData;
  208497. blankPageShown = false;
  208498. browser->goToURL (url, headers, postData);
  208499. }
  208500. void WebBrowserComponent::stop()
  208501. {
  208502. if (browser->browser != 0)
  208503. browser->browser->Stop();
  208504. }
  208505. void WebBrowserComponent::goBack()
  208506. {
  208507. lastURL = String::empty;
  208508. blankPageShown = false;
  208509. if (browser->browser != 0)
  208510. browser->browser->GoBack();
  208511. }
  208512. void WebBrowserComponent::goForward()
  208513. {
  208514. lastURL = String::empty;
  208515. if (browser->browser != 0)
  208516. browser->browser->GoForward();
  208517. }
  208518. void WebBrowserComponent::refresh()
  208519. {
  208520. if (browser->browser != 0)
  208521. browser->browser->Refresh();
  208522. }
  208523. void WebBrowserComponent::paint (Graphics& g)
  208524. {
  208525. if (browser->browser == 0)
  208526. g.fillAll (Colours::white);
  208527. }
  208528. void WebBrowserComponent::checkWindowAssociation()
  208529. {
  208530. if (isShowing())
  208531. {
  208532. if (browser->browser == 0 && getPeer() != 0)
  208533. {
  208534. browser->createBrowser();
  208535. reloadLastURL();
  208536. }
  208537. else
  208538. {
  208539. if (blankPageShown)
  208540. goBack();
  208541. }
  208542. }
  208543. else
  208544. {
  208545. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208546. {
  208547. // when the component becomes invisible, some stuff like flash
  208548. // carries on playing audio, so we need to force it onto a blank
  208549. // page to avoid this..
  208550. blankPageShown = true;
  208551. browser->goToURL ("about:blank", 0, 0);
  208552. }
  208553. }
  208554. }
  208555. void WebBrowserComponent::reloadLastURL()
  208556. {
  208557. if (lastURL.isNotEmpty())
  208558. {
  208559. goToURL (lastURL, &lastHeaders, &lastPostData);
  208560. lastURL = String::empty;
  208561. }
  208562. }
  208563. void WebBrowserComponent::parentHierarchyChanged()
  208564. {
  208565. checkWindowAssociation();
  208566. }
  208567. void WebBrowserComponent::resized()
  208568. {
  208569. browser->setSize (getWidth(), getHeight());
  208570. }
  208571. void WebBrowserComponent::visibilityChanged()
  208572. {
  208573. checkWindowAssociation();
  208574. }
  208575. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208576. {
  208577. return true;
  208578. }
  208579. #endif
  208580. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208581. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208582. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208583. // compiled on its own).
  208584. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208585. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208586. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208587. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208588. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208589. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208590. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208591. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208592. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208593. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208594. #define WGL_ACCELERATION_ARB 0x2003
  208595. #define WGL_SWAP_METHOD_ARB 0x2007
  208596. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208597. #define WGL_PIXEL_TYPE_ARB 0x2013
  208598. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208599. #define WGL_COLOR_BITS_ARB 0x2014
  208600. #define WGL_RED_BITS_ARB 0x2015
  208601. #define WGL_GREEN_BITS_ARB 0x2017
  208602. #define WGL_BLUE_BITS_ARB 0x2019
  208603. #define WGL_ALPHA_BITS_ARB 0x201B
  208604. #define WGL_DEPTH_BITS_ARB 0x2022
  208605. #define WGL_STENCIL_BITS_ARB 0x2023
  208606. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208607. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208608. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208609. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208610. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208611. #define WGL_STEREO_ARB 0x2012
  208612. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208613. #define WGL_SAMPLES_ARB 0x2042
  208614. #define WGL_TYPE_RGBA_ARB 0x202B
  208615. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208616. {
  208617. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208618. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208619. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208620. else
  208621. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208622. }
  208623. class WindowedGLContext : public OpenGLContext
  208624. {
  208625. public:
  208626. WindowedGLContext (Component* const component_,
  208627. HGLRC contextToShareWith,
  208628. const OpenGLPixelFormat& pixelFormat)
  208629. : renderContext (0),
  208630. nativeWindow (0),
  208631. dc (0),
  208632. component (component_)
  208633. {
  208634. jassert (component != 0);
  208635. createNativeWindow();
  208636. // Use a default pixel format that should be supported everywhere
  208637. PIXELFORMATDESCRIPTOR pfd;
  208638. zerostruct (pfd);
  208639. pfd.nSize = sizeof (pfd);
  208640. pfd.nVersion = 1;
  208641. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208642. pfd.iPixelType = PFD_TYPE_RGBA;
  208643. pfd.cColorBits = 24;
  208644. pfd.cDepthBits = 16;
  208645. const int format = ChoosePixelFormat (dc, &pfd);
  208646. if (format != 0)
  208647. SetPixelFormat (dc, format, &pfd);
  208648. renderContext = wglCreateContext (dc);
  208649. makeActive();
  208650. setPixelFormat (pixelFormat);
  208651. if (contextToShareWith != 0 && renderContext != 0)
  208652. wglShareLists (contextToShareWith, renderContext);
  208653. }
  208654. ~WindowedGLContext()
  208655. {
  208656. deleteContext();
  208657. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208658. delete nativeWindow;
  208659. }
  208660. void deleteContext()
  208661. {
  208662. makeInactive();
  208663. if (renderContext != 0)
  208664. {
  208665. wglDeleteContext (renderContext);
  208666. renderContext = 0;
  208667. }
  208668. }
  208669. bool makeActive() const throw()
  208670. {
  208671. jassert (renderContext != 0);
  208672. return wglMakeCurrent (dc, renderContext) != 0;
  208673. }
  208674. bool makeInactive() const throw()
  208675. {
  208676. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208677. }
  208678. bool isActive() const throw()
  208679. {
  208680. return wglGetCurrentContext() == renderContext;
  208681. }
  208682. const OpenGLPixelFormat getPixelFormat() const
  208683. {
  208684. OpenGLPixelFormat pf;
  208685. makeActive();
  208686. StringArray availableExtensions;
  208687. getWglExtensions (dc, availableExtensions);
  208688. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208689. return pf;
  208690. }
  208691. void* getRawContext() const throw()
  208692. {
  208693. return renderContext;
  208694. }
  208695. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208696. {
  208697. makeActive();
  208698. PIXELFORMATDESCRIPTOR pfd;
  208699. zerostruct (pfd);
  208700. pfd.nSize = sizeof (pfd);
  208701. pfd.nVersion = 1;
  208702. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208703. pfd.iPixelType = PFD_TYPE_RGBA;
  208704. pfd.iLayerType = PFD_MAIN_PLANE;
  208705. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208706. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208707. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208708. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208709. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208710. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208711. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208712. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208713. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208714. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208715. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208716. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208717. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208718. int format = 0;
  208719. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208720. StringArray availableExtensions;
  208721. getWglExtensions (dc, availableExtensions);
  208722. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208723. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208724. {
  208725. int attributes[64];
  208726. int n = 0;
  208727. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208728. attributes[n++] = GL_TRUE;
  208729. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208730. attributes[n++] = GL_TRUE;
  208731. attributes[n++] = WGL_ACCELERATION_ARB;
  208732. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208733. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208734. attributes[n++] = GL_TRUE;
  208735. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208736. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208737. attributes[n++] = WGL_COLOR_BITS_ARB;
  208738. attributes[n++] = pfd.cColorBits;
  208739. attributes[n++] = WGL_RED_BITS_ARB;
  208740. attributes[n++] = pixelFormat.redBits;
  208741. attributes[n++] = WGL_GREEN_BITS_ARB;
  208742. attributes[n++] = pixelFormat.greenBits;
  208743. attributes[n++] = WGL_BLUE_BITS_ARB;
  208744. attributes[n++] = pixelFormat.blueBits;
  208745. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208746. attributes[n++] = pixelFormat.alphaBits;
  208747. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208748. attributes[n++] = pixelFormat.depthBufferBits;
  208749. if (pixelFormat.stencilBufferBits > 0)
  208750. {
  208751. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208752. attributes[n++] = pixelFormat.stencilBufferBits;
  208753. }
  208754. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208755. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208756. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208757. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208758. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208759. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208760. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208761. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208762. if (availableExtensions.contains ("WGL_ARB_multisample")
  208763. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208764. {
  208765. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208766. attributes[n++] = 1;
  208767. attributes[n++] = WGL_SAMPLES_ARB;
  208768. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208769. }
  208770. attributes[n++] = 0;
  208771. UINT formatsCount;
  208772. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208773. (void) ok;
  208774. jassert (ok);
  208775. }
  208776. else
  208777. {
  208778. format = ChoosePixelFormat (dc, &pfd);
  208779. }
  208780. if (format != 0)
  208781. {
  208782. makeInactive();
  208783. // win32 can't change the pixel format of a window, so need to delete the
  208784. // old one and create a new one..
  208785. jassert (nativeWindow != 0);
  208786. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208787. delete nativeWindow;
  208788. createNativeWindow();
  208789. if (SetPixelFormat (dc, format, &pfd))
  208790. {
  208791. wglDeleteContext (renderContext);
  208792. renderContext = wglCreateContext (dc);
  208793. jassert (renderContext != 0);
  208794. return renderContext != 0;
  208795. }
  208796. }
  208797. return false;
  208798. }
  208799. void updateWindowPosition (int x, int y, int w, int h, int)
  208800. {
  208801. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208802. x, y, w, h,
  208803. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208804. }
  208805. void repaint()
  208806. {
  208807. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208808. }
  208809. void swapBuffers()
  208810. {
  208811. SwapBuffers (dc);
  208812. }
  208813. bool setSwapInterval (int numFramesPerSwap)
  208814. {
  208815. makeActive();
  208816. StringArray availableExtensions;
  208817. getWglExtensions (dc, availableExtensions);
  208818. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208819. return availableExtensions.contains ("WGL_EXT_swap_control")
  208820. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208821. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208822. }
  208823. int getSwapInterval() const
  208824. {
  208825. makeActive();
  208826. StringArray availableExtensions;
  208827. getWglExtensions (dc, availableExtensions);
  208828. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208829. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208830. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208831. return wglGetSwapIntervalEXT();
  208832. return 0;
  208833. }
  208834. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208835. {
  208836. jassert (isActive());
  208837. StringArray availableExtensions;
  208838. getWglExtensions (dc, availableExtensions);
  208839. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208840. int numTypes = 0;
  208841. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208842. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208843. {
  208844. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208845. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208846. jassertfalse;
  208847. }
  208848. else
  208849. {
  208850. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208851. }
  208852. OpenGLPixelFormat pf;
  208853. for (int i = 0; i < numTypes; ++i)
  208854. {
  208855. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208856. {
  208857. bool alreadyListed = false;
  208858. for (int j = results.size(); --j >= 0;)
  208859. if (pf == *results.getUnchecked(j))
  208860. alreadyListed = true;
  208861. if (! alreadyListed)
  208862. results.add (new OpenGLPixelFormat (pf));
  208863. }
  208864. }
  208865. }
  208866. void* getNativeWindowHandle() const
  208867. {
  208868. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208869. }
  208870. juce_UseDebuggingNewOperator
  208871. HGLRC renderContext;
  208872. private:
  208873. Win32ComponentPeer* nativeWindow;
  208874. Component* const component;
  208875. HDC dc;
  208876. void createNativeWindow()
  208877. {
  208878. nativeWindow = new Win32ComponentPeer (component, 0);
  208879. nativeWindow->dontRepaint = true;
  208880. nativeWindow->setVisible (true);
  208881. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208882. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208883. if (peer != 0)
  208884. {
  208885. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208886. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208887. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208888. }
  208889. dc = GetDC (hwnd);
  208890. }
  208891. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208892. OpenGLPixelFormat& result,
  208893. const StringArray& availableExtensions) const throw()
  208894. {
  208895. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208896. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208897. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208898. {
  208899. int attributes[32];
  208900. int numAttributes = 0;
  208901. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208902. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208903. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208904. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208905. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208906. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208907. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208908. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208909. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208910. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208911. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208912. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208913. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208914. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208915. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208916. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208917. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208918. int values[32];
  208919. zeromem (values, sizeof (values));
  208920. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208921. {
  208922. int n = 0;
  208923. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208924. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208925. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208926. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208927. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208928. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208929. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208930. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208931. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208932. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208933. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208934. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208935. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208936. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208937. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208938. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208939. return isValidFormat;
  208940. }
  208941. else
  208942. {
  208943. jassertfalse;
  208944. }
  208945. }
  208946. else
  208947. {
  208948. PIXELFORMATDESCRIPTOR pfd;
  208949. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208950. {
  208951. result.redBits = pfd.cRedBits;
  208952. result.greenBits = pfd.cGreenBits;
  208953. result.blueBits = pfd.cBlueBits;
  208954. result.alphaBits = pfd.cAlphaBits;
  208955. result.depthBufferBits = pfd.cDepthBits;
  208956. result.stencilBufferBits = pfd.cStencilBits;
  208957. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208958. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208959. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208960. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208961. result.fullSceneAntiAliasingNumSamples = 0;
  208962. return true;
  208963. }
  208964. else
  208965. {
  208966. jassertfalse;
  208967. }
  208968. }
  208969. return false;
  208970. }
  208971. WindowedGLContext (const WindowedGLContext&);
  208972. WindowedGLContext& operator= (const WindowedGLContext&);
  208973. };
  208974. OpenGLContext* OpenGLComponent::createContext()
  208975. {
  208976. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208977. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208978. preferredPixelFormat));
  208979. return (c->renderContext != 0) ? c.release() : 0;
  208980. }
  208981. void* OpenGLComponent::getNativeWindowHandle() const
  208982. {
  208983. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208984. }
  208985. void juce_glViewport (const int w, const int h)
  208986. {
  208987. glViewport (0, 0, w, h);
  208988. }
  208989. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208990. OwnedArray <OpenGLPixelFormat>& results)
  208991. {
  208992. Component tempComp;
  208993. {
  208994. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208995. wc.makeActive();
  208996. wc.findAlternativeOpenGLPixelFormats (results);
  208997. }
  208998. }
  208999. #endif
  209000. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209001. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  209002. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209003. // compiled on its own).
  209004. #if JUCE_INCLUDED_FILE
  209005. #if JUCE_USE_CDREADER
  209006. namespace CDReaderHelpers
  209007. {
  209008. //***************************************************************************
  209009. // %%% TARGET STATUS VALUES %%%
  209010. //***************************************************************************
  209011. #define STATUS_GOOD 0x00 // Status Good
  209012. #define STATUS_CHKCOND 0x02 // Check Condition
  209013. #define STATUS_CONDMET 0x04 // Condition Met
  209014. #define STATUS_BUSY 0x08 // Busy
  209015. #define STATUS_INTERM 0x10 // Intermediate
  209016. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  209017. #define STATUS_RESCONF 0x18 // Reservation conflict
  209018. #define STATUS_COMTERM 0x22 // Command Terminated
  209019. #define STATUS_QFULL 0x28 // Queue full
  209020. //***************************************************************************
  209021. // %%% SCSI MISCELLANEOUS EQUATES %%%
  209022. //***************************************************************************
  209023. #define MAXLUN 7 // Maximum Logical Unit Id
  209024. #define MAXTARG 7 // Maximum Target Id
  209025. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  209026. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  209027. //***************************************************************************
  209028. // %%% Commands for all Device Types %%%
  209029. //***************************************************************************
  209030. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  209031. #define SCSI_COMPARE 0x39 // Compare (O)
  209032. #define SCSI_COPY 0x18 // Copy (O)
  209033. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  209034. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  209035. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  209036. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  209037. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  209038. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  209039. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  209040. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  209041. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  209042. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  209043. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  209044. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  209045. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  209046. //***************************************************************************
  209047. // %%% Commands Unique to Direct Access Devices %%%
  209048. //***************************************************************************
  209049. #define SCSI_COMPARE 0x39 // Compare (O)
  209050. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  209051. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  209052. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  209053. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  209054. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  209055. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  209056. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  209057. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  209058. #define SCSI_READ_LONG 0x3E // Read Long (O)
  209059. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  209060. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  209061. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  209062. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  209063. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  209064. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  209065. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  209066. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  209067. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  209068. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  209069. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  209070. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  209071. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  209072. #define SCSI_VERIFY 0x2F // Verify (O)
  209073. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  209074. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  209075. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  209076. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  209077. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  209078. //***************************************************************************
  209079. // %%% Commands Unique to Sequential Access Devices %%%
  209080. //***************************************************************************
  209081. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  209082. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  209083. #define SCSI_LOCATE 0x2B // Locate (O)
  209084. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  209085. #define SCSI_READ_POS 0x34 // Read Position (O)
  209086. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  209087. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  209088. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  209089. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  209090. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  209091. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  209092. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  209093. //***************************************************************************
  209094. // %%% Commands Unique to Printer Devices %%%
  209095. //***************************************************************************
  209096. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  209097. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  209098. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  209099. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  209100. //***************************************************************************
  209101. // %%% Commands Unique to Processor Devices %%%
  209102. //***************************************************************************
  209103. #define SCSI_RECEIVE 0x08 // Receive (O)
  209104. #define SCSI_SEND 0x0A // Send (O)
  209105. //***************************************************************************
  209106. // %%% Commands Unique to Write-Once Devices %%%
  209107. //***************************************************************************
  209108. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  209109. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  209110. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  209111. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  209112. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  209113. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  209114. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  209115. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  209116. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  209117. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  209118. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  209119. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  209120. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  209121. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  209122. //***************************************************************************
  209123. // %%% Commands Unique to CD-ROM Devices %%%
  209124. //***************************************************************************
  209125. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  209126. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  209127. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  209128. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  209129. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  209130. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  209131. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  209132. #define SCSI_READHEADER 0x44 // Read Header (O)
  209133. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  209134. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  209135. //***************************************************************************
  209136. // %%% Commands Unique to Scanner Devices %%%
  209137. //***************************************************************************
  209138. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  209139. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  209140. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  209141. #define SCSI_SCAN 0x1B // Scan (O)
  209142. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  209143. //***************************************************************************
  209144. // %%% Commands Unique to Optical Memory Devices %%%
  209145. //***************************************************************************
  209146. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  209147. //***************************************************************************
  209148. // %%% Commands Unique to Medium Changer Devices %%%
  209149. //***************************************************************************
  209150. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  209151. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  209152. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  209153. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  209154. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  209155. //***************************************************************************
  209156. // %%% Commands Unique to Communication Devices %%%
  209157. //***************************************************************************
  209158. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  209159. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  209160. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  209161. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  209162. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  209163. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  209164. //***************************************************************************
  209165. // %%% Request Sense Data Format %%%
  209166. //***************************************************************************
  209167. typedef struct {
  209168. BYTE ErrorCode; // Error Code (70H or 71H)
  209169. BYTE SegmentNum; // Number of current segment descriptor
  209170. BYTE SenseKey; // Sense Key(See bit definitions too)
  209171. BYTE InfoByte0; // Information MSB
  209172. BYTE InfoByte1; // Information MID
  209173. BYTE InfoByte2; // Information MID
  209174. BYTE InfoByte3; // Information LSB
  209175. BYTE AddSenLen; // Additional Sense Length
  209176. BYTE ComSpecInf0; // Command Specific Information MSB
  209177. BYTE ComSpecInf1; // Command Specific Information MID
  209178. BYTE ComSpecInf2; // Command Specific Information MID
  209179. BYTE ComSpecInf3; // Command Specific Information LSB
  209180. BYTE AddSenseCode; // Additional Sense Code
  209181. BYTE AddSenQual; // Additional Sense Code Qualifier
  209182. BYTE FieldRepUCode; // Field Replaceable Unit Code
  209183. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  209184. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  209185. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  209186. BYTE AddSenseBytes; // Additional Sense Bytes
  209187. } SENSE_DATA_FMT;
  209188. //***************************************************************************
  209189. // %%% REQUEST SENSE ERROR CODE %%%
  209190. //***************************************************************************
  209191. #define SERROR_CURRENT 0x70 // Current Errors
  209192. #define SERROR_DEFERED 0x71 // Deferred Errors
  209193. //***************************************************************************
  209194. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  209195. //***************************************************************************
  209196. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  209197. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  209198. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  209199. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  209200. //***************************************************************************
  209201. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  209202. //***************************************************************************
  209203. #define KEY_NOSENSE 0x00 // No Sense
  209204. #define KEY_RECERROR 0x01 // Recovered Error
  209205. #define KEY_NOTREADY 0x02 // Not Ready
  209206. #define KEY_MEDIUMERR 0x03 // Medium Error
  209207. #define KEY_HARDERROR 0x04 // Hardware Error
  209208. #define KEY_ILLGLREQ 0x05 // Illegal Request
  209209. #define KEY_UNITATT 0x06 // Unit Attention
  209210. #define KEY_DATAPROT 0x07 // Data Protect
  209211. #define KEY_BLANKCHK 0x08 // Blank Check
  209212. #define KEY_VENDSPEC 0x09 // Vendor Specific
  209213. #define KEY_COPYABORT 0x0A // Copy Abort
  209214. #define KEY_EQUAL 0x0C // Equal (Search)
  209215. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  209216. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  209217. #define KEY_RESERVED 0x0F // Reserved
  209218. //***************************************************************************
  209219. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  209220. //***************************************************************************
  209221. #define DTYPE_DASD 0x00 // Disk Device
  209222. #define DTYPE_SEQD 0x01 // Tape Device
  209223. #define DTYPE_PRNT 0x02 // Printer
  209224. #define DTYPE_PROC 0x03 // Processor
  209225. #define DTYPE_WORM 0x04 // Write-once read-multiple
  209226. #define DTYPE_CROM 0x05 // CD-ROM device
  209227. #define DTYPE_SCAN 0x06 // Scanner device
  209228. #define DTYPE_OPTI 0x07 // Optical memory device
  209229. #define DTYPE_JUKE 0x08 // Medium Changer device
  209230. #define DTYPE_COMM 0x09 // Communications device
  209231. #define DTYPE_RESL 0x0A // Reserved (low)
  209232. #define DTYPE_RESH 0x1E // Reserved (high)
  209233. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  209234. //***************************************************************************
  209235. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  209236. //***************************************************************************
  209237. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  209238. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  209239. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  209240. #define ANSI_RESLO 0x3 // Reserved (low)
  209241. #define ANSI_RESHI 0x7 // Reserved (high)
  209242. typedef struct
  209243. {
  209244. USHORT Length;
  209245. UCHAR ScsiStatus;
  209246. UCHAR PathId;
  209247. UCHAR TargetId;
  209248. UCHAR Lun;
  209249. UCHAR CdbLength;
  209250. UCHAR SenseInfoLength;
  209251. UCHAR DataIn;
  209252. ULONG DataTransferLength;
  209253. ULONG TimeOutValue;
  209254. ULONG DataBufferOffset;
  209255. ULONG SenseInfoOffset;
  209256. UCHAR Cdb[16];
  209257. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  209258. typedef struct
  209259. {
  209260. USHORT Length;
  209261. UCHAR ScsiStatus;
  209262. UCHAR PathId;
  209263. UCHAR TargetId;
  209264. UCHAR Lun;
  209265. UCHAR CdbLength;
  209266. UCHAR SenseInfoLength;
  209267. UCHAR DataIn;
  209268. ULONG DataTransferLength;
  209269. ULONG TimeOutValue;
  209270. PVOID DataBuffer;
  209271. ULONG SenseInfoOffset;
  209272. UCHAR Cdb[16];
  209273. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  209274. typedef struct
  209275. {
  209276. SCSI_PASS_THROUGH_DIRECT spt;
  209277. ULONG Filler;
  209278. UCHAR ucSenseBuf[32];
  209279. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  209280. typedef struct
  209281. {
  209282. ULONG Length;
  209283. UCHAR PortNumber;
  209284. UCHAR PathId;
  209285. UCHAR TargetId;
  209286. UCHAR Lun;
  209287. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  209288. #define METHOD_BUFFERED 0
  209289. #define METHOD_IN_DIRECT 1
  209290. #define METHOD_OUT_DIRECT 2
  209291. #define METHOD_NEITHER 3
  209292. #define FILE_ANY_ACCESS 0
  209293. #ifndef FILE_READ_ACCESS
  209294. #define FILE_READ_ACCESS (0x0001)
  209295. #endif
  209296. #ifndef FILE_WRITE_ACCESS
  209297. #define FILE_WRITE_ACCESS (0x0002)
  209298. #endif
  209299. #define IOCTL_SCSI_BASE 0x00000004
  209300. #define SCSI_IOCTL_DATA_OUT 0
  209301. #define SCSI_IOCTL_DATA_IN 1
  209302. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  209303. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  209304. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  209305. )
  209306. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209307. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  209308. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209309. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  209310. #define SENSE_LEN 14
  209311. #define SRB_DIR_SCSI 0x00
  209312. #define SRB_POSTING 0x01
  209313. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  209314. #define SRB_DIR_IN 0x08
  209315. #define SRB_DIR_OUT 0x10
  209316. #define SRB_EVENT_NOTIFY 0x40
  209317. #define RESIDUAL_COUNT_SUPPORTED 0x02
  209318. #define MAX_SRB_TIMEOUT 1080001u
  209319. #define DEFAULT_SRB_TIMEOUT 1080001u
  209320. #define SC_HA_INQUIRY 0x00
  209321. #define SC_GET_DEV_TYPE 0x01
  209322. #define SC_EXEC_SCSI_CMD 0x02
  209323. #define SC_ABORT_SRB 0x03
  209324. #define SC_RESET_DEV 0x04
  209325. #define SC_SET_HA_PARMS 0x05
  209326. #define SC_GET_DISK_INFO 0x06
  209327. #define SC_RESCAN_SCSI_BUS 0x07
  209328. #define SC_GETSET_TIMEOUTS 0x08
  209329. #define SS_PENDING 0x00
  209330. #define SS_COMP 0x01
  209331. #define SS_ABORTED 0x02
  209332. #define SS_ABORT_FAIL 0x03
  209333. #define SS_ERR 0x04
  209334. #define SS_INVALID_CMD 0x80
  209335. #define SS_INVALID_HA 0x81
  209336. #define SS_NO_DEVICE 0x82
  209337. #define SS_INVALID_SRB 0xE0
  209338. #define SS_OLD_MANAGER 0xE1
  209339. #define SS_BUFFER_ALIGN 0xE1
  209340. #define SS_ILLEGAL_MODE 0xE2
  209341. #define SS_NO_ASPI 0xE3
  209342. #define SS_FAILED_INIT 0xE4
  209343. #define SS_ASPI_IS_BUSY 0xE5
  209344. #define SS_BUFFER_TO_BIG 0xE6
  209345. #define SS_BUFFER_TOO_BIG 0xE6
  209346. #define SS_MISMATCHED_COMPONENTS 0xE7
  209347. #define SS_NO_ADAPTERS 0xE8
  209348. #define SS_INSUFFICIENT_RESOURCES 0xE9
  209349. #define SS_ASPI_IS_SHUTDOWN 0xEA
  209350. #define SS_BAD_INSTALL 0xEB
  209351. #define HASTAT_OK 0x00
  209352. #define HASTAT_SEL_TO 0x11
  209353. #define HASTAT_DO_DU 0x12
  209354. #define HASTAT_BUS_FREE 0x13
  209355. #define HASTAT_PHASE_ERR 0x14
  209356. #define HASTAT_TIMEOUT 0x09
  209357. #define HASTAT_COMMAND_TIMEOUT 0x0B
  209358. #define HASTAT_MESSAGE_REJECT 0x0D
  209359. #define HASTAT_BUS_RESET 0x0E
  209360. #define HASTAT_PARITY_ERROR 0x0F
  209361. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  209362. #define PACKED
  209363. #pragma pack(1)
  209364. typedef struct
  209365. {
  209366. BYTE SRB_Cmd;
  209367. BYTE SRB_Status;
  209368. BYTE SRB_HaID;
  209369. BYTE SRB_Flags;
  209370. DWORD SRB_Hdr_Rsvd;
  209371. BYTE HA_Count;
  209372. BYTE HA_SCSI_ID;
  209373. BYTE HA_ManagerId[16];
  209374. BYTE HA_Identifier[16];
  209375. BYTE HA_Unique[16];
  209376. WORD HA_Rsvd1;
  209377. BYTE pad[20];
  209378. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  209379. typedef struct
  209380. {
  209381. BYTE SRB_Cmd;
  209382. BYTE SRB_Status;
  209383. BYTE SRB_HaID;
  209384. BYTE SRB_Flags;
  209385. DWORD SRB_Hdr_Rsvd;
  209386. BYTE SRB_Target;
  209387. BYTE SRB_Lun;
  209388. BYTE SRB_DeviceType;
  209389. BYTE SRB_Rsvd1;
  209390. BYTE pad[68];
  209391. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  209392. typedef struct
  209393. {
  209394. BYTE SRB_Cmd;
  209395. BYTE SRB_Status;
  209396. BYTE SRB_HaID;
  209397. BYTE SRB_Flags;
  209398. DWORD SRB_Hdr_Rsvd;
  209399. BYTE SRB_Target;
  209400. BYTE SRB_Lun;
  209401. WORD SRB_Rsvd1;
  209402. DWORD SRB_BufLen;
  209403. BYTE FAR *SRB_BufPointer;
  209404. BYTE SRB_SenseLen;
  209405. BYTE SRB_CDBLen;
  209406. BYTE SRB_HaStat;
  209407. BYTE SRB_TargStat;
  209408. VOID FAR *SRB_PostProc;
  209409. BYTE SRB_Rsvd2[20];
  209410. BYTE CDBByte[16];
  209411. BYTE SenseArea[SENSE_LEN+2];
  209412. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  209413. typedef struct
  209414. {
  209415. BYTE SRB_Cmd;
  209416. BYTE SRB_Status;
  209417. BYTE SRB_HaId;
  209418. BYTE SRB_Flags;
  209419. DWORD SRB_Hdr_Rsvd;
  209420. } PACKED SRB, *PSRB, FAR *LPSRB;
  209421. #pragma pack()
  209422. struct CDDeviceInfo
  209423. {
  209424. char vendor[9];
  209425. char productId[17];
  209426. char rev[5];
  209427. char vendorSpec[21];
  209428. BYTE ha;
  209429. BYTE tgt;
  209430. BYTE lun;
  209431. char scsiDriveLetter; // will be 0 if not using scsi
  209432. };
  209433. class CDReadBuffer
  209434. {
  209435. public:
  209436. int startFrame;
  209437. int numFrames;
  209438. int dataStartOffset;
  209439. int dataLength;
  209440. int bufferSize;
  209441. HeapBlock<BYTE> buffer;
  209442. int index;
  209443. bool wantsIndex;
  209444. CDReadBuffer (const int numberOfFrames)
  209445. : startFrame (0),
  209446. numFrames (0),
  209447. dataStartOffset (0),
  209448. dataLength (0),
  209449. bufferSize (2352 * numberOfFrames),
  209450. buffer (bufferSize),
  209451. index (0),
  209452. wantsIndex (false)
  209453. {
  209454. }
  209455. bool isZero() const throw()
  209456. {
  209457. BYTE* p = buffer + dataStartOffset;
  209458. for (int i = dataLength; --i >= 0;)
  209459. if (*p++ != 0)
  209460. return false;
  209461. return true;
  209462. }
  209463. };
  209464. class CDDeviceHandle;
  209465. class CDController
  209466. {
  209467. public:
  209468. CDController();
  209469. virtual ~CDController();
  209470. virtual bool read (CDReadBuffer* t) = 0;
  209471. virtual void shutDown();
  209472. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  209473. int getLastIndex();
  209474. public:
  209475. bool initialised;
  209476. CDDeviceHandle* deviceInfo;
  209477. int framesToCheck, framesOverlap;
  209478. void prepare (SRB_ExecSCSICmd& s);
  209479. void perform (SRB_ExecSCSICmd& s);
  209480. void setPaused (bool paused);
  209481. };
  209482. #pragma pack(1)
  209483. struct TOCTRACK
  209484. {
  209485. BYTE rsvd;
  209486. BYTE ADR;
  209487. BYTE trackNumber;
  209488. BYTE rsvd2;
  209489. BYTE addr[4];
  209490. };
  209491. struct TOC
  209492. {
  209493. WORD tocLen;
  209494. BYTE firstTrack;
  209495. BYTE lastTrack;
  209496. TOCTRACK tracks[100];
  209497. };
  209498. #pragma pack()
  209499. enum
  209500. {
  209501. READTYPE_ANY = 0,
  209502. READTYPE_ATAPI1 = 1,
  209503. READTYPE_ATAPI2 = 2,
  209504. READTYPE_READ6 = 3,
  209505. READTYPE_READ10 = 4,
  209506. READTYPE_READ_D8 = 5,
  209507. READTYPE_READ_D4 = 6,
  209508. READTYPE_READ_D4_1 = 7,
  209509. READTYPE_READ10_2 = 8
  209510. };
  209511. class CDDeviceHandle
  209512. {
  209513. public:
  209514. CDDeviceHandle (const CDDeviceInfo* const device)
  209515. : scsiHandle (0),
  209516. readType (READTYPE_ANY),
  209517. controller (0)
  209518. {
  209519. memcpy (&info, device, sizeof (info));
  209520. }
  209521. ~CDDeviceHandle()
  209522. {
  209523. if (controller != 0)
  209524. {
  209525. controller->shutDown();
  209526. controller = 0;
  209527. }
  209528. if (scsiHandle != 0)
  209529. CloseHandle (scsiHandle);
  209530. }
  209531. bool readTOC (TOC* lpToc);
  209532. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209533. void openDrawer (bool shouldBeOpen);
  209534. CDDeviceInfo info;
  209535. HANDLE scsiHandle;
  209536. BYTE readType;
  209537. private:
  209538. ScopedPointer<CDController> controller;
  209539. bool testController (const int readType,
  209540. CDController* const newController,
  209541. CDReadBuffer* const bufferToUse);
  209542. };
  209543. DWORD (*fGetASPI32SupportInfo)(void);
  209544. DWORD (*fSendASPI32Command)(LPSRB);
  209545. static HINSTANCE winAspiLib = 0;
  209546. static bool usingScsi = false;
  209547. static bool initialised = false;
  209548. static bool InitialiseCDRipper()
  209549. {
  209550. if (! initialised)
  209551. {
  209552. initialised = true;
  209553. OSVERSIONINFO info;
  209554. info.dwOSVersionInfoSize = sizeof (info);
  209555. GetVersionEx (&info);
  209556. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209557. if (! usingScsi)
  209558. {
  209559. fGetASPI32SupportInfo = 0;
  209560. fSendASPI32Command = 0;
  209561. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209562. if (winAspiLib != 0)
  209563. {
  209564. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209565. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209566. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209567. return false;
  209568. }
  209569. else
  209570. {
  209571. usingScsi = true;
  209572. }
  209573. }
  209574. }
  209575. return true;
  209576. }
  209577. static void DeinitialiseCDRipper()
  209578. {
  209579. if (winAspiLib != 0)
  209580. {
  209581. fGetASPI32SupportInfo = 0;
  209582. fSendASPI32Command = 0;
  209583. FreeLibrary (winAspiLib);
  209584. winAspiLib = 0;
  209585. }
  209586. initialised = false;
  209587. }
  209588. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209589. {
  209590. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209591. OSVERSIONINFO info;
  209592. info.dwOSVersionInfoSize = sizeof (info);
  209593. GetVersionEx (&info);
  209594. DWORD flags = GENERIC_READ;
  209595. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209596. flags = GENERIC_READ | GENERIC_WRITE;
  209597. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209598. if (h == INVALID_HANDLE_VALUE)
  209599. {
  209600. flags ^= GENERIC_WRITE;
  209601. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209602. }
  209603. return h;
  209604. }
  209605. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209606. const char driveLetter,
  209607. HANDLE& deviceHandle,
  209608. const bool retryOnFailure = true)
  209609. {
  209610. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209611. zerostruct (s);
  209612. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209613. s.spt.CdbLength = srb->SRB_CDBLen;
  209614. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209615. ? SCSI_IOCTL_DATA_IN
  209616. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209617. ? SCSI_IOCTL_DATA_OUT
  209618. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209619. s.spt.DataTransferLength = srb->SRB_BufLen;
  209620. s.spt.TimeOutValue = 5;
  209621. s.spt.DataBuffer = srb->SRB_BufPointer;
  209622. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209623. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209624. srb->SRB_Status = SS_ERR;
  209625. srb->SRB_TargStat = 0x0004;
  209626. DWORD bytesReturned = 0;
  209627. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209628. &s, sizeof (s),
  209629. &s, sizeof (s),
  209630. &bytesReturned, 0) != 0)
  209631. {
  209632. srb->SRB_Status = SS_COMP;
  209633. }
  209634. else if (retryOnFailure)
  209635. {
  209636. const DWORD error = GetLastError();
  209637. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209638. {
  209639. if (error != ERROR_INVALID_HANDLE)
  209640. CloseHandle (deviceHandle);
  209641. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209642. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209643. }
  209644. }
  209645. return srb->SRB_Status;
  209646. }
  209647. // Controller types..
  209648. class ControllerType1 : public CDController
  209649. {
  209650. public:
  209651. ControllerType1() {}
  209652. ~ControllerType1() {}
  209653. bool read (CDReadBuffer* rb)
  209654. {
  209655. if (rb->numFrames * 2352 > rb->bufferSize)
  209656. return false;
  209657. SRB_ExecSCSICmd s;
  209658. prepare (s);
  209659. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209660. s.SRB_BufLen = rb->bufferSize;
  209661. s.SRB_BufPointer = rb->buffer;
  209662. s.SRB_CDBLen = 12;
  209663. s.CDBByte[0] = 0xBE;
  209664. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209665. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209666. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209667. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209668. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209669. perform (s);
  209670. if (s.SRB_Status != SS_COMP)
  209671. return false;
  209672. rb->dataLength = rb->numFrames * 2352;
  209673. rb->dataStartOffset = 0;
  209674. return true;
  209675. }
  209676. };
  209677. class ControllerType2 : public CDController
  209678. {
  209679. public:
  209680. ControllerType2() {}
  209681. ~ControllerType2() {}
  209682. void shutDown()
  209683. {
  209684. if (initialised)
  209685. {
  209686. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209687. SRB_ExecSCSICmd s;
  209688. prepare (s);
  209689. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209690. s.SRB_BufLen = 0x0C;
  209691. s.SRB_BufPointer = bufPointer;
  209692. s.SRB_CDBLen = 6;
  209693. s.CDBByte[0] = 0x15;
  209694. s.CDBByte[4] = 0x0C;
  209695. perform (s);
  209696. }
  209697. }
  209698. bool init()
  209699. {
  209700. SRB_ExecSCSICmd s;
  209701. s.SRB_Status = SS_ERR;
  209702. if (deviceInfo->readType == READTYPE_READ10_2)
  209703. {
  209704. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209705. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209706. for (int i = 0; i < 2; ++i)
  209707. {
  209708. prepare (s);
  209709. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209710. s.SRB_BufLen = 0x14;
  209711. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209712. s.SRB_CDBLen = 6;
  209713. s.CDBByte[0] = 0x15;
  209714. s.CDBByte[1] = 0x10;
  209715. s.CDBByte[4] = 0x14;
  209716. perform (s);
  209717. if (s.SRB_Status != SS_COMP)
  209718. return false;
  209719. }
  209720. }
  209721. else
  209722. {
  209723. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209724. prepare (s);
  209725. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209726. s.SRB_BufLen = 0x0C;
  209727. s.SRB_BufPointer = bufPointer;
  209728. s.SRB_CDBLen = 6;
  209729. s.CDBByte[0] = 0x15;
  209730. s.CDBByte[4] = 0x0C;
  209731. perform (s);
  209732. }
  209733. return s.SRB_Status == SS_COMP;
  209734. }
  209735. bool read (CDReadBuffer* rb)
  209736. {
  209737. if (rb->numFrames * 2352 > rb->bufferSize)
  209738. return false;
  209739. if (!initialised)
  209740. {
  209741. initialised = init();
  209742. if (!initialised)
  209743. return false;
  209744. }
  209745. SRB_ExecSCSICmd s;
  209746. prepare (s);
  209747. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209748. s.SRB_BufLen = rb->bufferSize;
  209749. s.SRB_BufPointer = rb->buffer;
  209750. s.SRB_CDBLen = 10;
  209751. s.CDBByte[0] = 0x28;
  209752. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209753. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209754. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209755. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209756. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209757. perform (s);
  209758. if (s.SRB_Status != SS_COMP)
  209759. return false;
  209760. rb->dataLength = rb->numFrames * 2352;
  209761. rb->dataStartOffset = 0;
  209762. return true;
  209763. }
  209764. };
  209765. class ControllerType3 : public CDController
  209766. {
  209767. public:
  209768. ControllerType3() {}
  209769. ~ControllerType3() {}
  209770. bool read (CDReadBuffer* rb)
  209771. {
  209772. if (rb->numFrames * 2352 > rb->bufferSize)
  209773. return false;
  209774. if (!initialised)
  209775. {
  209776. setPaused (false);
  209777. initialised = true;
  209778. }
  209779. SRB_ExecSCSICmd s;
  209780. prepare (s);
  209781. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209782. s.SRB_BufLen = rb->numFrames * 2352;
  209783. s.SRB_BufPointer = rb->buffer;
  209784. s.SRB_CDBLen = 12;
  209785. s.CDBByte[0] = 0xD8;
  209786. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209787. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209788. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209789. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209790. perform (s);
  209791. if (s.SRB_Status != SS_COMP)
  209792. return false;
  209793. rb->dataLength = rb->numFrames * 2352;
  209794. rb->dataStartOffset = 0;
  209795. return true;
  209796. }
  209797. };
  209798. class ControllerType4 : public CDController
  209799. {
  209800. public:
  209801. ControllerType4() {}
  209802. ~ControllerType4() {}
  209803. bool selectD4Mode()
  209804. {
  209805. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209806. SRB_ExecSCSICmd s;
  209807. prepare (s);
  209808. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209809. s.SRB_CDBLen = 6;
  209810. s.SRB_BufLen = 12;
  209811. s.SRB_BufPointer = bufPointer;
  209812. s.CDBByte[0] = 0x15;
  209813. s.CDBByte[1] = 0x10;
  209814. s.CDBByte[4] = 0x08;
  209815. perform (s);
  209816. return s.SRB_Status == SS_COMP;
  209817. }
  209818. bool read (CDReadBuffer* rb)
  209819. {
  209820. if (rb->numFrames * 2352 > rb->bufferSize)
  209821. return false;
  209822. if (!initialised)
  209823. {
  209824. setPaused (true);
  209825. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209826. selectD4Mode();
  209827. initialised = true;
  209828. }
  209829. SRB_ExecSCSICmd s;
  209830. prepare (s);
  209831. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209832. s.SRB_BufLen = rb->bufferSize;
  209833. s.SRB_BufPointer = rb->buffer;
  209834. s.SRB_CDBLen = 10;
  209835. s.CDBByte[0] = 0xD4;
  209836. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209837. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209838. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209839. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209840. perform (s);
  209841. if (s.SRB_Status != SS_COMP)
  209842. return false;
  209843. rb->dataLength = rb->numFrames * 2352;
  209844. rb->dataStartOffset = 0;
  209845. return true;
  209846. }
  209847. };
  209848. CDController::CDController() : initialised (false)
  209849. {
  209850. }
  209851. CDController::~CDController()
  209852. {
  209853. }
  209854. void CDController::prepare (SRB_ExecSCSICmd& s)
  209855. {
  209856. zerostruct (s);
  209857. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209858. s.SRB_HaID = deviceInfo->info.ha;
  209859. s.SRB_Target = deviceInfo->info.tgt;
  209860. s.SRB_Lun = deviceInfo->info.lun;
  209861. s.SRB_SenseLen = SENSE_LEN;
  209862. }
  209863. void CDController::perform (SRB_ExecSCSICmd& s)
  209864. {
  209865. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209866. s.SRB_PostProc = event;
  209867. ResetEvent (event);
  209868. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209869. deviceInfo->info.scsiDriveLetter,
  209870. deviceInfo->scsiHandle)
  209871. : fSendASPI32Command ((LPSRB)&s);
  209872. if (status == SS_PENDING)
  209873. WaitForSingleObject (event, 4000);
  209874. CloseHandle (event);
  209875. }
  209876. void CDController::setPaused (bool paused)
  209877. {
  209878. SRB_ExecSCSICmd s;
  209879. prepare (s);
  209880. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209881. s.SRB_CDBLen = 10;
  209882. s.CDBByte[0] = 0x4B;
  209883. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209884. perform (s);
  209885. }
  209886. void CDController::shutDown()
  209887. {
  209888. }
  209889. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209890. {
  209891. if (overlapBuffer != 0)
  209892. {
  209893. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209894. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209895. if (doJitter
  209896. && overlapBuffer->startFrame > 0
  209897. && overlapBuffer->numFrames > 0
  209898. && overlapBuffer->dataLength > 0)
  209899. {
  209900. const int numFrames = rb->numFrames;
  209901. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209902. {
  209903. rb->startFrame -= framesOverlap;
  209904. if (framesToCheck < framesOverlap
  209905. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209906. rb->numFrames += framesOverlap;
  209907. }
  209908. else
  209909. {
  209910. overlapBuffer->dataLength = 0;
  209911. overlapBuffer->startFrame = 0;
  209912. overlapBuffer->numFrames = 0;
  209913. }
  209914. }
  209915. if (! read (rb))
  209916. return false;
  209917. if (doJitter)
  209918. {
  209919. const int checkLen = framesToCheck * 2352;
  209920. const int maxToCheck = rb->dataLength - checkLen;
  209921. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209922. return true;
  209923. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209924. bool found = false;
  209925. for (int i = 0; i < maxToCheck; ++i)
  209926. {
  209927. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209928. {
  209929. i += checkLen;
  209930. rb->dataStartOffset = i;
  209931. rb->dataLength -= i;
  209932. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209933. found = true;
  209934. break;
  209935. }
  209936. }
  209937. rb->numFrames = rb->dataLength / 2352;
  209938. rb->dataLength = 2352 * rb->numFrames;
  209939. if (!found)
  209940. return false;
  209941. }
  209942. if (canDoJitter)
  209943. {
  209944. memcpy (overlapBuffer->buffer,
  209945. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209946. 2352 * framesToCheck);
  209947. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209948. overlapBuffer->numFrames = framesToCheck;
  209949. overlapBuffer->dataLength = 2352 * framesToCheck;
  209950. overlapBuffer->dataStartOffset = 0;
  209951. }
  209952. else
  209953. {
  209954. overlapBuffer->startFrame = 0;
  209955. overlapBuffer->numFrames = 0;
  209956. overlapBuffer->dataLength = 0;
  209957. }
  209958. return true;
  209959. }
  209960. else
  209961. {
  209962. return read (rb);
  209963. }
  209964. }
  209965. int CDController::getLastIndex()
  209966. {
  209967. char qdata[100];
  209968. SRB_ExecSCSICmd s;
  209969. prepare (s);
  209970. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209971. s.SRB_BufLen = sizeof (qdata);
  209972. s.SRB_BufPointer = (BYTE*)qdata;
  209973. s.SRB_CDBLen = 12;
  209974. s.CDBByte[0] = 0x42;
  209975. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209976. s.CDBByte[2] = 64;
  209977. s.CDBByte[3] = 1; // get current position
  209978. s.CDBByte[7] = 0;
  209979. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209980. perform (s);
  209981. if (s.SRB_Status == SS_COMP)
  209982. return qdata[7];
  209983. return 0;
  209984. }
  209985. bool CDDeviceHandle::readTOC (TOC* lpToc)
  209986. {
  209987. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209988. SRB_ExecSCSICmd s;
  209989. zerostruct (s);
  209990. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209991. s.SRB_HaID = info.ha;
  209992. s.SRB_Target = info.tgt;
  209993. s.SRB_Lun = info.lun;
  209994. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209995. s.SRB_BufLen = 0x324;
  209996. s.SRB_BufPointer = (BYTE*)lpToc;
  209997. s.SRB_SenseLen = 0x0E;
  209998. s.SRB_CDBLen = 0x0A;
  209999. s.SRB_PostProc = event;
  210000. s.CDBByte[0] = 0x43;
  210001. s.CDBByte[1] = 0x00;
  210002. s.CDBByte[7] = 0x03;
  210003. s.CDBByte[8] = 0x24;
  210004. ResetEvent (event);
  210005. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  210006. : fSendASPI32Command ((LPSRB)&s);
  210007. if (status == SS_PENDING)
  210008. WaitForSingleObject (event, 4000);
  210009. CloseHandle (event);
  210010. return (s.SRB_Status == SS_COMP);
  210011. }
  210012. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  210013. CDReadBuffer* const overlapBuffer)
  210014. {
  210015. if (controller == 0)
  210016. {
  210017. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  210018. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  210019. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  210020. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  210021. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  210022. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  210023. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  210024. }
  210025. buffer->index = 0;
  210026. if ((controller != 0)
  210027. && controller->readAudio (buffer, overlapBuffer))
  210028. {
  210029. if (buffer->wantsIndex)
  210030. buffer->index = controller->getLastIndex();
  210031. return true;
  210032. }
  210033. return false;
  210034. }
  210035. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210036. {
  210037. if (shouldBeOpen)
  210038. {
  210039. if (controller != 0)
  210040. {
  210041. controller->shutDown();
  210042. controller = 0;
  210043. }
  210044. if (scsiHandle != 0)
  210045. {
  210046. CloseHandle (scsiHandle);
  210047. scsiHandle = 0;
  210048. }
  210049. }
  210050. SRB_ExecSCSICmd s;
  210051. zerostruct (s);
  210052. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210053. s.SRB_HaID = info.ha;
  210054. s.SRB_Target = info.tgt;
  210055. s.SRB_Lun = info.lun;
  210056. s.SRB_SenseLen = SENSE_LEN;
  210057. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210058. s.SRB_BufLen = 0;
  210059. s.SRB_BufPointer = 0;
  210060. s.SRB_CDBLen = 12;
  210061. s.CDBByte[0] = 0x1b;
  210062. s.CDBByte[1] = (BYTE)(info.lun << 5);
  210063. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  210064. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  210065. s.SRB_PostProc = event;
  210066. ResetEvent (event);
  210067. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  210068. : fSendASPI32Command ((LPSRB)&s);
  210069. if (status == SS_PENDING)
  210070. WaitForSingleObject (event, 4000);
  210071. CloseHandle (event);
  210072. }
  210073. bool CDDeviceHandle::testController (const int type,
  210074. CDController* const newController,
  210075. CDReadBuffer* const rb)
  210076. {
  210077. controller = newController;
  210078. readType = (BYTE)type;
  210079. controller->deviceInfo = this;
  210080. controller->framesToCheck = 1;
  210081. controller->framesOverlap = 3;
  210082. bool passed = false;
  210083. memset (rb->buffer, 0xcd, rb->bufferSize);
  210084. if (controller->read (rb))
  210085. {
  210086. passed = true;
  210087. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  210088. int wrong = 0;
  210089. for (int i = rb->dataLength / 4; --i >= 0;)
  210090. {
  210091. if (*p++ == (int) 0xcdcdcdcd)
  210092. {
  210093. if (++wrong == 4)
  210094. {
  210095. passed = false;
  210096. break;
  210097. }
  210098. }
  210099. else
  210100. {
  210101. wrong = 0;
  210102. }
  210103. }
  210104. }
  210105. if (! passed)
  210106. {
  210107. controller->shutDown();
  210108. controller = 0;
  210109. }
  210110. return passed;
  210111. }
  210112. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  210113. {
  210114. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  210115. const int bufSize = 128;
  210116. BYTE buffer[bufSize];
  210117. zeromem (buffer, bufSize);
  210118. SRB_ExecSCSICmd s;
  210119. zerostruct (s);
  210120. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210121. s.SRB_HaID = ha;
  210122. s.SRB_Target = tgt;
  210123. s.SRB_Lun = lun;
  210124. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210125. s.SRB_BufLen = bufSize;
  210126. s.SRB_BufPointer = buffer;
  210127. s.SRB_SenseLen = SENSE_LEN;
  210128. s.SRB_CDBLen = 6;
  210129. s.SRB_PostProc = event;
  210130. s.CDBByte[0] = SCSI_INQUIRY;
  210131. s.CDBByte[4] = 100;
  210132. ResetEvent (event);
  210133. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  210134. WaitForSingleObject (event, 4000);
  210135. CloseHandle (event);
  210136. if (s.SRB_Status == SS_COMP)
  210137. {
  210138. memcpy (dev->vendor, &buffer[8], 8);
  210139. memcpy (dev->productId, &buffer[16], 16);
  210140. memcpy (dev->rev, &buffer[32], 4);
  210141. memcpy (dev->vendorSpec, &buffer[36], 20);
  210142. }
  210143. }
  210144. static int FindCDDevices (CDDeviceInfo* const list,
  210145. int maxItems)
  210146. {
  210147. int count = 0;
  210148. if (usingScsi)
  210149. {
  210150. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210151. {
  210152. TCHAR drivePath[8];
  210153. drivePath[0] = driveLetter;
  210154. drivePath[1] = ':';
  210155. drivePath[2] = '\\';
  210156. drivePath[3] = 0;
  210157. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210158. {
  210159. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  210160. if (h != INVALID_HANDLE_VALUE)
  210161. {
  210162. BYTE buffer[100], passThroughStruct[1024];
  210163. zeromem (buffer, sizeof (buffer));
  210164. zeromem (passThroughStruct, sizeof (passThroughStruct));
  210165. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  210166. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  210167. p->spt.CdbLength = 6;
  210168. p->spt.SenseInfoLength = 24;
  210169. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  210170. p->spt.DataTransferLength = 100;
  210171. p->spt.TimeOutValue = 2;
  210172. p->spt.DataBuffer = buffer;
  210173. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210174. p->spt.Cdb[0] = 0x12;
  210175. p->spt.Cdb[4] = 100;
  210176. DWORD bytesReturned = 0;
  210177. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210178. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  210179. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  210180. &bytesReturned, 0) != 0)
  210181. {
  210182. zeromem (&list[count], sizeof (CDDeviceInfo));
  210183. list[count].scsiDriveLetter = driveLetter;
  210184. memcpy (list[count].vendor, &buffer[8], 8);
  210185. memcpy (list[count].productId, &buffer[16], 16);
  210186. memcpy (list[count].rev, &buffer[32], 4);
  210187. memcpy (list[count].vendorSpec, &buffer[36], 20);
  210188. zeromem (passThroughStruct, sizeof (passThroughStruct));
  210189. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  210190. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  210191. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210192. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  210193. &bytesReturned, 0) != 0)
  210194. {
  210195. list[count].ha = scsiAddr->PortNumber;
  210196. list[count].tgt = scsiAddr->TargetId;
  210197. list[count].lun = scsiAddr->Lun;
  210198. ++count;
  210199. }
  210200. }
  210201. CloseHandle (h);
  210202. }
  210203. }
  210204. }
  210205. }
  210206. else
  210207. {
  210208. const DWORD d = fGetASPI32SupportInfo();
  210209. BYTE status = HIBYTE (LOWORD (d));
  210210. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  210211. return 0;
  210212. const int numAdapters = LOBYTE (LOWORD (d));
  210213. for (BYTE ha = 0; ha < numAdapters; ++ha)
  210214. {
  210215. SRB_HAInquiry s;
  210216. zerostruct (s);
  210217. s.SRB_Cmd = SC_HA_INQUIRY;
  210218. s.SRB_HaID = ha;
  210219. fSendASPI32Command ((LPSRB)&s);
  210220. if (s.SRB_Status == SS_COMP)
  210221. {
  210222. maxItems = (int)s.HA_Unique[3];
  210223. if (maxItems == 0)
  210224. maxItems = 8;
  210225. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  210226. {
  210227. for (BYTE lun = 0; lun < 8; ++lun)
  210228. {
  210229. SRB_GDEVBlock sb;
  210230. zerostruct (sb);
  210231. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  210232. sb.SRB_HaID = ha;
  210233. sb.SRB_Target = tgt;
  210234. sb.SRB_Lun = lun;
  210235. fSendASPI32Command ((LPSRB) &sb);
  210236. if (sb.SRB_Status == SS_COMP
  210237. && sb.SRB_DeviceType == DTYPE_CROM)
  210238. {
  210239. zeromem (&list[count], sizeof (CDDeviceInfo));
  210240. list[count].ha = ha;
  210241. list[count].tgt = tgt;
  210242. list[count].lun = lun;
  210243. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  210244. ++count;
  210245. }
  210246. }
  210247. }
  210248. }
  210249. }
  210250. }
  210251. return count;
  210252. }
  210253. static int ripperUsers = 0;
  210254. static bool initialisedOk = false;
  210255. class DeinitialiseTimer : private Timer,
  210256. private DeletedAtShutdown
  210257. {
  210258. DeinitialiseTimer (const DeinitialiseTimer&);
  210259. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  210260. public:
  210261. DeinitialiseTimer()
  210262. {
  210263. startTimer (4000);
  210264. }
  210265. ~DeinitialiseTimer()
  210266. {
  210267. if (--ripperUsers == 0)
  210268. DeinitialiseCDRipper();
  210269. }
  210270. void timerCallback()
  210271. {
  210272. delete this;
  210273. }
  210274. juce_UseDebuggingNewOperator
  210275. };
  210276. static void incUserCount()
  210277. {
  210278. if (ripperUsers++ == 0)
  210279. initialisedOk = InitialiseCDRipper();
  210280. }
  210281. static void decUserCount()
  210282. {
  210283. new DeinitialiseTimer();
  210284. }
  210285. struct CDDeviceWrapper
  210286. {
  210287. ScopedPointer<CDDeviceHandle> cdH;
  210288. ScopedPointer<CDReadBuffer> overlapBuffer;
  210289. bool jitter;
  210290. };
  210291. static int getAddressOf (const TOCTRACK* const t)
  210292. {
  210293. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  210294. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  210295. }
  210296. static const int samplesPerFrame = 44100 / 75;
  210297. static const int bytesPerFrame = samplesPerFrame * 4;
  210298. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  210299. {
  210300. SRB_GDEVBlock s;
  210301. zerostruct (s);
  210302. s.SRB_Cmd = SC_GET_DEV_TYPE;
  210303. s.SRB_HaID = device->ha;
  210304. s.SRB_Target = device->tgt;
  210305. s.SRB_Lun = device->lun;
  210306. if (usingScsi)
  210307. {
  210308. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  210309. if (h != INVALID_HANDLE_VALUE)
  210310. {
  210311. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  210312. cdh->scsiHandle = h;
  210313. return cdh;
  210314. }
  210315. }
  210316. else
  210317. {
  210318. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  210319. && s.SRB_DeviceType == DTYPE_CROM)
  210320. {
  210321. return new CDDeviceHandle (device);
  210322. }
  210323. }
  210324. return 0;
  210325. }
  210326. }
  210327. const StringArray AudioCDReader::getAvailableCDNames()
  210328. {
  210329. using namespace CDReaderHelpers;
  210330. StringArray results;
  210331. incUserCount();
  210332. if (initialisedOk)
  210333. {
  210334. CDDeviceInfo list[8];
  210335. const int num = FindCDDevices (list, 8);
  210336. decUserCount();
  210337. for (int i = 0; i < num; ++i)
  210338. {
  210339. String s;
  210340. if (list[i].scsiDriveLetter > 0)
  210341. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210342. s << String (list[i].vendor).trim()
  210343. << ' ' << String (list[i].productId).trim()
  210344. << ' ' << String (list[i].rev).trim();
  210345. results.add (s);
  210346. }
  210347. }
  210348. return results;
  210349. }
  210350. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210351. {
  210352. using namespace CDReaderHelpers;
  210353. incUserCount();
  210354. if (initialisedOk)
  210355. {
  210356. CDDeviceInfo list[8];
  210357. const int num = FindCDDevices (list, 8);
  210358. if (((unsigned int) deviceIndex) < (unsigned int) num)
  210359. {
  210360. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  210361. if (handle != 0)
  210362. {
  210363. CDDeviceWrapper* const d = new CDDeviceWrapper();
  210364. d->cdH = handle;
  210365. d->overlapBuffer = new CDReadBuffer(3);
  210366. return new AudioCDReader (d);
  210367. }
  210368. }
  210369. }
  210370. decUserCount();
  210371. return 0;
  210372. }
  210373. AudioCDReader::AudioCDReader (void* handle_)
  210374. : AudioFormatReader (0, "CD Audio"),
  210375. handle (handle_),
  210376. indexingEnabled (false),
  210377. lastIndex (0),
  210378. firstFrameInBuffer (0),
  210379. samplesInBuffer (0)
  210380. {
  210381. using namespace CDReaderHelpers;
  210382. jassert (handle_ != 0);
  210383. refreshTrackLengths();
  210384. sampleRate = 44100.0;
  210385. bitsPerSample = 16;
  210386. numChannels = 2;
  210387. usesFloatingPointData = false;
  210388. buffer.setSize (4 * bytesPerFrame, true);
  210389. }
  210390. AudioCDReader::~AudioCDReader()
  210391. {
  210392. using namespace CDReaderHelpers;
  210393. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210394. delete device;
  210395. decUserCount();
  210396. }
  210397. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210398. int64 startSampleInFile, int numSamples)
  210399. {
  210400. using namespace CDReaderHelpers;
  210401. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210402. bool ok = true;
  210403. while (numSamples > 0)
  210404. {
  210405. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210406. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210407. if (startSampleInFile >= bufferStartSample
  210408. && startSampleInFile < bufferEndSample)
  210409. {
  210410. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210411. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210412. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210413. const short* src = (const short*) buffer.getData();
  210414. src += 2 * (startSampleInFile - bufferStartSample);
  210415. for (int i = 0; i < toDo; ++i)
  210416. {
  210417. l[i] = src [i << 1] << 16;
  210418. if (r != 0)
  210419. r[i] = src [(i << 1) + 1] << 16;
  210420. }
  210421. startOffsetInDestBuffer += toDo;
  210422. startSampleInFile += toDo;
  210423. numSamples -= toDo;
  210424. }
  210425. else
  210426. {
  210427. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210428. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210429. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210430. {
  210431. device->overlapBuffer->dataLength = 0;
  210432. device->overlapBuffer->startFrame = 0;
  210433. device->overlapBuffer->numFrames = 0;
  210434. device->jitter = false;
  210435. }
  210436. firstFrameInBuffer = frameNeeded;
  210437. lastIndex = 0;
  210438. CDReadBuffer readBuffer (framesInBuffer + 4);
  210439. readBuffer.wantsIndex = indexingEnabled;
  210440. int i;
  210441. for (i = 5; --i >= 0;)
  210442. {
  210443. readBuffer.startFrame = frameNeeded;
  210444. readBuffer.numFrames = framesInBuffer;
  210445. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  210446. break;
  210447. else
  210448. device->overlapBuffer->dataLength = 0;
  210449. }
  210450. if (i >= 0)
  210451. {
  210452. memcpy ((char*) buffer.getData(),
  210453. readBuffer.buffer + readBuffer.dataStartOffset,
  210454. readBuffer.dataLength);
  210455. samplesInBuffer = readBuffer.dataLength >> 2;
  210456. lastIndex = readBuffer.index;
  210457. }
  210458. else
  210459. {
  210460. int* l = destSamples[0] + startOffsetInDestBuffer;
  210461. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210462. while (--numSamples >= 0)
  210463. {
  210464. *l++ = 0;
  210465. if (r != 0)
  210466. *r++ = 0;
  210467. }
  210468. // sometimes the read fails for just the very last couple of blocks, so
  210469. // we'll ignore and errors in the last half-second of the disk..
  210470. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  210471. break;
  210472. }
  210473. }
  210474. }
  210475. return ok;
  210476. }
  210477. bool AudioCDReader::isCDStillPresent() const
  210478. {
  210479. using namespace CDReaderHelpers;
  210480. TOC toc;
  210481. zerostruct (toc);
  210482. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  210483. }
  210484. void AudioCDReader::refreshTrackLengths()
  210485. {
  210486. using namespace CDReaderHelpers;
  210487. trackStartSamples.clear();
  210488. zeromem (audioTracks, sizeof (audioTracks));
  210489. TOC toc;
  210490. zerostruct (toc);
  210491. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  210492. {
  210493. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210494. for (int i = 0; i <= numTracks; ++i)
  210495. {
  210496. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  210497. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  210498. }
  210499. }
  210500. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  210501. }
  210502. bool AudioCDReader::isTrackAudio (int trackNum) const
  210503. {
  210504. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  210505. }
  210506. void AudioCDReader::enableIndexScanning (bool b)
  210507. {
  210508. indexingEnabled = b;
  210509. }
  210510. int AudioCDReader::getLastIndex() const
  210511. {
  210512. return lastIndex;
  210513. }
  210514. const int framesPerIndexRead = 4;
  210515. int AudioCDReader::getIndexAt (int samplePos)
  210516. {
  210517. using namespace CDReaderHelpers;
  210518. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210519. const int frameNeeded = samplePos / samplesPerFrame;
  210520. device->overlapBuffer->dataLength = 0;
  210521. device->overlapBuffer->startFrame = 0;
  210522. device->overlapBuffer->numFrames = 0;
  210523. device->jitter = false;
  210524. firstFrameInBuffer = 0;
  210525. lastIndex = 0;
  210526. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210527. readBuffer.wantsIndex = true;
  210528. int i;
  210529. for (i = 5; --i >= 0;)
  210530. {
  210531. readBuffer.startFrame = frameNeeded;
  210532. readBuffer.numFrames = framesPerIndexRead;
  210533. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210534. break;
  210535. }
  210536. if (i >= 0)
  210537. return readBuffer.index;
  210538. return -1;
  210539. }
  210540. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210541. {
  210542. using namespace CDReaderHelpers;
  210543. Array <int> indexes;
  210544. const int trackStart = getPositionOfTrackStart (trackNumber);
  210545. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210546. bool needToScan = true;
  210547. if (trackEnd - trackStart > 20 * 44100)
  210548. {
  210549. // check the end of the track for indexes before scanning the whole thing
  210550. needToScan = false;
  210551. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210552. bool seenAnIndex = false;
  210553. while (pos <= trackEnd - samplesPerFrame)
  210554. {
  210555. const int index = getIndexAt (pos);
  210556. if (index == 0)
  210557. {
  210558. // lead-out, so skip back a bit if we've not found any indexes yet..
  210559. if (seenAnIndex)
  210560. break;
  210561. pos -= 44100 * 5;
  210562. if (pos < trackStart)
  210563. break;
  210564. }
  210565. else
  210566. {
  210567. if (index > 0)
  210568. seenAnIndex = true;
  210569. if (index > 1)
  210570. {
  210571. needToScan = true;
  210572. break;
  210573. }
  210574. pos += samplesPerFrame * framesPerIndexRead;
  210575. }
  210576. }
  210577. }
  210578. if (needToScan)
  210579. {
  210580. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210581. int pos = trackStart;
  210582. int last = -1;
  210583. while (pos < trackEnd - samplesPerFrame * 10)
  210584. {
  210585. const int frameNeeded = pos / samplesPerFrame;
  210586. device->overlapBuffer->dataLength = 0;
  210587. device->overlapBuffer->startFrame = 0;
  210588. device->overlapBuffer->numFrames = 0;
  210589. device->jitter = false;
  210590. firstFrameInBuffer = 0;
  210591. CDReadBuffer readBuffer (4);
  210592. readBuffer.wantsIndex = true;
  210593. int i;
  210594. for (i = 5; --i >= 0;)
  210595. {
  210596. readBuffer.startFrame = frameNeeded;
  210597. readBuffer.numFrames = framesPerIndexRead;
  210598. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210599. break;
  210600. }
  210601. if (i < 0)
  210602. break;
  210603. if (readBuffer.index > last && readBuffer.index > 1)
  210604. {
  210605. last = readBuffer.index;
  210606. indexes.add (pos);
  210607. }
  210608. pos += samplesPerFrame * framesPerIndexRead;
  210609. }
  210610. indexes.removeValue (trackStart);
  210611. }
  210612. return indexes;
  210613. }
  210614. void AudioCDReader::ejectDisk()
  210615. {
  210616. using namespace CDReaderHelpers;
  210617. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210618. }
  210619. #endif
  210620. #if JUCE_USE_CDBURNER
  210621. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210622. {
  210623. CoInitialize (0);
  210624. IDiscMaster* dm;
  210625. IDiscRecorder* result = 0;
  210626. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210627. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210628. IID_IDiscMaster,
  210629. (void**) &dm)))
  210630. {
  210631. if (SUCCEEDED (dm->Open()))
  210632. {
  210633. IEnumDiscRecorders* drEnum = 0;
  210634. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210635. {
  210636. IDiscRecorder* dr = 0;
  210637. DWORD dummy;
  210638. int index = 0;
  210639. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210640. {
  210641. if (indexToOpen == index)
  210642. {
  210643. result = dr;
  210644. break;
  210645. }
  210646. else if (list != 0)
  210647. {
  210648. BSTR path;
  210649. if (SUCCEEDED (dr->GetPath (&path)))
  210650. list->add ((const WCHAR*) path);
  210651. }
  210652. ++index;
  210653. dr->Release();
  210654. }
  210655. drEnum->Release();
  210656. }
  210657. if (master == 0)
  210658. dm->Close();
  210659. }
  210660. if (master != 0)
  210661. *master = dm;
  210662. else
  210663. dm->Release();
  210664. }
  210665. return result;
  210666. }
  210667. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210668. public Timer
  210669. {
  210670. public:
  210671. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210672. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210673. listener (0), progress (0), shouldCancel (false)
  210674. {
  210675. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210676. jassert (SUCCEEDED (hr));
  210677. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210678. //jassert (SUCCEEDED (hr));
  210679. lastState = getDiskState();
  210680. startTimer (2000);
  210681. }
  210682. ~Pimpl() {}
  210683. void releaseObjects()
  210684. {
  210685. discRecorder->Close();
  210686. if (redbook != 0)
  210687. redbook->Release();
  210688. discRecorder->Release();
  210689. discMaster->Release();
  210690. Release();
  210691. }
  210692. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210693. {
  210694. if (listener != 0 && ! shouldCancel)
  210695. shouldCancel = listener->audioCDBurnProgress (progress);
  210696. *pbCancel = shouldCancel;
  210697. return S_OK;
  210698. }
  210699. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210700. {
  210701. progress = nCompleted / (float) nTotal;
  210702. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210703. return E_NOTIMPL;
  210704. }
  210705. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210706. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210707. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210708. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210709. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210710. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210711. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210712. class ScopedDiscOpener
  210713. {
  210714. public:
  210715. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210716. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210717. private:
  210718. Pimpl& pimpl;
  210719. ScopedDiscOpener (const ScopedDiscOpener&);
  210720. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210721. };
  210722. DiskState getDiskState()
  210723. {
  210724. const ScopedDiscOpener opener (*this);
  210725. long type, flags;
  210726. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210727. if (FAILED (hr))
  210728. return unknown;
  210729. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210730. return writableDiskPresent;
  210731. if (type == 0)
  210732. return noDisc;
  210733. else
  210734. return readOnlyDiskPresent;
  210735. }
  210736. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210737. {
  210738. ComSmartPtr<IPropertyStorage> prop;
  210739. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210740. return defaultReturn;
  210741. PROPSPEC iPropSpec;
  210742. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210743. iPropSpec.lpwstr = name;
  210744. PROPVARIANT iPropVariant;
  210745. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210746. ? defaultReturn : (int) iPropVariant.lVal;
  210747. }
  210748. bool setIntProperty (const LPOLESTR name, const int value) const
  210749. {
  210750. ComSmartPtr<IPropertyStorage> prop;
  210751. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210752. return false;
  210753. PROPSPEC iPropSpec;
  210754. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210755. iPropSpec.lpwstr = name;
  210756. PROPVARIANT iPropVariant;
  210757. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210758. return false;
  210759. iPropVariant.lVal = (long) value;
  210760. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210761. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210762. }
  210763. void timerCallback()
  210764. {
  210765. const DiskState state = getDiskState();
  210766. if (state != lastState)
  210767. {
  210768. lastState = state;
  210769. owner.sendChangeMessage (&owner);
  210770. }
  210771. }
  210772. AudioCDBurner& owner;
  210773. DiskState lastState;
  210774. IDiscMaster* discMaster;
  210775. IDiscRecorder* discRecorder;
  210776. IRedbookDiscMaster* redbook;
  210777. AudioCDBurner::BurnProgressListener* listener;
  210778. float progress;
  210779. bool shouldCancel;
  210780. };
  210781. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210782. {
  210783. IDiscMaster* discMaster = 0;
  210784. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210785. if (discRecorder != 0)
  210786. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210787. }
  210788. AudioCDBurner::~AudioCDBurner()
  210789. {
  210790. if (pimpl != 0)
  210791. pimpl.release()->releaseObjects();
  210792. }
  210793. const StringArray AudioCDBurner::findAvailableDevices()
  210794. {
  210795. StringArray devs;
  210796. enumCDBurners (&devs, -1, 0);
  210797. return devs;
  210798. }
  210799. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210800. {
  210801. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210802. if (b->pimpl == 0)
  210803. b = 0;
  210804. return b.release();
  210805. }
  210806. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210807. {
  210808. return pimpl->getDiskState();
  210809. }
  210810. bool AudioCDBurner::isDiskPresent() const
  210811. {
  210812. return getDiskState() == writableDiskPresent;
  210813. }
  210814. bool AudioCDBurner::openTray()
  210815. {
  210816. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210817. return SUCCEEDED (pimpl->discRecorder->Eject());
  210818. }
  210819. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210820. {
  210821. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210822. DiskState oldState = getDiskState();
  210823. DiskState newState = oldState;
  210824. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210825. {
  210826. newState = getDiskState();
  210827. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210828. }
  210829. return newState;
  210830. }
  210831. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210832. {
  210833. Array<int> results;
  210834. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210835. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210836. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210837. if (speeds[i] <= maxSpeed)
  210838. results.add (speeds[i]);
  210839. results.addIfNotAlreadyThere (maxSpeed);
  210840. return results;
  210841. }
  210842. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210843. {
  210844. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210845. return false;
  210846. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210847. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210848. }
  210849. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210850. {
  210851. long blocksFree = 0;
  210852. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210853. return blocksFree;
  210854. }
  210855. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210856. bool performFakeBurnForTesting, int writeSpeed)
  210857. {
  210858. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210859. pimpl->listener = listener;
  210860. pimpl->progress = 0;
  210861. pimpl->shouldCancel = false;
  210862. UINT_PTR cookie;
  210863. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210864. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210865. ejectDiscAfterwards);
  210866. String error;
  210867. if (hr != S_OK)
  210868. {
  210869. const char* e = "Couldn't open or write to the CD device";
  210870. if (hr == IMAPI_E_USERABORT)
  210871. e = "User cancelled the write operation";
  210872. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210873. e = "No Disk present";
  210874. error = e;
  210875. }
  210876. pimpl->discMaster->ProgressUnadvise (cookie);
  210877. pimpl->listener = 0;
  210878. return error;
  210879. }
  210880. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210881. {
  210882. if (audioSource == 0)
  210883. return false;
  210884. ScopedPointer<AudioSource> source (audioSource);
  210885. long bytesPerBlock;
  210886. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210887. const int samplesPerBlock = bytesPerBlock / 4;
  210888. bool ok = true;
  210889. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210890. HeapBlock <byte> buffer (bytesPerBlock);
  210891. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210892. int samplesDone = 0;
  210893. source->prepareToPlay (samplesPerBlock, 44100.0);
  210894. while (ok)
  210895. {
  210896. {
  210897. AudioSourceChannelInfo info;
  210898. info.buffer = &sourceBuffer;
  210899. info.numSamples = samplesPerBlock;
  210900. info.startSample = 0;
  210901. sourceBuffer.clear();
  210902. source->getNextAudioBlock (info);
  210903. }
  210904. zeromem (buffer, bytesPerBlock);
  210905. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210906. buffer, samplesPerBlock, 4);
  210907. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210908. buffer + 2, samplesPerBlock, 4);
  210909. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210910. if (FAILED (hr))
  210911. ok = false;
  210912. samplesDone += samplesPerBlock;
  210913. if (samplesDone >= numSamples)
  210914. break;
  210915. }
  210916. hr = pimpl->redbook->CloseAudioTrack();
  210917. return ok && hr == S_OK;
  210918. }
  210919. #endif
  210920. #endif
  210921. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210922. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210923. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210924. // compiled on its own).
  210925. #if JUCE_INCLUDED_FILE
  210926. using ::free;
  210927. namespace MidiConstants
  210928. {
  210929. static const int midiBufferSize = 1024 * 10;
  210930. static const int numInHeaders = 32;
  210931. static const int inBufferSize = 256;
  210932. }
  210933. class MidiInThread : public Thread
  210934. {
  210935. public:
  210936. MidiInThread (MidiInput* const input_,
  210937. MidiInputCallback* const callback_)
  210938. : Thread ("Juce Midi"),
  210939. hIn (0),
  210940. input (input_),
  210941. callback (callback_),
  210942. isStarted (false),
  210943. startTime (0),
  210944. pendingLength(0)
  210945. {
  210946. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210947. {
  210948. zeromem (&hdr[i], sizeof (MIDIHDR));
  210949. hdr[i].lpData = inData[i];
  210950. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210951. }
  210952. };
  210953. ~MidiInThread()
  210954. {
  210955. stop();
  210956. if (hIn != 0)
  210957. {
  210958. int count = 5;
  210959. while (--count >= 0)
  210960. {
  210961. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210962. break;
  210963. Sleep (20);
  210964. }
  210965. }
  210966. }
  210967. void handle (const uint32 message, const uint32 timeStamp)
  210968. {
  210969. const int byte = message & 0xff;
  210970. if (byte < 0x80)
  210971. return;
  210972. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210973. const double time = timeStampToTime (timeStamp);
  210974. {
  210975. const ScopedLock sl (lock);
  210976. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210977. {
  210978. char* const p = pending + pendingLength;
  210979. *(double*) p = time;
  210980. *(uint32*) (p + 8) = numBytes;
  210981. *(uint32*) (p + 12) = message;
  210982. pendingLength += 12 + numBytes;
  210983. }
  210984. else
  210985. {
  210986. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210987. }
  210988. }
  210989. notify();
  210990. }
  210991. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  210992. {
  210993. const int num = hdr->dwBytesRecorded;
  210994. if (num > 0)
  210995. {
  210996. const double time = timeStampToTime (timeStamp);
  210997. {
  210998. const ScopedLock sl (lock);
  210999. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  211000. {
  211001. char* const p = pending + pendingLength;
  211002. *(double*) p = time;
  211003. *(uint32*) (p + 8) = num;
  211004. memcpy (p + 12, hdr->lpData, num);
  211005. pendingLength += 12 + num;
  211006. }
  211007. else
  211008. {
  211009. jassertfalse; // midi buffer overflow! You might need to increase the size..
  211010. }
  211011. }
  211012. notify();
  211013. }
  211014. }
  211015. void writeBlock (const int i)
  211016. {
  211017. hdr[i].dwBytesRecorded = 0;
  211018. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  211019. jassert (res == MMSYSERR_NOERROR);
  211020. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  211021. jassert (res == MMSYSERR_NOERROR);
  211022. }
  211023. void run()
  211024. {
  211025. MemoryBlock pendingCopy (64);
  211026. while (! threadShouldExit())
  211027. {
  211028. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  211029. {
  211030. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  211031. {
  211032. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  211033. (void) res;
  211034. jassert (res == MMSYSERR_NOERROR);
  211035. writeBlock (i);
  211036. }
  211037. }
  211038. int len;
  211039. {
  211040. const ScopedLock sl (lock);
  211041. len = pendingLength;
  211042. if (len > 0)
  211043. {
  211044. pendingCopy.ensureSize (len);
  211045. pendingCopy.copyFrom (pending, 0, len);
  211046. pendingLength = 0;
  211047. }
  211048. }
  211049. //xxx needs to figure out if blocks are broken up or not
  211050. if (len == 0)
  211051. {
  211052. wait (500);
  211053. }
  211054. else
  211055. {
  211056. const char* p = (const char*) pendingCopy.getData();
  211057. while (len > 0)
  211058. {
  211059. const double time = *(const double*) p;
  211060. const int messageLen = *(const int*) (p + 8);
  211061. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  211062. callback->handleIncomingMidiMessage (input, message);
  211063. p += 12 + messageLen;
  211064. len -= 12 + messageLen;
  211065. }
  211066. }
  211067. }
  211068. }
  211069. void start()
  211070. {
  211071. jassert (hIn != 0);
  211072. if (hIn != 0 && ! isStarted)
  211073. {
  211074. stop();
  211075. activeMidiThreads.addIfNotAlreadyThere (this);
  211076. int i;
  211077. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  211078. writeBlock (i);
  211079. startTime = Time::getMillisecondCounter();
  211080. MMRESULT res = midiInStart (hIn);
  211081. jassert (res == MMSYSERR_NOERROR);
  211082. if (res == MMSYSERR_NOERROR)
  211083. {
  211084. isStarted = true;
  211085. pendingLength = 0;
  211086. startThread (6);
  211087. }
  211088. }
  211089. }
  211090. void stop()
  211091. {
  211092. if (isStarted)
  211093. {
  211094. stopThread (5000);
  211095. midiInReset (hIn);
  211096. midiInStop (hIn);
  211097. activeMidiThreads.removeValue (this);
  211098. { const ScopedLock sl (lock); }
  211099. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  211100. {
  211101. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  211102. {
  211103. int c = 10;
  211104. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  211105. Sleep (20);
  211106. jassert (c >= 0);
  211107. }
  211108. }
  211109. isStarted = false;
  211110. pendingLength = 0;
  211111. }
  211112. }
  211113. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211114. {
  211115. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  211116. if (thread != 0 && activeMidiThreads.contains (thread))
  211117. {
  211118. if (uMsg == MIM_DATA)
  211119. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  211120. else if (uMsg == MIM_LONGDATA)
  211121. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211122. }
  211123. }
  211124. juce_UseDebuggingNewOperator
  211125. HMIDIIN hIn;
  211126. private:
  211127. static Array <void*, CriticalSection> activeMidiThreads;
  211128. MidiInput* input;
  211129. MidiInputCallback* callback;
  211130. bool isStarted;
  211131. uint32 startTime;
  211132. CriticalSection lock;
  211133. MIDIHDR hdr [MidiConstants::numInHeaders];
  211134. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  211135. int pendingLength;
  211136. char pending [MidiConstants::midiBufferSize];
  211137. double timeStampToTime (uint32 timeStamp)
  211138. {
  211139. timeStamp += startTime;
  211140. const uint32 now = Time::getMillisecondCounter();
  211141. if (timeStamp > now)
  211142. {
  211143. if (timeStamp > now + 2)
  211144. --startTime;
  211145. timeStamp = now;
  211146. }
  211147. return 0.001 * timeStamp;
  211148. }
  211149. MidiInThread (const MidiInThread&);
  211150. MidiInThread& operator= (const MidiInThread&);
  211151. };
  211152. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  211153. const StringArray MidiInput::getDevices()
  211154. {
  211155. StringArray s;
  211156. const int num = midiInGetNumDevs();
  211157. for (int i = 0; i < num; ++i)
  211158. {
  211159. MIDIINCAPS mc;
  211160. zerostruct (mc);
  211161. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211162. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211163. }
  211164. return s;
  211165. }
  211166. int MidiInput::getDefaultDeviceIndex()
  211167. {
  211168. return 0;
  211169. }
  211170. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211171. {
  211172. if (callback == 0)
  211173. return 0;
  211174. UINT deviceId = MIDI_MAPPER;
  211175. int n = 0;
  211176. String name;
  211177. const int num = midiInGetNumDevs();
  211178. for (int i = 0; i < num; ++i)
  211179. {
  211180. MIDIINCAPS mc;
  211181. zerostruct (mc);
  211182. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211183. {
  211184. if (index == n)
  211185. {
  211186. deviceId = i;
  211187. name = String (mc.szPname, sizeof (mc.szPname));
  211188. break;
  211189. }
  211190. ++n;
  211191. }
  211192. }
  211193. ScopedPointer <MidiInput> in (new MidiInput (name));
  211194. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  211195. HMIDIIN h;
  211196. HRESULT err = midiInOpen (&h, deviceId,
  211197. (DWORD_PTR) &MidiInThread::midiInCallback,
  211198. (DWORD_PTR) (MidiInThread*) thread,
  211199. CALLBACK_FUNCTION);
  211200. if (err == MMSYSERR_NOERROR)
  211201. {
  211202. thread->hIn = h;
  211203. in->internal = thread.release();
  211204. return in.release();
  211205. }
  211206. return 0;
  211207. }
  211208. MidiInput::MidiInput (const String& name_)
  211209. : name (name_),
  211210. internal (0)
  211211. {
  211212. }
  211213. MidiInput::~MidiInput()
  211214. {
  211215. delete static_cast <MidiInThread*> (internal);
  211216. }
  211217. void MidiInput::start()
  211218. {
  211219. static_cast <MidiInThread*> (internal)->start();
  211220. }
  211221. void MidiInput::stop()
  211222. {
  211223. static_cast <MidiInThread*> (internal)->stop();
  211224. }
  211225. struct MidiOutHandle
  211226. {
  211227. int refCount;
  211228. UINT deviceId;
  211229. HMIDIOUT handle;
  211230. static Array<MidiOutHandle*> activeHandles;
  211231. juce_UseDebuggingNewOperator
  211232. };
  211233. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211234. const StringArray MidiOutput::getDevices()
  211235. {
  211236. StringArray s;
  211237. const int num = midiOutGetNumDevs();
  211238. for (int i = 0; i < num; ++i)
  211239. {
  211240. MIDIOUTCAPS mc;
  211241. zerostruct (mc);
  211242. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211243. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211244. }
  211245. return s;
  211246. }
  211247. int MidiOutput::getDefaultDeviceIndex()
  211248. {
  211249. const int num = midiOutGetNumDevs();
  211250. int n = 0;
  211251. for (int i = 0; i < num; ++i)
  211252. {
  211253. MIDIOUTCAPS mc;
  211254. zerostruct (mc);
  211255. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211256. {
  211257. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211258. return n;
  211259. ++n;
  211260. }
  211261. }
  211262. return 0;
  211263. }
  211264. MidiOutput* MidiOutput::openDevice (int index)
  211265. {
  211266. UINT deviceId = MIDI_MAPPER;
  211267. const int num = midiOutGetNumDevs();
  211268. int i, n = 0;
  211269. for (i = 0; i < num; ++i)
  211270. {
  211271. MIDIOUTCAPS mc;
  211272. zerostruct (mc);
  211273. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211274. {
  211275. // use the microsoft sw synth as a default - best not to allow deviceId
  211276. // to be MIDI_MAPPER, or else device sharing breaks
  211277. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211278. deviceId = i;
  211279. if (index == n)
  211280. {
  211281. deviceId = i;
  211282. break;
  211283. }
  211284. ++n;
  211285. }
  211286. }
  211287. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211288. {
  211289. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211290. if (han != 0 && han->deviceId == deviceId)
  211291. {
  211292. han->refCount++;
  211293. MidiOutput* const out = new MidiOutput();
  211294. out->internal = han;
  211295. return out;
  211296. }
  211297. }
  211298. for (i = 4; --i >= 0;)
  211299. {
  211300. HMIDIOUT h = 0;
  211301. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211302. if (res == MMSYSERR_NOERROR)
  211303. {
  211304. MidiOutHandle* const han = new MidiOutHandle();
  211305. han->deviceId = deviceId;
  211306. han->refCount = 1;
  211307. han->handle = h;
  211308. MidiOutHandle::activeHandles.add (han);
  211309. MidiOutput* const out = new MidiOutput();
  211310. out->internal = han;
  211311. return out;
  211312. }
  211313. else if (res == MMSYSERR_ALLOCATED)
  211314. {
  211315. Sleep (100);
  211316. }
  211317. else
  211318. {
  211319. break;
  211320. }
  211321. }
  211322. return 0;
  211323. }
  211324. MidiOutput::~MidiOutput()
  211325. {
  211326. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211327. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211328. {
  211329. midiOutClose (h->handle);
  211330. MidiOutHandle::activeHandles.removeValue (h);
  211331. delete h;
  211332. }
  211333. }
  211334. void MidiOutput::reset()
  211335. {
  211336. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211337. midiOutReset (h->handle);
  211338. }
  211339. bool MidiOutput::getVolume (float& leftVol,
  211340. float& rightVol)
  211341. {
  211342. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211343. DWORD n;
  211344. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211345. {
  211346. const unsigned short* const nn = (const unsigned short*) &n;
  211347. rightVol = nn[0] / (float) 0xffff;
  211348. leftVol = nn[1] / (float) 0xffff;
  211349. return true;
  211350. }
  211351. else
  211352. {
  211353. rightVol = leftVol = 1.0f;
  211354. return false;
  211355. }
  211356. }
  211357. void MidiOutput::setVolume (float leftVol,
  211358. float rightVol)
  211359. {
  211360. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211361. DWORD n;
  211362. unsigned short* const nn = (unsigned short*) &n;
  211363. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211364. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211365. midiOutSetVolume (handle->handle, n);
  211366. }
  211367. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211368. {
  211369. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211370. if (message.getRawDataSize() > 3
  211371. || message.isSysEx())
  211372. {
  211373. MIDIHDR h;
  211374. zerostruct (h);
  211375. h.lpData = (char*) message.getRawData();
  211376. h.dwBufferLength = message.getRawDataSize();
  211377. h.dwBytesRecorded = message.getRawDataSize();
  211378. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211379. {
  211380. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211381. if (res == MMSYSERR_NOERROR)
  211382. {
  211383. while ((h.dwFlags & MHDR_DONE) == 0)
  211384. Sleep (1);
  211385. int count = 500; // 1 sec timeout
  211386. while (--count >= 0)
  211387. {
  211388. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211389. if (res == MIDIERR_STILLPLAYING)
  211390. Sleep (2);
  211391. else
  211392. break;
  211393. }
  211394. }
  211395. }
  211396. }
  211397. else
  211398. {
  211399. midiOutShortMsg (handle->handle,
  211400. *(unsigned int*) message.getRawData());
  211401. }
  211402. }
  211403. #endif
  211404. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211405. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211406. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211407. // compiled on its own).
  211408. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211409. #undef WINDOWS
  211410. // #define ASIO_DEBUGGING
  211411. #ifdef ASIO_DEBUGGING
  211412. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211413. #else
  211414. #define log(a) {}
  211415. #endif
  211416. #ifdef ASIO_DEBUGGING
  211417. static void logError (const String& context, long error)
  211418. {
  211419. String err ("unknown error");
  211420. if (error == ASE_NotPresent)
  211421. err = "Not Present";
  211422. else if (error == ASE_HWMalfunction)
  211423. err = "Hardware Malfunction";
  211424. else if (error == ASE_InvalidParameter)
  211425. err = "Invalid Parameter";
  211426. else if (error == ASE_InvalidMode)
  211427. err = "Invalid Mode";
  211428. else if (error == ASE_SPNotAdvancing)
  211429. err = "Sample position not advancing";
  211430. else if (error == ASE_NoClock)
  211431. err = "No Clock";
  211432. else if (error == ASE_NoMemory)
  211433. err = "Out of memory";
  211434. log ("!!error: " + context + " - " + err);
  211435. }
  211436. #else
  211437. #define logError(a, b) {}
  211438. #endif
  211439. class ASIOAudioIODevice;
  211440. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211441. static const int maxASIOChannels = 160;
  211442. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211443. private Timer
  211444. {
  211445. public:
  211446. Component ourWindow;
  211447. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211448. const String& optionalDllForDirectLoading_)
  211449. : AudioIODevice (name_, "ASIO"),
  211450. asioObject (0),
  211451. classId (classId_),
  211452. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211453. currentBitDepth (16),
  211454. currentSampleRate (0),
  211455. isOpen_ (false),
  211456. isStarted (false),
  211457. postOutput (true),
  211458. insideControlPanelModalLoop (false),
  211459. shouldUsePreferredSize (false)
  211460. {
  211461. name = name_;
  211462. ourWindow.addToDesktop (0);
  211463. windowHandle = ourWindow.getWindowHandle();
  211464. jassert (currentASIODev [slotNumber] == 0);
  211465. currentASIODev [slotNumber] = this;
  211466. openDevice();
  211467. }
  211468. ~ASIOAudioIODevice()
  211469. {
  211470. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211471. if (currentASIODev[i] == this)
  211472. currentASIODev[i] = 0;
  211473. close();
  211474. log ("ASIO - exiting");
  211475. removeCurrentDriver();
  211476. }
  211477. void updateSampleRates()
  211478. {
  211479. // find a list of sample rates..
  211480. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211481. sampleRates.clear();
  211482. if (asioObject != 0)
  211483. {
  211484. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211485. {
  211486. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211487. if (err == 0)
  211488. {
  211489. sampleRates.add ((int) possibleSampleRates[index]);
  211490. log ("rate: " + String ((int) possibleSampleRates[index]));
  211491. }
  211492. else if (err != ASE_NoClock)
  211493. {
  211494. logError ("CanSampleRate", err);
  211495. }
  211496. }
  211497. if (sampleRates.size() == 0)
  211498. {
  211499. double cr = 0;
  211500. const long err = asioObject->getSampleRate (&cr);
  211501. log ("No sample rates supported - current rate: " + String ((int) cr));
  211502. if (err == 0)
  211503. sampleRates.add ((int) cr);
  211504. }
  211505. }
  211506. }
  211507. const StringArray getOutputChannelNames()
  211508. {
  211509. return outputChannelNames;
  211510. }
  211511. const StringArray getInputChannelNames()
  211512. {
  211513. return inputChannelNames;
  211514. }
  211515. int getNumSampleRates()
  211516. {
  211517. return sampleRates.size();
  211518. }
  211519. double getSampleRate (int index)
  211520. {
  211521. return sampleRates [index];
  211522. }
  211523. int getNumBufferSizesAvailable()
  211524. {
  211525. return bufferSizes.size();
  211526. }
  211527. int getBufferSizeSamples (int index)
  211528. {
  211529. return bufferSizes [index];
  211530. }
  211531. int getDefaultBufferSize()
  211532. {
  211533. return preferredSize;
  211534. }
  211535. const String open (const BigInteger& inputChannels,
  211536. const BigInteger& outputChannels,
  211537. double sr,
  211538. int bufferSizeSamples)
  211539. {
  211540. close();
  211541. currentCallback = 0;
  211542. if (bufferSizeSamples <= 0)
  211543. shouldUsePreferredSize = true;
  211544. if (asioObject == 0 || ! isASIOOpen)
  211545. {
  211546. log ("Warning: device not open");
  211547. const String err (openDevice());
  211548. if (asioObject == 0 || ! isASIOOpen)
  211549. return err;
  211550. }
  211551. isStarted = false;
  211552. bufferIndex = -1;
  211553. long err = 0;
  211554. long newPreferredSize = 0;
  211555. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211556. minSize = 0;
  211557. maxSize = 0;
  211558. newPreferredSize = 0;
  211559. granularity = 0;
  211560. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211561. {
  211562. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211563. shouldUsePreferredSize = true;
  211564. preferredSize = newPreferredSize;
  211565. }
  211566. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211567. // dynamic changes to the buffer size...
  211568. shouldUsePreferredSize = shouldUsePreferredSize
  211569. || getName().containsIgnoreCase ("Digidesign");
  211570. if (shouldUsePreferredSize)
  211571. {
  211572. log ("Using preferred size for buffer..");
  211573. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211574. {
  211575. bufferSizeSamples = preferredSize;
  211576. }
  211577. else
  211578. {
  211579. bufferSizeSamples = 1024;
  211580. logError ("GetBufferSize1", err);
  211581. }
  211582. shouldUsePreferredSize = false;
  211583. }
  211584. int sampleRate = roundDoubleToInt (sr);
  211585. currentSampleRate = sampleRate;
  211586. currentBlockSizeSamples = bufferSizeSamples;
  211587. currentChansOut.clear();
  211588. currentChansIn.clear();
  211589. zeromem (inBuffers, sizeof (inBuffers));
  211590. zeromem (outBuffers, sizeof (outBuffers));
  211591. updateSampleRates();
  211592. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211593. sampleRate = sampleRates[0];
  211594. jassert (sampleRate != 0);
  211595. if (sampleRate == 0)
  211596. sampleRate = 44100;
  211597. long numSources = 32;
  211598. ASIOClockSource clocks[32];
  211599. zeromem (clocks, sizeof (clocks));
  211600. asioObject->getClockSources (clocks, &numSources);
  211601. bool isSourceSet = false;
  211602. // careful not to remove this loop because it does more than just logging!
  211603. int i;
  211604. for (i = 0; i < numSources; ++i)
  211605. {
  211606. String s ("clock: ");
  211607. s += clocks[i].name;
  211608. if (clocks[i].isCurrentSource)
  211609. {
  211610. isSourceSet = true;
  211611. s << " (cur)";
  211612. }
  211613. log (s);
  211614. }
  211615. if (numSources > 1 && ! isSourceSet)
  211616. {
  211617. log ("setting clock source");
  211618. asioObject->setClockSource (clocks[0].index);
  211619. Thread::sleep (20);
  211620. }
  211621. else
  211622. {
  211623. if (numSources == 0)
  211624. {
  211625. log ("ASIO - no clock sources!");
  211626. }
  211627. }
  211628. double cr = 0;
  211629. err = asioObject->getSampleRate (&cr);
  211630. if (err == 0)
  211631. {
  211632. currentSampleRate = cr;
  211633. }
  211634. else
  211635. {
  211636. logError ("GetSampleRate", err);
  211637. currentSampleRate = 0;
  211638. }
  211639. error = String::empty;
  211640. needToReset = false;
  211641. isReSync = false;
  211642. err = 0;
  211643. bool buffersCreated = false;
  211644. if (currentSampleRate != sampleRate)
  211645. {
  211646. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211647. err = asioObject->setSampleRate (sampleRate);
  211648. if (err == ASE_NoClock && numSources > 0)
  211649. {
  211650. log ("trying to set a clock source..");
  211651. Thread::sleep (10);
  211652. err = asioObject->setClockSource (clocks[0].index);
  211653. if (err != 0)
  211654. {
  211655. logError ("SetClock", err);
  211656. }
  211657. Thread::sleep (10);
  211658. err = asioObject->setSampleRate (sampleRate);
  211659. }
  211660. }
  211661. if (err == 0)
  211662. {
  211663. currentSampleRate = sampleRate;
  211664. if (needToReset)
  211665. {
  211666. if (isReSync)
  211667. {
  211668. log ("Resync request");
  211669. }
  211670. log ("! Resetting ASIO after sample rate change");
  211671. removeCurrentDriver();
  211672. loadDriver();
  211673. const String error (initDriver());
  211674. if (error.isNotEmpty())
  211675. {
  211676. log ("ASIOInit: " + error);
  211677. }
  211678. needToReset = false;
  211679. isReSync = false;
  211680. }
  211681. numActiveInputChans = 0;
  211682. numActiveOutputChans = 0;
  211683. ASIOBufferInfo* info = bufferInfos;
  211684. int i;
  211685. for (i = 0; i < totalNumInputChans; ++i)
  211686. {
  211687. if (inputChannels[i])
  211688. {
  211689. currentChansIn.setBit (i);
  211690. info->isInput = 1;
  211691. info->channelNum = i;
  211692. info->buffers[0] = info->buffers[1] = 0;
  211693. ++info;
  211694. ++numActiveInputChans;
  211695. }
  211696. }
  211697. for (i = 0; i < totalNumOutputChans; ++i)
  211698. {
  211699. if (outputChannels[i])
  211700. {
  211701. currentChansOut.setBit (i);
  211702. info->isInput = 0;
  211703. info->channelNum = i;
  211704. info->buffers[0] = info->buffers[1] = 0;
  211705. ++info;
  211706. ++numActiveOutputChans;
  211707. }
  211708. }
  211709. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211710. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211711. if (currentASIODev[0] == this)
  211712. {
  211713. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211714. callbacks.asioMessage = &asioMessagesCallback0;
  211715. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211716. }
  211717. else if (currentASIODev[1] == this)
  211718. {
  211719. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211720. callbacks.asioMessage = &asioMessagesCallback1;
  211721. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211722. }
  211723. else if (currentASIODev[2] == this)
  211724. {
  211725. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211726. callbacks.asioMessage = &asioMessagesCallback2;
  211727. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211728. }
  211729. else
  211730. {
  211731. jassertfalse;
  211732. }
  211733. log ("disposing buffers");
  211734. err = asioObject->disposeBuffers();
  211735. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211736. err = asioObject->createBuffers (bufferInfos,
  211737. totalBuffers,
  211738. currentBlockSizeSamples,
  211739. &callbacks);
  211740. if (err != 0)
  211741. {
  211742. currentBlockSizeSamples = preferredSize;
  211743. logError ("create buffers 2", err);
  211744. asioObject->disposeBuffers();
  211745. err = asioObject->createBuffers (bufferInfos,
  211746. totalBuffers,
  211747. currentBlockSizeSamples,
  211748. &callbacks);
  211749. }
  211750. if (err == 0)
  211751. {
  211752. buffersCreated = true;
  211753. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211754. int n = 0;
  211755. Array <int> types;
  211756. currentBitDepth = 16;
  211757. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211758. {
  211759. if (inputChannels[i])
  211760. {
  211761. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211762. ASIOChannelInfo channelInfo;
  211763. zerostruct (channelInfo);
  211764. channelInfo.channel = i;
  211765. channelInfo.isInput = 1;
  211766. asioObject->getChannelInfo (&channelInfo);
  211767. types.addIfNotAlreadyThere (channelInfo.type);
  211768. typeToFormatParameters (channelInfo.type,
  211769. inputChannelBitDepths[n],
  211770. inputChannelBytesPerSample[n],
  211771. inputChannelIsFloat[n],
  211772. inputChannelLittleEndian[n]);
  211773. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211774. ++n;
  211775. }
  211776. }
  211777. jassert (numActiveInputChans == n);
  211778. n = 0;
  211779. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211780. {
  211781. if (outputChannels[i])
  211782. {
  211783. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211784. ASIOChannelInfo channelInfo;
  211785. zerostruct (channelInfo);
  211786. channelInfo.channel = i;
  211787. channelInfo.isInput = 0;
  211788. asioObject->getChannelInfo (&channelInfo);
  211789. types.addIfNotAlreadyThere (channelInfo.type);
  211790. typeToFormatParameters (channelInfo.type,
  211791. outputChannelBitDepths[n],
  211792. outputChannelBytesPerSample[n],
  211793. outputChannelIsFloat[n],
  211794. outputChannelLittleEndian[n]);
  211795. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211796. ++n;
  211797. }
  211798. }
  211799. jassert (numActiveOutputChans == n);
  211800. for (i = types.size(); --i >= 0;)
  211801. {
  211802. log ("channel format: " + String (types[i]));
  211803. }
  211804. jassert (n <= totalBuffers);
  211805. for (i = 0; i < numActiveOutputChans; ++i)
  211806. {
  211807. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211808. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211809. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211810. {
  211811. log ("!! Null buffers");
  211812. }
  211813. else
  211814. {
  211815. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211816. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211817. }
  211818. }
  211819. inputLatency = outputLatency = 0;
  211820. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211821. {
  211822. log ("ASIO - no latencies");
  211823. }
  211824. else
  211825. {
  211826. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211827. }
  211828. isOpen_ = true;
  211829. log ("starting ASIO");
  211830. calledback = false;
  211831. err = asioObject->start();
  211832. if (err != 0)
  211833. {
  211834. isOpen_ = false;
  211835. log ("ASIO - stop on failure");
  211836. Thread::sleep (10);
  211837. asioObject->stop();
  211838. error = "Can't start device";
  211839. Thread::sleep (10);
  211840. }
  211841. else
  211842. {
  211843. int count = 300;
  211844. while (--count > 0 && ! calledback)
  211845. Thread::sleep (10);
  211846. isStarted = true;
  211847. if (! calledback)
  211848. {
  211849. error = "Device didn't start correctly";
  211850. log ("ASIO didn't callback - stopping..");
  211851. asioObject->stop();
  211852. }
  211853. }
  211854. }
  211855. else
  211856. {
  211857. error = "Can't create i/o buffers";
  211858. }
  211859. }
  211860. else
  211861. {
  211862. error = "Can't set sample rate: ";
  211863. error << sampleRate;
  211864. }
  211865. if (error.isNotEmpty())
  211866. {
  211867. logError (error, err);
  211868. if (asioObject != 0 && buffersCreated)
  211869. asioObject->disposeBuffers();
  211870. Thread::sleep (20);
  211871. isStarted = false;
  211872. isOpen_ = false;
  211873. const String errorCopy (error);
  211874. close(); // (this resets the error string)
  211875. error = errorCopy;
  211876. }
  211877. needToReset = false;
  211878. isReSync = false;
  211879. return error;
  211880. }
  211881. void close()
  211882. {
  211883. error = String::empty;
  211884. stopTimer();
  211885. stop();
  211886. if (isASIOOpen && isOpen_)
  211887. {
  211888. const ScopedLock sl (callbackLock);
  211889. isOpen_ = false;
  211890. isStarted = false;
  211891. needToReset = false;
  211892. isReSync = false;
  211893. log ("ASIO - stopping");
  211894. if (asioObject != 0)
  211895. {
  211896. Thread::sleep (20);
  211897. asioObject->stop();
  211898. Thread::sleep (10);
  211899. asioObject->disposeBuffers();
  211900. }
  211901. Thread::sleep (10);
  211902. }
  211903. }
  211904. bool isOpen()
  211905. {
  211906. return isOpen_ || insideControlPanelModalLoop;
  211907. }
  211908. int getCurrentBufferSizeSamples()
  211909. {
  211910. return currentBlockSizeSamples;
  211911. }
  211912. double getCurrentSampleRate()
  211913. {
  211914. return currentSampleRate;
  211915. }
  211916. const BigInteger getActiveOutputChannels() const
  211917. {
  211918. return currentChansOut;
  211919. }
  211920. const BigInteger getActiveInputChannels() const
  211921. {
  211922. return currentChansIn;
  211923. }
  211924. int getCurrentBitDepth()
  211925. {
  211926. return currentBitDepth;
  211927. }
  211928. int getOutputLatencyInSamples()
  211929. {
  211930. return outputLatency + currentBlockSizeSamples / 4;
  211931. }
  211932. int getInputLatencyInSamples()
  211933. {
  211934. return inputLatency + currentBlockSizeSamples / 4;
  211935. }
  211936. void start (AudioIODeviceCallback* callback)
  211937. {
  211938. if (callback != 0)
  211939. {
  211940. callback->audioDeviceAboutToStart (this);
  211941. const ScopedLock sl (callbackLock);
  211942. currentCallback = callback;
  211943. }
  211944. }
  211945. void stop()
  211946. {
  211947. AudioIODeviceCallback* const lastCallback = currentCallback;
  211948. {
  211949. const ScopedLock sl (callbackLock);
  211950. currentCallback = 0;
  211951. }
  211952. if (lastCallback != 0)
  211953. lastCallback->audioDeviceStopped();
  211954. }
  211955. bool isPlaying()
  211956. {
  211957. return isASIOOpen && (currentCallback != 0);
  211958. }
  211959. const String getLastError()
  211960. {
  211961. return error;
  211962. }
  211963. bool hasControlPanel() const
  211964. {
  211965. return true;
  211966. }
  211967. bool showControlPanel()
  211968. {
  211969. log ("ASIO - showing control panel");
  211970. Component modalWindow (String::empty);
  211971. modalWindow.setOpaque (true);
  211972. modalWindow.addToDesktop (0);
  211973. modalWindow.enterModalState();
  211974. bool done = false;
  211975. JUCE_TRY
  211976. {
  211977. // are there are devices that need to be closed before showing their control panel?
  211978. // close();
  211979. insideControlPanelModalLoop = true;
  211980. const uint32 started = Time::getMillisecondCounter();
  211981. if (asioObject != 0)
  211982. {
  211983. asioObject->controlPanel();
  211984. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211985. log ("spent: " + String (spent));
  211986. if (spent > 300)
  211987. {
  211988. shouldUsePreferredSize = true;
  211989. done = true;
  211990. }
  211991. }
  211992. }
  211993. JUCE_CATCH_ALL
  211994. insideControlPanelModalLoop = false;
  211995. return done;
  211996. }
  211997. void resetRequest() throw()
  211998. {
  211999. needToReset = true;
  212000. }
  212001. void resyncRequest() throw()
  212002. {
  212003. needToReset = true;
  212004. isReSync = true;
  212005. }
  212006. void timerCallback()
  212007. {
  212008. if (! insideControlPanelModalLoop)
  212009. {
  212010. stopTimer();
  212011. // used to cause a reset
  212012. log ("! ASIO restart request!");
  212013. if (isOpen_)
  212014. {
  212015. AudioIODeviceCallback* const oldCallback = currentCallback;
  212016. close();
  212017. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212018. currentSampleRate, currentBlockSizeSamples);
  212019. if (oldCallback != 0)
  212020. start (oldCallback);
  212021. }
  212022. }
  212023. else
  212024. {
  212025. startTimer (100);
  212026. }
  212027. }
  212028. juce_UseDebuggingNewOperator
  212029. private:
  212030. IASIO* volatile asioObject;
  212031. ASIOCallbacks callbacks;
  212032. void* windowHandle;
  212033. CLSID classId;
  212034. const String optionalDllForDirectLoading;
  212035. String error;
  212036. long totalNumInputChans, totalNumOutputChans;
  212037. StringArray inputChannelNames, outputChannelNames;
  212038. Array<int> sampleRates, bufferSizes;
  212039. long inputLatency, outputLatency;
  212040. long minSize, maxSize, preferredSize, granularity;
  212041. int volatile currentBlockSizeSamples;
  212042. int volatile currentBitDepth;
  212043. double volatile currentSampleRate;
  212044. BigInteger currentChansOut, currentChansIn;
  212045. AudioIODeviceCallback* volatile currentCallback;
  212046. CriticalSection callbackLock;
  212047. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212048. float* inBuffers [maxASIOChannels];
  212049. float* outBuffers [maxASIOChannels];
  212050. int inputChannelBitDepths [maxASIOChannels];
  212051. int outputChannelBitDepths [maxASIOChannels];
  212052. int inputChannelBytesPerSample [maxASIOChannels];
  212053. int outputChannelBytesPerSample [maxASIOChannels];
  212054. bool inputChannelIsFloat [maxASIOChannels];
  212055. bool outputChannelIsFloat [maxASIOChannels];
  212056. bool inputChannelLittleEndian [maxASIOChannels];
  212057. bool outputChannelLittleEndian [maxASIOChannels];
  212058. WaitableEvent event1;
  212059. HeapBlock <float> tempBuffer;
  212060. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212061. bool isOpen_, isStarted;
  212062. bool volatile isASIOOpen;
  212063. bool volatile calledback;
  212064. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212065. bool volatile insideControlPanelModalLoop;
  212066. bool volatile shouldUsePreferredSize;
  212067. void removeCurrentDriver()
  212068. {
  212069. if (asioObject != 0)
  212070. {
  212071. asioObject->Release();
  212072. asioObject = 0;
  212073. }
  212074. }
  212075. bool loadDriver()
  212076. {
  212077. removeCurrentDriver();
  212078. JUCE_TRY
  212079. {
  212080. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212081. classId, (void**) &asioObject) == S_OK)
  212082. {
  212083. return true;
  212084. }
  212085. // If a class isn't registered but we have a path for it, we can fallback to
  212086. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212087. if (optionalDllForDirectLoading.isNotEmpty())
  212088. {
  212089. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212090. if (h != 0)
  212091. {
  212092. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212093. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212094. if (dllGetClassObject != 0)
  212095. {
  212096. IClassFactory* classFactory = 0;
  212097. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212098. if (classFactory != 0)
  212099. {
  212100. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212101. classFactory->Release();
  212102. }
  212103. return asioObject != 0;
  212104. }
  212105. }
  212106. }
  212107. }
  212108. JUCE_CATCH_ALL
  212109. asioObject = 0;
  212110. return false;
  212111. }
  212112. const String initDriver()
  212113. {
  212114. if (asioObject != 0)
  212115. {
  212116. char buffer [256];
  212117. zeromem (buffer, sizeof (buffer));
  212118. if (! asioObject->init (windowHandle))
  212119. {
  212120. asioObject->getErrorMessage (buffer);
  212121. return String (buffer, sizeof (buffer) - 1);
  212122. }
  212123. // just in case any daft drivers expect this to be called..
  212124. asioObject->getDriverName (buffer);
  212125. return String::empty;
  212126. }
  212127. return "No Driver";
  212128. }
  212129. const String openDevice()
  212130. {
  212131. // use this in case the driver starts opening dialog boxes..
  212132. Component modalWindow (String::empty);
  212133. modalWindow.setOpaque (true);
  212134. modalWindow.addToDesktop (0);
  212135. modalWindow.enterModalState();
  212136. // open the device and get its info..
  212137. log ("opening ASIO device: " + getName());
  212138. needToReset = false;
  212139. isReSync = false;
  212140. outputChannelNames.clear();
  212141. inputChannelNames.clear();
  212142. bufferSizes.clear();
  212143. sampleRates.clear();
  212144. isASIOOpen = false;
  212145. isOpen_ = false;
  212146. totalNumInputChans = 0;
  212147. totalNumOutputChans = 0;
  212148. numActiveInputChans = 0;
  212149. numActiveOutputChans = 0;
  212150. currentCallback = 0;
  212151. error = String::empty;
  212152. if (getName().isEmpty())
  212153. return error;
  212154. long err = 0;
  212155. if (loadDriver())
  212156. {
  212157. if ((error = initDriver()).isEmpty())
  212158. {
  212159. numActiveInputChans = 0;
  212160. numActiveOutputChans = 0;
  212161. totalNumInputChans = 0;
  212162. totalNumOutputChans = 0;
  212163. if (asioObject != 0
  212164. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212165. {
  212166. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212167. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212168. {
  212169. // find a list of buffer sizes..
  212170. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212171. if (granularity >= 0)
  212172. {
  212173. granularity = jmax (1, (int) granularity);
  212174. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212175. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212176. }
  212177. else if (granularity < 0)
  212178. {
  212179. for (int i = 0; i < 18; ++i)
  212180. {
  212181. const int s = (1 << i);
  212182. if (s >= minSize && s <= maxSize)
  212183. bufferSizes.add (s);
  212184. }
  212185. }
  212186. if (! bufferSizes.contains (preferredSize))
  212187. bufferSizes.insert (0, preferredSize);
  212188. double currentRate = 0;
  212189. asioObject->getSampleRate (&currentRate);
  212190. if (currentRate <= 0.0 || currentRate > 192001.0)
  212191. {
  212192. log ("setting sample rate");
  212193. err = asioObject->setSampleRate (44100.0);
  212194. if (err != 0)
  212195. {
  212196. logError ("setting sample rate", err);
  212197. }
  212198. asioObject->getSampleRate (&currentRate);
  212199. }
  212200. currentSampleRate = currentRate;
  212201. postOutput = (asioObject->outputReady() == 0);
  212202. if (postOutput)
  212203. {
  212204. log ("ASIO outputReady = ok");
  212205. }
  212206. updateSampleRates();
  212207. // ..because cubase does it at this point
  212208. inputLatency = outputLatency = 0;
  212209. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212210. {
  212211. log ("ASIO - no latencies");
  212212. }
  212213. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212214. // create some dummy buffers now.. because cubase does..
  212215. numActiveInputChans = 0;
  212216. numActiveOutputChans = 0;
  212217. ASIOBufferInfo* info = bufferInfos;
  212218. int i, numChans = 0;
  212219. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212220. {
  212221. info->isInput = 1;
  212222. info->channelNum = i;
  212223. info->buffers[0] = info->buffers[1] = 0;
  212224. ++info;
  212225. ++numChans;
  212226. }
  212227. const int outputBufferIndex = numChans;
  212228. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212229. {
  212230. info->isInput = 0;
  212231. info->channelNum = i;
  212232. info->buffers[0] = info->buffers[1] = 0;
  212233. ++info;
  212234. ++numChans;
  212235. }
  212236. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212237. if (currentASIODev[0] == this)
  212238. {
  212239. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212240. callbacks.asioMessage = &asioMessagesCallback0;
  212241. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212242. }
  212243. else if (currentASIODev[1] == this)
  212244. {
  212245. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212246. callbacks.asioMessage = &asioMessagesCallback1;
  212247. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212248. }
  212249. else if (currentASIODev[2] == this)
  212250. {
  212251. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212252. callbacks.asioMessage = &asioMessagesCallback2;
  212253. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212254. }
  212255. else
  212256. {
  212257. jassertfalse;
  212258. }
  212259. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212260. if (preferredSize > 0)
  212261. {
  212262. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212263. if (err != 0)
  212264. {
  212265. logError ("dummy buffers", err);
  212266. }
  212267. }
  212268. long newInps = 0, newOuts = 0;
  212269. asioObject->getChannels (&newInps, &newOuts);
  212270. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212271. {
  212272. totalNumInputChans = newInps;
  212273. totalNumOutputChans = newOuts;
  212274. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212275. }
  212276. updateSampleRates();
  212277. ASIOChannelInfo channelInfo;
  212278. channelInfo.type = 0;
  212279. for (i = 0; i < totalNumInputChans; ++i)
  212280. {
  212281. zerostruct (channelInfo);
  212282. channelInfo.channel = i;
  212283. channelInfo.isInput = 1;
  212284. asioObject->getChannelInfo (&channelInfo);
  212285. inputChannelNames.add (String (channelInfo.name));
  212286. }
  212287. for (i = 0; i < totalNumOutputChans; ++i)
  212288. {
  212289. zerostruct (channelInfo);
  212290. channelInfo.channel = i;
  212291. channelInfo.isInput = 0;
  212292. asioObject->getChannelInfo (&channelInfo);
  212293. outputChannelNames.add (String (channelInfo.name));
  212294. typeToFormatParameters (channelInfo.type,
  212295. outputChannelBitDepths[i],
  212296. outputChannelBytesPerSample[i],
  212297. outputChannelIsFloat[i],
  212298. outputChannelLittleEndian[i]);
  212299. if (i < 2)
  212300. {
  212301. // clear the channels that are used with the dummy stuff
  212302. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212303. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212304. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212305. }
  212306. }
  212307. outputChannelNames.trim();
  212308. inputChannelNames.trim();
  212309. outputChannelNames.appendNumbersToDuplicates (false, true);
  212310. inputChannelNames.appendNumbersToDuplicates (false, true);
  212311. // start and stop because cubase does it..
  212312. asioObject->getLatencies (&inputLatency, &outputLatency);
  212313. if ((err = asioObject->start()) != 0)
  212314. {
  212315. // ignore an error here, as it might start later after setting other stuff up
  212316. logError ("ASIO start", err);
  212317. }
  212318. Thread::sleep (100);
  212319. asioObject->stop();
  212320. }
  212321. else
  212322. {
  212323. error = "Can't detect buffer sizes";
  212324. }
  212325. }
  212326. else
  212327. {
  212328. error = "Can't detect asio channels";
  212329. }
  212330. }
  212331. }
  212332. else
  212333. {
  212334. error = "No such device";
  212335. }
  212336. if (error.isNotEmpty())
  212337. {
  212338. logError (error, err);
  212339. if (asioObject != 0)
  212340. asioObject->disposeBuffers();
  212341. removeCurrentDriver();
  212342. isASIOOpen = false;
  212343. }
  212344. else
  212345. {
  212346. isASIOOpen = true;
  212347. log ("ASIO device open");
  212348. }
  212349. isOpen_ = false;
  212350. needToReset = false;
  212351. isReSync = false;
  212352. return error;
  212353. }
  212354. void callback (const long index)
  212355. {
  212356. if (isStarted)
  212357. {
  212358. bufferIndex = index;
  212359. processBuffer();
  212360. }
  212361. else
  212362. {
  212363. if (postOutput && (asioObject != 0))
  212364. asioObject->outputReady();
  212365. }
  212366. calledback = true;
  212367. }
  212368. void processBuffer()
  212369. {
  212370. const ASIOBufferInfo* const infos = bufferInfos;
  212371. const int bi = bufferIndex;
  212372. const ScopedLock sl (callbackLock);
  212373. if (needToReset)
  212374. {
  212375. needToReset = false;
  212376. if (isReSync)
  212377. {
  212378. log ("! ASIO resync");
  212379. isReSync = false;
  212380. }
  212381. else
  212382. {
  212383. startTimer (20);
  212384. }
  212385. }
  212386. if (bi >= 0)
  212387. {
  212388. const int samps = currentBlockSizeSamples;
  212389. if (currentCallback != 0)
  212390. {
  212391. int i;
  212392. for (i = 0; i < numActiveInputChans; ++i)
  212393. {
  212394. float* const dst = inBuffers[i];
  212395. jassert (dst != 0);
  212396. const char* const src = (const char*) (infos[i].buffers[bi]);
  212397. if (inputChannelIsFloat[i])
  212398. {
  212399. memcpy (dst, src, samps * sizeof (float));
  212400. }
  212401. else
  212402. {
  212403. jassert (dst == tempBuffer + (samps * i));
  212404. switch (inputChannelBitDepths[i])
  212405. {
  212406. case 16:
  212407. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212408. samps, inputChannelLittleEndian[i]);
  212409. break;
  212410. case 24:
  212411. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212412. samps, inputChannelLittleEndian[i]);
  212413. break;
  212414. case 32:
  212415. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212416. samps, inputChannelLittleEndian[i]);
  212417. break;
  212418. case 64:
  212419. jassertfalse;
  212420. break;
  212421. }
  212422. }
  212423. }
  212424. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  212425. numActiveInputChans,
  212426. outBuffers,
  212427. numActiveOutputChans,
  212428. samps);
  212429. for (i = 0; i < numActiveOutputChans; ++i)
  212430. {
  212431. float* const src = outBuffers[i];
  212432. jassert (src != 0);
  212433. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212434. if (outputChannelIsFloat[i])
  212435. {
  212436. memcpy (dst, src, samps * sizeof (float));
  212437. }
  212438. else
  212439. {
  212440. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212441. switch (outputChannelBitDepths[i])
  212442. {
  212443. case 16:
  212444. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212445. samps, outputChannelLittleEndian[i]);
  212446. break;
  212447. case 24:
  212448. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212449. samps, outputChannelLittleEndian[i]);
  212450. break;
  212451. case 32:
  212452. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212453. samps, outputChannelLittleEndian[i]);
  212454. break;
  212455. case 64:
  212456. jassertfalse;
  212457. break;
  212458. }
  212459. }
  212460. }
  212461. }
  212462. else
  212463. {
  212464. for (int i = 0; i < numActiveOutputChans; ++i)
  212465. {
  212466. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212467. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212468. }
  212469. }
  212470. }
  212471. if (postOutput)
  212472. asioObject->outputReady();
  212473. }
  212474. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212475. {
  212476. if (currentASIODev[0] != 0)
  212477. currentASIODev[0]->callback (index);
  212478. return 0;
  212479. }
  212480. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212481. {
  212482. if (currentASIODev[1] != 0)
  212483. currentASIODev[1]->callback (index);
  212484. return 0;
  212485. }
  212486. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212487. {
  212488. if (currentASIODev[2] != 0)
  212489. currentASIODev[2]->callback (index);
  212490. return 0;
  212491. }
  212492. static void bufferSwitchCallback0 (long index, long)
  212493. {
  212494. if (currentASIODev[0] != 0)
  212495. currentASIODev[0]->callback (index);
  212496. }
  212497. static void bufferSwitchCallback1 (long index, long)
  212498. {
  212499. if (currentASIODev[1] != 0)
  212500. currentASIODev[1]->callback (index);
  212501. }
  212502. static void bufferSwitchCallback2 (long index, long)
  212503. {
  212504. if (currentASIODev[2] != 0)
  212505. currentASIODev[2]->callback (index);
  212506. }
  212507. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212508. {
  212509. return asioMessagesCallback (selector, value, 0);
  212510. }
  212511. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212512. {
  212513. return asioMessagesCallback (selector, value, 1);
  212514. }
  212515. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212516. {
  212517. return asioMessagesCallback (selector, value, 2);
  212518. }
  212519. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212520. {
  212521. switch (selector)
  212522. {
  212523. case kAsioSelectorSupported:
  212524. if (value == kAsioResetRequest
  212525. || value == kAsioEngineVersion
  212526. || value == kAsioResyncRequest
  212527. || value == kAsioLatenciesChanged
  212528. || value == kAsioSupportsInputMonitor)
  212529. return 1;
  212530. break;
  212531. case kAsioBufferSizeChange:
  212532. break;
  212533. case kAsioResetRequest:
  212534. if (currentASIODev[deviceIndex] != 0)
  212535. currentASIODev[deviceIndex]->resetRequest();
  212536. return 1;
  212537. case kAsioResyncRequest:
  212538. if (currentASIODev[deviceIndex] != 0)
  212539. currentASIODev[deviceIndex]->resyncRequest();
  212540. return 1;
  212541. case kAsioLatenciesChanged:
  212542. return 1;
  212543. case kAsioEngineVersion:
  212544. return 2;
  212545. case kAsioSupportsTimeInfo:
  212546. case kAsioSupportsTimeCode:
  212547. return 0;
  212548. }
  212549. return 0;
  212550. }
  212551. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212552. {
  212553. }
  212554. static void convertInt16ToFloat (const char* src,
  212555. float* dest,
  212556. const int srcStrideBytes,
  212557. int numSamples,
  212558. const bool littleEndian) throw()
  212559. {
  212560. const double g = 1.0 / 32768.0;
  212561. if (littleEndian)
  212562. {
  212563. while (--numSamples >= 0)
  212564. {
  212565. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212566. src += srcStrideBytes;
  212567. }
  212568. }
  212569. else
  212570. {
  212571. while (--numSamples >= 0)
  212572. {
  212573. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212574. src += srcStrideBytes;
  212575. }
  212576. }
  212577. }
  212578. static void convertFloatToInt16 (const float* src,
  212579. char* dest,
  212580. const int dstStrideBytes,
  212581. int numSamples,
  212582. const bool littleEndian) throw()
  212583. {
  212584. const double maxVal = (double) 0x7fff;
  212585. if (littleEndian)
  212586. {
  212587. while (--numSamples >= 0)
  212588. {
  212589. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212590. dest += dstStrideBytes;
  212591. }
  212592. }
  212593. else
  212594. {
  212595. while (--numSamples >= 0)
  212596. {
  212597. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212598. dest += dstStrideBytes;
  212599. }
  212600. }
  212601. }
  212602. static void convertInt24ToFloat (const char* src,
  212603. float* dest,
  212604. const int srcStrideBytes,
  212605. int numSamples,
  212606. const bool littleEndian) throw()
  212607. {
  212608. const double g = 1.0 / 0x7fffff;
  212609. if (littleEndian)
  212610. {
  212611. while (--numSamples >= 0)
  212612. {
  212613. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212614. src += srcStrideBytes;
  212615. }
  212616. }
  212617. else
  212618. {
  212619. while (--numSamples >= 0)
  212620. {
  212621. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212622. src += srcStrideBytes;
  212623. }
  212624. }
  212625. }
  212626. static void convertFloatToInt24 (const float* src,
  212627. char* dest,
  212628. const int dstStrideBytes,
  212629. int numSamples,
  212630. const bool littleEndian) throw()
  212631. {
  212632. const double maxVal = (double) 0x7fffff;
  212633. if (littleEndian)
  212634. {
  212635. while (--numSamples >= 0)
  212636. {
  212637. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212638. dest += dstStrideBytes;
  212639. }
  212640. }
  212641. else
  212642. {
  212643. while (--numSamples >= 0)
  212644. {
  212645. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212646. dest += dstStrideBytes;
  212647. }
  212648. }
  212649. }
  212650. static void convertInt32ToFloat (const char* src,
  212651. float* dest,
  212652. const int srcStrideBytes,
  212653. int numSamples,
  212654. const bool littleEndian) throw()
  212655. {
  212656. const double g = 1.0 / 0x7fffffff;
  212657. if (littleEndian)
  212658. {
  212659. while (--numSamples >= 0)
  212660. {
  212661. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212662. src += srcStrideBytes;
  212663. }
  212664. }
  212665. else
  212666. {
  212667. while (--numSamples >= 0)
  212668. {
  212669. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212670. src += srcStrideBytes;
  212671. }
  212672. }
  212673. }
  212674. static void convertFloatToInt32 (const float* src,
  212675. char* dest,
  212676. const int dstStrideBytes,
  212677. int numSamples,
  212678. const bool littleEndian) throw()
  212679. {
  212680. const double maxVal = (double) 0x7fffffff;
  212681. if (littleEndian)
  212682. {
  212683. while (--numSamples >= 0)
  212684. {
  212685. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212686. dest += dstStrideBytes;
  212687. }
  212688. }
  212689. else
  212690. {
  212691. while (--numSamples >= 0)
  212692. {
  212693. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212694. dest += dstStrideBytes;
  212695. }
  212696. }
  212697. }
  212698. static void typeToFormatParameters (const long type,
  212699. int& bitDepth,
  212700. int& byteStride,
  212701. bool& formatIsFloat,
  212702. bool& littleEndian) throw()
  212703. {
  212704. bitDepth = 0;
  212705. littleEndian = false;
  212706. formatIsFloat = false;
  212707. switch (type)
  212708. {
  212709. case ASIOSTInt16MSB:
  212710. case ASIOSTInt16LSB:
  212711. case ASIOSTInt32MSB16:
  212712. case ASIOSTInt32LSB16:
  212713. bitDepth = 16; break;
  212714. case ASIOSTFloat32MSB:
  212715. case ASIOSTFloat32LSB:
  212716. formatIsFloat = true;
  212717. bitDepth = 32; break;
  212718. case ASIOSTInt32MSB:
  212719. case ASIOSTInt32LSB:
  212720. bitDepth = 32; break;
  212721. case ASIOSTInt24MSB:
  212722. case ASIOSTInt24LSB:
  212723. case ASIOSTInt32MSB24:
  212724. case ASIOSTInt32LSB24:
  212725. case ASIOSTInt32MSB18:
  212726. case ASIOSTInt32MSB20:
  212727. case ASIOSTInt32LSB18:
  212728. case ASIOSTInt32LSB20:
  212729. bitDepth = 24; break;
  212730. case ASIOSTFloat64MSB:
  212731. case ASIOSTFloat64LSB:
  212732. default:
  212733. bitDepth = 64;
  212734. break;
  212735. }
  212736. switch (type)
  212737. {
  212738. case ASIOSTInt16MSB:
  212739. case ASIOSTInt32MSB16:
  212740. case ASIOSTFloat32MSB:
  212741. case ASIOSTFloat64MSB:
  212742. case ASIOSTInt32MSB:
  212743. case ASIOSTInt32MSB18:
  212744. case ASIOSTInt32MSB20:
  212745. case ASIOSTInt32MSB24:
  212746. case ASIOSTInt24MSB:
  212747. littleEndian = false; break;
  212748. case ASIOSTInt16LSB:
  212749. case ASIOSTInt32LSB16:
  212750. case ASIOSTFloat32LSB:
  212751. case ASIOSTFloat64LSB:
  212752. case ASIOSTInt32LSB:
  212753. case ASIOSTInt32LSB18:
  212754. case ASIOSTInt32LSB20:
  212755. case ASIOSTInt32LSB24:
  212756. case ASIOSTInt24LSB:
  212757. littleEndian = true; break;
  212758. default:
  212759. break;
  212760. }
  212761. switch (type)
  212762. {
  212763. case ASIOSTInt16LSB:
  212764. case ASIOSTInt16MSB:
  212765. byteStride = 2; break;
  212766. case ASIOSTInt24LSB:
  212767. case ASIOSTInt24MSB:
  212768. byteStride = 3; break;
  212769. case ASIOSTInt32MSB16:
  212770. case ASIOSTInt32LSB16:
  212771. case ASIOSTInt32MSB:
  212772. case ASIOSTInt32MSB18:
  212773. case ASIOSTInt32MSB20:
  212774. case ASIOSTInt32MSB24:
  212775. case ASIOSTInt32LSB:
  212776. case ASIOSTInt32LSB18:
  212777. case ASIOSTInt32LSB20:
  212778. case ASIOSTInt32LSB24:
  212779. case ASIOSTFloat32LSB:
  212780. case ASIOSTFloat32MSB:
  212781. byteStride = 4; break;
  212782. case ASIOSTFloat64MSB:
  212783. case ASIOSTFloat64LSB:
  212784. byteStride = 8; break;
  212785. default:
  212786. break;
  212787. }
  212788. }
  212789. };
  212790. class ASIOAudioIODeviceType : public AudioIODeviceType
  212791. {
  212792. public:
  212793. ASIOAudioIODeviceType()
  212794. : AudioIODeviceType ("ASIO"),
  212795. hasScanned (false)
  212796. {
  212797. CoInitialize (0);
  212798. }
  212799. ~ASIOAudioIODeviceType()
  212800. {
  212801. }
  212802. void scanForDevices()
  212803. {
  212804. hasScanned = true;
  212805. deviceNames.clear();
  212806. classIds.clear();
  212807. HKEY hk = 0;
  212808. int index = 0;
  212809. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212810. {
  212811. for (;;)
  212812. {
  212813. char name [256];
  212814. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212815. {
  212816. addDriverInfo (name, hk);
  212817. }
  212818. else
  212819. {
  212820. break;
  212821. }
  212822. }
  212823. RegCloseKey (hk);
  212824. }
  212825. }
  212826. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212827. {
  212828. jassert (hasScanned); // need to call scanForDevices() before doing this
  212829. return deviceNames;
  212830. }
  212831. int getDefaultDeviceIndex (bool) const
  212832. {
  212833. jassert (hasScanned); // need to call scanForDevices() before doing this
  212834. for (int i = deviceNames.size(); --i >= 0;)
  212835. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212836. return i; // asio4all is a safe choice for a default..
  212837. #if JUCE_DEBUG
  212838. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212839. return 1; // (the digi m-box driver crashes the app when you run
  212840. // it in the debugger, which can be a bit annoying)
  212841. #endif
  212842. return 0;
  212843. }
  212844. static int findFreeSlot()
  212845. {
  212846. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212847. if (currentASIODev[i] == 0)
  212848. return i;
  212849. jassertfalse; // unfortunately you can only have a finite number
  212850. // of ASIO devices open at the same time..
  212851. return -1;
  212852. }
  212853. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212854. {
  212855. jassert (hasScanned); // need to call scanForDevices() before doing this
  212856. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212857. }
  212858. bool hasSeparateInputsAndOutputs() const { return false; }
  212859. AudioIODevice* createDevice (const String& outputDeviceName,
  212860. const String& inputDeviceName)
  212861. {
  212862. // ASIO can't open two different devices for input and output - they must be the same one.
  212863. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212864. jassert (hasScanned); // need to call scanForDevices() before doing this
  212865. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212866. : inputDeviceName);
  212867. if (index >= 0)
  212868. {
  212869. const int freeSlot = findFreeSlot();
  212870. if (freeSlot >= 0)
  212871. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212872. }
  212873. return 0;
  212874. }
  212875. juce_UseDebuggingNewOperator
  212876. private:
  212877. StringArray deviceNames;
  212878. OwnedArray <CLSID> classIds;
  212879. bool hasScanned;
  212880. static bool checkClassIsOk (const String& classId)
  212881. {
  212882. HKEY hk = 0;
  212883. bool ok = false;
  212884. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212885. {
  212886. int index = 0;
  212887. for (;;)
  212888. {
  212889. WCHAR buf [512];
  212890. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212891. {
  212892. if (classId.equalsIgnoreCase (buf))
  212893. {
  212894. HKEY subKey, pathKey;
  212895. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212896. {
  212897. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212898. {
  212899. WCHAR pathName [1024];
  212900. DWORD dtype = REG_SZ;
  212901. DWORD dsize = sizeof (pathName);
  212902. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212903. ok = File (pathName).exists();
  212904. RegCloseKey (pathKey);
  212905. }
  212906. RegCloseKey (subKey);
  212907. }
  212908. break;
  212909. }
  212910. }
  212911. else
  212912. {
  212913. break;
  212914. }
  212915. }
  212916. RegCloseKey (hk);
  212917. }
  212918. return ok;
  212919. }
  212920. void addDriverInfo (const String& keyName, HKEY hk)
  212921. {
  212922. HKEY subKey;
  212923. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212924. {
  212925. WCHAR buf [256];
  212926. zerostruct (buf);
  212927. DWORD dtype = REG_SZ;
  212928. DWORD dsize = sizeof (buf);
  212929. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212930. {
  212931. if (dsize > 0 && checkClassIsOk (buf))
  212932. {
  212933. CLSID classId;
  212934. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212935. {
  212936. dtype = REG_SZ;
  212937. dsize = sizeof (buf);
  212938. String deviceName;
  212939. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212940. deviceName = buf;
  212941. else
  212942. deviceName = keyName;
  212943. log ("found " + deviceName);
  212944. deviceNames.add (deviceName);
  212945. classIds.add (new CLSID (classId));
  212946. }
  212947. }
  212948. RegCloseKey (subKey);
  212949. }
  212950. }
  212951. }
  212952. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212953. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212954. };
  212955. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212956. {
  212957. return new ASIOAudioIODeviceType();
  212958. }
  212959. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212960. void* guid,
  212961. const String& optionalDllForDirectLoading)
  212962. {
  212963. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212964. if (freeSlot < 0)
  212965. return 0;
  212966. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212967. }
  212968. #undef log
  212969. #endif
  212970. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212971. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212972. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212973. // compiled on its own).
  212974. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212975. END_JUCE_NAMESPACE
  212976. extern "C"
  212977. {
  212978. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212979. typedef struct typeDSBUFFERDESC
  212980. {
  212981. DWORD dwSize;
  212982. DWORD dwFlags;
  212983. DWORD dwBufferBytes;
  212984. DWORD dwReserved;
  212985. LPWAVEFORMATEX lpwfxFormat;
  212986. GUID guid3DAlgorithm;
  212987. } DSBUFFERDESC;
  212988. struct IDirectSoundBuffer;
  212989. #undef INTERFACE
  212990. #define INTERFACE IDirectSound
  212991. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  212992. {
  212993. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212994. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212995. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212996. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  212997. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212998. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  212999. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213000. STDMETHOD(Compact) (THIS) PURE;
  213001. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213002. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213003. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213004. };
  213005. #undef INTERFACE
  213006. #define INTERFACE IDirectSoundBuffer
  213007. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213008. {
  213009. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213010. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213011. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213012. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213013. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213014. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213015. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213016. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213017. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213018. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213019. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213020. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213021. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213022. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213023. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213024. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213025. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213026. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213027. STDMETHOD(Stop) (THIS) PURE;
  213028. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213029. STDMETHOD(Restore) (THIS) PURE;
  213030. };
  213031. typedef struct typeDSCBUFFERDESC
  213032. {
  213033. DWORD dwSize;
  213034. DWORD dwFlags;
  213035. DWORD dwBufferBytes;
  213036. DWORD dwReserved;
  213037. LPWAVEFORMATEX lpwfxFormat;
  213038. } DSCBUFFERDESC;
  213039. struct IDirectSoundCaptureBuffer;
  213040. #undef INTERFACE
  213041. #define INTERFACE IDirectSoundCapture
  213042. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213043. {
  213044. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213045. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213046. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213047. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213048. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213049. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213050. };
  213051. #undef INTERFACE
  213052. #define INTERFACE IDirectSoundCaptureBuffer
  213053. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213054. {
  213055. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213056. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213057. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213058. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213059. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213060. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213061. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213062. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213063. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213064. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213065. STDMETHOD(Stop) (THIS) PURE;
  213066. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213067. };
  213068. };
  213069. BEGIN_JUCE_NAMESPACE
  213070. static const String getDSErrorMessage (HRESULT hr)
  213071. {
  213072. const char* result = 0;
  213073. switch (hr)
  213074. {
  213075. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213076. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213077. case E_INVALIDARG: result = "Invalid parameter"; break;
  213078. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213079. case E_FAIL: result = "Generic error"; break;
  213080. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213081. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213082. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213083. case E_NOTIMPL: result = "Unsupported function"; break;
  213084. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213085. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213086. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213087. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213088. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213089. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213090. case E_NOINTERFACE: result = "No interface"; break;
  213091. case S_OK: result = "No error"; break;
  213092. default: return "Unknown error: " + String ((int) hr);
  213093. }
  213094. return result;
  213095. }
  213096. #define DS_DEBUGGING 1
  213097. #ifdef DS_DEBUGGING
  213098. #define CATCH JUCE_CATCH_EXCEPTION
  213099. #undef log
  213100. #define log(a) Logger::writeToLog(a);
  213101. #undef logError
  213102. #define logError(a) logDSError(a, __LINE__);
  213103. static void logDSError (HRESULT hr, int lineNum)
  213104. {
  213105. if (hr != S_OK)
  213106. {
  213107. String error ("DS error at line ");
  213108. error << lineNum << " - " << getDSErrorMessage (hr);
  213109. log (error);
  213110. }
  213111. }
  213112. #else
  213113. #define CATCH JUCE_CATCH_ALL
  213114. #define log(a)
  213115. #define logError(a)
  213116. #endif
  213117. #define DSOUND_FUNCTION(functionName, params) \
  213118. typedef HRESULT (WINAPI *type##functionName) params; \
  213119. static type##functionName ds##functionName = 0;
  213120. #define DSOUND_FUNCTION_LOAD(functionName) \
  213121. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213122. jassert (ds##functionName != 0);
  213123. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213124. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213125. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213126. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213127. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213128. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213129. static void initialiseDSoundFunctions()
  213130. {
  213131. if (dsDirectSoundCreate == 0)
  213132. {
  213133. HMODULE h = LoadLibraryA ("dsound.dll");
  213134. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213135. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213136. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213137. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213138. }
  213139. }
  213140. class DSoundInternalOutChannel
  213141. {
  213142. String name;
  213143. LPGUID guid;
  213144. int sampleRate, bufferSizeSamples;
  213145. float* leftBuffer;
  213146. float* rightBuffer;
  213147. IDirectSound* pDirectSound;
  213148. IDirectSoundBuffer* pOutputBuffer;
  213149. DWORD writeOffset;
  213150. int totalBytesPerBuffer;
  213151. int bytesPerBuffer;
  213152. unsigned int lastPlayCursor;
  213153. public:
  213154. int bitDepth;
  213155. bool doneFlag;
  213156. DSoundInternalOutChannel (const String& name_,
  213157. LPGUID guid_,
  213158. int rate,
  213159. int bufferSize,
  213160. float* left,
  213161. float* right)
  213162. : name (name_),
  213163. guid (guid_),
  213164. sampleRate (rate),
  213165. bufferSizeSamples (bufferSize),
  213166. leftBuffer (left),
  213167. rightBuffer (right),
  213168. pDirectSound (0),
  213169. pOutputBuffer (0),
  213170. bitDepth (16)
  213171. {
  213172. }
  213173. ~DSoundInternalOutChannel()
  213174. {
  213175. close();
  213176. }
  213177. void close()
  213178. {
  213179. HRESULT hr;
  213180. if (pOutputBuffer != 0)
  213181. {
  213182. JUCE_TRY
  213183. {
  213184. log ("closing dsound out: " + name);
  213185. hr = pOutputBuffer->Stop();
  213186. logError (hr);
  213187. }
  213188. CATCH
  213189. JUCE_TRY
  213190. {
  213191. hr = pOutputBuffer->Release();
  213192. logError (hr);
  213193. }
  213194. CATCH
  213195. pOutputBuffer = 0;
  213196. }
  213197. if (pDirectSound != 0)
  213198. {
  213199. JUCE_TRY
  213200. {
  213201. hr = pDirectSound->Release();
  213202. logError (hr);
  213203. }
  213204. CATCH
  213205. pDirectSound = 0;
  213206. }
  213207. }
  213208. const String open()
  213209. {
  213210. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213211. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213212. pDirectSound = 0;
  213213. pOutputBuffer = 0;
  213214. writeOffset = 0;
  213215. String error;
  213216. HRESULT hr = E_NOINTERFACE;
  213217. if (dsDirectSoundCreate != 0)
  213218. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213219. if (hr == S_OK)
  213220. {
  213221. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213222. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213223. const int numChannels = 2;
  213224. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213225. logError (hr);
  213226. if (hr == S_OK)
  213227. {
  213228. IDirectSoundBuffer* pPrimaryBuffer;
  213229. DSBUFFERDESC primaryDesc;
  213230. zerostruct (primaryDesc);
  213231. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213232. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213233. primaryDesc.dwBufferBytes = 0;
  213234. primaryDesc.lpwfxFormat = 0;
  213235. log ("opening dsound out step 2");
  213236. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213237. logError (hr);
  213238. if (hr == S_OK)
  213239. {
  213240. WAVEFORMATEX wfFormat;
  213241. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213242. wfFormat.nChannels = (unsigned short) numChannels;
  213243. wfFormat.nSamplesPerSec = sampleRate;
  213244. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213245. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213246. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213247. wfFormat.cbSize = 0;
  213248. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213249. logError (hr);
  213250. if (hr == S_OK)
  213251. {
  213252. DSBUFFERDESC secondaryDesc;
  213253. zerostruct (secondaryDesc);
  213254. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213255. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213256. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213257. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213258. secondaryDesc.lpwfxFormat = &wfFormat;
  213259. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213260. logError (hr);
  213261. if (hr == S_OK)
  213262. {
  213263. log ("opening dsound out step 3");
  213264. DWORD dwDataLen;
  213265. unsigned char* pDSBuffData;
  213266. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213267. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213268. logError (hr);
  213269. if (hr == S_OK)
  213270. {
  213271. zeromem (pDSBuffData, dwDataLen);
  213272. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213273. if (hr == S_OK)
  213274. {
  213275. hr = pOutputBuffer->SetCurrentPosition (0);
  213276. if (hr == S_OK)
  213277. {
  213278. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213279. if (hr == S_OK)
  213280. return String::empty;
  213281. }
  213282. }
  213283. }
  213284. }
  213285. }
  213286. }
  213287. }
  213288. }
  213289. error = getDSErrorMessage (hr);
  213290. close();
  213291. return error;
  213292. }
  213293. void synchronisePosition()
  213294. {
  213295. if (pOutputBuffer != 0)
  213296. {
  213297. DWORD playCursor;
  213298. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213299. }
  213300. }
  213301. bool service()
  213302. {
  213303. if (pOutputBuffer == 0)
  213304. return true;
  213305. DWORD playCursor, writeCursor;
  213306. for (;;)
  213307. {
  213308. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213309. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213310. {
  213311. pOutputBuffer->Restore();
  213312. continue;
  213313. }
  213314. if (hr == S_OK)
  213315. break;
  213316. logError (hr);
  213317. jassertfalse;
  213318. return true;
  213319. }
  213320. int playWriteGap = writeCursor - playCursor;
  213321. if (playWriteGap < 0)
  213322. playWriteGap += totalBytesPerBuffer;
  213323. int bytesEmpty = playCursor - writeOffset;
  213324. if (bytesEmpty < 0)
  213325. bytesEmpty += totalBytesPerBuffer;
  213326. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213327. {
  213328. writeOffset = writeCursor;
  213329. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213330. }
  213331. if (bytesEmpty >= bytesPerBuffer)
  213332. {
  213333. LPBYTE lpbuf1 = 0;
  213334. LPBYTE lpbuf2 = 0;
  213335. DWORD dwSize1 = 0;
  213336. DWORD dwSize2 = 0;
  213337. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  213338. bytesPerBuffer,
  213339. (void**) &lpbuf1, &dwSize1,
  213340. (void**) &lpbuf2, &dwSize2, 0);
  213341. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213342. {
  213343. pOutputBuffer->Restore();
  213344. hr = pOutputBuffer->Lock (writeOffset,
  213345. bytesPerBuffer,
  213346. (void**) &lpbuf1, &dwSize1,
  213347. (void**) &lpbuf2, &dwSize2, 0);
  213348. }
  213349. if (hr == S_OK)
  213350. {
  213351. if (bitDepth == 16)
  213352. {
  213353. const float gainL = 32767.0f;
  213354. const float gainR = 32767.0f;
  213355. int* dest = (int*)lpbuf1;
  213356. const float* left = leftBuffer;
  213357. const float* right = rightBuffer;
  213358. int samples1 = dwSize1 >> 2;
  213359. int samples2 = dwSize2 >> 2;
  213360. if (left == 0)
  213361. {
  213362. while (--samples1 >= 0)
  213363. {
  213364. int r = roundToInt (gainR * *right++);
  213365. if (r < -32768)
  213366. r = -32768;
  213367. else if (r > 32767)
  213368. r = 32767;
  213369. *dest++ = (r << 16);
  213370. }
  213371. dest = (int*)lpbuf2;
  213372. while (--samples2 >= 0)
  213373. {
  213374. int r = roundToInt (gainR * *right++);
  213375. if (r < -32768)
  213376. r = -32768;
  213377. else if (r > 32767)
  213378. r = 32767;
  213379. *dest++ = (r << 16);
  213380. }
  213381. }
  213382. else if (right == 0)
  213383. {
  213384. while (--samples1 >= 0)
  213385. {
  213386. int l = roundToInt (gainL * *left++);
  213387. if (l < -32768)
  213388. l = -32768;
  213389. else if (l > 32767)
  213390. l = 32767;
  213391. l &= 0xffff;
  213392. *dest++ = l;
  213393. }
  213394. dest = (int*)lpbuf2;
  213395. while (--samples2 >= 0)
  213396. {
  213397. int l = roundToInt (gainL * *left++);
  213398. if (l < -32768)
  213399. l = -32768;
  213400. else if (l > 32767)
  213401. l = 32767;
  213402. l &= 0xffff;
  213403. *dest++ = l;
  213404. }
  213405. }
  213406. else
  213407. {
  213408. while (--samples1 >= 0)
  213409. {
  213410. int l = roundToInt (gainL * *left++);
  213411. if (l < -32768)
  213412. l = -32768;
  213413. else if (l > 32767)
  213414. l = 32767;
  213415. l &= 0xffff;
  213416. int r = roundToInt (gainR * *right++);
  213417. if (r < -32768)
  213418. r = -32768;
  213419. else if (r > 32767)
  213420. r = 32767;
  213421. *dest++ = (r << 16) | l;
  213422. }
  213423. dest = (int*)lpbuf2;
  213424. while (--samples2 >= 0)
  213425. {
  213426. int l = roundToInt (gainL * *left++);
  213427. if (l < -32768)
  213428. l = -32768;
  213429. else if (l > 32767)
  213430. l = 32767;
  213431. l &= 0xffff;
  213432. int r = roundToInt (gainR * *right++);
  213433. if (r < -32768)
  213434. r = -32768;
  213435. else if (r > 32767)
  213436. r = 32767;
  213437. *dest++ = (r << 16) | l;
  213438. }
  213439. }
  213440. }
  213441. else
  213442. {
  213443. jassertfalse;
  213444. }
  213445. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213446. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213447. }
  213448. else
  213449. {
  213450. jassertfalse;
  213451. logError (hr);
  213452. }
  213453. bytesEmpty -= bytesPerBuffer;
  213454. return true;
  213455. }
  213456. else
  213457. {
  213458. return false;
  213459. }
  213460. }
  213461. };
  213462. struct DSoundInternalInChannel
  213463. {
  213464. String name;
  213465. LPGUID guid;
  213466. int sampleRate, bufferSizeSamples;
  213467. float* leftBuffer;
  213468. float* rightBuffer;
  213469. IDirectSound* pDirectSound;
  213470. IDirectSoundCapture* pDirectSoundCapture;
  213471. IDirectSoundCaptureBuffer* pInputBuffer;
  213472. public:
  213473. unsigned int readOffset;
  213474. int bytesPerBuffer, totalBytesPerBuffer;
  213475. int bitDepth;
  213476. bool doneFlag;
  213477. DSoundInternalInChannel (const String& name_,
  213478. LPGUID guid_,
  213479. int rate,
  213480. int bufferSize,
  213481. float* left,
  213482. float* right)
  213483. : name (name_),
  213484. guid (guid_),
  213485. sampleRate (rate),
  213486. bufferSizeSamples (bufferSize),
  213487. leftBuffer (left),
  213488. rightBuffer (right),
  213489. pDirectSound (0),
  213490. pDirectSoundCapture (0),
  213491. pInputBuffer (0),
  213492. bitDepth (16)
  213493. {
  213494. }
  213495. ~DSoundInternalInChannel()
  213496. {
  213497. close();
  213498. }
  213499. void close()
  213500. {
  213501. HRESULT hr;
  213502. if (pInputBuffer != 0)
  213503. {
  213504. JUCE_TRY
  213505. {
  213506. log ("closing dsound in: " + name);
  213507. hr = pInputBuffer->Stop();
  213508. logError (hr);
  213509. }
  213510. CATCH
  213511. JUCE_TRY
  213512. {
  213513. hr = pInputBuffer->Release();
  213514. logError (hr);
  213515. }
  213516. CATCH
  213517. pInputBuffer = 0;
  213518. }
  213519. if (pDirectSoundCapture != 0)
  213520. {
  213521. JUCE_TRY
  213522. {
  213523. hr = pDirectSoundCapture->Release();
  213524. logError (hr);
  213525. }
  213526. CATCH
  213527. pDirectSoundCapture = 0;
  213528. }
  213529. if (pDirectSound != 0)
  213530. {
  213531. JUCE_TRY
  213532. {
  213533. hr = pDirectSound->Release();
  213534. logError (hr);
  213535. }
  213536. CATCH
  213537. pDirectSound = 0;
  213538. }
  213539. }
  213540. const String open()
  213541. {
  213542. log ("opening dsound in device: " + name
  213543. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213544. pDirectSound = 0;
  213545. pDirectSoundCapture = 0;
  213546. pInputBuffer = 0;
  213547. readOffset = 0;
  213548. totalBytesPerBuffer = 0;
  213549. String error;
  213550. HRESULT hr = E_NOINTERFACE;
  213551. if (dsDirectSoundCaptureCreate != 0)
  213552. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213553. logError (hr);
  213554. if (hr == S_OK)
  213555. {
  213556. const int numChannels = 2;
  213557. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213558. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213559. WAVEFORMATEX wfFormat;
  213560. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213561. wfFormat.nChannels = (unsigned short)numChannels;
  213562. wfFormat.nSamplesPerSec = sampleRate;
  213563. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213564. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213565. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213566. wfFormat.cbSize = 0;
  213567. DSCBUFFERDESC captureDesc;
  213568. zerostruct (captureDesc);
  213569. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213570. captureDesc.dwFlags = 0;
  213571. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213572. captureDesc.lpwfxFormat = &wfFormat;
  213573. log ("opening dsound in step 2");
  213574. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213575. logError (hr);
  213576. if (hr == S_OK)
  213577. {
  213578. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213579. logError (hr);
  213580. if (hr == S_OK)
  213581. return String::empty;
  213582. }
  213583. }
  213584. error = getDSErrorMessage (hr);
  213585. close();
  213586. return error;
  213587. }
  213588. void synchronisePosition()
  213589. {
  213590. if (pInputBuffer != 0)
  213591. {
  213592. DWORD capturePos;
  213593. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213594. }
  213595. }
  213596. bool service()
  213597. {
  213598. if (pInputBuffer == 0)
  213599. return true;
  213600. DWORD capturePos, readPos;
  213601. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213602. logError (hr);
  213603. if (hr != S_OK)
  213604. return true;
  213605. int bytesFilled = readPos - readOffset;
  213606. if (bytesFilled < 0)
  213607. bytesFilled += totalBytesPerBuffer;
  213608. if (bytesFilled >= bytesPerBuffer)
  213609. {
  213610. LPBYTE lpbuf1 = 0;
  213611. LPBYTE lpbuf2 = 0;
  213612. DWORD dwsize1 = 0;
  213613. DWORD dwsize2 = 0;
  213614. HRESULT hr = pInputBuffer->Lock (readOffset,
  213615. bytesPerBuffer,
  213616. (void**) &lpbuf1, &dwsize1,
  213617. (void**) &lpbuf2, &dwsize2, 0);
  213618. if (hr == S_OK)
  213619. {
  213620. if (bitDepth == 16)
  213621. {
  213622. const float g = 1.0f / 32768.0f;
  213623. float* destL = leftBuffer;
  213624. float* destR = rightBuffer;
  213625. int samples1 = dwsize1 >> 2;
  213626. int samples2 = dwsize2 >> 2;
  213627. const short* src = (const short*)lpbuf1;
  213628. if (destL == 0)
  213629. {
  213630. while (--samples1 >= 0)
  213631. {
  213632. ++src;
  213633. *destR++ = *src++ * g;
  213634. }
  213635. src = (const short*)lpbuf2;
  213636. while (--samples2 >= 0)
  213637. {
  213638. ++src;
  213639. *destR++ = *src++ * g;
  213640. }
  213641. }
  213642. else if (destR == 0)
  213643. {
  213644. while (--samples1 >= 0)
  213645. {
  213646. *destL++ = *src++ * g;
  213647. ++src;
  213648. }
  213649. src = (const short*)lpbuf2;
  213650. while (--samples2 >= 0)
  213651. {
  213652. *destL++ = *src++ * g;
  213653. ++src;
  213654. }
  213655. }
  213656. else
  213657. {
  213658. while (--samples1 >= 0)
  213659. {
  213660. *destL++ = *src++ * g;
  213661. *destR++ = *src++ * g;
  213662. }
  213663. src = (const short*)lpbuf2;
  213664. while (--samples2 >= 0)
  213665. {
  213666. *destL++ = *src++ * g;
  213667. *destR++ = *src++ * g;
  213668. }
  213669. }
  213670. }
  213671. else
  213672. {
  213673. jassertfalse;
  213674. }
  213675. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213676. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213677. }
  213678. else
  213679. {
  213680. logError (hr);
  213681. jassertfalse;
  213682. }
  213683. bytesFilled -= bytesPerBuffer;
  213684. return true;
  213685. }
  213686. else
  213687. {
  213688. return false;
  213689. }
  213690. }
  213691. };
  213692. class DSoundAudioIODevice : public AudioIODevice,
  213693. public Thread
  213694. {
  213695. public:
  213696. DSoundAudioIODevice (const String& deviceName,
  213697. const int outputDeviceIndex_,
  213698. const int inputDeviceIndex_)
  213699. : AudioIODevice (deviceName, "DirectSound"),
  213700. Thread ("Juce DSound"),
  213701. isOpen_ (false),
  213702. isStarted (false),
  213703. outputDeviceIndex (outputDeviceIndex_),
  213704. inputDeviceIndex (inputDeviceIndex_),
  213705. totalSamplesOut (0),
  213706. sampleRate (0.0),
  213707. inputBuffers (1, 1),
  213708. outputBuffers (1, 1),
  213709. callback (0),
  213710. bufferSizeSamples (0)
  213711. {
  213712. if (outputDeviceIndex_ >= 0)
  213713. {
  213714. outChannels.add (TRANS("Left"));
  213715. outChannels.add (TRANS("Right"));
  213716. }
  213717. if (inputDeviceIndex_ >= 0)
  213718. {
  213719. inChannels.add (TRANS("Left"));
  213720. inChannels.add (TRANS("Right"));
  213721. }
  213722. }
  213723. ~DSoundAudioIODevice()
  213724. {
  213725. close();
  213726. }
  213727. const StringArray getOutputChannelNames()
  213728. {
  213729. return outChannels;
  213730. }
  213731. const StringArray getInputChannelNames()
  213732. {
  213733. return inChannels;
  213734. }
  213735. int getNumSampleRates()
  213736. {
  213737. return 4;
  213738. }
  213739. double getSampleRate (int index)
  213740. {
  213741. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213742. return samps [jlimit (0, 3, index)];
  213743. }
  213744. int getNumBufferSizesAvailable()
  213745. {
  213746. return 50;
  213747. }
  213748. int getBufferSizeSamples (int index)
  213749. {
  213750. int n = 64;
  213751. for (int i = 0; i < index; ++i)
  213752. n += (n < 512) ? 32
  213753. : ((n < 1024) ? 64
  213754. : ((n < 2048) ? 128 : 256));
  213755. return n;
  213756. }
  213757. int getDefaultBufferSize()
  213758. {
  213759. return 2560;
  213760. }
  213761. const String open (const BigInteger& inputChannels,
  213762. const BigInteger& outputChannels,
  213763. double sampleRate,
  213764. int bufferSizeSamples)
  213765. {
  213766. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213767. isOpen_ = lastError.isEmpty();
  213768. return lastError;
  213769. }
  213770. void close()
  213771. {
  213772. stop();
  213773. if (isOpen_)
  213774. {
  213775. closeDevice();
  213776. isOpen_ = false;
  213777. }
  213778. }
  213779. bool isOpen()
  213780. {
  213781. return isOpen_ && isThreadRunning();
  213782. }
  213783. int getCurrentBufferSizeSamples()
  213784. {
  213785. return bufferSizeSamples;
  213786. }
  213787. double getCurrentSampleRate()
  213788. {
  213789. return sampleRate;
  213790. }
  213791. int getCurrentBitDepth()
  213792. {
  213793. int i, bits = 256;
  213794. for (i = inChans.size(); --i >= 0;)
  213795. bits = jmin (bits, inChans[i]->bitDepth);
  213796. for (i = outChans.size(); --i >= 0;)
  213797. bits = jmin (bits, outChans[i]->bitDepth);
  213798. if (bits > 32)
  213799. bits = 16;
  213800. return bits;
  213801. }
  213802. const BigInteger getActiveOutputChannels() const
  213803. {
  213804. return enabledOutputs;
  213805. }
  213806. const BigInteger getActiveInputChannels() const
  213807. {
  213808. return enabledInputs;
  213809. }
  213810. int getOutputLatencyInSamples()
  213811. {
  213812. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213813. }
  213814. int getInputLatencyInSamples()
  213815. {
  213816. return getOutputLatencyInSamples();
  213817. }
  213818. void start (AudioIODeviceCallback* call)
  213819. {
  213820. if (isOpen_ && call != 0 && ! isStarted)
  213821. {
  213822. if (! isThreadRunning())
  213823. {
  213824. // something gone wrong and the thread's stopped..
  213825. isOpen_ = false;
  213826. return;
  213827. }
  213828. call->audioDeviceAboutToStart (this);
  213829. const ScopedLock sl (startStopLock);
  213830. callback = call;
  213831. isStarted = true;
  213832. }
  213833. }
  213834. void stop()
  213835. {
  213836. if (isStarted)
  213837. {
  213838. AudioIODeviceCallback* const callbackLocal = callback;
  213839. {
  213840. const ScopedLock sl (startStopLock);
  213841. isStarted = false;
  213842. }
  213843. if (callbackLocal != 0)
  213844. callbackLocal->audioDeviceStopped();
  213845. }
  213846. }
  213847. bool isPlaying()
  213848. {
  213849. return isStarted && isOpen_ && isThreadRunning();
  213850. }
  213851. const String getLastError()
  213852. {
  213853. return lastError;
  213854. }
  213855. juce_UseDebuggingNewOperator
  213856. StringArray inChannels, outChannels;
  213857. int outputDeviceIndex, inputDeviceIndex;
  213858. private:
  213859. bool isOpen_;
  213860. bool isStarted;
  213861. String lastError;
  213862. OwnedArray <DSoundInternalInChannel> inChans;
  213863. OwnedArray <DSoundInternalOutChannel> outChans;
  213864. WaitableEvent startEvent;
  213865. int bufferSizeSamples;
  213866. int volatile totalSamplesOut;
  213867. int64 volatile lastBlockTime;
  213868. double sampleRate;
  213869. BigInteger enabledInputs, enabledOutputs;
  213870. AudioSampleBuffer inputBuffers, outputBuffers;
  213871. AudioIODeviceCallback* callback;
  213872. CriticalSection startStopLock;
  213873. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213874. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213875. const String openDevice (const BigInteger& inputChannels,
  213876. const BigInteger& outputChannels,
  213877. double sampleRate_,
  213878. int bufferSizeSamples_);
  213879. void closeDevice()
  213880. {
  213881. isStarted = false;
  213882. stopThread (5000);
  213883. inChans.clear();
  213884. outChans.clear();
  213885. inputBuffers.setSize (1, 1);
  213886. outputBuffers.setSize (1, 1);
  213887. }
  213888. void resync()
  213889. {
  213890. if (! threadShouldExit())
  213891. {
  213892. sleep (5);
  213893. int i;
  213894. for (i = 0; i < outChans.size(); ++i)
  213895. outChans.getUnchecked(i)->synchronisePosition();
  213896. for (i = 0; i < inChans.size(); ++i)
  213897. inChans.getUnchecked(i)->synchronisePosition();
  213898. }
  213899. }
  213900. public:
  213901. void run()
  213902. {
  213903. while (! threadShouldExit())
  213904. {
  213905. if (wait (100))
  213906. break;
  213907. }
  213908. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213909. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213910. while (! threadShouldExit())
  213911. {
  213912. int numToDo = 0;
  213913. uint32 startTime = Time::getMillisecondCounter();
  213914. int i;
  213915. for (i = inChans.size(); --i >= 0;)
  213916. {
  213917. inChans.getUnchecked(i)->doneFlag = false;
  213918. ++numToDo;
  213919. }
  213920. for (i = outChans.size(); --i >= 0;)
  213921. {
  213922. outChans.getUnchecked(i)->doneFlag = false;
  213923. ++numToDo;
  213924. }
  213925. if (numToDo > 0)
  213926. {
  213927. const int maxCount = 3;
  213928. int count = maxCount;
  213929. for (;;)
  213930. {
  213931. for (i = inChans.size(); --i >= 0;)
  213932. {
  213933. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213934. if ((! in->doneFlag) && in->service())
  213935. {
  213936. in->doneFlag = true;
  213937. --numToDo;
  213938. }
  213939. }
  213940. for (i = outChans.size(); --i >= 0;)
  213941. {
  213942. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213943. if ((! out->doneFlag) && out->service())
  213944. {
  213945. out->doneFlag = true;
  213946. --numToDo;
  213947. }
  213948. }
  213949. if (numToDo <= 0)
  213950. break;
  213951. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213952. {
  213953. resync();
  213954. break;
  213955. }
  213956. if (--count <= 0)
  213957. {
  213958. Sleep (1);
  213959. count = maxCount;
  213960. }
  213961. if (threadShouldExit())
  213962. return;
  213963. }
  213964. }
  213965. else
  213966. {
  213967. sleep (1);
  213968. }
  213969. const ScopedLock sl (startStopLock);
  213970. if (isStarted)
  213971. {
  213972. JUCE_TRY
  213973. {
  213974. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213975. inputBuffers.getNumChannels(),
  213976. outputBuffers.getArrayOfChannels(),
  213977. outputBuffers.getNumChannels(),
  213978. bufferSizeSamples);
  213979. }
  213980. JUCE_CATCH_EXCEPTION
  213981. totalSamplesOut += bufferSizeSamples;
  213982. }
  213983. else
  213984. {
  213985. outputBuffers.clear();
  213986. totalSamplesOut = 0;
  213987. sleep (1);
  213988. }
  213989. }
  213990. }
  213991. };
  213992. class DSoundAudioIODeviceType : public AudioIODeviceType
  213993. {
  213994. public:
  213995. DSoundAudioIODeviceType()
  213996. : AudioIODeviceType ("DirectSound"),
  213997. hasScanned (false)
  213998. {
  213999. initialiseDSoundFunctions();
  214000. }
  214001. ~DSoundAudioIODeviceType()
  214002. {
  214003. }
  214004. void scanForDevices()
  214005. {
  214006. hasScanned = true;
  214007. outputDeviceNames.clear();
  214008. outputGuids.clear();
  214009. inputDeviceNames.clear();
  214010. inputGuids.clear();
  214011. if (dsDirectSoundEnumerateW != 0)
  214012. {
  214013. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214014. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214015. }
  214016. }
  214017. const StringArray getDeviceNames (bool wantInputNames) const
  214018. {
  214019. jassert (hasScanned); // need to call scanForDevices() before doing this
  214020. return wantInputNames ? inputDeviceNames
  214021. : outputDeviceNames;
  214022. }
  214023. int getDefaultDeviceIndex (bool /*forInput*/) const
  214024. {
  214025. jassert (hasScanned); // need to call scanForDevices() before doing this
  214026. return 0;
  214027. }
  214028. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214029. {
  214030. jassert (hasScanned); // need to call scanForDevices() before doing this
  214031. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214032. if (d == 0)
  214033. return -1;
  214034. return asInput ? d->inputDeviceIndex
  214035. : d->outputDeviceIndex;
  214036. }
  214037. bool hasSeparateInputsAndOutputs() const { return true; }
  214038. AudioIODevice* createDevice (const String& outputDeviceName,
  214039. const String& inputDeviceName)
  214040. {
  214041. jassert (hasScanned); // need to call scanForDevices() before doing this
  214042. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214043. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214044. if (outputIndex >= 0 || inputIndex >= 0)
  214045. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214046. : inputDeviceName,
  214047. outputIndex, inputIndex);
  214048. return 0;
  214049. }
  214050. juce_UseDebuggingNewOperator
  214051. StringArray outputDeviceNames;
  214052. OwnedArray <GUID> outputGuids;
  214053. StringArray inputDeviceNames;
  214054. OwnedArray <GUID> inputGuids;
  214055. private:
  214056. bool hasScanned;
  214057. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214058. {
  214059. desc = desc.trim();
  214060. if (desc.isNotEmpty())
  214061. {
  214062. const String origDesc (desc);
  214063. int n = 2;
  214064. while (outputDeviceNames.contains (desc))
  214065. desc = origDesc + " (" + String (n++) + ")";
  214066. outputDeviceNames.add (desc);
  214067. if (lpGUID != 0)
  214068. outputGuids.add (new GUID (*lpGUID));
  214069. else
  214070. outputGuids.add (0);
  214071. }
  214072. return TRUE;
  214073. }
  214074. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214075. {
  214076. return ((DSoundAudioIODeviceType*) object)
  214077. ->outputEnumProc (lpGUID, String (description));
  214078. }
  214079. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214080. {
  214081. return ((DSoundAudioIODeviceType*) object)
  214082. ->outputEnumProc (lpGUID, String (description));
  214083. }
  214084. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214085. {
  214086. desc = desc.trim();
  214087. if (desc.isNotEmpty())
  214088. {
  214089. const String origDesc (desc);
  214090. int n = 2;
  214091. while (inputDeviceNames.contains (desc))
  214092. desc = origDesc + " (" + String (n++) + ")";
  214093. inputDeviceNames.add (desc);
  214094. if (lpGUID != 0)
  214095. inputGuids.add (new GUID (*lpGUID));
  214096. else
  214097. inputGuids.add (0);
  214098. }
  214099. return TRUE;
  214100. }
  214101. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214102. {
  214103. return ((DSoundAudioIODeviceType*) object)
  214104. ->inputEnumProc (lpGUID, String (description));
  214105. }
  214106. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214107. {
  214108. return ((DSoundAudioIODeviceType*) object)
  214109. ->inputEnumProc (lpGUID, String (description));
  214110. }
  214111. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  214112. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  214113. };
  214114. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214115. const BigInteger& outputChannels,
  214116. double sampleRate_,
  214117. int bufferSizeSamples_)
  214118. {
  214119. closeDevice();
  214120. totalSamplesOut = 0;
  214121. sampleRate = sampleRate_;
  214122. if (bufferSizeSamples_ <= 0)
  214123. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214124. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214125. DSoundAudioIODeviceType dlh;
  214126. dlh.scanForDevices();
  214127. enabledInputs = inputChannels;
  214128. enabledInputs.setRange (inChannels.size(),
  214129. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214130. false);
  214131. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214132. inputBuffers.clear();
  214133. int i, numIns = 0;
  214134. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214135. {
  214136. float* left = 0;
  214137. if (enabledInputs[i])
  214138. left = inputBuffers.getSampleData (numIns++);
  214139. float* right = 0;
  214140. if (enabledInputs[i + 1])
  214141. right = inputBuffers.getSampleData (numIns++);
  214142. if (left != 0 || right != 0)
  214143. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214144. dlh.inputGuids [inputDeviceIndex],
  214145. (int) sampleRate, bufferSizeSamples,
  214146. left, right));
  214147. }
  214148. enabledOutputs = outputChannels;
  214149. enabledOutputs.setRange (outChannels.size(),
  214150. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214151. false);
  214152. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214153. outputBuffers.clear();
  214154. int numOuts = 0;
  214155. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214156. {
  214157. float* left = 0;
  214158. if (enabledOutputs[i])
  214159. left = outputBuffers.getSampleData (numOuts++);
  214160. float* right = 0;
  214161. if (enabledOutputs[i + 1])
  214162. right = outputBuffers.getSampleData (numOuts++);
  214163. if (left != 0 || right != 0)
  214164. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214165. dlh.outputGuids [outputDeviceIndex],
  214166. (int) sampleRate, bufferSizeSamples,
  214167. left, right));
  214168. }
  214169. String error;
  214170. // boost our priority while opening the devices to try to get better sync between them
  214171. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214172. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214173. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214174. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214175. for (i = 0; i < outChans.size(); ++i)
  214176. {
  214177. error = outChans[i]->open();
  214178. if (error.isNotEmpty())
  214179. {
  214180. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214181. break;
  214182. }
  214183. }
  214184. if (error.isEmpty())
  214185. {
  214186. for (i = 0; i < inChans.size(); ++i)
  214187. {
  214188. error = inChans[i]->open();
  214189. if (error.isNotEmpty())
  214190. {
  214191. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214192. break;
  214193. }
  214194. }
  214195. }
  214196. if (error.isEmpty())
  214197. {
  214198. totalSamplesOut = 0;
  214199. for (i = 0; i < outChans.size(); ++i)
  214200. outChans.getUnchecked(i)->synchronisePosition();
  214201. for (i = 0; i < inChans.size(); ++i)
  214202. inChans.getUnchecked(i)->synchronisePosition();
  214203. startThread (9);
  214204. sleep (10);
  214205. notify();
  214206. }
  214207. else
  214208. {
  214209. log (error);
  214210. }
  214211. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214212. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214213. return error;
  214214. }
  214215. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214216. {
  214217. return new DSoundAudioIODeviceType();
  214218. }
  214219. #undef log
  214220. #endif
  214221. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214222. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214223. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214224. // compiled on its own).
  214225. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214226. #if 1
  214227. const String getAudioErrorDesc (HRESULT hr)
  214228. {
  214229. const char* e = 0;
  214230. switch (hr)
  214231. {
  214232. case E_POINTER: e = "E_POINTER"; break;
  214233. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  214234. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  214235. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214236. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214237. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214238. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  214239. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214240. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  214241. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214242. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  214243. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  214244. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214245. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214246. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214247. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214248. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214249. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214250. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214251. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214252. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214253. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214254. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214255. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  214256. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214257. default: return String::toHexString ((int) hr);
  214258. }
  214259. return e;
  214260. }
  214261. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  214262. #define OK(a) wasapi_checkResult(a)
  214263. static bool wasapi_checkResult (HRESULT hr)
  214264. {
  214265. logFailure (hr);
  214266. return SUCCEEDED (hr);
  214267. }
  214268. #else
  214269. #define logFailure(hr) {}
  214270. #define OK(a) SUCCEEDED(a)
  214271. #endif
  214272. static const String wasapi_getDeviceID (IMMDevice* const device)
  214273. {
  214274. String s;
  214275. WCHAR* deviceId = 0;
  214276. if (OK (device->GetId (&deviceId)))
  214277. {
  214278. s = String (deviceId);
  214279. CoTaskMemFree (deviceId);
  214280. }
  214281. return s;
  214282. }
  214283. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  214284. {
  214285. EDataFlow flow = eRender;
  214286. ComSmartPtr <IMMEndpoint> endPoint;
  214287. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  214288. (void) OK (endPoint->GetDataFlow (&flow));
  214289. return flow;
  214290. }
  214291. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214292. {
  214293. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214294. }
  214295. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214296. {
  214297. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214298. : sizeof (WAVEFORMATEX));
  214299. }
  214300. class WASAPIDeviceBase
  214301. {
  214302. public:
  214303. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214304. : device (device_),
  214305. sampleRate (0),
  214306. numChannels (0),
  214307. actualNumChannels (0),
  214308. defaultSampleRate (0),
  214309. minBufferSize (0),
  214310. defaultBufferSize (0),
  214311. latencySamples (0),
  214312. useExclusiveMode (useExclusiveMode_)
  214313. {
  214314. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214315. ComSmartPtr <IAudioClient> tempClient (createClient());
  214316. if (tempClient == 0)
  214317. return;
  214318. REFERENCE_TIME defaultPeriod, minPeriod;
  214319. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214320. return;
  214321. WAVEFORMATEX* mixFormat = 0;
  214322. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  214323. return;
  214324. WAVEFORMATEXTENSIBLE format;
  214325. wasapi_copyWavFormat (format, mixFormat);
  214326. CoTaskMemFree (mixFormat);
  214327. actualNumChannels = numChannels = format.Format.nChannels;
  214328. defaultSampleRate = format.Format.nSamplesPerSec;
  214329. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  214330. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  214331. rates.addUsingDefaultSort (defaultSampleRate);
  214332. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214333. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214334. {
  214335. if (ratesToTest[i] == defaultSampleRate)
  214336. continue;
  214337. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214338. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214339. (WAVEFORMATEX*) &format, 0)))
  214340. if (! rates.contains (ratesToTest[i]))
  214341. rates.addUsingDefaultSort (ratesToTest[i]);
  214342. }
  214343. }
  214344. ~WASAPIDeviceBase()
  214345. {
  214346. device = 0;
  214347. CloseHandle (clientEvent);
  214348. }
  214349. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214350. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214351. {
  214352. sampleRate = newSampleRate;
  214353. channels = newChannels;
  214354. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214355. numChannels = channels.getHighestBit() + 1;
  214356. if (numChannels == 0)
  214357. return true;
  214358. client = createClient();
  214359. if (client != 0
  214360. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214361. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214362. {
  214363. channelMaps.clear();
  214364. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214365. if (channels[i])
  214366. channelMaps.add (i);
  214367. REFERENCE_TIME latency;
  214368. if (OK (client->GetStreamLatency (&latency)))
  214369. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  214370. (void) OK (client->GetBufferSize (&actualBufferSize));
  214371. return OK (client->SetEventHandle (clientEvent));
  214372. }
  214373. return false;
  214374. }
  214375. void closeClient()
  214376. {
  214377. if (client != 0)
  214378. client->Stop();
  214379. client = 0;
  214380. ResetEvent (clientEvent);
  214381. }
  214382. ComSmartPtr <IMMDevice> device;
  214383. ComSmartPtr <IAudioClient> client;
  214384. double sampleRate, defaultSampleRate;
  214385. int numChannels, actualNumChannels;
  214386. int minBufferSize, defaultBufferSize, latencySamples;
  214387. const bool useExclusiveMode;
  214388. Array <double> rates;
  214389. HANDLE clientEvent;
  214390. BigInteger channels;
  214391. AudioDataConverters::DataFormat dataFormat;
  214392. Array <int> channelMaps;
  214393. UINT32 actualBufferSize;
  214394. int bytesPerSample;
  214395. private:
  214396. const ComSmartPtr <IAudioClient> createClient()
  214397. {
  214398. ComSmartPtr <IAudioClient> client;
  214399. if (device != 0)
  214400. {
  214401. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  214402. logFailure (hr);
  214403. }
  214404. return client;
  214405. }
  214406. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214407. {
  214408. WAVEFORMATEXTENSIBLE format;
  214409. zerostruct (format);
  214410. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214411. {
  214412. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214413. }
  214414. else
  214415. {
  214416. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214417. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214418. }
  214419. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214420. format.Format.nChannels = (WORD) numChannels;
  214421. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214422. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214423. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214424. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214425. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214426. switch (numChannels)
  214427. {
  214428. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214429. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214430. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214431. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214432. 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;
  214433. default: break;
  214434. }
  214435. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214436. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214437. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214438. logFailure (hr);
  214439. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214440. {
  214441. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214442. hr = S_OK;
  214443. }
  214444. CoTaskMemFree (nearestFormat);
  214445. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214446. if (useExclusiveMode)
  214447. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214448. GUID session;
  214449. if (hr == S_OK
  214450. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214451. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214452. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214453. {
  214454. actualNumChannels = format.Format.nChannels;
  214455. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214456. bytesPerSample = format.Format.wBitsPerSample / 8;
  214457. dataFormat = isFloat ? AudioDataConverters::float32LE
  214458. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214459. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214460. : AudioDataConverters::int16LE)));
  214461. return true;
  214462. }
  214463. return false;
  214464. }
  214465. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214466. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214467. };
  214468. class WASAPIInputDevice : public WASAPIDeviceBase
  214469. {
  214470. public:
  214471. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214472. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214473. reservoir (1, 1)
  214474. {
  214475. }
  214476. ~WASAPIInputDevice()
  214477. {
  214478. close();
  214479. }
  214480. bool open (const double newSampleRate, const BigInteger& newChannels)
  214481. {
  214482. reservoirSize = 0;
  214483. reservoirCapacity = 16384;
  214484. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214485. return openClient (newSampleRate, newChannels)
  214486. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214487. }
  214488. void close()
  214489. {
  214490. closeClient();
  214491. captureClient = 0;
  214492. reservoir.setSize (0);
  214493. }
  214494. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214495. {
  214496. if (numChannels <= 0)
  214497. return;
  214498. int offset = 0;
  214499. while (bufferSize > 0)
  214500. {
  214501. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214502. {
  214503. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214504. for (int i = 0; i < numDestBuffers; ++i)
  214505. {
  214506. float* const dest = destBuffers[i] + offset;
  214507. const int srcChan = channelMaps.getUnchecked(i);
  214508. switch (dataFormat)
  214509. {
  214510. case AudioDataConverters::float32LE:
  214511. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214512. break;
  214513. case AudioDataConverters::int32LE:
  214514. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214515. break;
  214516. case AudioDataConverters::int24LE:
  214517. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214518. break;
  214519. case AudioDataConverters::int16LE:
  214520. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214521. break;
  214522. default: jassertfalse; break;
  214523. }
  214524. }
  214525. bufferSize -= samplesToDo;
  214526. offset += samplesToDo;
  214527. reservoirSize -= samplesToDo;
  214528. }
  214529. else
  214530. {
  214531. UINT32 packetLength = 0;
  214532. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214533. break;
  214534. if (packetLength == 0)
  214535. {
  214536. if (thread.threadShouldExit())
  214537. break;
  214538. Thread::sleep (1);
  214539. continue;
  214540. }
  214541. uint8* inputData = 0;
  214542. UINT32 numSamplesAvailable;
  214543. DWORD flags;
  214544. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214545. {
  214546. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214547. for (int i = 0; i < numDestBuffers; ++i)
  214548. {
  214549. float* const dest = destBuffers[i] + offset;
  214550. const int srcChan = channelMaps.getUnchecked(i);
  214551. switch (dataFormat)
  214552. {
  214553. case AudioDataConverters::float32LE:
  214554. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214555. break;
  214556. case AudioDataConverters::int32LE:
  214557. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214558. break;
  214559. case AudioDataConverters::int24LE:
  214560. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214561. break;
  214562. case AudioDataConverters::int16LE:
  214563. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214564. break;
  214565. default: jassertfalse; break;
  214566. }
  214567. }
  214568. bufferSize -= samplesToDo;
  214569. offset += samplesToDo;
  214570. if (samplesToDo < (int) numSamplesAvailable)
  214571. {
  214572. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214573. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214574. bytesPerSample * actualNumChannels * reservoirSize);
  214575. }
  214576. captureClient->ReleaseBuffer (numSamplesAvailable);
  214577. }
  214578. }
  214579. }
  214580. }
  214581. ComSmartPtr <IAudioCaptureClient> captureClient;
  214582. MemoryBlock reservoir;
  214583. int reservoirSize, reservoirCapacity;
  214584. private:
  214585. WASAPIInputDevice (const WASAPIInputDevice&);
  214586. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214587. };
  214588. class WASAPIOutputDevice : public WASAPIDeviceBase
  214589. {
  214590. public:
  214591. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214592. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214593. {
  214594. }
  214595. ~WASAPIOutputDevice()
  214596. {
  214597. close();
  214598. }
  214599. bool open (const double newSampleRate, const BigInteger& newChannels)
  214600. {
  214601. return openClient (newSampleRate, newChannels)
  214602. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214603. }
  214604. void close()
  214605. {
  214606. closeClient();
  214607. renderClient = 0;
  214608. }
  214609. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214610. {
  214611. if (numChannels <= 0)
  214612. return;
  214613. int offset = 0;
  214614. while (bufferSize > 0)
  214615. {
  214616. UINT32 padding = 0;
  214617. if (! OK (client->GetCurrentPadding (&padding)))
  214618. return;
  214619. int samplesToDo = useExclusiveMode ? bufferSize
  214620. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214621. if (samplesToDo <= 0)
  214622. {
  214623. if (thread.threadShouldExit())
  214624. break;
  214625. Thread::sleep (0);
  214626. continue;
  214627. }
  214628. uint8* outputData = 0;
  214629. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214630. {
  214631. for (int i = 0; i < numSrcBuffers; ++i)
  214632. {
  214633. const float* const source = srcBuffers[i] + offset;
  214634. const int destChan = channelMaps.getUnchecked(i);
  214635. switch (dataFormat)
  214636. {
  214637. case AudioDataConverters::float32LE:
  214638. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214639. break;
  214640. case AudioDataConverters::int32LE:
  214641. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214642. break;
  214643. case AudioDataConverters::int24LE:
  214644. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214645. break;
  214646. case AudioDataConverters::int16LE:
  214647. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214648. break;
  214649. default: jassertfalse; break;
  214650. }
  214651. }
  214652. renderClient->ReleaseBuffer (samplesToDo, 0);
  214653. offset += samplesToDo;
  214654. bufferSize -= samplesToDo;
  214655. }
  214656. }
  214657. }
  214658. ComSmartPtr <IAudioRenderClient> renderClient;
  214659. private:
  214660. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214661. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214662. };
  214663. class WASAPIAudioIODevice : public AudioIODevice,
  214664. public Thread
  214665. {
  214666. public:
  214667. WASAPIAudioIODevice (const String& deviceName,
  214668. const String& outputDeviceId_,
  214669. const String& inputDeviceId_,
  214670. const bool useExclusiveMode_)
  214671. : AudioIODevice (deviceName, "Windows Audio"),
  214672. Thread ("Juce WASAPI"),
  214673. isOpen_ (false),
  214674. isStarted (false),
  214675. outputDevice (0),
  214676. outputDeviceId (outputDeviceId_),
  214677. inputDevice (0),
  214678. inputDeviceId (inputDeviceId_),
  214679. useExclusiveMode (useExclusiveMode_),
  214680. currentBufferSizeSamples (0),
  214681. currentSampleRate (0),
  214682. callback (0)
  214683. {
  214684. }
  214685. ~WASAPIAudioIODevice()
  214686. {
  214687. close();
  214688. deleteAndZero (inputDevice);
  214689. deleteAndZero (outputDevice);
  214690. }
  214691. bool initialise()
  214692. {
  214693. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214694. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214695. latencyIn = latencyOut = 0;
  214696. Array <double> ratesIn, ratesOut;
  214697. if (createDevices())
  214698. {
  214699. jassert (inputDevice != 0 || outputDevice != 0);
  214700. if (inputDevice != 0 && outputDevice != 0)
  214701. {
  214702. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214703. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214704. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214705. sampleRates = inputDevice->rates;
  214706. sampleRates.removeValuesNotIn (outputDevice->rates);
  214707. }
  214708. else
  214709. {
  214710. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214711. defaultSampleRate = d->defaultSampleRate;
  214712. minBufferSize = d->minBufferSize;
  214713. defaultBufferSize = d->defaultBufferSize;
  214714. sampleRates = d->rates;
  214715. }
  214716. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214717. if (minBufferSize != defaultBufferSize)
  214718. bufferSizes.addUsingDefaultSort (minBufferSize);
  214719. int n = 64;
  214720. for (int i = 0; i < 40; ++i)
  214721. {
  214722. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214723. bufferSizes.addUsingDefaultSort (n);
  214724. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214725. }
  214726. return true;
  214727. }
  214728. return false;
  214729. }
  214730. const StringArray getOutputChannelNames()
  214731. {
  214732. StringArray outChannels;
  214733. if (outputDevice != 0)
  214734. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214735. outChannels.add ("Output channel " + String (i));
  214736. return outChannels;
  214737. }
  214738. const StringArray getInputChannelNames()
  214739. {
  214740. StringArray inChannels;
  214741. if (inputDevice != 0)
  214742. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214743. inChannels.add ("Input channel " + String (i));
  214744. return inChannels;
  214745. }
  214746. int getNumSampleRates() { return sampleRates.size(); }
  214747. double getSampleRate (int index) { return sampleRates [index]; }
  214748. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214749. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214750. int getDefaultBufferSize() { return defaultBufferSize; }
  214751. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214752. double getCurrentSampleRate() { return currentSampleRate; }
  214753. int getCurrentBitDepth() { return 32; }
  214754. int getOutputLatencyInSamples() { return latencyOut; }
  214755. int getInputLatencyInSamples() { return latencyIn; }
  214756. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214757. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214758. const String getLastError() { return lastError; }
  214759. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214760. double sampleRate, int bufferSizeSamples)
  214761. {
  214762. close();
  214763. lastError = String::empty;
  214764. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214765. {
  214766. lastError = "The input and output devices don't share a common sample rate!";
  214767. return lastError;
  214768. }
  214769. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214770. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214771. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214772. {
  214773. lastError = "Couldn't open the input device!";
  214774. return lastError;
  214775. }
  214776. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214777. {
  214778. close();
  214779. lastError = "Couldn't open the output device!";
  214780. return lastError;
  214781. }
  214782. if (inputDevice != 0)
  214783. ResetEvent (inputDevice->clientEvent);
  214784. if (outputDevice != 0)
  214785. ResetEvent (outputDevice->clientEvent);
  214786. startThread (8);
  214787. Thread::sleep (5);
  214788. if (inputDevice != 0 && inputDevice->client != 0)
  214789. {
  214790. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214791. HRESULT hr = inputDevice->client->Start();
  214792. logFailure (hr); //xxx handle this
  214793. }
  214794. if (outputDevice != 0 && outputDevice->client != 0)
  214795. {
  214796. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214797. HRESULT hr = outputDevice->client->Start();
  214798. logFailure (hr); //xxx handle this
  214799. }
  214800. isOpen_ = true;
  214801. return lastError;
  214802. }
  214803. void close()
  214804. {
  214805. stop();
  214806. if (inputDevice != 0)
  214807. SetEvent (inputDevice->clientEvent);
  214808. if (outputDevice != 0)
  214809. SetEvent (outputDevice->clientEvent);
  214810. stopThread (5000);
  214811. if (inputDevice != 0)
  214812. inputDevice->close();
  214813. if (outputDevice != 0)
  214814. outputDevice->close();
  214815. isOpen_ = false;
  214816. }
  214817. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214818. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214819. void start (AudioIODeviceCallback* call)
  214820. {
  214821. if (isOpen_ && call != 0 && ! isStarted)
  214822. {
  214823. if (! isThreadRunning())
  214824. {
  214825. // something's gone wrong and the thread's stopped..
  214826. isOpen_ = false;
  214827. return;
  214828. }
  214829. call->audioDeviceAboutToStart (this);
  214830. const ScopedLock sl (startStopLock);
  214831. callback = call;
  214832. isStarted = true;
  214833. }
  214834. }
  214835. void stop()
  214836. {
  214837. if (isStarted)
  214838. {
  214839. AudioIODeviceCallback* const callbackLocal = callback;
  214840. {
  214841. const ScopedLock sl (startStopLock);
  214842. isStarted = false;
  214843. }
  214844. if (callbackLocal != 0)
  214845. callbackLocal->audioDeviceStopped();
  214846. }
  214847. }
  214848. void setMMThreadPriority()
  214849. {
  214850. DynamicLibraryLoader dll ("avrt.dll");
  214851. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214852. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214853. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214854. {
  214855. DWORD dummy = 0;
  214856. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214857. if (h != 0)
  214858. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214859. }
  214860. }
  214861. void run()
  214862. {
  214863. setMMThreadPriority();
  214864. const int bufferSize = currentBufferSizeSamples;
  214865. HANDLE events[2];
  214866. int numEvents = 0;
  214867. if (inputDevice != 0)
  214868. events [numEvents++] = inputDevice->clientEvent;
  214869. if (outputDevice != 0)
  214870. events [numEvents++] = outputDevice->clientEvent;
  214871. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214872. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214873. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214874. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214875. float** const inputBuffers = ins.getArrayOfChannels();
  214876. float** const outputBuffers = outs.getArrayOfChannels();
  214877. ins.clear();
  214878. while (! threadShouldExit())
  214879. {
  214880. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  214881. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214882. if (result == WAIT_TIMEOUT)
  214883. continue;
  214884. if (threadShouldExit())
  214885. break;
  214886. if (inputDevice != 0)
  214887. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214888. // Make the callback..
  214889. {
  214890. const ScopedLock sl (startStopLock);
  214891. if (isStarted)
  214892. {
  214893. JUCE_TRY
  214894. {
  214895. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214896. numInputBuffers,
  214897. outputBuffers,
  214898. numOutputBuffers,
  214899. bufferSize);
  214900. }
  214901. JUCE_CATCH_EXCEPTION
  214902. }
  214903. else
  214904. {
  214905. outs.clear();
  214906. }
  214907. }
  214908. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214909. continue;
  214910. if (outputDevice != 0)
  214911. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214912. }
  214913. }
  214914. juce_UseDebuggingNewOperator
  214915. String outputDeviceId, inputDeviceId;
  214916. String lastError;
  214917. private:
  214918. // Device stats...
  214919. WASAPIInputDevice* inputDevice;
  214920. WASAPIOutputDevice* outputDevice;
  214921. const bool useExclusiveMode;
  214922. double defaultSampleRate;
  214923. int minBufferSize, defaultBufferSize;
  214924. int latencyIn, latencyOut;
  214925. Array <double> sampleRates;
  214926. Array <int> bufferSizes;
  214927. // Active state...
  214928. bool isOpen_, isStarted;
  214929. int currentBufferSizeSamples;
  214930. double currentSampleRate;
  214931. AudioIODeviceCallback* callback;
  214932. CriticalSection startStopLock;
  214933. bool createDevices()
  214934. {
  214935. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214936. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214937. return false;
  214938. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214939. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214940. return false;
  214941. UINT32 numDevices = 0;
  214942. if (! OK (deviceCollection->GetCount (&numDevices)))
  214943. return false;
  214944. for (UINT32 i = 0; i < numDevices; ++i)
  214945. {
  214946. ComSmartPtr <IMMDevice> device;
  214947. if (! OK (deviceCollection->Item (i, &device)))
  214948. continue;
  214949. const String deviceId (wasapi_getDeviceID (device));
  214950. if (deviceId.isEmpty())
  214951. continue;
  214952. const EDataFlow flow = wasapi_getDataFlow (device);
  214953. if (deviceId == inputDeviceId && flow == eCapture)
  214954. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214955. else if (deviceId == outputDeviceId && flow == eRender)
  214956. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214957. }
  214958. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214959. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214960. }
  214961. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214962. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214963. };
  214964. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214965. {
  214966. public:
  214967. WASAPIAudioIODeviceType()
  214968. : AudioIODeviceType ("Windows Audio"),
  214969. hasScanned (false)
  214970. {
  214971. }
  214972. ~WASAPIAudioIODeviceType()
  214973. {
  214974. }
  214975. void scanForDevices()
  214976. {
  214977. hasScanned = true;
  214978. outputDeviceNames.clear();
  214979. inputDeviceNames.clear();
  214980. outputDeviceIds.clear();
  214981. inputDeviceIds.clear();
  214982. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214983. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214984. return;
  214985. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214986. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  214987. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214988. UINT32 numDevices = 0;
  214989. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  214990. && OK (deviceCollection->GetCount (&numDevices))))
  214991. return;
  214992. for (UINT32 i = 0; i < numDevices; ++i)
  214993. {
  214994. ComSmartPtr <IMMDevice> device;
  214995. if (! OK (deviceCollection->Item (i, &device)))
  214996. continue;
  214997. const String deviceId (wasapi_getDeviceID (device));
  214998. DWORD state = 0;
  214999. if (! OK (device->GetState (&state)))
  215000. continue;
  215001. if (state != DEVICE_STATE_ACTIVE)
  215002. continue;
  215003. String name;
  215004. {
  215005. ComSmartPtr <IPropertyStore> properties;
  215006. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  215007. continue;
  215008. PROPVARIANT value;
  215009. PropVariantInit (&value);
  215010. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215011. name = value.pwszVal;
  215012. PropVariantClear (&value);
  215013. }
  215014. const EDataFlow flow = wasapi_getDataFlow (device);
  215015. if (flow == eRender)
  215016. {
  215017. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215018. outputDeviceIds.insert (index, deviceId);
  215019. outputDeviceNames.insert (index, name);
  215020. }
  215021. else if (flow == eCapture)
  215022. {
  215023. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215024. inputDeviceIds.insert (index, deviceId);
  215025. inputDeviceNames.insert (index, name);
  215026. }
  215027. }
  215028. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215029. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215030. }
  215031. const StringArray getDeviceNames (bool wantInputNames) const
  215032. {
  215033. jassert (hasScanned); // need to call scanForDevices() before doing this
  215034. return wantInputNames ? inputDeviceNames
  215035. : outputDeviceNames;
  215036. }
  215037. int getDefaultDeviceIndex (bool /*forInput*/) const
  215038. {
  215039. jassert (hasScanned); // need to call scanForDevices() before doing this
  215040. return 0;
  215041. }
  215042. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215043. {
  215044. jassert (hasScanned); // need to call scanForDevices() before doing this
  215045. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215046. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215047. : outputDeviceIds.indexOf (d->outputDeviceId));
  215048. }
  215049. bool hasSeparateInputsAndOutputs() const { return true; }
  215050. AudioIODevice* createDevice (const String& outputDeviceName,
  215051. const String& inputDeviceName)
  215052. {
  215053. jassert (hasScanned); // need to call scanForDevices() before doing this
  215054. const bool useExclusiveMode = false;
  215055. ScopedPointer<WASAPIAudioIODevice> device;
  215056. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215057. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215058. if (outputIndex >= 0 || inputIndex >= 0)
  215059. {
  215060. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215061. : inputDeviceName,
  215062. outputDeviceIds [outputIndex],
  215063. inputDeviceIds [inputIndex],
  215064. useExclusiveMode);
  215065. if (! device->initialise())
  215066. device = 0;
  215067. }
  215068. return device.release();
  215069. }
  215070. juce_UseDebuggingNewOperator
  215071. StringArray outputDeviceNames, outputDeviceIds;
  215072. StringArray inputDeviceNames, inputDeviceIds;
  215073. private:
  215074. bool hasScanned;
  215075. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215076. {
  215077. String s;
  215078. IMMDevice* dev = 0;
  215079. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215080. eMultimedia, &dev)))
  215081. {
  215082. WCHAR* deviceId = 0;
  215083. if (OK (dev->GetId (&deviceId)))
  215084. {
  215085. s = String (deviceId);
  215086. CoTaskMemFree (deviceId);
  215087. }
  215088. dev->Release();
  215089. }
  215090. return s;
  215091. }
  215092. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  215093. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  215094. };
  215095. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215096. {
  215097. return new WASAPIAudioIODeviceType();
  215098. }
  215099. #undef logFailure
  215100. #undef OK
  215101. #endif
  215102. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215103. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215104. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215105. // compiled on its own).
  215106. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215107. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215108. {
  215109. public:
  215110. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215111. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215112. const ComSmartPtr <IBaseFilter>& filter_,
  215113. int minWidth, int minHeight,
  215114. int maxWidth, int maxHeight)
  215115. : owner (owner_),
  215116. captureGraphBuilder (captureGraphBuilder_),
  215117. filter (filter_),
  215118. ok (false),
  215119. imageNeedsFlipping (false),
  215120. width (0),
  215121. height (0),
  215122. activeUsers (0),
  215123. recordNextFrameTime (false)
  215124. {
  215125. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215126. if (FAILED (hr))
  215127. return;
  215128. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215129. if (FAILED (hr))
  215130. return;
  215131. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  215132. if (FAILED (hr))
  215133. return;
  215134. {
  215135. ComSmartPtr <IAMStreamConfig> streamConfig;
  215136. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215137. IID_IAMStreamConfig, (void**) &streamConfig);
  215138. if (streamConfig != 0)
  215139. {
  215140. getVideoSizes (streamConfig);
  215141. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215142. return;
  215143. }
  215144. }
  215145. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215146. if (FAILED (hr))
  215147. return;
  215148. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215149. if (FAILED (hr))
  215150. return;
  215151. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215152. if (FAILED (hr))
  215153. return;
  215154. if (! connectFilters (filter, smartTee))
  215155. return;
  215156. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215157. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215158. if (FAILED (hr))
  215159. return;
  215160. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  215161. if (FAILED (hr))
  215162. return;
  215163. AM_MEDIA_TYPE mt;
  215164. zerostruct (mt);
  215165. mt.majortype = MEDIATYPE_Video;
  215166. mt.subtype = MEDIASUBTYPE_RGB24;
  215167. mt.formattype = FORMAT_VideoInfo;
  215168. sampleGrabber->SetMediaType (&mt);
  215169. callback = new GrabberCallback (*this);
  215170. sampleGrabber->SetCallback (callback, 1);
  215171. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215172. if (FAILED (hr))
  215173. return;
  215174. ComSmartPtr <IPin> grabberInputPin;
  215175. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  215176. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  215177. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  215178. return;
  215179. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215180. if (FAILED (hr))
  215181. return;
  215182. zerostruct (mt);
  215183. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215184. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215185. width = pVih->bmiHeader.biWidth;
  215186. height = pVih->bmiHeader.biHeight;
  215187. ComSmartPtr <IBaseFilter> nullFilter;
  215188. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215189. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215190. if (connectFilters (sampleGrabberBase, nullFilter)
  215191. && addGraphToRot())
  215192. {
  215193. activeImage = Image (Image::RGB, width, height, true);
  215194. loadingImage = Image (Image::RGB, width, height, true);
  215195. ok = true;
  215196. }
  215197. }
  215198. ~DShowCameraDeviceInteral()
  215199. {
  215200. if (mediaControl != 0)
  215201. mediaControl->Stop();
  215202. removeGraphFromRot();
  215203. for (int i = viewerComps.size(); --i >= 0;)
  215204. viewerComps.getUnchecked(i)->ownerDeleted();
  215205. callback = 0;
  215206. graphBuilder = 0;
  215207. sampleGrabber = 0;
  215208. mediaControl = 0;
  215209. filter = 0;
  215210. captureGraphBuilder = 0;
  215211. smartTee = 0;
  215212. smartTeePreviewOutputPin = 0;
  215213. smartTeeCaptureOutputPin = 0;
  215214. asfWriter = 0;
  215215. }
  215216. void addUser()
  215217. {
  215218. if (ok && activeUsers++ == 0)
  215219. mediaControl->Run();
  215220. }
  215221. void removeUser()
  215222. {
  215223. if (ok && --activeUsers == 0)
  215224. mediaControl->Stop();
  215225. }
  215226. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215227. {
  215228. if (recordNextFrameTime)
  215229. {
  215230. const double defaultCameraLatency = 0.1;
  215231. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215232. recordNextFrameTime = false;
  215233. ComSmartPtr <IPin> pin;
  215234. if (getPin (filter, PINDIR_OUTPUT, &pin))
  215235. {
  215236. ComSmartPtr <IAMPushSource> pushSource;
  215237. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  215238. if (pushSource != 0)
  215239. {
  215240. REFERENCE_TIME latency = 0;
  215241. hr = pushSource->GetLatency (&latency);
  215242. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215243. }
  215244. }
  215245. }
  215246. {
  215247. const int lineStride = width * 3;
  215248. const ScopedLock sl (imageSwapLock);
  215249. {
  215250. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215251. for (int i = 0; i < height; ++i)
  215252. memcpy (destData.getLinePointer ((height - 1) - i),
  215253. buffer + lineStride * i,
  215254. lineStride);
  215255. }
  215256. imageNeedsFlipping = true;
  215257. }
  215258. if (listeners.size() > 0)
  215259. callListeners (loadingImage);
  215260. sendChangeMessage (this);
  215261. }
  215262. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215263. {
  215264. if (imageNeedsFlipping)
  215265. {
  215266. const ScopedLock sl (imageSwapLock);
  215267. swapVariables (loadingImage, activeImage);
  215268. imageNeedsFlipping = false;
  215269. }
  215270. RectanglePlacement rp (RectanglePlacement::centred);
  215271. double dx = 0, dy = 0, dw = width, dh = height;
  215272. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215273. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215274. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215275. g.saveState();
  215276. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215277. g.fillAll (Colours::black);
  215278. g.restoreState();
  215279. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215280. }
  215281. bool createFileCaptureFilter (const File& file)
  215282. {
  215283. removeFileCaptureFilter();
  215284. file.deleteFile();
  215285. mediaControl->Stop();
  215286. firstRecordedTime = Time();
  215287. recordNextFrameTime = true;
  215288. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215289. if (SUCCEEDED (hr))
  215290. {
  215291. ComSmartPtr <IFileSinkFilter> fileSink;
  215292. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  215293. if (SUCCEEDED (hr))
  215294. {
  215295. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215296. if (SUCCEEDED (hr))
  215297. {
  215298. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215299. if (SUCCEEDED (hr))
  215300. {
  215301. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215302. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  215303. asfConfig->SetIndexMode (true);
  215304. ComSmartPtr <IWMProfileManager> profileManager;
  215305. hr = WMCreateProfileManager (&profileManager);
  215306. // This gibberish is the DirectShow profile for a video-only wmv file.
  215307. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  215308. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215309. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215310. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  215311. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  215312. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215313. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  215314. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  215315. prof = prof.replace ("$WIDTH", String (width))
  215316. .replace ("$HEIGHT", String (height));
  215317. ComSmartPtr <IWMProfile> currentProfile;
  215318. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  215319. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215320. if (SUCCEEDED (hr))
  215321. {
  215322. ComSmartPtr <IPin> asfWriterInputPin;
  215323. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  215324. {
  215325. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215326. if (SUCCEEDED (hr)
  215327. && ok && activeUsers > 0
  215328. && SUCCEEDED (mediaControl->Run()))
  215329. {
  215330. return true;
  215331. }
  215332. }
  215333. }
  215334. }
  215335. }
  215336. }
  215337. }
  215338. removeFileCaptureFilter();
  215339. if (ok && activeUsers > 0)
  215340. mediaControl->Run();
  215341. return false;
  215342. }
  215343. void removeFileCaptureFilter()
  215344. {
  215345. mediaControl->Stop();
  215346. if (asfWriter != 0)
  215347. {
  215348. graphBuilder->RemoveFilter (asfWriter);
  215349. asfWriter = 0;
  215350. }
  215351. if (ok && activeUsers > 0)
  215352. mediaControl->Run();
  215353. }
  215354. void addListener (CameraDevice::Listener* listenerToAdd)
  215355. {
  215356. const ScopedLock sl (listenerLock);
  215357. if (listeners.size() == 0)
  215358. addUser();
  215359. listeners.addIfNotAlreadyThere (listenerToAdd);
  215360. }
  215361. void removeListener (CameraDevice::Listener* listenerToRemove)
  215362. {
  215363. const ScopedLock sl (listenerLock);
  215364. listeners.removeValue (listenerToRemove);
  215365. if (listeners.size() == 0)
  215366. removeUser();
  215367. }
  215368. void callListeners (const Image& image)
  215369. {
  215370. const ScopedLock sl (listenerLock);
  215371. for (int i = listeners.size(); --i >= 0;)
  215372. {
  215373. CameraDevice::Listener* const l = listeners[i];
  215374. if (l != 0)
  215375. l->imageReceived (image);
  215376. }
  215377. }
  215378. class DShowCaptureViewerComp : public Component,
  215379. public ChangeListener
  215380. {
  215381. public:
  215382. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215383. : owner (owner_)
  215384. {
  215385. setOpaque (true);
  215386. owner->addChangeListener (this);
  215387. owner->addUser();
  215388. owner->viewerComps.add (this);
  215389. setSize (owner_->width, owner_->height);
  215390. }
  215391. ~DShowCaptureViewerComp()
  215392. {
  215393. if (owner != 0)
  215394. {
  215395. owner->viewerComps.removeValue (this);
  215396. owner->removeUser();
  215397. owner->removeChangeListener (this);
  215398. }
  215399. }
  215400. void ownerDeleted()
  215401. {
  215402. owner = 0;
  215403. }
  215404. void paint (Graphics& g)
  215405. {
  215406. g.setColour (Colours::black);
  215407. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215408. if (owner != 0)
  215409. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215410. else
  215411. g.fillAll (Colours::black);
  215412. }
  215413. void changeListenerCallback (void*)
  215414. {
  215415. repaint();
  215416. }
  215417. private:
  215418. DShowCameraDeviceInteral* owner;
  215419. };
  215420. bool ok;
  215421. int width, height;
  215422. Time firstRecordedTime;
  215423. Array <DShowCaptureViewerComp*> viewerComps;
  215424. private:
  215425. CameraDevice* const owner;
  215426. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215427. ComSmartPtr <IBaseFilter> filter;
  215428. ComSmartPtr <IBaseFilter> smartTee;
  215429. ComSmartPtr <IGraphBuilder> graphBuilder;
  215430. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215431. ComSmartPtr <IMediaControl> mediaControl;
  215432. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215433. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215434. ComSmartPtr <IBaseFilter> asfWriter;
  215435. int activeUsers;
  215436. Array <int> widths, heights;
  215437. DWORD graphRegistrationID;
  215438. CriticalSection imageSwapLock;
  215439. bool imageNeedsFlipping;
  215440. Image loadingImage;
  215441. Image activeImage;
  215442. bool recordNextFrameTime;
  215443. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215444. {
  215445. widths.clear();
  215446. heights.clear();
  215447. int count = 0, size = 0;
  215448. streamConfig->GetNumberOfCapabilities (&count, &size);
  215449. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215450. {
  215451. for (int i = 0; i < count; ++i)
  215452. {
  215453. VIDEO_STREAM_CONFIG_CAPS scc;
  215454. AM_MEDIA_TYPE* config;
  215455. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215456. if (SUCCEEDED (hr))
  215457. {
  215458. const int w = scc.InputSize.cx;
  215459. const int h = scc.InputSize.cy;
  215460. bool duplicate = false;
  215461. for (int j = widths.size(); --j >= 0;)
  215462. {
  215463. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215464. {
  215465. duplicate = true;
  215466. break;
  215467. }
  215468. }
  215469. if (! duplicate)
  215470. {
  215471. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215472. widths.add (w);
  215473. heights.add (h);
  215474. }
  215475. deleteMediaType (config);
  215476. }
  215477. }
  215478. }
  215479. }
  215480. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215481. const int minWidth, const int minHeight,
  215482. const int maxWidth, const int maxHeight)
  215483. {
  215484. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215485. streamConfig->GetNumberOfCapabilities (&count, &size);
  215486. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215487. {
  215488. AM_MEDIA_TYPE* config;
  215489. VIDEO_STREAM_CONFIG_CAPS scc;
  215490. for (int i = 0; i < count; ++i)
  215491. {
  215492. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215493. if (SUCCEEDED (hr))
  215494. {
  215495. if (scc.InputSize.cx >= minWidth
  215496. && scc.InputSize.cy >= minHeight
  215497. && scc.InputSize.cx <= maxWidth
  215498. && scc.InputSize.cy <= maxHeight)
  215499. {
  215500. int area = scc.InputSize.cx * scc.InputSize.cy;
  215501. if (area > bestArea)
  215502. {
  215503. bestIndex = i;
  215504. bestArea = area;
  215505. }
  215506. }
  215507. deleteMediaType (config);
  215508. }
  215509. }
  215510. if (bestIndex >= 0)
  215511. {
  215512. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215513. hr = streamConfig->SetFormat (config);
  215514. deleteMediaType (config);
  215515. return SUCCEEDED (hr);
  215516. }
  215517. }
  215518. return false;
  215519. }
  215520. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215521. {
  215522. ComSmartPtr <IEnumPins> enumerator;
  215523. ComSmartPtr <IPin> pin;
  215524. filter->EnumPins (&enumerator);
  215525. while (enumerator->Next (1, &pin, 0) == S_OK)
  215526. {
  215527. PIN_DIRECTION dir;
  215528. pin->QueryDirection (&dir);
  215529. if (wantedDirection == dir)
  215530. {
  215531. PIN_INFO info;
  215532. zerostruct (info);
  215533. pin->QueryPinInfo (&info);
  215534. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215535. {
  215536. pin->AddRef();
  215537. *result = pin;
  215538. return true;
  215539. }
  215540. }
  215541. }
  215542. return false;
  215543. }
  215544. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215545. {
  215546. ComSmartPtr <IPin> in, out;
  215547. return getPin (first, PINDIR_OUTPUT, &out)
  215548. && getPin (second, PINDIR_INPUT, &in)
  215549. && SUCCEEDED (graphBuilder->Connect (out, in));
  215550. }
  215551. bool addGraphToRot()
  215552. {
  215553. ComSmartPtr <IRunningObjectTable> rot;
  215554. if (FAILED (GetRunningObjectTable (0, &rot)))
  215555. return false;
  215556. ComSmartPtr <IMoniker> moniker;
  215557. WCHAR buffer[128];
  215558. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215559. if (FAILED (hr))
  215560. return false;
  215561. graphRegistrationID = 0;
  215562. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215563. }
  215564. void removeGraphFromRot()
  215565. {
  215566. ComSmartPtr <IRunningObjectTable> rot;
  215567. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215568. rot->Revoke (graphRegistrationID);
  215569. }
  215570. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215571. {
  215572. if (pmt->cbFormat != 0)
  215573. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215574. if (pmt->pUnk != 0)
  215575. pmt->pUnk->Release();
  215576. CoTaskMemFree (pmt);
  215577. }
  215578. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215579. {
  215580. public:
  215581. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215582. : owner (owner_)
  215583. {
  215584. }
  215585. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215586. {
  215587. return E_FAIL;
  215588. }
  215589. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215590. {
  215591. owner.handleFrame (time, buffer, bufferSize);
  215592. return S_OK;
  215593. }
  215594. private:
  215595. DShowCameraDeviceInteral& owner;
  215596. GrabberCallback (const GrabberCallback&);
  215597. GrabberCallback& operator= (const GrabberCallback&);
  215598. };
  215599. ComSmartPtr <GrabberCallback> callback;
  215600. Array <CameraDevice::Listener*> listeners;
  215601. CriticalSection listenerLock;
  215602. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215603. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215604. };
  215605. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215606. : name (name_)
  215607. {
  215608. isRecording = false;
  215609. }
  215610. CameraDevice::~CameraDevice()
  215611. {
  215612. stopRecording();
  215613. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215614. internal = 0;
  215615. }
  215616. Component* CameraDevice::createViewerComponent()
  215617. {
  215618. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215619. }
  215620. const String CameraDevice::getFileExtension()
  215621. {
  215622. return ".wmv";
  215623. }
  215624. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215625. {
  215626. stopRecording();
  215627. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215628. d->addUser();
  215629. isRecording = d->createFileCaptureFilter (file);
  215630. }
  215631. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215632. {
  215633. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215634. return d->firstRecordedTime;
  215635. }
  215636. void CameraDevice::stopRecording()
  215637. {
  215638. if (isRecording)
  215639. {
  215640. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215641. d->removeFileCaptureFilter();
  215642. d->removeUser();
  215643. isRecording = false;
  215644. }
  215645. }
  215646. void CameraDevice::addListener (Listener* listenerToAdd)
  215647. {
  215648. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215649. if (listenerToAdd != 0)
  215650. d->addListener (listenerToAdd);
  215651. }
  215652. void CameraDevice::removeListener (Listener* listenerToRemove)
  215653. {
  215654. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215655. if (listenerToRemove != 0)
  215656. d->removeListener (listenerToRemove);
  215657. }
  215658. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215659. const int deviceIndexToOpen,
  215660. String& name)
  215661. {
  215662. int index = 0;
  215663. ComSmartPtr <IBaseFilter> result;
  215664. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215665. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215666. if (SUCCEEDED (hr))
  215667. {
  215668. ComSmartPtr <IEnumMoniker> enumerator;
  215669. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215670. if (SUCCEEDED (hr) && enumerator != 0)
  215671. {
  215672. ComSmartPtr <IBaseFilter> captureFilter;
  215673. ComSmartPtr <IMoniker> moniker;
  215674. ULONG fetched;
  215675. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215676. {
  215677. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215678. if (SUCCEEDED (hr))
  215679. {
  215680. ComSmartPtr <IPropertyBag> propertyBag;
  215681. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215682. if (SUCCEEDED (hr))
  215683. {
  215684. VARIANT var;
  215685. var.vt = VT_BSTR;
  215686. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215687. propertyBag = 0;
  215688. if (SUCCEEDED (hr))
  215689. {
  215690. if (names != 0)
  215691. names->add (var.bstrVal);
  215692. if (index == deviceIndexToOpen)
  215693. {
  215694. name = var.bstrVal;
  215695. result = captureFilter;
  215696. captureFilter = 0;
  215697. break;
  215698. }
  215699. ++index;
  215700. }
  215701. moniker = 0;
  215702. }
  215703. captureFilter = 0;
  215704. }
  215705. }
  215706. }
  215707. }
  215708. return result;
  215709. }
  215710. const StringArray CameraDevice::getAvailableDevices()
  215711. {
  215712. StringArray devs;
  215713. String dummy;
  215714. enumerateCameras (&devs, -1, dummy);
  215715. return devs;
  215716. }
  215717. CameraDevice* CameraDevice::openDevice (int index,
  215718. int minWidth, int minHeight,
  215719. int maxWidth, int maxHeight)
  215720. {
  215721. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215722. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215723. if (SUCCEEDED (hr))
  215724. {
  215725. String name;
  215726. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215727. if (filter != 0)
  215728. {
  215729. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215730. DShowCameraDeviceInteral* const intern
  215731. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215732. minWidth, minHeight, maxWidth, maxHeight);
  215733. cam->internal = intern;
  215734. if (intern->ok)
  215735. return cam.release();
  215736. }
  215737. }
  215738. return 0;
  215739. }
  215740. #endif
  215741. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215742. #endif
  215743. // Auto-link the other win32 libs that are needed by library calls..
  215744. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215745. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215746. // Auto-links to various win32 libs that are needed by library calls..
  215747. #pragma comment(lib, "kernel32.lib")
  215748. #pragma comment(lib, "user32.lib")
  215749. #pragma comment(lib, "shell32.lib")
  215750. #pragma comment(lib, "gdi32.lib")
  215751. #pragma comment(lib, "vfw32.lib")
  215752. #pragma comment(lib, "comdlg32.lib")
  215753. #pragma comment(lib, "winmm.lib")
  215754. #pragma comment(lib, "wininet.lib")
  215755. #pragma comment(lib, "ole32.lib")
  215756. #pragma comment(lib, "oleaut32.lib")
  215757. #pragma comment(lib, "advapi32.lib")
  215758. #pragma comment(lib, "ws2_32.lib")
  215759. #pragma comment(lib, "comsupp.lib")
  215760. #pragma comment(lib, "version.lib")
  215761. #if JUCE_OPENGL
  215762. #pragma comment(lib, "OpenGL32.Lib")
  215763. #pragma comment(lib, "GlU32.Lib")
  215764. #endif
  215765. #if JUCE_QUICKTIME
  215766. #pragma comment (lib, "QTMLClient.lib")
  215767. #endif
  215768. #if JUCE_USE_CAMERA
  215769. #pragma comment (lib, "Strmiids.lib")
  215770. #pragma comment (lib, "wmvcore.lib")
  215771. #endif
  215772. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215773. #endif
  215774. END_JUCE_NAMESPACE
  215775. #endif
  215776. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215777. #endif
  215778. #if JUCE_LINUX
  215779. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215780. /*
  215781. This file wraps together all the mac-specific code, so that
  215782. we can include all the native headers just once, and compile all our
  215783. platform-specific stuff in one big lump, keeping it out of the way of
  215784. the rest of the codebase.
  215785. */
  215786. #if JUCE_LINUX
  215787. BEGIN_JUCE_NAMESPACE
  215788. #define JUCE_INCLUDED_FILE 1
  215789. // Now include the actual code files..
  215790. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215791. /*
  215792. This file contains posix routines that are common to both the Linux and Mac builds.
  215793. It gets included directly in the cpp files for these platforms.
  215794. */
  215795. CriticalSection::CriticalSection() throw()
  215796. {
  215797. pthread_mutexattr_t atts;
  215798. pthread_mutexattr_init (&atts);
  215799. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215800. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215801. pthread_mutex_init (&internal, &atts);
  215802. }
  215803. CriticalSection::~CriticalSection() throw()
  215804. {
  215805. pthread_mutex_destroy (&internal);
  215806. }
  215807. void CriticalSection::enter() const throw()
  215808. {
  215809. pthread_mutex_lock (&internal);
  215810. }
  215811. bool CriticalSection::tryEnter() const throw()
  215812. {
  215813. return pthread_mutex_trylock (&internal) == 0;
  215814. }
  215815. void CriticalSection::exit() const throw()
  215816. {
  215817. pthread_mutex_unlock (&internal);
  215818. }
  215819. class WaitableEventImpl
  215820. {
  215821. public:
  215822. WaitableEventImpl (const bool manualReset_)
  215823. : triggered (false),
  215824. manualReset (manualReset_)
  215825. {
  215826. pthread_cond_init (&condition, 0);
  215827. pthread_mutexattr_t atts;
  215828. pthread_mutexattr_init (&atts);
  215829. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215830. pthread_mutex_init (&mutex, &atts);
  215831. }
  215832. ~WaitableEventImpl()
  215833. {
  215834. pthread_cond_destroy (&condition);
  215835. pthread_mutex_destroy (&mutex);
  215836. }
  215837. bool wait (const int timeOutMillisecs) throw()
  215838. {
  215839. pthread_mutex_lock (&mutex);
  215840. if (! triggered)
  215841. {
  215842. if (timeOutMillisecs < 0)
  215843. {
  215844. do
  215845. {
  215846. pthread_cond_wait (&condition, &mutex);
  215847. }
  215848. while (! triggered);
  215849. }
  215850. else
  215851. {
  215852. struct timeval now;
  215853. gettimeofday (&now, 0);
  215854. struct timespec time;
  215855. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215856. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215857. if (time.tv_nsec >= 1000000000)
  215858. {
  215859. time.tv_nsec -= 1000000000;
  215860. time.tv_sec++;
  215861. }
  215862. do
  215863. {
  215864. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215865. {
  215866. pthread_mutex_unlock (&mutex);
  215867. return false;
  215868. }
  215869. }
  215870. while (! triggered);
  215871. }
  215872. }
  215873. if (! manualReset)
  215874. triggered = false;
  215875. pthread_mutex_unlock (&mutex);
  215876. return true;
  215877. }
  215878. void signal() throw()
  215879. {
  215880. pthread_mutex_lock (&mutex);
  215881. triggered = true;
  215882. pthread_cond_broadcast (&condition);
  215883. pthread_mutex_unlock (&mutex);
  215884. }
  215885. void reset() throw()
  215886. {
  215887. pthread_mutex_lock (&mutex);
  215888. triggered = false;
  215889. pthread_mutex_unlock (&mutex);
  215890. }
  215891. private:
  215892. pthread_cond_t condition;
  215893. pthread_mutex_t mutex;
  215894. bool triggered;
  215895. const bool manualReset;
  215896. WaitableEventImpl (const WaitableEventImpl&);
  215897. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215898. };
  215899. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215900. : internal (new WaitableEventImpl (manualReset))
  215901. {
  215902. }
  215903. WaitableEvent::~WaitableEvent() throw()
  215904. {
  215905. delete static_cast <WaitableEventImpl*> (internal);
  215906. }
  215907. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215908. {
  215909. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215910. }
  215911. void WaitableEvent::signal() const throw()
  215912. {
  215913. static_cast <WaitableEventImpl*> (internal)->signal();
  215914. }
  215915. void WaitableEvent::reset() const throw()
  215916. {
  215917. static_cast <WaitableEventImpl*> (internal)->reset();
  215918. }
  215919. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215920. {
  215921. struct timespec time;
  215922. time.tv_sec = millisecs / 1000;
  215923. time.tv_nsec = (millisecs % 1000) * 1000000;
  215924. nanosleep (&time, 0);
  215925. }
  215926. const juce_wchar File::separator = '/';
  215927. const String File::separatorString ("/");
  215928. const File File::getCurrentWorkingDirectory()
  215929. {
  215930. HeapBlock<char> heapBuffer;
  215931. char localBuffer [1024];
  215932. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215933. int bufferSize = 4096;
  215934. while (cwd == 0 && errno == ERANGE)
  215935. {
  215936. heapBuffer.malloc (bufferSize);
  215937. cwd = getcwd (heapBuffer, bufferSize - 1);
  215938. bufferSize += 1024;
  215939. }
  215940. return File (String::fromUTF8 (cwd));
  215941. }
  215942. bool File::setAsCurrentWorkingDirectory() const
  215943. {
  215944. return chdir (getFullPathName().toUTF8()) == 0;
  215945. }
  215946. static bool juce_stat (const String& fileName, struct stat& info)
  215947. {
  215948. return fileName.isNotEmpty()
  215949. && (stat (fileName.toUTF8(), &info) == 0);
  215950. }
  215951. bool File::isDirectory() const
  215952. {
  215953. struct stat info;
  215954. return fullPath.isEmpty()
  215955. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215956. }
  215957. bool File::exists() const
  215958. {
  215959. return fullPath.isNotEmpty()
  215960. && access (fullPath.toUTF8(), F_OK) == 0;
  215961. }
  215962. bool File::existsAsFile() const
  215963. {
  215964. return exists() && ! isDirectory();
  215965. }
  215966. int64 File::getSize() const
  215967. {
  215968. struct stat info;
  215969. return juce_stat (fullPath, info) ? info.st_size : 0;
  215970. }
  215971. bool File::hasWriteAccess() const
  215972. {
  215973. if (exists())
  215974. return access (fullPath.toUTF8(), W_OK) == 0;
  215975. if ((! isDirectory()) && fullPath.containsChar (separator))
  215976. return getParentDirectory().hasWriteAccess();
  215977. return false;
  215978. }
  215979. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215980. {
  215981. struct stat info;
  215982. const int res = stat (fullPath.toUTF8(), &info);
  215983. if (res != 0)
  215984. return false;
  215985. info.st_mode &= 0777; // Just permissions
  215986. if (shouldBeReadOnly)
  215987. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215988. else
  215989. // Give everybody write permission?
  215990. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215991. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  215992. }
  215993. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  215994. {
  215995. modificationTime = 0;
  215996. accessTime = 0;
  215997. creationTime = 0;
  215998. struct stat info;
  215999. const int res = stat (fullPath.toUTF8(), &info);
  216000. if (res == 0)
  216001. {
  216002. modificationTime = (int64) info.st_mtime * 1000;
  216003. accessTime = (int64) info.st_atime * 1000;
  216004. creationTime = (int64) info.st_ctime * 1000;
  216005. }
  216006. }
  216007. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216008. {
  216009. struct utimbuf times;
  216010. times.actime = (time_t) (accessTime / 1000);
  216011. times.modtime = (time_t) (modificationTime / 1000);
  216012. return utime (fullPath.toUTF8(), &times) == 0;
  216013. }
  216014. bool File::deleteFile() const
  216015. {
  216016. if (! exists())
  216017. return true;
  216018. else if (isDirectory())
  216019. return rmdir (fullPath.toUTF8()) == 0;
  216020. else
  216021. return remove (fullPath.toUTF8()) == 0;
  216022. }
  216023. bool File::moveInternal (const File& dest) const
  216024. {
  216025. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216026. return true;
  216027. if (hasWriteAccess() && copyInternal (dest))
  216028. {
  216029. if (deleteFile())
  216030. return true;
  216031. dest.deleteFile();
  216032. }
  216033. return false;
  216034. }
  216035. void File::createDirectoryInternal (const String& fileName) const
  216036. {
  216037. mkdir (fileName.toUTF8(), 0777);
  216038. }
  216039. void* juce_fileOpen (const File& file, bool forWriting)
  216040. {
  216041. int flags = O_RDONLY;
  216042. if (forWriting)
  216043. {
  216044. if (file.exists())
  216045. {
  216046. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216047. if (f != -1)
  216048. lseek (f, 0, SEEK_END);
  216049. return (void*) f;
  216050. }
  216051. else
  216052. {
  216053. flags = O_RDWR + O_CREAT;
  216054. }
  216055. }
  216056. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  216057. }
  216058. void juce_fileClose (void* handle)
  216059. {
  216060. if (handle != 0)
  216061. close ((int) (pointer_sized_int) handle);
  216062. }
  216063. int juce_fileRead (void* handle, void* buffer, int size)
  216064. {
  216065. if (handle != 0)
  216066. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  216067. return 0;
  216068. }
  216069. int juce_fileWrite (void* handle, const void* buffer, int size)
  216070. {
  216071. if (handle != 0)
  216072. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  216073. return 0;
  216074. }
  216075. int64 juce_fileSetPosition (void* handle, int64 pos)
  216076. {
  216077. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216078. return pos;
  216079. return -1;
  216080. }
  216081. int64 FileOutputStream::getPositionInternal() const
  216082. {
  216083. if (fileHandle != 0)
  216084. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  216085. return -1;
  216086. }
  216087. void FileOutputStream::flushInternal()
  216088. {
  216089. if (fileHandle != 0)
  216090. fsync ((int) (pointer_sized_int) fileHandle);
  216091. }
  216092. const File juce_getExecutableFile()
  216093. {
  216094. Dl_info exeInfo;
  216095. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216096. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216097. }
  216098. // if this file doesn't exist, find a parent of it that does..
  216099. static bool juce_doStatFS (File f, struct statfs& result)
  216100. {
  216101. for (int i = 5; --i >= 0;)
  216102. {
  216103. if (f.exists())
  216104. break;
  216105. f = f.getParentDirectory();
  216106. }
  216107. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216108. }
  216109. int64 File::getBytesFreeOnVolume() const
  216110. {
  216111. struct statfs buf;
  216112. if (juce_doStatFS (*this, buf))
  216113. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216114. return 0;
  216115. }
  216116. int64 File::getVolumeTotalSize() const
  216117. {
  216118. struct statfs buf;
  216119. if (juce_doStatFS (*this, buf))
  216120. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216121. return 0;
  216122. }
  216123. const String File::getVolumeLabel() const
  216124. {
  216125. #if JUCE_MAC
  216126. struct VolAttrBuf
  216127. {
  216128. u_int32_t length;
  216129. attrreference_t mountPointRef;
  216130. char mountPointSpace [MAXPATHLEN];
  216131. } attrBuf;
  216132. struct attrlist attrList;
  216133. zerostruct (attrList);
  216134. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216135. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216136. File f (*this);
  216137. for (;;)
  216138. {
  216139. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216140. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216141. (int) attrBuf.mountPointRef.attr_length);
  216142. const File parent (f.getParentDirectory());
  216143. if (f == parent)
  216144. break;
  216145. f = parent;
  216146. }
  216147. #endif
  216148. return String::empty;
  216149. }
  216150. int File::getVolumeSerialNumber() const
  216151. {
  216152. return 0; // xxx
  216153. }
  216154. void juce_runSystemCommand (const String& command)
  216155. {
  216156. int result = system (command.toUTF8());
  216157. (void) result;
  216158. }
  216159. const String juce_getOutputFromCommand (const String& command)
  216160. {
  216161. // slight bodge here, as we just pipe the output into a temp file and read it...
  216162. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216163. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216164. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216165. String result (tempFile.loadFileAsString());
  216166. tempFile.deleteFile();
  216167. return result;
  216168. }
  216169. class InterProcessLock::Pimpl
  216170. {
  216171. public:
  216172. Pimpl (const String& name, const int timeOutMillisecs)
  216173. : handle (0), refCount (1)
  216174. {
  216175. #if JUCE_MAC
  216176. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216177. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216178. #else
  216179. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216180. #endif
  216181. temp.create();
  216182. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216183. if (handle != 0)
  216184. {
  216185. struct flock fl;
  216186. zerostruct (fl);
  216187. fl.l_whence = SEEK_SET;
  216188. fl.l_type = F_WRLCK;
  216189. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216190. for (;;)
  216191. {
  216192. const int result = fcntl (handle, F_SETLK, &fl);
  216193. if (result >= 0)
  216194. return;
  216195. if (errno != EINTR)
  216196. {
  216197. if (timeOutMillisecs == 0
  216198. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216199. break;
  216200. Thread::sleep (10);
  216201. }
  216202. }
  216203. }
  216204. closeFile();
  216205. }
  216206. ~Pimpl()
  216207. {
  216208. closeFile();
  216209. }
  216210. void closeFile()
  216211. {
  216212. if (handle != 0)
  216213. {
  216214. struct flock fl;
  216215. zerostruct (fl);
  216216. fl.l_whence = SEEK_SET;
  216217. fl.l_type = F_UNLCK;
  216218. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216219. {}
  216220. close (handle);
  216221. handle = 0;
  216222. }
  216223. }
  216224. int handle, refCount;
  216225. };
  216226. InterProcessLock::InterProcessLock (const String& name_)
  216227. : name (name_)
  216228. {
  216229. }
  216230. InterProcessLock::~InterProcessLock()
  216231. {
  216232. }
  216233. bool InterProcessLock::enter (const int timeOutMillisecs)
  216234. {
  216235. const ScopedLock sl (lock);
  216236. if (pimpl == 0)
  216237. {
  216238. pimpl = new Pimpl (name, timeOutMillisecs);
  216239. if (pimpl->handle == 0)
  216240. pimpl = 0;
  216241. }
  216242. else
  216243. {
  216244. pimpl->refCount++;
  216245. }
  216246. return pimpl != 0;
  216247. }
  216248. void InterProcessLock::exit()
  216249. {
  216250. const ScopedLock sl (lock);
  216251. // Trying to release the lock too many times!
  216252. jassert (pimpl != 0);
  216253. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216254. pimpl = 0;
  216255. }
  216256. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216257. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216258. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216259. // compiled on its own).
  216260. #if JUCE_INCLUDED_FILE
  216261. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  216262. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  216263. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  216264. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  216265. bool File::copyInternal (const File& dest) const
  216266. {
  216267. FileInputStream in (*this);
  216268. if (dest.deleteFile())
  216269. {
  216270. {
  216271. FileOutputStream out (dest);
  216272. if (out.failedToOpen())
  216273. return false;
  216274. if (out.writeFromInputStream (in, -1) == getSize())
  216275. return true;
  216276. }
  216277. dest.deleteFile();
  216278. }
  216279. return false;
  216280. }
  216281. void File::findFileSystemRoots (Array<File>& destArray)
  216282. {
  216283. destArray.add (File ("/"));
  216284. }
  216285. bool File::isOnCDRomDrive() const
  216286. {
  216287. struct statfs buf;
  216288. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216289. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  216290. }
  216291. bool File::isOnHardDisk() const
  216292. {
  216293. struct statfs buf;
  216294. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216295. {
  216296. switch (buf.f_type)
  216297. {
  216298. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216299. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216300. case U_NFS_SUPER_MAGIC: // Network NFS
  216301. case U_SMB_SUPER_MAGIC: // Network Samba
  216302. return false;
  216303. default:
  216304. // Assume anything else is a hard-disk (but note it could
  216305. // be a RAM disk. There isn't a good way of determining
  216306. // this for sure)
  216307. return true;
  216308. }
  216309. }
  216310. // Assume so if this fails for some reason
  216311. return true;
  216312. }
  216313. bool File::isOnRemovableDrive() const
  216314. {
  216315. jassertfalse; // xxx not implemented for linux!
  216316. return false;
  216317. }
  216318. bool File::isHidden() const
  216319. {
  216320. return getFileName().startsWithChar ('.');
  216321. }
  216322. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216323. const File File::getSpecialLocation (const SpecialLocationType type)
  216324. {
  216325. switch (type)
  216326. {
  216327. case userHomeDirectory:
  216328. {
  216329. const char* homeDir = getenv ("HOME");
  216330. if (homeDir == 0)
  216331. {
  216332. struct passwd* const pw = getpwuid (getuid());
  216333. if (pw != 0)
  216334. homeDir = pw->pw_dir;
  216335. }
  216336. return File (String::fromUTF8 (homeDir));
  216337. }
  216338. case userDocumentsDirectory:
  216339. case userMusicDirectory:
  216340. case userMoviesDirectory:
  216341. case userApplicationDataDirectory:
  216342. return File ("~");
  216343. case userDesktopDirectory:
  216344. return File ("~/Desktop");
  216345. case commonApplicationDataDirectory:
  216346. return File ("/var");
  216347. case globalApplicationsDirectory:
  216348. return File ("/usr");
  216349. case tempDirectory:
  216350. {
  216351. File tmp ("/var/tmp");
  216352. if (! tmp.isDirectory())
  216353. {
  216354. tmp = "/tmp";
  216355. if (! tmp.isDirectory())
  216356. tmp = File::getCurrentWorkingDirectory();
  216357. }
  216358. return tmp;
  216359. }
  216360. case invokedExecutableFile:
  216361. if (juce_Argv0 != 0)
  216362. return File (String::fromUTF8 (juce_Argv0));
  216363. // deliberate fall-through...
  216364. case currentExecutableFile:
  216365. case currentApplicationFile:
  216366. return juce_getExecutableFile();
  216367. case hostApplicationPath:
  216368. {
  216369. unsigned int size = 8192;
  216370. HeapBlock<char> buffer;
  216371. buffer.calloc (size + 8);
  216372. readlink ("/proc/self/exe", buffer.getData(), size);
  216373. return String::fromUTF8 (buffer, size);
  216374. }
  216375. default:
  216376. jassertfalse; // unknown type?
  216377. break;
  216378. }
  216379. return File::nonexistent;
  216380. }
  216381. const String File::getVersion() const
  216382. {
  216383. return String::empty; // xxx not yet implemented
  216384. }
  216385. const File File::getLinkedTarget() const
  216386. {
  216387. char buffer [4096];
  216388. size_t numChars = readlink (getFullPathName().toUTF8(),
  216389. buffer, sizeof (buffer));
  216390. if (numChars > 0 && numChars <= sizeof (buffer))
  216391. return File (String::fromUTF8 (buffer, (int) numChars));
  216392. return *this;
  216393. }
  216394. bool File::moveToTrash() const
  216395. {
  216396. if (! exists())
  216397. return true;
  216398. File trashCan ("~/.Trash");
  216399. if (! trashCan.isDirectory())
  216400. trashCan = "~/.local/share/Trash/files";
  216401. if (! trashCan.isDirectory())
  216402. return false;
  216403. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216404. getFileExtension()));
  216405. }
  216406. class DirectoryIterator::NativeIterator::Pimpl
  216407. {
  216408. public:
  216409. Pimpl (const File& directory, const String& wildCard_)
  216410. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216411. wildCard (wildCard_),
  216412. dir (opendir (directory.getFullPathName().toUTF8()))
  216413. {
  216414. if (wildCard == "*.*")
  216415. wildCard = "*";
  216416. wildcardUTF8 = wildCard.toUTF8();
  216417. }
  216418. ~Pimpl()
  216419. {
  216420. if (dir != 0)
  216421. closedir (dir);
  216422. }
  216423. bool next (String& filenameFound,
  216424. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216425. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216426. {
  216427. if (dir == 0)
  216428. return false;
  216429. for (;;)
  216430. {
  216431. struct dirent* const de = readdir (dir);
  216432. if (de == 0)
  216433. return false;
  216434. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216435. {
  216436. filenameFound = String::fromUTF8 (de->d_name);
  216437. const String path (parentDir + filenameFound);
  216438. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216439. {
  216440. struct stat info;
  216441. const bool statOk = juce_stat (path, info);
  216442. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216443. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216444. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216445. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216446. }
  216447. if (isHidden != 0)
  216448. *isHidden = filenameFound.startsWithChar ('.');
  216449. if (isReadOnly != 0)
  216450. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216451. return true;
  216452. }
  216453. }
  216454. }
  216455. private:
  216456. String parentDir, wildCard;
  216457. const char* wildcardUTF8;
  216458. DIR* dir;
  216459. Pimpl (const Pimpl&);
  216460. Pimpl& operator= (const Pimpl&);
  216461. };
  216462. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216463. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216464. {
  216465. }
  216466. DirectoryIterator::NativeIterator::~NativeIterator()
  216467. {
  216468. }
  216469. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216470. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216471. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216472. {
  216473. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216474. }
  216475. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216476. {
  216477. String cmdString (fileName.replace (" ", "\\ ",false));
  216478. cmdString << " " << parameters;
  216479. if (URL::isProbablyAWebsiteURL (fileName)
  216480. || cmdString.startsWithIgnoreCase ("file:")
  216481. || URL::isProbablyAnEmailAddress (fileName))
  216482. {
  216483. // create a command that tries to launch a bunch of likely browsers
  216484. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216485. StringArray cmdLines;
  216486. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216487. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216488. cmdString = cmdLines.joinIntoString (" || ");
  216489. }
  216490. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216491. const int cpid = fork();
  216492. if (cpid == 0)
  216493. {
  216494. setsid();
  216495. // Child process
  216496. execve (argv[0], (char**) argv, environ);
  216497. exit (0);
  216498. }
  216499. return cpid >= 0;
  216500. }
  216501. void File::revealToUser() const
  216502. {
  216503. if (isDirectory())
  216504. startAsProcess();
  216505. else if (getParentDirectory().exists())
  216506. getParentDirectory().startAsProcess();
  216507. }
  216508. #endif
  216509. /*** End of inlined file: juce_linux_Files.cpp ***/
  216510. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216511. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216512. // compiled on its own).
  216513. #if JUCE_INCLUDED_FILE
  216514. struct NamedPipeInternal
  216515. {
  216516. String pipeInName, pipeOutName;
  216517. int pipeIn, pipeOut;
  216518. bool volatile createdPipe, blocked, stopReadOperation;
  216519. static void signalHandler (int) {}
  216520. };
  216521. void NamedPipe::cancelPendingReads()
  216522. {
  216523. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216524. {
  216525. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216526. intern->stopReadOperation = true;
  216527. char buffer [1] = { 0 };
  216528. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216529. (void) bytesWritten;
  216530. int timeout = 2000;
  216531. while (intern->blocked && --timeout >= 0)
  216532. Thread::sleep (2);
  216533. intern->stopReadOperation = false;
  216534. }
  216535. }
  216536. void NamedPipe::close()
  216537. {
  216538. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216539. if (intern != 0)
  216540. {
  216541. internal = 0;
  216542. if (intern->pipeIn != -1)
  216543. ::close (intern->pipeIn);
  216544. if (intern->pipeOut != -1)
  216545. ::close (intern->pipeOut);
  216546. if (intern->createdPipe)
  216547. {
  216548. unlink (intern->pipeInName.toUTF8());
  216549. unlink (intern->pipeOutName.toUTF8());
  216550. }
  216551. delete intern;
  216552. }
  216553. }
  216554. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216555. {
  216556. close();
  216557. NamedPipeInternal* const intern = new NamedPipeInternal();
  216558. internal = intern;
  216559. intern->createdPipe = createPipe;
  216560. intern->blocked = false;
  216561. intern->stopReadOperation = false;
  216562. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216563. siginterrupt (SIGPIPE, 1);
  216564. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216565. intern->pipeInName = pipePath + "_in";
  216566. intern->pipeOutName = pipePath + "_out";
  216567. intern->pipeIn = -1;
  216568. intern->pipeOut = -1;
  216569. if (createPipe)
  216570. {
  216571. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216572. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216573. {
  216574. delete intern;
  216575. internal = 0;
  216576. return false;
  216577. }
  216578. }
  216579. return true;
  216580. }
  216581. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216582. {
  216583. int bytesRead = -1;
  216584. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216585. if (intern != 0)
  216586. {
  216587. intern->blocked = true;
  216588. if (intern->pipeIn == -1)
  216589. {
  216590. if (intern->createdPipe)
  216591. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216592. else
  216593. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216594. if (intern->pipeIn == -1)
  216595. {
  216596. intern->blocked = false;
  216597. return -1;
  216598. }
  216599. }
  216600. bytesRead = 0;
  216601. char* p = (char*) destBuffer;
  216602. while (bytesRead < maxBytesToRead)
  216603. {
  216604. const int bytesThisTime = maxBytesToRead - bytesRead;
  216605. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216606. if (numRead <= 0 || intern->stopReadOperation)
  216607. {
  216608. bytesRead = -1;
  216609. break;
  216610. }
  216611. bytesRead += numRead;
  216612. p += bytesRead;
  216613. }
  216614. intern->blocked = false;
  216615. }
  216616. return bytesRead;
  216617. }
  216618. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216619. {
  216620. int bytesWritten = -1;
  216621. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216622. if (intern != 0)
  216623. {
  216624. if (intern->pipeOut == -1)
  216625. {
  216626. if (intern->createdPipe)
  216627. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216628. else
  216629. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216630. if (intern->pipeOut == -1)
  216631. {
  216632. return -1;
  216633. }
  216634. }
  216635. const char* p = (const char*) sourceBuffer;
  216636. bytesWritten = 0;
  216637. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216638. while (bytesWritten < numBytesToWrite
  216639. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216640. {
  216641. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216642. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216643. if (numWritten <= 0)
  216644. {
  216645. bytesWritten = -1;
  216646. break;
  216647. }
  216648. bytesWritten += numWritten;
  216649. p += bytesWritten;
  216650. }
  216651. }
  216652. return bytesWritten;
  216653. }
  216654. #endif
  216655. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216656. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216657. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216658. // compiled on its own).
  216659. #if JUCE_INCLUDED_FILE
  216660. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216661. {
  216662. int numResults = 0;
  216663. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216664. if (s != -1)
  216665. {
  216666. char buf [1024];
  216667. struct ifconf ifc;
  216668. ifc.ifc_len = sizeof (buf);
  216669. ifc.ifc_buf = buf;
  216670. ioctl (s, SIOCGIFCONF, &ifc);
  216671. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216672. {
  216673. struct ifreq ifr;
  216674. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216675. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216676. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216677. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216678. && numResults < maxNum)
  216679. {
  216680. int64 a = 0;
  216681. for (int j = 6; --j >= 0;)
  216682. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216683. *addresses++ = a;
  216684. ++numResults;
  216685. }
  216686. }
  216687. close (s);
  216688. }
  216689. return numResults;
  216690. }
  216691. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216692. const String& emailSubject,
  216693. const String& bodyText,
  216694. const StringArray& filesToAttach)
  216695. {
  216696. jassertfalse; // xxx todo
  216697. return false;
  216698. }
  216699. /** A HTTP input stream that uses sockets.
  216700. */
  216701. class JUCE_HTTPSocketStream
  216702. {
  216703. public:
  216704. JUCE_HTTPSocketStream()
  216705. : readPosition (0),
  216706. socketHandle (-1),
  216707. levelsOfRedirection (0),
  216708. timeoutSeconds (15)
  216709. {
  216710. }
  216711. ~JUCE_HTTPSocketStream()
  216712. {
  216713. closeSocket();
  216714. }
  216715. bool open (const String& url,
  216716. const String& headers,
  216717. const MemoryBlock& postData,
  216718. const bool isPost,
  216719. URL::OpenStreamProgressCallback* callback,
  216720. void* callbackContext,
  216721. int timeOutMs)
  216722. {
  216723. closeSocket();
  216724. uint32 timeOutTime = Time::getMillisecondCounter();
  216725. if (timeOutMs == 0)
  216726. timeOutTime += 60000;
  216727. else if (timeOutMs < 0)
  216728. timeOutTime = 0xffffffff;
  216729. else
  216730. timeOutTime += timeOutMs;
  216731. String hostName, hostPath;
  216732. int hostPort;
  216733. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216734. return false;
  216735. const struct hostent* host = 0;
  216736. int port = 0;
  216737. String proxyName, proxyPath;
  216738. int proxyPort = 0;
  216739. String proxyURL (getenv ("http_proxy"));
  216740. if (proxyURL.startsWithIgnoreCase ("http://"))
  216741. {
  216742. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216743. return false;
  216744. host = gethostbyname (proxyName.toUTF8());
  216745. port = proxyPort;
  216746. }
  216747. else
  216748. {
  216749. host = gethostbyname (hostName.toUTF8());
  216750. port = hostPort;
  216751. }
  216752. if (host == 0)
  216753. return false;
  216754. struct sockaddr_in address;
  216755. zerostruct (address);
  216756. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216757. address.sin_family = host->h_addrtype;
  216758. address.sin_port = htons (port);
  216759. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216760. if (socketHandle == -1)
  216761. return false;
  216762. int receiveBufferSize = 16384;
  216763. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216764. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216765. #if JUCE_MAC
  216766. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216767. #endif
  216768. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216769. {
  216770. closeSocket();
  216771. return false;
  216772. }
  216773. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216774. proxyName, proxyPort,
  216775. hostPath, url,
  216776. headers, postData,
  216777. isPost));
  216778. size_t totalHeaderSent = 0;
  216779. while (totalHeaderSent < requestHeader.getSize())
  216780. {
  216781. if (Time::getMillisecondCounter() > timeOutTime)
  216782. {
  216783. closeSocket();
  216784. return false;
  216785. }
  216786. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216787. if (send (socketHandle,
  216788. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216789. numToSend, 0)
  216790. != numToSend)
  216791. {
  216792. closeSocket();
  216793. return false;
  216794. }
  216795. totalHeaderSent += numToSend;
  216796. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216797. {
  216798. closeSocket();
  216799. return false;
  216800. }
  216801. }
  216802. const String responseHeader (readResponse (timeOutTime));
  216803. if (responseHeader.isNotEmpty())
  216804. {
  216805. //DBG (responseHeader);
  216806. headerLines.clear();
  216807. headerLines.addLines (responseHeader);
  216808. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216809. .substring (0, 3).getIntValue();
  216810. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216811. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216812. String location (findHeaderItem (headerLines, "Location:"));
  216813. if (statusCode >= 300 && statusCode < 400
  216814. && location.isNotEmpty())
  216815. {
  216816. if (! location.startsWithIgnoreCase ("http://"))
  216817. location = "http://" + location;
  216818. if (levelsOfRedirection++ < 3)
  216819. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216820. }
  216821. else
  216822. {
  216823. levelsOfRedirection = 0;
  216824. return true;
  216825. }
  216826. }
  216827. closeSocket();
  216828. return false;
  216829. }
  216830. int read (void* buffer, int bytesToRead)
  216831. {
  216832. fd_set readbits;
  216833. FD_ZERO (&readbits);
  216834. FD_SET (socketHandle, &readbits);
  216835. struct timeval tv;
  216836. tv.tv_sec = timeoutSeconds;
  216837. tv.tv_usec = 0;
  216838. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216839. return 0; // (timeout)
  216840. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216841. readPosition += bytesRead;
  216842. return bytesRead;
  216843. }
  216844. int readPosition;
  216845. StringArray headerLines;
  216846. juce_UseDebuggingNewOperator
  216847. private:
  216848. int socketHandle, levelsOfRedirection;
  216849. const int timeoutSeconds;
  216850. void closeSocket()
  216851. {
  216852. if (socketHandle >= 0)
  216853. close (socketHandle);
  216854. socketHandle = -1;
  216855. }
  216856. const MemoryBlock createRequestHeader (const String& hostName,
  216857. const int hostPort,
  216858. const String& proxyName,
  216859. const int proxyPort,
  216860. const String& hostPath,
  216861. const String& originalURL,
  216862. const String& headers,
  216863. const MemoryBlock& postData,
  216864. const bool isPost)
  216865. {
  216866. String header (isPost ? "POST " : "GET ");
  216867. if (proxyName.isEmpty())
  216868. {
  216869. header << hostPath << " HTTP/1.0\r\nHost: "
  216870. << hostName << ':' << hostPort;
  216871. }
  216872. else
  216873. {
  216874. header << originalURL << " HTTP/1.0\r\nHost: "
  216875. << proxyName << ':' << proxyPort;
  216876. }
  216877. header << "\r\nUser-Agent: JUCE/"
  216878. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216879. << "\r\nConnection: Close\r\nContent-Length: "
  216880. << postData.getSize() << "\r\n"
  216881. << headers << "\r\n";
  216882. MemoryBlock mb;
  216883. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216884. mb.append (postData.getData(), postData.getSize());
  216885. return mb;
  216886. }
  216887. const String readResponse (const uint32 timeOutTime)
  216888. {
  216889. int bytesRead = 0, numConsecutiveLFs = 0;
  216890. MemoryBlock buffer (1024, true);
  216891. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216892. && Time::getMillisecondCounter() <= timeOutTime)
  216893. {
  216894. fd_set readbits;
  216895. FD_ZERO (&readbits);
  216896. FD_SET (socketHandle, &readbits);
  216897. struct timeval tv;
  216898. tv.tv_sec = timeoutSeconds;
  216899. tv.tv_usec = 0;
  216900. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216901. return String::empty; // (timeout)
  216902. buffer.ensureSize (bytesRead + 8, true);
  216903. char* const dest = (char*) buffer.getData() + bytesRead;
  216904. if (recv (socketHandle, dest, 1, 0) == -1)
  216905. return String::empty;
  216906. const char lastByte = *dest;
  216907. ++bytesRead;
  216908. if (lastByte == '\n')
  216909. ++numConsecutiveLFs;
  216910. else if (lastByte != '\r')
  216911. numConsecutiveLFs = 0;
  216912. }
  216913. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216914. if (header.startsWithIgnoreCase ("HTTP/"))
  216915. return header.trimEnd();
  216916. return String::empty;
  216917. }
  216918. static bool decomposeURL (const String& url,
  216919. String& host, String& path, int& port)
  216920. {
  216921. if (! url.startsWithIgnoreCase ("http://"))
  216922. return false;
  216923. const int nextSlash = url.indexOfChar (7, '/');
  216924. int nextColon = url.indexOfChar (7, ':');
  216925. if (nextColon > nextSlash && nextSlash > 0)
  216926. nextColon = -1;
  216927. if (nextColon >= 0)
  216928. {
  216929. host = url.substring (7, nextColon);
  216930. if (nextSlash >= 0)
  216931. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216932. else
  216933. port = url.substring (nextColon + 1).getIntValue();
  216934. }
  216935. else
  216936. {
  216937. port = 80;
  216938. if (nextSlash >= 0)
  216939. host = url.substring (7, nextSlash);
  216940. else
  216941. host = url.substring (7);
  216942. }
  216943. if (nextSlash >= 0)
  216944. path = url.substring (nextSlash);
  216945. else
  216946. path = "/";
  216947. return true;
  216948. }
  216949. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216950. {
  216951. for (int i = 0; i < lines.size(); ++i)
  216952. if (lines[i].startsWithIgnoreCase (itemName))
  216953. return lines[i].substring (itemName.length()).trim();
  216954. return String::empty;
  216955. }
  216956. };
  216957. void* juce_openInternetFile (const String& url,
  216958. const String& headers,
  216959. const MemoryBlock& postData,
  216960. const bool isPost,
  216961. URL::OpenStreamProgressCallback* callback,
  216962. void* callbackContext,
  216963. int timeOutMs)
  216964. {
  216965. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216966. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216967. return s.release();
  216968. return 0;
  216969. }
  216970. void juce_closeInternetFile (void* handle)
  216971. {
  216972. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216973. }
  216974. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216975. {
  216976. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216977. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216978. }
  216979. int64 juce_getInternetFileContentLength (void* handle)
  216980. {
  216981. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216982. if (s != 0)
  216983. {
  216984. //xxx todo
  216985. jassertfalse
  216986. }
  216987. return -1;
  216988. }
  216989. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216990. {
  216991. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216992. if (s != 0)
  216993. {
  216994. for (int i = 0; i < s->headerLines.size(); ++i)
  216995. {
  216996. const String& headersEntry = s->headerLines[i];
  216997. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  216998. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  216999. const String previousValue (headers [key]);
  217000. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217001. }
  217002. }
  217003. }
  217004. int juce_seekInInternetFile (void* handle, int newPosition)
  217005. {
  217006. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  217007. return s != 0 ? s->readPosition : 0;
  217008. }
  217009. #endif
  217010. /*** End of inlined file: juce_linux_Network.cpp ***/
  217011. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217012. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217013. // compiled on its own).
  217014. #if JUCE_INCLUDED_FILE
  217015. void Logger::outputDebugString (const String& text)
  217016. {
  217017. std::cerr << text << std::endl;
  217018. }
  217019. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217020. {
  217021. return Linux;
  217022. }
  217023. const String SystemStats::getOperatingSystemName()
  217024. {
  217025. return "Linux";
  217026. }
  217027. bool SystemStats::isOperatingSystem64Bit()
  217028. {
  217029. #if JUCE_64BIT
  217030. return true;
  217031. #else
  217032. //xxx not sure how to find this out?..
  217033. return false;
  217034. #endif
  217035. }
  217036. static const String juce_getCpuInfo (const char* const key)
  217037. {
  217038. StringArray lines;
  217039. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217040. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217041. if (lines[i].startsWithIgnoreCase (key))
  217042. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217043. return String::empty;
  217044. }
  217045. const String SystemStats::getCpuVendor()
  217046. {
  217047. return juce_getCpuInfo ("vendor_id");
  217048. }
  217049. int SystemStats::getCpuSpeedInMegaherz()
  217050. {
  217051. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  217052. }
  217053. int SystemStats::getMemorySizeInMegabytes()
  217054. {
  217055. struct sysinfo sysi;
  217056. if (sysinfo (&sysi) == 0)
  217057. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217058. return 0;
  217059. }
  217060. int SystemStats::getPageSize()
  217061. {
  217062. return sysconf (_SC_PAGESIZE);
  217063. }
  217064. const String SystemStats::getLogonName()
  217065. {
  217066. const char* user = getenv ("USER");
  217067. if (user == 0)
  217068. {
  217069. struct passwd* const pw = getpwuid (getuid());
  217070. if (pw != 0)
  217071. user = pw->pw_name;
  217072. }
  217073. return String::fromUTF8 (user);
  217074. }
  217075. const String SystemStats::getFullUserName()
  217076. {
  217077. return getLogonName();
  217078. }
  217079. void SystemStats::initialiseStats()
  217080. {
  217081. const String flags (juce_getCpuInfo ("flags"));
  217082. cpuFlags.hasMMX = flags.contains ("mmx");
  217083. cpuFlags.hasSSE = flags.contains ("sse");
  217084. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217085. cpuFlags.has3DNow = flags.contains ("3dnow");
  217086. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  217087. }
  217088. void PlatformUtilities::fpuReset()
  217089. {
  217090. }
  217091. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  217092. {
  217093. if (gettimeofday (t, 0) != 0)
  217094. return false;
  217095. static unsigned int calibrate = 0;
  217096. static bool calibrated = false;
  217097. if (! calibrated)
  217098. {
  217099. calibrated = true;
  217100. struct sysinfo sysi;
  217101. if (sysinfo (&sysi) == 0)
  217102. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  217103. }
  217104. t->tv_sec -= calibrate;
  217105. return true;
  217106. }
  217107. uint32 juce_millisecondsSinceStartup() throw()
  217108. {
  217109. timeval t;
  217110. if (juce_getTimeSinceStartup (&t))
  217111. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  217112. return 0;
  217113. }
  217114. int64 Time::getHighResolutionTicks() throw()
  217115. {
  217116. timeval t;
  217117. if (juce_getTimeSinceStartup (&t))
  217118. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  217119. return 0;
  217120. }
  217121. int64 Time::getHighResolutionTicksPerSecond() throw()
  217122. {
  217123. return 1000000; // (microseconds)
  217124. }
  217125. double Time::getMillisecondCounterHiRes() throw()
  217126. {
  217127. return getHighResolutionTicks() * 0.001;
  217128. }
  217129. bool Time::setSystemTimeToThisTime() const
  217130. {
  217131. timeval t;
  217132. t.tv_sec = millisSinceEpoch % 1000000;
  217133. t.tv_usec = millisSinceEpoch - t.tv_sec;
  217134. return settimeofday (&t, 0) ? false : true;
  217135. }
  217136. #endif
  217137. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217138. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217139. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217140. // compiled on its own).
  217141. #if JUCE_INCLUDED_FILE
  217142. /*
  217143. Note that a lot of methods that you'd expect to find in this file actually
  217144. live in juce_posix_SharedCode.h!
  217145. */
  217146. void JUCE_API juce_threadEntryPoint (void*);
  217147. void* threadEntryProc (void* value)
  217148. {
  217149. juce_threadEntryPoint (value);
  217150. return 0;
  217151. }
  217152. void* juce_createThread (void* userData)
  217153. {
  217154. pthread_t handle = 0;
  217155. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217156. {
  217157. pthread_detach (handle);
  217158. return (void*) handle;
  217159. }
  217160. return 0;
  217161. }
  217162. void juce_killThread (void* handle)
  217163. {
  217164. if (handle != 0)
  217165. pthread_cancel ((pthread_t) handle);
  217166. }
  217167. void juce_setCurrentThreadName (const String& /*name*/)
  217168. {
  217169. }
  217170. Thread::ThreadID Thread::getCurrentThreadId()
  217171. {
  217172. return (ThreadID) pthread_self();
  217173. }
  217174. /* This is all a bit non-ideal... the trouble is that on Linux you
  217175. need to call setpriority to affect the dynamic priority for
  217176. non-realtime processes, but this requires the pid, which is not
  217177. accessible from the pthread_t. We could get it by calling getpid
  217178. once each thread has started, but then we would need a list of
  217179. running threads etc etc.
  217180. Also there is no such thing as IDLE priority on Linux.
  217181. For the moment, map idle, low and normal process priorities to
  217182. SCHED_OTHER, with the thread priority ignored for these classes.
  217183. Map high priority processes to the lower half of the SCHED_RR
  217184. range, and realtime to the upper half.
  217185. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  217186. priority of the current thread
  217187. */
  217188. bool juce_setThreadPriority (void* handle, int priority)
  217189. {
  217190. struct sched_param param;
  217191. int policy;
  217192. if (handle == 0)
  217193. handle = (void*) pthread_self();
  217194. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  217195. && policy != SCHED_OTHER)
  217196. {
  217197. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  217198. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217199. }
  217200. return false;
  217201. }
  217202. /* Remove this macro if you're having problems compiling the cpu affinity
  217203. calls (the API for these has changed about quite a bit in various Linux
  217204. versions, and a lot of distros seem to ship with obsolete versions)
  217205. */
  217206. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217207. #define SUPPORT_AFFINITIES 1
  217208. #endif
  217209. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217210. {
  217211. #if SUPPORT_AFFINITIES
  217212. cpu_set_t affinity;
  217213. CPU_ZERO (&affinity);
  217214. for (int i = 0; i < 32; ++i)
  217215. if ((affinityMask & (1 << i)) != 0)
  217216. CPU_SET (i, &affinity);
  217217. /*
  217218. N.B. If this line causes a compile error, then you've probably not got the latest
  217219. version of glibc installed.
  217220. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217221. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217222. */
  217223. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217224. sched_yield();
  217225. #else
  217226. /* affinities aren't supported because either the appropriate header files weren't found,
  217227. or the SUPPORT_AFFINITIES macro was turned off
  217228. */
  217229. jassertfalse;
  217230. #endif
  217231. }
  217232. void Thread::yield()
  217233. {
  217234. sched_yield();
  217235. }
  217236. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217237. void Process::setPriority (ProcessPriority prior)
  217238. {
  217239. struct sched_param param;
  217240. int policy, maxp, minp;
  217241. const int p = (int) prior;
  217242. if (p <= 1)
  217243. policy = SCHED_OTHER;
  217244. else
  217245. policy = SCHED_RR;
  217246. minp = sched_get_priority_min (policy);
  217247. maxp = sched_get_priority_max (policy);
  217248. if (p < 2)
  217249. param.sched_priority = 0;
  217250. else if (p == 2 )
  217251. // Set to middle of lower realtime priority range
  217252. param.sched_priority = minp + (maxp - minp) / 4;
  217253. else
  217254. // Set to middle of higher realtime priority range
  217255. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217256. pthread_setschedparam (pthread_self(), policy, &param);
  217257. }
  217258. void Process::terminate()
  217259. {
  217260. exit (0);
  217261. }
  217262. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  217263. {
  217264. static char testResult = 0;
  217265. if (testResult == 0)
  217266. {
  217267. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217268. if (testResult >= 0)
  217269. {
  217270. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217271. testResult = 1;
  217272. }
  217273. }
  217274. return testResult < 0;
  217275. }
  217276. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217277. {
  217278. return juce_isRunningUnderDebugger();
  217279. }
  217280. void Process::raisePrivilege()
  217281. {
  217282. // If running suid root, change effective user
  217283. // to root
  217284. if (geteuid() != 0 && getuid() == 0)
  217285. {
  217286. setreuid (geteuid(), getuid());
  217287. setregid (getegid(), getgid());
  217288. }
  217289. }
  217290. void Process::lowerPrivilege()
  217291. {
  217292. // If runing suid root, change effective user
  217293. // back to real user
  217294. if (geteuid() == 0 && getuid() != 0)
  217295. {
  217296. setreuid (geteuid(), getuid());
  217297. setregid (getegid(), getgid());
  217298. }
  217299. }
  217300. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217301. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217302. {
  217303. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217304. }
  217305. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217306. {
  217307. dlclose(handle);
  217308. }
  217309. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217310. {
  217311. return dlsym (libraryHandle, procedureName.toCString());
  217312. }
  217313. #endif
  217314. #endif
  217315. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217316. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217317. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217318. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217319. // compiled on its own).
  217320. #if JUCE_INCLUDED_FILE
  217321. extern Display* display;
  217322. extern Window juce_messageWindowHandle;
  217323. namespace ClipboardHelpers
  217324. {
  217325. static String localClipboardContent;
  217326. static Atom atom_UTF8_STRING;
  217327. static Atom atom_CLIPBOARD;
  217328. static Atom atom_TARGETS;
  217329. static void initSelectionAtoms()
  217330. {
  217331. static bool isInitialised = false;
  217332. if (! isInitialised)
  217333. {
  217334. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217335. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217336. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217337. }
  217338. }
  217339. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217340. // works only for strings shorter than 1000000 bytes
  217341. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217342. {
  217343. String returnData;
  217344. char* clipData;
  217345. Atom actualType;
  217346. int actualFormat;
  217347. unsigned long numItems, bytesLeft;
  217348. if (XGetWindowProperty (display, window, prop,
  217349. 0L /* offset */, 1000000 /* length (max) */, False,
  217350. AnyPropertyType /* format */,
  217351. &actualType, &actualFormat, &numItems, &bytesLeft,
  217352. (unsigned char**) &clipData) == Success)
  217353. {
  217354. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217355. returnData = String::fromUTF8 (clipData, numItems);
  217356. else if (actualType == XA_STRING && actualFormat == 8)
  217357. returnData = String (clipData, numItems);
  217358. if (clipData != 0)
  217359. XFree (clipData);
  217360. jassert (bytesLeft == 0 || numItems == 1000000);
  217361. }
  217362. XDeleteProperty (display, window, prop);
  217363. return returnData;
  217364. }
  217365. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217366. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217367. {
  217368. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217369. // The selection owner will be asked to set the JUCE_SEL property on the
  217370. // juce_messageWindowHandle with the selection content
  217371. XConvertSelection (display, selection, requestedFormat, property_name,
  217372. juce_messageWindowHandle, CurrentTime);
  217373. int count = 50; // will wait at most for 200 ms
  217374. while (--count >= 0)
  217375. {
  217376. XEvent event;
  217377. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217378. {
  217379. if (event.xselection.property == property_name)
  217380. {
  217381. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217382. selectionContent = readWindowProperty (event.xselection.requestor,
  217383. event.xselection.property,
  217384. requestedFormat);
  217385. return true;
  217386. }
  217387. else
  217388. {
  217389. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217390. }
  217391. }
  217392. // not very elegant.. we could do a select() or something like that...
  217393. // however clipboard content requesting is inherently slow on x11, it
  217394. // often takes 50ms or more so...
  217395. Thread::sleep (4);
  217396. }
  217397. return false;
  217398. }
  217399. }
  217400. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217401. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217402. {
  217403. ClipboardHelpers::initSelectionAtoms();
  217404. // the selection content is sent to the target window as a window property
  217405. XSelectionEvent reply;
  217406. reply.type = SelectionNotify;
  217407. reply.display = evt.display;
  217408. reply.requestor = evt.requestor;
  217409. reply.selection = evt.selection;
  217410. reply.target = evt.target;
  217411. reply.property = None; // == "fail"
  217412. reply.time = evt.time;
  217413. HeapBlock <char> data;
  217414. int propertyFormat = 0, numDataItems = 0;
  217415. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217416. {
  217417. if (evt.target == XA_STRING)
  217418. {
  217419. // format data according to system locale
  217420. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217421. data.calloc (numDataItems + 1);
  217422. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217423. propertyFormat = 8; // bits/item
  217424. }
  217425. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217426. {
  217427. // translate to utf8
  217428. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217429. data.calloc (numDataItems + 1);
  217430. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217431. propertyFormat = 8; // bits/item
  217432. }
  217433. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217434. {
  217435. // another application wants to know what we are able to send
  217436. numDataItems = 2;
  217437. propertyFormat = 32; // atoms are 32-bit
  217438. data.calloc (numDataItems * 4);
  217439. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217440. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217441. atoms[1] = XA_STRING;
  217442. }
  217443. }
  217444. else
  217445. {
  217446. DBG ("requested unsupported clipboard");
  217447. }
  217448. if (data != 0)
  217449. {
  217450. const int maxReasonableSelectionSize = 1000000;
  217451. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217452. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217453. {
  217454. XChangeProperty (evt.display, evt.requestor,
  217455. evt.property, evt.target,
  217456. propertyFormat /* 8 or 32 */, PropModeReplace,
  217457. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217458. reply.property = evt.property; // " == success"
  217459. }
  217460. }
  217461. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217462. }
  217463. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217464. {
  217465. ClipboardHelpers::initSelectionAtoms();
  217466. ClipboardHelpers::localClipboardContent = clipText;
  217467. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217468. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217469. }
  217470. const String SystemClipboard::getTextFromClipboard()
  217471. {
  217472. ClipboardHelpers::initSelectionAtoms();
  217473. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217474. level" clipboard that is supposed to be filled by ctrl-C
  217475. etc). When a clipboard manager is running, the content of this
  217476. selection is preserved even when the original selection owner
  217477. exits.
  217478. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217479. filled by good old x11 apps such as xterm)
  217480. */
  217481. String content;
  217482. Atom selection = XA_PRIMARY;
  217483. Window selectionOwner = None;
  217484. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217485. {
  217486. selection = ClipboardHelpers::atom_CLIPBOARD;
  217487. selectionOwner = XGetSelectionOwner (display, selection);
  217488. }
  217489. if (selectionOwner != None)
  217490. {
  217491. if (selectionOwner == juce_messageWindowHandle)
  217492. {
  217493. content = ClipboardHelpers::localClipboardContent;
  217494. }
  217495. else
  217496. {
  217497. // first try: we want an utf8 string
  217498. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217499. if (! ok)
  217500. {
  217501. // second chance, ask for a good old locale-dependent string ..
  217502. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217503. }
  217504. }
  217505. }
  217506. return content;
  217507. }
  217508. #endif
  217509. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217510. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217511. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217512. // compiled on its own).
  217513. #if JUCE_INCLUDED_FILE
  217514. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217515. #define JUCE_DEBUG_XERRORS 1
  217516. #endif
  217517. Display* display = 0;
  217518. Window juce_messageWindowHandle = None;
  217519. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217520. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217521. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217522. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217523. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217524. class InternalMessageQueue
  217525. {
  217526. public:
  217527. InternalMessageQueue()
  217528. : bytesInSocket (0),
  217529. totalEventCount (0)
  217530. {
  217531. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217532. (void) ret; jassert (ret == 0);
  217533. //setNonBlocking (fd[0]);
  217534. //setNonBlocking (fd[1]);
  217535. }
  217536. ~InternalMessageQueue()
  217537. {
  217538. close (fd[0]);
  217539. close (fd[1]);
  217540. clearSingletonInstance();
  217541. }
  217542. void postMessage (Message* msg)
  217543. {
  217544. const int maxBytesInSocketQueue = 128;
  217545. ScopedLock sl (lock);
  217546. queue.add (msg);
  217547. if (bytesInSocket < maxBytesInSocketQueue)
  217548. {
  217549. ++bytesInSocket;
  217550. ScopedUnlock ul (lock);
  217551. const unsigned char x = 0xff;
  217552. size_t bytesWritten = write (fd[0], &x, 1);
  217553. (void) bytesWritten;
  217554. }
  217555. }
  217556. bool isEmpty() const
  217557. {
  217558. ScopedLock sl (lock);
  217559. return queue.size() == 0;
  217560. }
  217561. bool dispatchNextEvent()
  217562. {
  217563. // This alternates between giving priority to XEvents or internal messages,
  217564. // to keep everything running smoothly..
  217565. if ((++totalEventCount & 1) != 0)
  217566. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217567. else
  217568. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217569. }
  217570. // Wait for an event (either XEvent, or an internal Message)
  217571. bool sleepUntilEvent (const int timeoutMs)
  217572. {
  217573. if (! isEmpty())
  217574. return true;
  217575. if (display != 0)
  217576. {
  217577. ScopedXLock xlock;
  217578. if (XPending (display))
  217579. return true;
  217580. }
  217581. struct timeval tv;
  217582. tv.tv_sec = 0;
  217583. tv.tv_usec = timeoutMs * 1000;
  217584. int fd0 = getWaitHandle();
  217585. int fdmax = fd0;
  217586. fd_set readset;
  217587. FD_ZERO (&readset);
  217588. FD_SET (fd0, &readset);
  217589. if (display != 0)
  217590. {
  217591. ScopedXLock xlock;
  217592. int fd1 = XConnectionNumber (display);
  217593. FD_SET (fd1, &readset);
  217594. fdmax = jmax (fd0, fd1);
  217595. }
  217596. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217597. return (ret > 0); // ret <= 0 if error or timeout
  217598. }
  217599. struct MessageThreadFuncCall
  217600. {
  217601. enum { uniqueID = 0x73774623 };
  217602. MessageCallbackFunction* func;
  217603. void* parameter;
  217604. void* result;
  217605. CriticalSection lock;
  217606. WaitableEvent event;
  217607. };
  217608. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217609. private:
  217610. CriticalSection lock;
  217611. OwnedArray <Message> queue;
  217612. int fd[2];
  217613. int bytesInSocket;
  217614. int totalEventCount;
  217615. int getWaitHandle() const throw() { return fd[1]; }
  217616. static bool setNonBlocking (int handle)
  217617. {
  217618. int socketFlags = fcntl (handle, F_GETFL, 0);
  217619. if (socketFlags == -1)
  217620. return false;
  217621. socketFlags |= O_NONBLOCK;
  217622. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217623. }
  217624. static bool dispatchNextXEvent()
  217625. {
  217626. if (display == 0)
  217627. return false;
  217628. XEvent evt;
  217629. {
  217630. ScopedXLock xlock;
  217631. if (! XPending (display))
  217632. return false;
  217633. XNextEvent (display, &evt);
  217634. }
  217635. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217636. juce_handleSelectionRequest (evt.xselectionrequest);
  217637. else if (evt.xany.window != juce_messageWindowHandle)
  217638. juce_windowMessageReceive (&evt);
  217639. return true;
  217640. }
  217641. Message* popNextMessage()
  217642. {
  217643. ScopedLock sl (lock);
  217644. if (bytesInSocket > 0)
  217645. {
  217646. --bytesInSocket;
  217647. ScopedUnlock ul (lock);
  217648. unsigned char x;
  217649. size_t numBytes = read (fd[1], &x, 1);
  217650. (void) numBytes;
  217651. }
  217652. return queue.removeAndReturn (0);
  217653. }
  217654. bool dispatchNextInternalMessage()
  217655. {
  217656. ScopedPointer <Message> msg (popNextMessage());
  217657. if (msg == 0)
  217658. return false;
  217659. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217660. {
  217661. // Handle callback message
  217662. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217663. call->result = (*(call->func)) (call->parameter);
  217664. call->event.signal();
  217665. }
  217666. else
  217667. {
  217668. // Handle "normal" messages
  217669. MessageManager::getInstance()->deliverMessage (msg.release());
  217670. }
  217671. return true;
  217672. }
  217673. };
  217674. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217675. namespace LinuxErrorHandling
  217676. {
  217677. static bool errorOccurred = false;
  217678. static bool keyboardBreakOccurred = false;
  217679. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217680. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217681. // Usually happens when client-server connection is broken
  217682. static int ioErrorHandler (Display* display)
  217683. {
  217684. DBG ("ERROR: connection to X server broken.. terminating.");
  217685. if (JUCEApplication::isStandaloneApp())
  217686. MessageManager::getInstance()->stopDispatchLoop();
  217687. errorOccurred = true;
  217688. return 0;
  217689. }
  217690. // A protocol error has occurred
  217691. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217692. {
  217693. #if JUCE_DEBUG_XERRORS
  217694. char errorStr[64] = { 0 };
  217695. char requestStr[64] = { 0 };
  217696. XGetErrorText (display, event->error_code, errorStr, 64);
  217697. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217698. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217699. #endif
  217700. return 0;
  217701. }
  217702. static void installXErrorHandlers()
  217703. {
  217704. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217705. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217706. }
  217707. static void removeXErrorHandlers()
  217708. {
  217709. XSetIOErrorHandler (oldIOErrorHandler);
  217710. oldIOErrorHandler = 0;
  217711. XSetErrorHandler (oldErrorHandler);
  217712. oldErrorHandler = 0;
  217713. }
  217714. static void keyboardBreakSignalHandler (int sig)
  217715. {
  217716. if (sig == SIGINT)
  217717. keyboardBreakOccurred = true;
  217718. }
  217719. static void installKeyboardBreakHandler()
  217720. {
  217721. struct sigaction saction;
  217722. sigset_t maskSet;
  217723. sigemptyset (&maskSet);
  217724. saction.sa_handler = keyboardBreakSignalHandler;
  217725. saction.sa_mask = maskSet;
  217726. saction.sa_flags = 0;
  217727. sigaction (SIGINT, &saction, 0);
  217728. }
  217729. }
  217730. void MessageManager::doPlatformSpecificInitialisation()
  217731. {
  217732. // Initialise xlib for multiple thread support
  217733. static bool initThreadCalled = false;
  217734. if (! initThreadCalled)
  217735. {
  217736. if (! XInitThreads())
  217737. {
  217738. // This is fatal! Print error and closedown
  217739. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217740. if (JUCEApplication::isStandaloneApp())
  217741. Process::terminate();
  217742. return;
  217743. }
  217744. initThreadCalled = true;
  217745. }
  217746. LinuxErrorHandling::installXErrorHandlers();
  217747. LinuxErrorHandling::installKeyboardBreakHandler();
  217748. // Create the internal message queue
  217749. InternalMessageQueue::getInstance();
  217750. // Try to connect to a display
  217751. String displayName (getenv ("DISPLAY"));
  217752. if (displayName.isEmpty())
  217753. displayName = ":0.0";
  217754. display = XOpenDisplay (displayName.toCString());
  217755. if (display != 0) // This is not fatal! we can run headless.
  217756. {
  217757. // Create a context to store user data associated with Windows we create in WindowDriver
  217758. windowHandleXContext = XUniqueContext();
  217759. // We're only interested in client messages for this window, which are always sent
  217760. XSetWindowAttributes swa;
  217761. swa.event_mask = NoEventMask;
  217762. // Create our message window (this will never be mapped)
  217763. const int screen = DefaultScreen (display);
  217764. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217765. 0, 0, 1, 1, 0, 0, InputOnly,
  217766. DefaultVisual (display, screen),
  217767. CWEventMask, &swa);
  217768. }
  217769. }
  217770. void MessageManager::doPlatformSpecificShutdown()
  217771. {
  217772. InternalMessageQueue::deleteInstance();
  217773. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217774. {
  217775. XDestroyWindow (display, juce_messageWindowHandle);
  217776. XCloseDisplay (display);
  217777. juce_messageWindowHandle = 0;
  217778. display = 0;
  217779. LinuxErrorHandling::removeXErrorHandlers();
  217780. }
  217781. }
  217782. bool juce_postMessageToSystemQueue (Message* message)
  217783. {
  217784. if (LinuxErrorHandling::errorOccurred)
  217785. return false;
  217786. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  217787. return true;
  217788. }
  217789. void MessageManager::broadcastMessage (const String& value) throw()
  217790. {
  217791. /* TODO */
  217792. }
  217793. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217794. void* parameter)
  217795. {
  217796. if (LinuxErrorHandling::errorOccurred)
  217797. return 0;
  217798. if (isThisTheMessageThread())
  217799. return func (parameter);
  217800. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217801. messageCallContext.func = func;
  217802. messageCallContext.parameter = parameter;
  217803. InternalMessageQueue::getInstanceWithoutCreating()
  217804. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217805. 0, 0, &messageCallContext));
  217806. // Wait for it to complete before continuing
  217807. messageCallContext.event.wait();
  217808. return messageCallContext.result;
  217809. }
  217810. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217811. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217812. {
  217813. while (! LinuxErrorHandling::errorOccurred)
  217814. {
  217815. if (LinuxErrorHandling::keyboardBreakOccurred)
  217816. {
  217817. LinuxErrorHandling::errorOccurred = true;
  217818. if (JUCEApplication::isStandaloneApp())
  217819. Process::terminate();
  217820. break;
  217821. }
  217822. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217823. return true;
  217824. if (returnIfNoPendingMessages)
  217825. break;
  217826. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217827. }
  217828. return false;
  217829. }
  217830. #endif
  217831. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217832. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217833. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217834. // compiled on its own).
  217835. #if JUCE_INCLUDED_FILE
  217836. class FreeTypeFontFace
  217837. {
  217838. public:
  217839. enum FontStyle
  217840. {
  217841. Plain = 0,
  217842. Bold = 1,
  217843. Italic = 2
  217844. };
  217845. FreeTypeFontFace (const String& familyName)
  217846. : hasSerif (false),
  217847. monospaced (false)
  217848. {
  217849. family = familyName;
  217850. }
  217851. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217852. {
  217853. if (names [(int) style].fileName.isEmpty())
  217854. {
  217855. names [(int) style].fileName = name;
  217856. names [(int) style].faceIndex = faceIndex;
  217857. }
  217858. }
  217859. const String& getFamilyName() const throw() { return family; }
  217860. const String& getFileName (const int style, int& faceIndex) const throw()
  217861. {
  217862. faceIndex = names[style].faceIndex;
  217863. return names[style].fileName;
  217864. }
  217865. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217866. bool getMonospaced() const throw() { return monospaced; }
  217867. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217868. bool getSerif() const throw() { return hasSerif; }
  217869. private:
  217870. String family;
  217871. struct FontNameIndex
  217872. {
  217873. String fileName;
  217874. int faceIndex;
  217875. };
  217876. FontNameIndex names[4];
  217877. bool hasSerif, monospaced;
  217878. };
  217879. class FreeTypeInterface : public DeletedAtShutdown
  217880. {
  217881. public:
  217882. FreeTypeInterface()
  217883. : ftLib (0),
  217884. lastFace (0),
  217885. lastBold (false),
  217886. lastItalic (false)
  217887. {
  217888. if (FT_Init_FreeType (&ftLib) != 0)
  217889. {
  217890. ftLib = 0;
  217891. DBG ("Failed to initialize FreeType");
  217892. }
  217893. StringArray fontDirs;
  217894. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217895. fontDirs.removeEmptyStrings (true);
  217896. if (fontDirs.size() == 0)
  217897. {
  217898. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217899. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217900. if (fontsInfo != 0)
  217901. {
  217902. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217903. {
  217904. fontDirs.add (e->getAllSubText().trim());
  217905. }
  217906. }
  217907. }
  217908. if (fontDirs.size() == 0)
  217909. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217910. for (int i = 0; i < fontDirs.size(); ++i)
  217911. enumerateFaces (fontDirs[i]);
  217912. }
  217913. ~FreeTypeInterface()
  217914. {
  217915. if (lastFace != 0)
  217916. FT_Done_Face (lastFace);
  217917. if (ftLib != 0)
  217918. FT_Done_FreeType (ftLib);
  217919. clearSingletonInstance();
  217920. }
  217921. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217922. {
  217923. for (int i = 0; i < faces.size(); i++)
  217924. if (faces[i]->getFamilyName() == familyName)
  217925. return faces[i];
  217926. if (! create)
  217927. return 0;
  217928. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217929. faces.add (newFace);
  217930. return newFace;
  217931. }
  217932. // Enumerate all font faces available in a given directory
  217933. void enumerateFaces (const String& path)
  217934. {
  217935. File dirPath (path);
  217936. if (path.isEmpty() || ! dirPath.isDirectory())
  217937. return;
  217938. DirectoryIterator di (dirPath, true);
  217939. while (di.next())
  217940. {
  217941. File possible (di.getFile());
  217942. if (possible.hasFileExtension ("ttf")
  217943. || possible.hasFileExtension ("pfb")
  217944. || possible.hasFileExtension ("pcf"))
  217945. {
  217946. FT_Face face;
  217947. int faceIndex = 0;
  217948. int numFaces = 0;
  217949. do
  217950. {
  217951. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217952. faceIndex, &face) == 0)
  217953. {
  217954. if (faceIndex == 0)
  217955. numFaces = face->num_faces;
  217956. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217957. {
  217958. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217959. int style = (int) FreeTypeFontFace::Plain;
  217960. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217961. style |= (int) FreeTypeFontFace::Bold;
  217962. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217963. style |= (int) FreeTypeFontFace::Italic;
  217964. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217965. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217966. // Surely there must be a better way to do this?
  217967. const String name (face->family_name);
  217968. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217969. || name.containsIgnoreCase ("Verdana")
  217970. || name.containsIgnoreCase ("Arial")));
  217971. }
  217972. FT_Done_Face (face);
  217973. }
  217974. ++faceIndex;
  217975. }
  217976. while (faceIndex < numFaces);
  217977. }
  217978. }
  217979. }
  217980. // Create a FreeType face object for a given font
  217981. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217982. {
  217983. FT_Face face = 0;
  217984. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  217985. {
  217986. face = lastFace;
  217987. }
  217988. else
  217989. {
  217990. if (lastFace != 0)
  217991. {
  217992. FT_Done_Face (lastFace);
  217993. lastFace = 0;
  217994. }
  217995. lastFontName = fontName;
  217996. lastBold = bold;
  217997. lastItalic = italic;
  217998. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  217999. if (ftFace != 0)
  218000. {
  218001. int style = (int) FreeTypeFontFace::Plain;
  218002. if (bold)
  218003. style |= (int) FreeTypeFontFace::Bold;
  218004. if (italic)
  218005. style |= (int) FreeTypeFontFace::Italic;
  218006. int faceIndex;
  218007. String fileName (ftFace->getFileName (style, faceIndex));
  218008. if (fileName.isEmpty())
  218009. {
  218010. style ^= (int) FreeTypeFontFace::Bold;
  218011. fileName = ftFace->getFileName (style, faceIndex);
  218012. if (fileName.isEmpty())
  218013. {
  218014. style ^= (int) FreeTypeFontFace::Bold;
  218015. style ^= (int) FreeTypeFontFace::Italic;
  218016. fileName = ftFace->getFileName (style, faceIndex);
  218017. if (! fileName.length())
  218018. {
  218019. style ^= (int) FreeTypeFontFace::Bold;
  218020. fileName = ftFace->getFileName (style, faceIndex);
  218021. }
  218022. }
  218023. }
  218024. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218025. {
  218026. face = lastFace;
  218027. // If there isn't a unicode charmap then select the first one.
  218028. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218029. FT_Set_Charmap (face, face->charmaps[0]);
  218030. }
  218031. }
  218032. }
  218033. return face;
  218034. }
  218035. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218036. {
  218037. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218038. const float height = (float) (face->ascender - face->descender);
  218039. const float scaleX = 1.0f / height;
  218040. const float scaleY = -1.0f / height;
  218041. Path destShape;
  218042. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218043. || face->glyph->format != ft_glyph_format_outline)
  218044. {
  218045. return false;
  218046. }
  218047. const FT_Outline* const outline = &face->glyph->outline;
  218048. const short* const contours = outline->contours;
  218049. const char* const tags = outline->tags;
  218050. FT_Vector* const points = outline->points;
  218051. for (int c = 0; c < outline->n_contours; c++)
  218052. {
  218053. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218054. const int endPoint = contours[c];
  218055. for (int p = startPoint; p <= endPoint; p++)
  218056. {
  218057. const float x = scaleX * points[p].x;
  218058. const float y = scaleY * points[p].y;
  218059. if (p == startPoint)
  218060. {
  218061. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218062. {
  218063. float x2 = scaleX * points [endPoint].x;
  218064. float y2 = scaleY * points [endPoint].y;
  218065. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218066. {
  218067. x2 = (x + x2) * 0.5f;
  218068. y2 = (y + y2) * 0.5f;
  218069. }
  218070. destShape.startNewSubPath (x2, y2);
  218071. }
  218072. else
  218073. {
  218074. destShape.startNewSubPath (x, y);
  218075. }
  218076. }
  218077. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218078. {
  218079. if (p != startPoint)
  218080. destShape.lineTo (x, y);
  218081. }
  218082. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218083. {
  218084. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218085. float x2 = scaleX * points [nextIndex].x;
  218086. float y2 = scaleY * points [nextIndex].y;
  218087. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218088. {
  218089. x2 = (x + x2) * 0.5f;
  218090. y2 = (y + y2) * 0.5f;
  218091. }
  218092. else
  218093. {
  218094. ++p;
  218095. }
  218096. destShape.quadraticTo (x, y, x2, y2);
  218097. }
  218098. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218099. {
  218100. if (p >= endPoint)
  218101. return false;
  218102. const int next1 = p + 1;
  218103. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218104. const float x2 = scaleX * points [next1].x;
  218105. const float y2 = scaleY * points [next1].y;
  218106. const float x3 = scaleX * points [next2].x;
  218107. const float y3 = scaleY * points [next2].y;
  218108. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218109. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218110. return false;
  218111. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218112. p += 2;
  218113. }
  218114. }
  218115. destShape.closeSubPath();
  218116. }
  218117. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218118. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218119. addKerning (face, dest, character, glyphIndex);
  218120. return true;
  218121. }
  218122. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218123. {
  218124. const float height = (float) (face->ascender - face->descender);
  218125. uint32 rightGlyphIndex;
  218126. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218127. while (rightGlyphIndex != 0)
  218128. {
  218129. FT_Vector kerning;
  218130. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218131. {
  218132. if (kerning.x != 0)
  218133. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218134. }
  218135. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218136. }
  218137. }
  218138. // Add a glyph to a font
  218139. bool addGlyphToFont (const uint32 character, const String& fontName,
  218140. bool bold, bool italic, CustomTypeface& dest)
  218141. {
  218142. FT_Face face = createFT_Face (fontName, bold, italic);
  218143. return face != 0 && addGlyph (face, dest, character);
  218144. }
  218145. void getFamilyNames (StringArray& familyNames) const
  218146. {
  218147. for (int i = 0; i < faces.size(); i++)
  218148. familyNames.add (faces[i]->getFamilyName());
  218149. }
  218150. void getMonospacedNames (StringArray& monoSpaced) const
  218151. {
  218152. for (int i = 0; i < faces.size(); i++)
  218153. if (faces[i]->getMonospaced())
  218154. monoSpaced.add (faces[i]->getFamilyName());
  218155. }
  218156. void getSerifNames (StringArray& serif) const
  218157. {
  218158. for (int i = 0; i < faces.size(); i++)
  218159. if (faces[i]->getSerif())
  218160. serif.add (faces[i]->getFamilyName());
  218161. }
  218162. void getSansSerifNames (StringArray& sansSerif) const
  218163. {
  218164. for (int i = 0; i < faces.size(); i++)
  218165. if (! faces[i]->getSerif())
  218166. sansSerif.add (faces[i]->getFamilyName());
  218167. }
  218168. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218169. private:
  218170. FT_Library ftLib;
  218171. FT_Face lastFace;
  218172. String lastFontName;
  218173. bool lastBold, lastItalic;
  218174. OwnedArray<FreeTypeFontFace> faces;
  218175. };
  218176. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218177. class FreetypeTypeface : public CustomTypeface
  218178. {
  218179. public:
  218180. FreetypeTypeface (const Font& font)
  218181. {
  218182. FT_Face face = FreeTypeInterface::getInstance()
  218183. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218184. if (face == 0)
  218185. {
  218186. #if JUCE_DEBUG
  218187. String msg ("Failed to create typeface: ");
  218188. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218189. DBG (msg);
  218190. #endif
  218191. }
  218192. else
  218193. {
  218194. setCharacteristics (font.getTypefaceName(),
  218195. face->ascender / (float) (face->ascender - face->descender),
  218196. font.isBold(), font.isItalic(),
  218197. L' ');
  218198. }
  218199. }
  218200. bool loadGlyphIfPossible (juce_wchar character)
  218201. {
  218202. return FreeTypeInterface::getInstance()
  218203. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218204. }
  218205. };
  218206. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218207. {
  218208. return new FreetypeTypeface (font);
  218209. }
  218210. const StringArray Font::findAllTypefaceNames()
  218211. {
  218212. StringArray s;
  218213. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218214. s.sort (true);
  218215. return s;
  218216. }
  218217. static const String pickBestFont (const StringArray& names,
  218218. const char* const choicesString)
  218219. {
  218220. StringArray choices;
  218221. choices.addTokens (String (choicesString), ",", String::empty);
  218222. choices.trim();
  218223. choices.removeEmptyStrings();
  218224. int i, j;
  218225. for (j = 0; j < choices.size(); ++j)
  218226. if (names.contains (choices[j], true))
  218227. return choices[j];
  218228. for (j = 0; j < choices.size(); ++j)
  218229. for (i = 0; i < names.size(); i++)
  218230. if (names[i].startsWithIgnoreCase (choices[j]))
  218231. return names[i];
  218232. for (j = 0; j < choices.size(); ++j)
  218233. for (i = 0; i < names.size(); i++)
  218234. if (names[i].containsIgnoreCase (choices[j]))
  218235. return names[i];
  218236. return names[0];
  218237. }
  218238. static const String linux_getDefaultSansSerifFontName()
  218239. {
  218240. StringArray allFonts;
  218241. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218242. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218243. }
  218244. static const String linux_getDefaultSerifFontName()
  218245. {
  218246. StringArray allFonts;
  218247. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218248. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218249. }
  218250. static const String linux_getDefaultMonospacedFontName()
  218251. {
  218252. StringArray allFonts;
  218253. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218254. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218255. }
  218256. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  218257. {
  218258. defaultSans = linux_getDefaultSansSerifFontName();
  218259. defaultSerif = linux_getDefaultSerifFontName();
  218260. defaultFixed = linux_getDefaultMonospacedFontName();
  218261. }
  218262. #endif
  218263. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218264. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218265. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218266. // compiled on its own).
  218267. #if JUCE_INCLUDED_FILE
  218268. // These are defined in juce_linux_Messaging.cpp
  218269. extern Display* display;
  218270. extern XContext windowHandleXContext;
  218271. namespace Atoms
  218272. {
  218273. enum ProtocolItems
  218274. {
  218275. TAKE_FOCUS = 0,
  218276. DELETE_WINDOW = 1,
  218277. PING = 2
  218278. };
  218279. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218280. ActiveWin, Pid, WindowType, WindowState,
  218281. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218282. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218283. XdndActionDescription, XdndActionCopy,
  218284. allowedActions[5],
  218285. allowedMimeTypes[2];
  218286. const unsigned long DndVersion = 3;
  218287. static void initialiseAtoms()
  218288. {
  218289. static bool atomsInitialised = false;
  218290. if (! atomsInitialised)
  218291. {
  218292. atomsInitialised = true;
  218293. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218294. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218295. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218296. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218297. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218298. State = XInternAtom (display, "WM_STATE", True);
  218299. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218300. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218301. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218302. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218303. XdndAware = XInternAtom (display, "XdndAware", False);
  218304. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218305. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218306. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218307. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218308. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218309. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218310. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218311. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218312. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218313. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218314. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218315. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218316. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218317. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218318. allowedActions[1] = XdndActionCopy;
  218319. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218320. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218321. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218322. }
  218323. }
  218324. }
  218325. namespace Keys
  218326. {
  218327. enum MouseButtons
  218328. {
  218329. NoButton = 0,
  218330. LeftButton = 1,
  218331. MiddleButton = 2,
  218332. RightButton = 3,
  218333. WheelUp = 4,
  218334. WheelDown = 5
  218335. };
  218336. static int AltMask = 0;
  218337. static int NumLockMask = 0;
  218338. static bool numLock = false;
  218339. static bool capsLock = false;
  218340. static char keyStates [32];
  218341. static const int extendedKeyModifier = 0x10000000;
  218342. }
  218343. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218344. {
  218345. int keysym;
  218346. if (keyCode & Keys::extendedKeyModifier)
  218347. {
  218348. keysym = 0xff00 | (keyCode & 0xff);
  218349. }
  218350. else
  218351. {
  218352. keysym = keyCode;
  218353. if (keysym == (XK_Tab & 0xff)
  218354. || keysym == (XK_Return & 0xff)
  218355. || keysym == (XK_Escape & 0xff)
  218356. || keysym == (XK_BackSpace & 0xff))
  218357. {
  218358. keysym |= 0xff00;
  218359. }
  218360. }
  218361. ScopedXLock xlock;
  218362. const int keycode = XKeysymToKeycode (display, keysym);
  218363. const int keybyte = keycode >> 3;
  218364. const int keybit = (1 << (keycode & 7));
  218365. return (Keys::keyStates [keybyte] & keybit) != 0;
  218366. }
  218367. #if JUCE_USE_XSHM
  218368. namespace XSHMHelpers
  218369. {
  218370. static int trappedErrorCode = 0;
  218371. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218372. {
  218373. trappedErrorCode = err->error_code;
  218374. return 0;
  218375. }
  218376. static bool isShmAvailable() throw()
  218377. {
  218378. static bool isChecked = false;
  218379. static bool isAvailable = false;
  218380. if (! isChecked)
  218381. {
  218382. isChecked = true;
  218383. int major, minor;
  218384. Bool pixmaps;
  218385. ScopedXLock xlock;
  218386. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218387. {
  218388. trappedErrorCode = 0;
  218389. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218390. XShmSegmentInfo segmentInfo;
  218391. zerostruct (segmentInfo);
  218392. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218393. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218394. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218395. xImage->bytes_per_line * xImage->height,
  218396. IPC_CREAT | 0777)) >= 0)
  218397. {
  218398. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218399. if (segmentInfo.shmaddr != (void*) -1)
  218400. {
  218401. segmentInfo.readOnly = False;
  218402. xImage->data = segmentInfo.shmaddr;
  218403. XSync (display, False);
  218404. if (XShmAttach (display, &segmentInfo) != 0)
  218405. {
  218406. XSync (display, False);
  218407. XShmDetach (display, &segmentInfo);
  218408. isAvailable = true;
  218409. }
  218410. }
  218411. XFlush (display);
  218412. XDestroyImage (xImage);
  218413. shmdt (segmentInfo.shmaddr);
  218414. }
  218415. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218416. XSetErrorHandler (oldHandler);
  218417. if (trappedErrorCode != 0)
  218418. isAvailable = false;
  218419. }
  218420. }
  218421. return isAvailable;
  218422. }
  218423. }
  218424. #endif
  218425. #if JUCE_USE_XRENDER
  218426. namespace XRender
  218427. {
  218428. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218429. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218430. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218431. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218432. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218433. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218434. static tXRenderFindFormat xRenderFindFormat = 0;
  218435. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218436. static bool isAvailable()
  218437. {
  218438. static bool hasLoaded = false;
  218439. if (! hasLoaded)
  218440. {
  218441. ScopedXLock xlock;
  218442. hasLoaded = true;
  218443. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218444. if (h != 0)
  218445. {
  218446. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218447. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218448. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218449. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218450. }
  218451. if (xRenderQueryVersion != 0
  218452. && xRenderFindStandardFormat != 0
  218453. && xRenderFindFormat != 0
  218454. && xRenderFindVisualFormat != 0)
  218455. {
  218456. int major, minor;
  218457. if (xRenderQueryVersion (display, &major, &minor))
  218458. return true;
  218459. }
  218460. xRenderQueryVersion = 0;
  218461. }
  218462. return xRenderQueryVersion != 0;
  218463. }
  218464. static XRenderPictFormat* findPictureFormat()
  218465. {
  218466. ScopedXLock xlock;
  218467. XRenderPictFormat* pictFormat = 0;
  218468. if (isAvailable())
  218469. {
  218470. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218471. if (pictFormat == 0)
  218472. {
  218473. XRenderPictFormat desiredFormat;
  218474. desiredFormat.type = PictTypeDirect;
  218475. desiredFormat.depth = 32;
  218476. desiredFormat.direct.alphaMask = 0xff;
  218477. desiredFormat.direct.redMask = 0xff;
  218478. desiredFormat.direct.greenMask = 0xff;
  218479. desiredFormat.direct.blueMask = 0xff;
  218480. desiredFormat.direct.alpha = 24;
  218481. desiredFormat.direct.red = 16;
  218482. desiredFormat.direct.green = 8;
  218483. desiredFormat.direct.blue = 0;
  218484. pictFormat = xRenderFindFormat (display,
  218485. PictFormatType | PictFormatDepth
  218486. | PictFormatRedMask | PictFormatRed
  218487. | PictFormatGreenMask | PictFormatGreen
  218488. | PictFormatBlueMask | PictFormatBlue
  218489. | PictFormatAlphaMask | PictFormatAlpha,
  218490. &desiredFormat,
  218491. 0);
  218492. }
  218493. }
  218494. return pictFormat;
  218495. }
  218496. }
  218497. #endif
  218498. namespace Visuals
  218499. {
  218500. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218501. {
  218502. ScopedXLock xlock;
  218503. Visual* visual = 0;
  218504. int numVisuals = 0;
  218505. long desiredMask = VisualNoMask;
  218506. XVisualInfo desiredVisual;
  218507. desiredVisual.screen = DefaultScreen (display);
  218508. desiredVisual.depth = desiredDepth;
  218509. desiredMask = VisualScreenMask | VisualDepthMask;
  218510. if (desiredDepth == 32)
  218511. {
  218512. desiredVisual.c_class = TrueColor;
  218513. desiredVisual.red_mask = 0x00FF0000;
  218514. desiredVisual.green_mask = 0x0000FF00;
  218515. desiredVisual.blue_mask = 0x000000FF;
  218516. desiredVisual.bits_per_rgb = 8;
  218517. desiredMask |= VisualClassMask;
  218518. desiredMask |= VisualRedMaskMask;
  218519. desiredMask |= VisualGreenMaskMask;
  218520. desiredMask |= VisualBlueMaskMask;
  218521. desiredMask |= VisualBitsPerRGBMask;
  218522. }
  218523. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218524. desiredMask,
  218525. &desiredVisual,
  218526. &numVisuals);
  218527. if (xvinfos != 0)
  218528. {
  218529. for (int i = 0; i < numVisuals; i++)
  218530. {
  218531. if (xvinfos[i].depth == desiredDepth)
  218532. {
  218533. visual = xvinfos[i].visual;
  218534. break;
  218535. }
  218536. }
  218537. XFree (xvinfos);
  218538. }
  218539. return visual;
  218540. }
  218541. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218542. {
  218543. Visual* visual = 0;
  218544. if (desiredDepth == 32)
  218545. {
  218546. #if JUCE_USE_XSHM
  218547. if (XSHMHelpers::isShmAvailable())
  218548. {
  218549. #if JUCE_USE_XRENDER
  218550. if (XRender::isAvailable())
  218551. {
  218552. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218553. if (pictFormat != 0)
  218554. {
  218555. int numVisuals = 0;
  218556. XVisualInfo desiredVisual;
  218557. desiredVisual.screen = DefaultScreen (display);
  218558. desiredVisual.depth = 32;
  218559. desiredVisual.bits_per_rgb = 8;
  218560. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218561. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218562. &desiredVisual, &numVisuals);
  218563. if (xvinfos != 0)
  218564. {
  218565. for (int i = 0; i < numVisuals; ++i)
  218566. {
  218567. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218568. if (pictVisualFormat != 0
  218569. && pictVisualFormat->type == PictTypeDirect
  218570. && pictVisualFormat->direct.alphaMask)
  218571. {
  218572. visual = xvinfos[i].visual;
  218573. matchedDepth = 32;
  218574. break;
  218575. }
  218576. }
  218577. XFree (xvinfos);
  218578. }
  218579. }
  218580. }
  218581. #endif
  218582. if (visual == 0)
  218583. {
  218584. visual = findVisualWithDepth (32);
  218585. if (visual != 0)
  218586. matchedDepth = 32;
  218587. }
  218588. }
  218589. #endif
  218590. }
  218591. if (visual == 0 && desiredDepth >= 24)
  218592. {
  218593. visual = findVisualWithDepth (24);
  218594. if (visual != 0)
  218595. matchedDepth = 24;
  218596. }
  218597. if (visual == 0 && desiredDepth >= 16)
  218598. {
  218599. visual = findVisualWithDepth (16);
  218600. if (visual != 0)
  218601. matchedDepth = 16;
  218602. }
  218603. return visual;
  218604. }
  218605. }
  218606. class XBitmapImage : public Image::SharedImage
  218607. {
  218608. public:
  218609. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218610. const bool clearImage, const int imageDepth_, Visual* visual)
  218611. : Image::SharedImage (format_, w, h),
  218612. imageDepth (imageDepth_),
  218613. gc (None)
  218614. {
  218615. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218616. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218617. lineStride = ((w * pixelStride + 3) & ~3);
  218618. ScopedXLock xlock;
  218619. #if JUCE_USE_XSHM
  218620. usingXShm = false;
  218621. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218622. {
  218623. zerostruct (segmentInfo);
  218624. segmentInfo.shmid = -1;
  218625. segmentInfo.shmaddr = (char *) -1;
  218626. segmentInfo.readOnly = False;
  218627. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218628. if (xImage != 0)
  218629. {
  218630. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218631. xImage->bytes_per_line * xImage->height,
  218632. IPC_CREAT | 0777)) >= 0)
  218633. {
  218634. if (segmentInfo.shmid != -1)
  218635. {
  218636. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218637. if (segmentInfo.shmaddr != (void*) -1)
  218638. {
  218639. segmentInfo.readOnly = False;
  218640. xImage->data = segmentInfo.shmaddr;
  218641. imageData = (uint8*) segmentInfo.shmaddr;
  218642. if (XShmAttach (display, &segmentInfo) != 0)
  218643. usingXShm = true;
  218644. else
  218645. jassertfalse;
  218646. }
  218647. else
  218648. {
  218649. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218650. }
  218651. }
  218652. }
  218653. }
  218654. }
  218655. if (! usingXShm)
  218656. #endif
  218657. {
  218658. imageDataAllocated.malloc (lineStride * h);
  218659. imageData = imageDataAllocated;
  218660. if (format_ == Image::ARGB && clearImage)
  218661. zeromem (imageData, h * lineStride);
  218662. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218663. xImage->width = w;
  218664. xImage->height = h;
  218665. xImage->xoffset = 0;
  218666. xImage->format = ZPixmap;
  218667. xImage->data = (char*) imageData;
  218668. xImage->byte_order = ImageByteOrder (display);
  218669. xImage->bitmap_unit = BitmapUnit (display);
  218670. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218671. xImage->bitmap_pad = 32;
  218672. xImage->depth = pixelStride * 8;
  218673. xImage->bytes_per_line = lineStride;
  218674. xImage->bits_per_pixel = pixelStride * 8;
  218675. xImage->red_mask = 0x00FF0000;
  218676. xImage->green_mask = 0x0000FF00;
  218677. xImage->blue_mask = 0x000000FF;
  218678. if (imageDepth == 16)
  218679. {
  218680. const int pixelStride = 2;
  218681. const int lineStride = ((w * pixelStride + 3) & ~3);
  218682. imageData16Bit.malloc (lineStride * h);
  218683. xImage->data = imageData16Bit;
  218684. xImage->bitmap_pad = 16;
  218685. xImage->depth = pixelStride * 8;
  218686. xImage->bytes_per_line = lineStride;
  218687. xImage->bits_per_pixel = pixelStride * 8;
  218688. xImage->red_mask = visual->red_mask;
  218689. xImage->green_mask = visual->green_mask;
  218690. xImage->blue_mask = visual->blue_mask;
  218691. }
  218692. if (! XInitImage (xImage))
  218693. jassertfalse;
  218694. }
  218695. }
  218696. ~XBitmapImage()
  218697. {
  218698. ScopedXLock xlock;
  218699. if (gc != None)
  218700. XFreeGC (display, gc);
  218701. #if JUCE_USE_XSHM
  218702. if (usingXShm)
  218703. {
  218704. XShmDetach (display, &segmentInfo);
  218705. XFlush (display);
  218706. XDestroyImage (xImage);
  218707. shmdt (segmentInfo.shmaddr);
  218708. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218709. }
  218710. else
  218711. #endif
  218712. {
  218713. xImage->data = 0;
  218714. XDestroyImage (xImage);
  218715. }
  218716. }
  218717. Image::ImageType getType() const { return Image::NativeImage; }
  218718. LowLevelGraphicsContext* createLowLevelContext()
  218719. {
  218720. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218721. }
  218722. SharedImage* clone()
  218723. {
  218724. jassertfalse;
  218725. return 0;
  218726. }
  218727. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218728. {
  218729. ScopedXLock xlock;
  218730. if (gc == None)
  218731. {
  218732. XGCValues gcvalues;
  218733. gcvalues.foreground = None;
  218734. gcvalues.background = None;
  218735. gcvalues.function = GXcopy;
  218736. gcvalues.plane_mask = AllPlanes;
  218737. gcvalues.clip_mask = None;
  218738. gcvalues.graphics_exposures = False;
  218739. gc = XCreateGC (display, window,
  218740. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218741. &gcvalues);
  218742. }
  218743. if (imageDepth == 16)
  218744. {
  218745. const uint32 rMask = xImage->red_mask;
  218746. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218747. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218748. const uint32 gMask = xImage->green_mask;
  218749. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218750. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218751. const uint32 bMask = xImage->blue_mask;
  218752. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218753. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218754. const Image::BitmapData srcData (Image (this), false);
  218755. for (int y = sy; y < sy + dh; ++y)
  218756. {
  218757. const uint8* p = srcData.getPixelPointer (sx, y);
  218758. for (int x = sx; x < sx + dw; ++x)
  218759. {
  218760. const PixelRGB* const pixel = (const PixelRGB*) p;
  218761. p += srcData.pixelStride;
  218762. XPutPixel (xImage, x, y,
  218763. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218764. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218765. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218766. }
  218767. }
  218768. }
  218769. // blit results to screen.
  218770. #if JUCE_USE_XSHM
  218771. if (usingXShm)
  218772. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218773. else
  218774. #endif
  218775. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218776. }
  218777. juce_UseDebuggingNewOperator
  218778. private:
  218779. XImage* xImage;
  218780. const int imageDepth;
  218781. HeapBlock <uint8> imageDataAllocated;
  218782. HeapBlock <char> imageData16Bit;
  218783. GC gc;
  218784. #if JUCE_USE_XSHM
  218785. XShmSegmentInfo segmentInfo;
  218786. bool usingXShm;
  218787. #endif
  218788. static int getShiftNeeded (const uint32 mask) throw()
  218789. {
  218790. for (int i = 32; --i >= 0;)
  218791. if (((mask >> i) & 1) != 0)
  218792. return i - 7;
  218793. jassertfalse;
  218794. return 0;
  218795. }
  218796. };
  218797. class LinuxComponentPeer : public ComponentPeer
  218798. {
  218799. public:
  218800. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218801. : ComponentPeer (component, windowStyleFlags),
  218802. windowH (0),
  218803. parentWindow (0),
  218804. wx (0),
  218805. wy (0),
  218806. ww (0),
  218807. wh (0),
  218808. fullScreen (false),
  218809. mapped (false),
  218810. visual (0),
  218811. depth (0)
  218812. {
  218813. // it's dangerous to create a window on a thread other than the message thread..
  218814. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218815. repainter = new LinuxRepaintManager (this);
  218816. createWindow();
  218817. setTitle (component->getName());
  218818. }
  218819. ~LinuxComponentPeer()
  218820. {
  218821. // it's dangerous to delete a window on a thread other than the message thread..
  218822. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218823. deleteIconPixmaps();
  218824. destroyWindow();
  218825. windowH = 0;
  218826. }
  218827. void* getNativeHandle() const
  218828. {
  218829. return (void*) windowH;
  218830. }
  218831. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218832. {
  218833. XPointer peer = 0;
  218834. ScopedXLock xlock;
  218835. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218836. {
  218837. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218838. peer = 0;
  218839. }
  218840. return (LinuxComponentPeer*) peer;
  218841. }
  218842. void setVisible (bool shouldBeVisible)
  218843. {
  218844. ScopedXLock xlock;
  218845. if (shouldBeVisible)
  218846. XMapWindow (display, windowH);
  218847. else
  218848. XUnmapWindow (display, windowH);
  218849. }
  218850. void setTitle (const String& title)
  218851. {
  218852. setWindowTitle (windowH, title);
  218853. }
  218854. void setPosition (int x, int y)
  218855. {
  218856. setBounds (x, y, ww, wh, false);
  218857. }
  218858. void setSize (int w, int h)
  218859. {
  218860. setBounds (wx, wy, w, h, false);
  218861. }
  218862. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218863. {
  218864. fullScreen = isNowFullScreen;
  218865. if (windowH != 0)
  218866. {
  218867. Component::SafePointer<Component> deletionChecker (component);
  218868. wx = x;
  218869. wy = y;
  218870. ww = jmax (1, w);
  218871. wh = jmax (1, h);
  218872. ScopedXLock xlock;
  218873. // Make sure the Window manager does what we want
  218874. XSizeHints* hints = XAllocSizeHints();
  218875. hints->flags = USSize | USPosition;
  218876. hints->width = ww;
  218877. hints->height = wh;
  218878. hints->x = wx;
  218879. hints->y = wy;
  218880. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218881. {
  218882. hints->min_width = hints->max_width = hints->width;
  218883. hints->min_height = hints->max_height = hints->height;
  218884. hints->flags |= PMinSize | PMaxSize;
  218885. }
  218886. XSetWMNormalHints (display, windowH, hints);
  218887. XFree (hints);
  218888. XMoveResizeWindow (display, windowH,
  218889. wx - windowBorder.getLeft(),
  218890. wy - windowBorder.getTop(), ww, wh);
  218891. if (deletionChecker != 0)
  218892. {
  218893. updateBorderSize();
  218894. handleMovedOrResized();
  218895. }
  218896. }
  218897. }
  218898. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218899. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218900. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218901. {
  218902. return relativePosition + getScreenPosition();
  218903. }
  218904. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218905. {
  218906. return screenPosition - getScreenPosition();
  218907. }
  218908. void setMinimised (bool shouldBeMinimised)
  218909. {
  218910. if (shouldBeMinimised)
  218911. {
  218912. Window root = RootWindow (display, DefaultScreen (display));
  218913. XClientMessageEvent clientMsg;
  218914. clientMsg.display = display;
  218915. clientMsg.window = windowH;
  218916. clientMsg.type = ClientMessage;
  218917. clientMsg.format = 32;
  218918. clientMsg.message_type = Atoms::ChangeState;
  218919. clientMsg.data.l[0] = IconicState;
  218920. ScopedXLock xlock;
  218921. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218922. }
  218923. else
  218924. {
  218925. setVisible (true);
  218926. }
  218927. }
  218928. bool isMinimised() const
  218929. {
  218930. bool minimised = false;
  218931. unsigned char* stateProp;
  218932. unsigned long nitems, bytesLeft;
  218933. Atom actualType;
  218934. int actualFormat;
  218935. ScopedXLock xlock;
  218936. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218937. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218938. &stateProp) == Success
  218939. && actualType == Atoms::State
  218940. && actualFormat == 32
  218941. && nitems > 0)
  218942. {
  218943. if (((unsigned long*) stateProp)[0] == IconicState)
  218944. minimised = true;
  218945. XFree (stateProp);
  218946. }
  218947. return minimised;
  218948. }
  218949. void setFullScreen (const bool shouldBeFullScreen)
  218950. {
  218951. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218952. setMinimised (false);
  218953. if (fullScreen != shouldBeFullScreen)
  218954. {
  218955. if (shouldBeFullScreen)
  218956. r = Desktop::getInstance().getMainMonitorArea();
  218957. if (! r.isEmpty())
  218958. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218959. getComponent()->repaint();
  218960. }
  218961. }
  218962. bool isFullScreen() const
  218963. {
  218964. return fullScreen;
  218965. }
  218966. bool isChildWindowOf (Window possibleParent) const
  218967. {
  218968. Window* windowList = 0;
  218969. uint32 windowListSize = 0;
  218970. Window parent, root;
  218971. ScopedXLock xlock;
  218972. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218973. {
  218974. if (windowList != 0)
  218975. XFree (windowList);
  218976. return parent == possibleParent;
  218977. }
  218978. return false;
  218979. }
  218980. bool isFrontWindow() const
  218981. {
  218982. Window* windowList = 0;
  218983. uint32 windowListSize = 0;
  218984. bool result = false;
  218985. ScopedXLock xlock;
  218986. Window parent, root = RootWindow (display, DefaultScreen (display));
  218987. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  218988. {
  218989. for (int i = windowListSize; --i >= 0;)
  218990. {
  218991. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  218992. if (peer != 0)
  218993. {
  218994. result = (peer == this);
  218995. break;
  218996. }
  218997. }
  218998. }
  218999. if (windowList != 0)
  219000. XFree (windowList);
  219001. return result;
  219002. }
  219003. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219004. {
  219005. int x = position.getX();
  219006. int y = position.getY();
  219007. if (((unsigned int) x) >= (unsigned int) ww
  219008. || ((unsigned int) y) >= (unsigned int) wh)
  219009. return false;
  219010. bool inFront = false;
  219011. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  219012. {
  219013. Component* const c = Desktop::getInstance().getComponent (i);
  219014. if (inFront)
  219015. {
  219016. if (c->contains (x + wx - c->getScreenX(),
  219017. y + wy - c->getScreenY()))
  219018. {
  219019. return false;
  219020. }
  219021. }
  219022. else if (c == getComponent())
  219023. {
  219024. inFront = true;
  219025. }
  219026. }
  219027. if (trueIfInAChildWindow)
  219028. return true;
  219029. ::Window root, child;
  219030. unsigned int bw, depth;
  219031. int wx, wy, w, h;
  219032. ScopedXLock xlock;
  219033. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219034. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219035. &bw, &depth))
  219036. {
  219037. return false;
  219038. }
  219039. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  219040. return false;
  219041. return child == None;
  219042. }
  219043. const BorderSize getFrameSize() const
  219044. {
  219045. return BorderSize();
  219046. }
  219047. bool setAlwaysOnTop (bool alwaysOnTop)
  219048. {
  219049. return false;
  219050. }
  219051. void toFront (bool makeActive)
  219052. {
  219053. if (makeActive)
  219054. {
  219055. setVisible (true);
  219056. grabFocus();
  219057. }
  219058. XEvent ev;
  219059. ev.xclient.type = ClientMessage;
  219060. ev.xclient.serial = 0;
  219061. ev.xclient.send_event = True;
  219062. ev.xclient.message_type = Atoms::ActiveWin;
  219063. ev.xclient.window = windowH;
  219064. ev.xclient.format = 32;
  219065. ev.xclient.data.l[0] = 2;
  219066. ev.xclient.data.l[1] = CurrentTime;
  219067. ev.xclient.data.l[2] = 0;
  219068. ev.xclient.data.l[3] = 0;
  219069. ev.xclient.data.l[4] = 0;
  219070. {
  219071. ScopedXLock xlock;
  219072. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219073. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219074. XWindowAttributes attr;
  219075. XGetWindowAttributes (display, windowH, &attr);
  219076. if (component->isAlwaysOnTop())
  219077. XRaiseWindow (display, windowH);
  219078. XSync (display, False);
  219079. }
  219080. handleBroughtToFront();
  219081. }
  219082. void toBehind (ComponentPeer* other)
  219083. {
  219084. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219085. jassert (otherPeer != 0); // wrong type of window?
  219086. if (otherPeer != 0)
  219087. {
  219088. setMinimised (false);
  219089. Window newStack[] = { otherPeer->windowH, windowH };
  219090. ScopedXLock xlock;
  219091. XRestackWindows (display, newStack, 2);
  219092. }
  219093. }
  219094. bool isFocused() const
  219095. {
  219096. int revert = 0;
  219097. Window focusedWindow = 0;
  219098. ScopedXLock xlock;
  219099. XGetInputFocus (display, &focusedWindow, &revert);
  219100. return focusedWindow == windowH;
  219101. }
  219102. void grabFocus()
  219103. {
  219104. XWindowAttributes atts;
  219105. ScopedXLock xlock;
  219106. if (windowH != 0
  219107. && XGetWindowAttributes (display, windowH, &atts)
  219108. && atts.map_state == IsViewable
  219109. && ! isFocused())
  219110. {
  219111. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219112. isActiveApplication = true;
  219113. }
  219114. }
  219115. void textInputRequired (const Point<int>&)
  219116. {
  219117. }
  219118. void repaint (const Rectangle<int>& area)
  219119. {
  219120. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219121. }
  219122. void performAnyPendingRepaintsNow()
  219123. {
  219124. repainter->performAnyPendingRepaintsNow();
  219125. }
  219126. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  219127. {
  219128. ScopedXLock xlock;
  219129. const int width = image.getWidth();
  219130. const int height = image.getHeight();
  219131. HeapBlock <char> colour (width * height);
  219132. int index = 0;
  219133. for (int y = 0; y < height; ++y)
  219134. for (int x = 0; x < width; ++x)
  219135. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  219136. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219137. 0, colour.getData(),
  219138. width, height, 32, 0);
  219139. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219140. width, height, 24);
  219141. GC gc = XCreateGC (display, pixmap, 0, 0);
  219142. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219143. XFreeGC (display, gc);
  219144. return pixmap;
  219145. }
  219146. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  219147. {
  219148. ScopedXLock xlock;
  219149. const int width = image.getWidth();
  219150. const int height = image.getHeight();
  219151. const int stride = (width + 7) >> 3;
  219152. HeapBlock <char> mask;
  219153. mask.calloc (stride * height);
  219154. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219155. for (int y = 0; y < height; ++y)
  219156. {
  219157. for (int x = 0; x < width; ++x)
  219158. {
  219159. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219160. const int offset = y * stride + (x >> 3);
  219161. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219162. mask[offset] |= bit;
  219163. }
  219164. }
  219165. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219166. mask.getData(), width, height, 1, 0, 1);
  219167. }
  219168. void setIcon (const Image& newIcon)
  219169. {
  219170. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219171. HeapBlock <unsigned long> data (dataSize);
  219172. int index = 0;
  219173. data[index++] = newIcon.getWidth();
  219174. data[index++] = newIcon.getHeight();
  219175. for (int y = 0; y < newIcon.getHeight(); ++y)
  219176. for (int x = 0; x < newIcon.getWidth(); ++x)
  219177. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219178. ScopedXLock xlock;
  219179. XChangeProperty (display, windowH,
  219180. XInternAtom (display, "_NET_WM_ICON", False),
  219181. XA_CARDINAL, 32, PropModeReplace,
  219182. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219183. deleteIconPixmaps();
  219184. XWMHints* wmHints = XGetWMHints (display, windowH);
  219185. if (wmHints == 0)
  219186. wmHints = XAllocWMHints();
  219187. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219188. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  219189. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  219190. XSetWMHints (display, windowH, wmHints);
  219191. XFree (wmHints);
  219192. XSync (display, False);
  219193. }
  219194. void deleteIconPixmaps()
  219195. {
  219196. ScopedXLock xlock;
  219197. XWMHints* wmHints = XGetWMHints (display, windowH);
  219198. if (wmHints != 0)
  219199. {
  219200. if ((wmHints->flags & IconPixmapHint) != 0)
  219201. {
  219202. wmHints->flags &= ~IconPixmapHint;
  219203. XFreePixmap (display, wmHints->icon_pixmap);
  219204. }
  219205. if ((wmHints->flags & IconMaskHint) != 0)
  219206. {
  219207. wmHints->flags &= ~IconMaskHint;
  219208. XFreePixmap (display, wmHints->icon_mask);
  219209. }
  219210. XSetWMHints (display, windowH, wmHints);
  219211. XFree (wmHints);
  219212. }
  219213. }
  219214. void handleWindowMessage (XEvent* event)
  219215. {
  219216. switch (event->xany.type)
  219217. {
  219218. case 2: // 'KeyPress'
  219219. {
  219220. ScopedXLock xlock;
  219221. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  219222. updateKeyStates (keyEvent->keycode, true);
  219223. char utf8 [64];
  219224. zeromem (utf8, sizeof (utf8));
  219225. KeySym sym;
  219226. {
  219227. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219228. ::setlocale (LC_ALL, "");
  219229. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219230. ::setlocale (LC_ALL, oldLocale);
  219231. }
  219232. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219233. int keyCode = (int) unicodeChar;
  219234. if (keyCode < 0x20)
  219235. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219236. const ModifierKeys oldMods (currentModifiers);
  219237. bool keyPressed = false;
  219238. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219239. if ((sym & 0xff00) == 0xff00)
  219240. {
  219241. // Translate keypad
  219242. if (sym == XK_KP_Divide)
  219243. keyCode = XK_slash;
  219244. else if (sym == XK_KP_Multiply)
  219245. keyCode = XK_asterisk;
  219246. else if (sym == XK_KP_Subtract)
  219247. keyCode = XK_hyphen;
  219248. else if (sym == XK_KP_Add)
  219249. keyCode = XK_plus;
  219250. else if (sym == XK_KP_Enter)
  219251. keyCode = XK_Return;
  219252. else if (sym == XK_KP_Decimal)
  219253. keyCode = Keys::numLock ? XK_period : XK_Delete;
  219254. else if (sym == XK_KP_0)
  219255. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  219256. else if (sym == XK_KP_1)
  219257. keyCode = Keys::numLock ? XK_1 : XK_End;
  219258. else if (sym == XK_KP_2)
  219259. keyCode = Keys::numLock ? XK_2 : XK_Down;
  219260. else if (sym == XK_KP_3)
  219261. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  219262. else if (sym == XK_KP_4)
  219263. keyCode = Keys::numLock ? XK_4 : XK_Left;
  219264. else if (sym == XK_KP_5)
  219265. keyCode = XK_5;
  219266. else if (sym == XK_KP_6)
  219267. keyCode = Keys::numLock ? XK_6 : XK_Right;
  219268. else if (sym == XK_KP_7)
  219269. keyCode = Keys::numLock ? XK_7 : XK_Home;
  219270. else if (sym == XK_KP_8)
  219271. keyCode = Keys::numLock ? XK_8 : XK_Up;
  219272. else if (sym == XK_KP_9)
  219273. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  219274. switch (sym)
  219275. {
  219276. case XK_Left:
  219277. case XK_Right:
  219278. case XK_Up:
  219279. case XK_Down:
  219280. case XK_Page_Up:
  219281. case XK_Page_Down:
  219282. case XK_End:
  219283. case XK_Home:
  219284. case XK_Delete:
  219285. case XK_Insert:
  219286. keyPressed = true;
  219287. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219288. break;
  219289. case XK_Tab:
  219290. case XK_Return:
  219291. case XK_Escape:
  219292. case XK_BackSpace:
  219293. keyPressed = true;
  219294. keyCode &= 0xff;
  219295. break;
  219296. default:
  219297. {
  219298. if (sym >= XK_F1 && sym <= XK_F16)
  219299. {
  219300. keyPressed = true;
  219301. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219302. }
  219303. break;
  219304. }
  219305. }
  219306. }
  219307. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219308. keyPressed = true;
  219309. if (oldMods != currentModifiers)
  219310. handleModifierKeysChange();
  219311. if (keyDownChange)
  219312. handleKeyUpOrDown (true);
  219313. if (keyPressed)
  219314. handleKeyPress (keyCode, unicodeChar);
  219315. break;
  219316. }
  219317. case KeyRelease:
  219318. {
  219319. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  219320. updateKeyStates (keyEvent->keycode, false);
  219321. ScopedXLock xlock;
  219322. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219323. const ModifierKeys oldMods (currentModifiers);
  219324. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219325. if (oldMods != currentModifiers)
  219326. handleModifierKeysChange();
  219327. if (keyDownChange)
  219328. handleKeyUpOrDown (false);
  219329. break;
  219330. }
  219331. case ButtonPress:
  219332. {
  219333. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  219334. updateKeyModifiers (buttonPressEvent->state);
  219335. bool buttonMsg = false;
  219336. const int map = pointerMap [buttonPressEvent->button - Button1];
  219337. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219338. {
  219339. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219340. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219341. }
  219342. if (map == Keys::LeftButton)
  219343. {
  219344. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219345. buttonMsg = true;
  219346. }
  219347. else if (map == Keys::RightButton)
  219348. {
  219349. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219350. buttonMsg = true;
  219351. }
  219352. else if (map == Keys::MiddleButton)
  219353. {
  219354. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219355. buttonMsg = true;
  219356. }
  219357. if (buttonMsg)
  219358. {
  219359. toFront (true);
  219360. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219361. getEventTime (buttonPressEvent->time));
  219362. }
  219363. clearLastMousePos();
  219364. break;
  219365. }
  219366. case ButtonRelease:
  219367. {
  219368. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  219369. updateKeyModifiers (buttonRelEvent->state);
  219370. const int map = pointerMap [buttonRelEvent->button - Button1];
  219371. if (map == Keys::LeftButton)
  219372. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219373. else if (map == Keys::RightButton)
  219374. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219375. else if (map == Keys::MiddleButton)
  219376. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219377. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219378. getEventTime (buttonRelEvent->time));
  219379. clearLastMousePos();
  219380. break;
  219381. }
  219382. case MotionNotify:
  219383. {
  219384. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  219385. updateKeyModifiers (movedEvent->state);
  219386. const Point<int> mousePos (Desktop::getMousePosition());
  219387. if (lastMousePos != mousePos)
  219388. {
  219389. lastMousePos = mousePos;
  219390. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219391. {
  219392. Window wRoot = 0, wParent = 0;
  219393. {
  219394. ScopedXLock xlock;
  219395. unsigned int numChildren;
  219396. Window* wChild = 0;
  219397. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219398. }
  219399. if (wParent != 0
  219400. && wParent != windowH
  219401. && wParent != wRoot)
  219402. {
  219403. parentWindow = wParent;
  219404. updateBounds();
  219405. }
  219406. else
  219407. {
  219408. parentWindow = 0;
  219409. }
  219410. }
  219411. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219412. }
  219413. break;
  219414. }
  219415. case EnterNotify:
  219416. {
  219417. clearLastMousePos();
  219418. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219419. if (! currentModifiers.isAnyMouseButtonDown())
  219420. {
  219421. updateKeyModifiers (enterEvent->state);
  219422. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219423. }
  219424. break;
  219425. }
  219426. case LeaveNotify:
  219427. {
  219428. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219429. // Suppress the normal leave if we've got a pointer grab, or if
  219430. // it's a bogus one caused by clicking a mouse button when running
  219431. // in a Window manager
  219432. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219433. || leaveEvent->mode == NotifyUngrab)
  219434. {
  219435. updateKeyModifiers (leaveEvent->state);
  219436. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219437. }
  219438. break;
  219439. }
  219440. case FocusIn:
  219441. {
  219442. isActiveApplication = true;
  219443. if (isFocused())
  219444. handleFocusGain();
  219445. break;
  219446. }
  219447. case FocusOut:
  219448. {
  219449. isActiveApplication = false;
  219450. if (! isFocused())
  219451. handleFocusLoss();
  219452. break;
  219453. }
  219454. case Expose:
  219455. {
  219456. // Batch together all pending expose events
  219457. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219458. XEvent nextEvent;
  219459. ScopedXLock xlock;
  219460. if (exposeEvent->window != windowH)
  219461. {
  219462. Window child;
  219463. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219464. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219465. &child);
  219466. }
  219467. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219468. exposeEvent->width, exposeEvent->height));
  219469. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219470. {
  219471. XPeekEvent (display, (XEvent*) &nextEvent);
  219472. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219473. break;
  219474. XNextEvent (display, (XEvent*) &nextEvent);
  219475. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219476. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219477. nextExposeEvent->width, nextExposeEvent->height));
  219478. }
  219479. break;
  219480. }
  219481. case CirculateNotify:
  219482. case CreateNotify:
  219483. case DestroyNotify:
  219484. // Think we can ignore these
  219485. break;
  219486. case ConfigureNotify:
  219487. {
  219488. updateBounds();
  219489. updateBorderSize();
  219490. handleMovedOrResized();
  219491. // if the native title bar is dragged, need to tell any active menus, etc.
  219492. if ((styleFlags & windowHasTitleBar) != 0
  219493. && component->isCurrentlyBlockedByAnotherModalComponent())
  219494. {
  219495. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219496. if (currentModalComp != 0)
  219497. currentModalComp->inputAttemptWhenModal();
  219498. }
  219499. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219500. if (confEvent->window == windowH
  219501. && confEvent->above != 0
  219502. && isFrontWindow())
  219503. {
  219504. handleBroughtToFront();
  219505. }
  219506. break;
  219507. }
  219508. case ReparentNotify:
  219509. {
  219510. parentWindow = 0;
  219511. Window wRoot = 0;
  219512. Window* wChild = 0;
  219513. unsigned int numChildren;
  219514. {
  219515. ScopedXLock xlock;
  219516. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219517. }
  219518. if (parentWindow == windowH || parentWindow == wRoot)
  219519. parentWindow = 0;
  219520. updateBounds();
  219521. updateBorderSize();
  219522. handleMovedOrResized();
  219523. break;
  219524. }
  219525. case GravityNotify:
  219526. {
  219527. updateBounds();
  219528. updateBorderSize();
  219529. handleMovedOrResized();
  219530. break;
  219531. }
  219532. case MapNotify:
  219533. mapped = true;
  219534. handleBroughtToFront();
  219535. break;
  219536. case UnmapNotify:
  219537. mapped = false;
  219538. break;
  219539. case MappingNotify:
  219540. {
  219541. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219542. if (mappingEvent->request != MappingPointer)
  219543. {
  219544. // Deal with modifier/keyboard mapping
  219545. ScopedXLock xlock;
  219546. XRefreshKeyboardMapping (mappingEvent);
  219547. updateModifierMappings();
  219548. }
  219549. break;
  219550. }
  219551. case ClientMessage:
  219552. {
  219553. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219554. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219555. {
  219556. const Atom atom = (Atom) clientMsg->data.l[0];
  219557. if (atom == Atoms::ProtocolList [Atoms::PING])
  219558. {
  219559. Window root = RootWindow (display, DefaultScreen (display));
  219560. event->xclient.window = root;
  219561. XSendEvent (display, root, False, NoEventMask, event);
  219562. XFlush (display);
  219563. }
  219564. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219565. {
  219566. XWindowAttributes atts;
  219567. ScopedXLock xlock;
  219568. if (clientMsg->window != 0
  219569. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219570. {
  219571. if (atts.map_state == IsViewable)
  219572. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219573. }
  219574. }
  219575. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219576. {
  219577. handleUserClosingWindow();
  219578. }
  219579. }
  219580. else if (clientMsg->message_type == Atoms::XdndEnter)
  219581. {
  219582. handleDragAndDropEnter (clientMsg);
  219583. }
  219584. else if (clientMsg->message_type == Atoms::XdndLeave)
  219585. {
  219586. resetDragAndDrop();
  219587. }
  219588. else if (clientMsg->message_type == Atoms::XdndPosition)
  219589. {
  219590. handleDragAndDropPosition (clientMsg);
  219591. }
  219592. else if (clientMsg->message_type == Atoms::XdndDrop)
  219593. {
  219594. handleDragAndDropDrop (clientMsg);
  219595. }
  219596. else if (clientMsg->message_type == Atoms::XdndStatus)
  219597. {
  219598. handleDragAndDropStatus (clientMsg);
  219599. }
  219600. else if (clientMsg->message_type == Atoms::XdndFinished)
  219601. {
  219602. resetDragAndDrop();
  219603. }
  219604. break;
  219605. }
  219606. case SelectionNotify:
  219607. handleDragAndDropSelection (event);
  219608. break;
  219609. case SelectionClear:
  219610. case SelectionRequest:
  219611. break;
  219612. default:
  219613. #if JUCE_USE_XSHM
  219614. {
  219615. ScopedXLock xlock;
  219616. if (event->xany.type == XShmGetEventBase (display))
  219617. repainter->notifyPaintCompleted();
  219618. }
  219619. #endif
  219620. break;
  219621. }
  219622. }
  219623. void showMouseCursor (Cursor cursor) throw()
  219624. {
  219625. ScopedXLock xlock;
  219626. XDefineCursor (display, windowH, cursor);
  219627. }
  219628. void setTaskBarIcon (const Image& image)
  219629. {
  219630. ScopedXLock xlock;
  219631. taskbarImage = image;
  219632. Screen* const screen = XDefaultScreenOfDisplay (display);
  219633. const int screenNumber = XScreenNumberOfScreen (screen);
  219634. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219635. screenAtom << screenNumber;
  219636. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219637. XGrabServer (display);
  219638. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219639. if (managerWin != None)
  219640. XSelectInput (display, managerWin, StructureNotifyMask);
  219641. XUngrabServer (display);
  219642. XFlush (display);
  219643. if (managerWin != None)
  219644. {
  219645. XEvent ev;
  219646. zerostruct (ev);
  219647. ev.xclient.type = ClientMessage;
  219648. ev.xclient.window = managerWin;
  219649. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219650. ev.xclient.format = 32;
  219651. ev.xclient.data.l[0] = CurrentTime;
  219652. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219653. ev.xclient.data.l[2] = windowH;
  219654. ev.xclient.data.l[3] = 0;
  219655. ev.xclient.data.l[4] = 0;
  219656. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219657. XSync (display, False);
  219658. }
  219659. // For older KDE's ...
  219660. long atomData = 1;
  219661. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219662. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219663. // For more recent KDE's...
  219664. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219665. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219666. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219667. XSizeHints* hints = XAllocSizeHints();
  219668. hints->flags = PMinSize;
  219669. hints->min_width = 22;
  219670. hints->min_height = 22;
  219671. XSetWMNormalHints (display, windowH, hints);
  219672. XFree (hints);
  219673. }
  219674. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219675. juce_UseDebuggingNewOperator
  219676. bool dontRepaint;
  219677. static ModifierKeys currentModifiers;
  219678. static bool isActiveApplication;
  219679. private:
  219680. class LinuxRepaintManager : public Timer
  219681. {
  219682. public:
  219683. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219684. : peer (peer_),
  219685. lastTimeImageUsed (0)
  219686. {
  219687. #if JUCE_USE_XSHM
  219688. shmCompletedDrawing = true;
  219689. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219690. if (useARGBImagesForRendering)
  219691. {
  219692. ScopedXLock xlock;
  219693. XShmSegmentInfo segmentinfo;
  219694. XImage* const testImage
  219695. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219696. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219697. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219698. XDestroyImage (testImage);
  219699. }
  219700. #endif
  219701. }
  219702. ~LinuxRepaintManager()
  219703. {
  219704. }
  219705. void timerCallback()
  219706. {
  219707. #if JUCE_USE_XSHM
  219708. if (! shmCompletedDrawing)
  219709. return;
  219710. #endif
  219711. if (! regionsNeedingRepaint.isEmpty())
  219712. {
  219713. stopTimer();
  219714. performAnyPendingRepaintsNow();
  219715. }
  219716. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219717. {
  219718. stopTimer();
  219719. image = Image::null;
  219720. }
  219721. }
  219722. void repaint (const Rectangle<int>& area)
  219723. {
  219724. if (! isTimerRunning())
  219725. startTimer (repaintTimerPeriod);
  219726. regionsNeedingRepaint.add (area);
  219727. }
  219728. void performAnyPendingRepaintsNow()
  219729. {
  219730. #if JUCE_USE_XSHM
  219731. if (! shmCompletedDrawing)
  219732. {
  219733. startTimer (repaintTimerPeriod);
  219734. return;
  219735. }
  219736. #endif
  219737. peer->clearMaskedRegion();
  219738. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219739. regionsNeedingRepaint.clear();
  219740. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219741. if (! totalArea.isEmpty())
  219742. {
  219743. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219744. || image.getHeight() < totalArea.getHeight())
  219745. {
  219746. #if JUCE_USE_XSHM
  219747. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219748. : Image::RGB,
  219749. #else
  219750. image = Image (new XBitmapImage (Image::RGB,
  219751. #endif
  219752. (totalArea.getWidth() + 31) & ~31,
  219753. (totalArea.getHeight() + 31) & ~31,
  219754. false, peer->depth, peer->visual));
  219755. }
  219756. startTimer (repaintTimerPeriod);
  219757. RectangleList adjustedList (originalRepaintRegion);
  219758. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219759. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219760. if (peer->depth == 32)
  219761. {
  219762. RectangleList::Iterator i (originalRepaintRegion);
  219763. while (i.next())
  219764. image.clear (*i.getRectangle() - totalArea.getPosition());
  219765. }
  219766. peer->handlePaint (context);
  219767. if (! peer->maskedRegion.isEmpty())
  219768. originalRepaintRegion.subtract (peer->maskedRegion);
  219769. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219770. {
  219771. #if JUCE_USE_XSHM
  219772. shmCompletedDrawing = false;
  219773. #endif
  219774. const Rectangle<int>& r = *i.getRectangle();
  219775. static_cast<XBitmapImage*> (image.getSharedImage())
  219776. ->blitToWindow (peer->windowH,
  219777. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219778. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219779. }
  219780. }
  219781. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219782. startTimer (repaintTimerPeriod);
  219783. }
  219784. #if JUCE_USE_XSHM
  219785. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219786. #endif
  219787. private:
  219788. enum { repaintTimerPeriod = 1000 / 100 };
  219789. LinuxComponentPeer* const peer;
  219790. Image image;
  219791. uint32 lastTimeImageUsed;
  219792. RectangleList regionsNeedingRepaint;
  219793. #if JUCE_USE_XSHM
  219794. bool useARGBImagesForRendering, shmCompletedDrawing;
  219795. #endif
  219796. LinuxRepaintManager (const LinuxRepaintManager&);
  219797. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219798. };
  219799. ScopedPointer <LinuxRepaintManager> repainter;
  219800. friend class LinuxRepaintManager;
  219801. Window windowH, parentWindow;
  219802. int wx, wy, ww, wh;
  219803. Image taskbarImage;
  219804. bool fullScreen, mapped;
  219805. Visual* visual;
  219806. int depth;
  219807. BorderSize windowBorder;
  219808. struct MotifWmHints
  219809. {
  219810. unsigned long flags;
  219811. unsigned long functions;
  219812. unsigned long decorations;
  219813. long input_mode;
  219814. unsigned long status;
  219815. };
  219816. static void updateKeyStates (const int keycode, const bool press) throw()
  219817. {
  219818. const int keybyte = keycode >> 3;
  219819. const int keybit = (1 << (keycode & 7));
  219820. if (press)
  219821. Keys::keyStates [keybyte] |= keybit;
  219822. else
  219823. Keys::keyStates [keybyte] &= ~keybit;
  219824. }
  219825. static void updateKeyModifiers (const int status) throw()
  219826. {
  219827. int keyMods = 0;
  219828. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219829. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219830. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219831. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219832. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219833. Keys::capsLock = ((status & LockMask) != 0);
  219834. }
  219835. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219836. {
  219837. int modifier = 0;
  219838. bool isModifier = true;
  219839. switch (sym)
  219840. {
  219841. case XK_Shift_L:
  219842. case XK_Shift_R:
  219843. modifier = ModifierKeys::shiftModifier;
  219844. break;
  219845. case XK_Control_L:
  219846. case XK_Control_R:
  219847. modifier = ModifierKeys::ctrlModifier;
  219848. break;
  219849. case XK_Alt_L:
  219850. case XK_Alt_R:
  219851. modifier = ModifierKeys::altModifier;
  219852. break;
  219853. case XK_Num_Lock:
  219854. if (press)
  219855. Keys::numLock = ! Keys::numLock;
  219856. break;
  219857. case XK_Caps_Lock:
  219858. if (press)
  219859. Keys::capsLock = ! Keys::capsLock;
  219860. break;
  219861. case XK_Scroll_Lock:
  219862. break;
  219863. default:
  219864. isModifier = false;
  219865. break;
  219866. }
  219867. if (modifier != 0)
  219868. {
  219869. if (press)
  219870. currentModifiers = currentModifiers.withFlags (modifier);
  219871. else
  219872. currentModifiers = currentModifiers.withoutFlags (modifier);
  219873. }
  219874. return isModifier;
  219875. }
  219876. // Alt and Num lock are not defined by standard X
  219877. // modifier constants: check what they're mapped to
  219878. static void updateModifierMappings() throw()
  219879. {
  219880. ScopedXLock xlock;
  219881. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219882. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219883. Keys::AltMask = 0;
  219884. Keys::NumLockMask = 0;
  219885. XModifierKeymap* mapping = XGetModifierMapping (display);
  219886. if (mapping)
  219887. {
  219888. for (int i = 0; i < 8; i++)
  219889. {
  219890. if (mapping->modifiermap [i << 1] == altLeftCode)
  219891. Keys::AltMask = 1 << i;
  219892. else if (mapping->modifiermap [i << 1] == numLockCode)
  219893. Keys::NumLockMask = 1 << i;
  219894. }
  219895. XFreeModifiermap (mapping);
  219896. }
  219897. }
  219898. void removeWindowDecorations (Window wndH)
  219899. {
  219900. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219901. if (hints != None)
  219902. {
  219903. MotifWmHints motifHints;
  219904. zerostruct (motifHints);
  219905. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219906. motifHints.decorations = 0;
  219907. ScopedXLock xlock;
  219908. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219909. (unsigned char*) &motifHints, 4);
  219910. }
  219911. hints = XInternAtom (display, "_WIN_HINTS", True);
  219912. if (hints != None)
  219913. {
  219914. long gnomeHints = 0;
  219915. ScopedXLock xlock;
  219916. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219917. (unsigned char*) &gnomeHints, 1);
  219918. }
  219919. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219920. if (hints != None)
  219921. {
  219922. long kwmHints = 2; /*KDE_tinyDecoration*/
  219923. ScopedXLock xlock;
  219924. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219925. (unsigned char*) &kwmHints, 1);
  219926. }
  219927. }
  219928. void addWindowButtons (Window wndH)
  219929. {
  219930. ScopedXLock xlock;
  219931. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219932. if (hints != None)
  219933. {
  219934. MotifWmHints motifHints;
  219935. zerostruct (motifHints);
  219936. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219937. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219938. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219939. if ((styleFlags & windowHasCloseButton) != 0)
  219940. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219941. if ((styleFlags & windowHasMinimiseButton) != 0)
  219942. {
  219943. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219944. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219945. }
  219946. if ((styleFlags & windowHasMaximiseButton) != 0)
  219947. {
  219948. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219949. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219950. }
  219951. if ((styleFlags & windowIsResizable) != 0)
  219952. {
  219953. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219954. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219955. }
  219956. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219957. }
  219958. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219959. if (hints != None)
  219960. {
  219961. int netHints [6];
  219962. int num = 0;
  219963. if ((styleFlags & windowIsResizable) != 0)
  219964. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219965. if ((styleFlags & windowHasMaximiseButton) != 0)
  219966. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219967. if ((styleFlags & windowHasMinimiseButton) != 0)
  219968. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219969. if ((styleFlags & windowHasCloseButton) != 0)
  219970. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219971. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219972. }
  219973. }
  219974. void setWindowType()
  219975. {
  219976. int netHints [2];
  219977. int numHints = 0;
  219978. if ((styleFlags & windowIsTemporary) != 0
  219979. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219980. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219981. else
  219982. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219983. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219984. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  219985. (unsigned char*) &netHints, numHints);
  219986. numHints = 0;
  219987. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  219988. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  219989. if (component->isAlwaysOnTop())
  219990. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  219991. if (numHints > 0)
  219992. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  219993. (unsigned char*) &netHints, numHints);
  219994. }
  219995. void createWindow()
  219996. {
  219997. ScopedXLock xlock;
  219998. Atoms::initialiseAtoms();
  219999. resetDragAndDrop();
  220000. // Get defaults for various properties
  220001. const int screen = DefaultScreen (display);
  220002. Window root = RootWindow (display, screen);
  220003. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220004. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220005. if (visual == 0)
  220006. {
  220007. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220008. Process::terminate();
  220009. }
  220010. // Create and install a colormap suitable fr our visual
  220011. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220012. XInstallColormap (display, colormap);
  220013. // Set up the window attributes
  220014. XSetWindowAttributes swa;
  220015. swa.border_pixel = 0;
  220016. swa.background_pixmap = None;
  220017. swa.colormap = colormap;
  220018. swa.event_mask = getAllEventsMask();
  220019. windowH = XCreateWindow (display, root,
  220020. 0, 0, 1, 1,
  220021. 0, depth, InputOutput, visual,
  220022. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220023. &swa);
  220024. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220025. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220026. GrabModeAsync, GrabModeAsync, None, None);
  220027. // Set the window context to identify the window handle object
  220028. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220029. {
  220030. // Failed
  220031. jassertfalse;
  220032. Logger::outputDebugString ("Failed to create context information for window.\n");
  220033. XDestroyWindow (display, windowH);
  220034. windowH = 0;
  220035. return;
  220036. }
  220037. // Set window manager hints
  220038. XWMHints* wmHints = XAllocWMHints();
  220039. wmHints->flags = InputHint | StateHint;
  220040. wmHints->input = True; // Locally active input model
  220041. wmHints->initial_state = NormalState;
  220042. XSetWMHints (display, windowH, wmHints);
  220043. XFree (wmHints);
  220044. // Set the window type
  220045. setWindowType();
  220046. // Define decoration
  220047. if ((styleFlags & windowHasTitleBar) == 0)
  220048. removeWindowDecorations (windowH);
  220049. else
  220050. addWindowButtons (windowH);
  220051. // Set window name
  220052. setWindowTitle (windowH, getComponent()->getName());
  220053. // Associate the PID, allowing to be shut down when something goes wrong
  220054. unsigned long pid = getpid();
  220055. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220056. (unsigned char*) &pid, 1);
  220057. // Set window manager protocols
  220058. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220059. (unsigned char*) Atoms::ProtocolList, 2);
  220060. // Set drag and drop flags
  220061. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220062. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220063. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220064. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220065. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220066. (const unsigned char*) "", 0);
  220067. unsigned long dndVersion = Atoms::DndVersion;
  220068. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220069. (const unsigned char*) &dndVersion, 1);
  220070. // Initialise the pointer and keyboard mapping
  220071. // This is not the same as the logical pointer mapping the X server uses:
  220072. // we don't mess with this.
  220073. static bool mappingInitialised = false;
  220074. if (! mappingInitialised)
  220075. {
  220076. mappingInitialised = true;
  220077. const int numButtons = XGetPointerMapping (display, 0, 0);
  220078. if (numButtons == 2)
  220079. {
  220080. pointerMap[0] = Keys::LeftButton;
  220081. pointerMap[1] = Keys::RightButton;
  220082. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220083. }
  220084. else if (numButtons >= 3)
  220085. {
  220086. pointerMap[0] = Keys::LeftButton;
  220087. pointerMap[1] = Keys::MiddleButton;
  220088. pointerMap[2] = Keys::RightButton;
  220089. if (numButtons >= 5)
  220090. {
  220091. pointerMap[3] = Keys::WheelUp;
  220092. pointerMap[4] = Keys::WheelDown;
  220093. }
  220094. }
  220095. updateModifierMappings();
  220096. }
  220097. }
  220098. void destroyWindow()
  220099. {
  220100. ScopedXLock xlock;
  220101. XPointer handlePointer;
  220102. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220103. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220104. XDestroyWindow (display, windowH);
  220105. // Wait for it to complete and then remove any events for this
  220106. // window from the event queue.
  220107. XSync (display, false);
  220108. XEvent event;
  220109. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220110. {}
  220111. }
  220112. static int getAllEventsMask() throw()
  220113. {
  220114. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220115. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220116. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220117. }
  220118. static int64 getEventTime (::Time t)
  220119. {
  220120. static int64 eventTimeOffset = 0x12345678;
  220121. const int64 thisMessageTime = t;
  220122. if (eventTimeOffset == 0x12345678)
  220123. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220124. return eventTimeOffset + thisMessageTime;
  220125. }
  220126. static void setWindowTitle (Window xwin, const String& title)
  220127. {
  220128. XTextProperty nameProperty;
  220129. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  220130. ScopedXLock xlock;
  220131. if (XStringListToTextProperty (strings, 1, &nameProperty))
  220132. {
  220133. XSetWMName (display, xwin, &nameProperty);
  220134. XSetWMIconName (display, xwin, &nameProperty);
  220135. XFree (nameProperty.value);
  220136. }
  220137. }
  220138. void updateBorderSize()
  220139. {
  220140. if ((styleFlags & windowHasTitleBar) == 0)
  220141. {
  220142. windowBorder = BorderSize (0);
  220143. }
  220144. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220145. {
  220146. ScopedXLock xlock;
  220147. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220148. if (hints != None)
  220149. {
  220150. unsigned char* data = 0;
  220151. unsigned long nitems, bytesLeft;
  220152. Atom actualType;
  220153. int actualFormat;
  220154. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220155. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220156. &data) == Success)
  220157. {
  220158. const unsigned long* const sizes = (const unsigned long*) data;
  220159. if (actualFormat == 32)
  220160. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220161. (int) sizes[3], (int) sizes[1]);
  220162. XFree (data);
  220163. }
  220164. }
  220165. }
  220166. }
  220167. void updateBounds()
  220168. {
  220169. jassert (windowH != 0);
  220170. if (windowH != 0)
  220171. {
  220172. Window root, child;
  220173. unsigned int bw, depth;
  220174. ScopedXLock xlock;
  220175. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220176. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220177. &bw, &depth))
  220178. {
  220179. wx = wy = ww = wh = 0;
  220180. }
  220181. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220182. {
  220183. wx = wy = 0;
  220184. }
  220185. }
  220186. }
  220187. void resetDragAndDrop()
  220188. {
  220189. dragAndDropFiles.clear();
  220190. lastDropPos = Point<int> (-1, -1);
  220191. dragAndDropCurrentMimeType = 0;
  220192. dragAndDropSourceWindow = 0;
  220193. srcMimeTypeAtomList.clear();
  220194. }
  220195. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220196. {
  220197. msg.type = ClientMessage;
  220198. msg.display = display;
  220199. msg.window = dragAndDropSourceWindow;
  220200. msg.format = 32;
  220201. msg.data.l[0] = windowH;
  220202. ScopedXLock xlock;
  220203. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220204. }
  220205. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220206. {
  220207. XClientMessageEvent msg;
  220208. zerostruct (msg);
  220209. msg.message_type = Atoms::XdndStatus;
  220210. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220211. msg.data.l[4] = dropAction;
  220212. sendDragAndDropMessage (msg);
  220213. }
  220214. void sendDragAndDropLeave()
  220215. {
  220216. XClientMessageEvent msg;
  220217. zerostruct (msg);
  220218. msg.message_type = Atoms::XdndLeave;
  220219. sendDragAndDropMessage (msg);
  220220. }
  220221. void sendDragAndDropFinish()
  220222. {
  220223. XClientMessageEvent msg;
  220224. zerostruct (msg);
  220225. msg.message_type = Atoms::XdndFinished;
  220226. sendDragAndDropMessage (msg);
  220227. }
  220228. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220229. {
  220230. if ((clientMsg->data.l[1] & 1) == 0)
  220231. {
  220232. sendDragAndDropLeave();
  220233. if (dragAndDropFiles.size() > 0)
  220234. handleFileDragExit (dragAndDropFiles);
  220235. dragAndDropFiles.clear();
  220236. }
  220237. }
  220238. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220239. {
  220240. if (dragAndDropSourceWindow == 0)
  220241. return;
  220242. dragAndDropSourceWindow = clientMsg->data.l[0];
  220243. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220244. (int) clientMsg->data.l[2] & 0xffff);
  220245. dropPos -= getScreenPosition();
  220246. if (lastDropPos != dropPos)
  220247. {
  220248. lastDropPos = dropPos;
  220249. dragAndDropTimestamp = clientMsg->data.l[3];
  220250. Atom targetAction = Atoms::XdndActionCopy;
  220251. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220252. {
  220253. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220254. {
  220255. targetAction = Atoms::allowedActions[i];
  220256. break;
  220257. }
  220258. }
  220259. sendDragAndDropStatus (true, targetAction);
  220260. if (dragAndDropFiles.size() == 0)
  220261. updateDraggedFileList (clientMsg);
  220262. if (dragAndDropFiles.size() > 0)
  220263. handleFileDragMove (dragAndDropFiles, dropPos);
  220264. }
  220265. }
  220266. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220267. {
  220268. if (dragAndDropFiles.size() == 0)
  220269. updateDraggedFileList (clientMsg);
  220270. const StringArray files (dragAndDropFiles);
  220271. const Point<int> lastPos (lastDropPos);
  220272. sendDragAndDropFinish();
  220273. resetDragAndDrop();
  220274. if (files.size() > 0)
  220275. handleFileDragDrop (files, lastPos);
  220276. }
  220277. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220278. {
  220279. dragAndDropFiles.clear();
  220280. srcMimeTypeAtomList.clear();
  220281. dragAndDropCurrentMimeType = 0;
  220282. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220283. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220284. {
  220285. dragAndDropSourceWindow = 0;
  220286. return;
  220287. }
  220288. dragAndDropSourceWindow = clientMsg->data.l[0];
  220289. if ((clientMsg->data.l[1] & 1) != 0)
  220290. {
  220291. Atom actual;
  220292. int format;
  220293. unsigned long count = 0, remaining = 0;
  220294. unsigned char* data = 0;
  220295. ScopedXLock xlock;
  220296. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220297. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220298. &count, &remaining, &data);
  220299. if (data != 0)
  220300. {
  220301. if (actual == XA_ATOM && format == 32 && count != 0)
  220302. {
  220303. const unsigned long* const types = (const unsigned long*) data;
  220304. for (unsigned int i = 0; i < count; ++i)
  220305. if (types[i] != None)
  220306. srcMimeTypeAtomList.add (types[i]);
  220307. }
  220308. XFree (data);
  220309. }
  220310. }
  220311. if (srcMimeTypeAtomList.size() == 0)
  220312. {
  220313. for (int i = 2; i < 5; ++i)
  220314. if (clientMsg->data.l[i] != None)
  220315. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220316. if (srcMimeTypeAtomList.size() == 0)
  220317. {
  220318. dragAndDropSourceWindow = 0;
  220319. return;
  220320. }
  220321. }
  220322. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220323. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220324. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220325. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220326. handleDragAndDropPosition (clientMsg);
  220327. }
  220328. void handleDragAndDropSelection (const XEvent* const evt)
  220329. {
  220330. dragAndDropFiles.clear();
  220331. if (evt->xselection.property != 0)
  220332. {
  220333. StringArray lines;
  220334. {
  220335. MemoryBlock dropData;
  220336. for (;;)
  220337. {
  220338. Atom actual;
  220339. uint8* data = 0;
  220340. unsigned long count = 0, remaining = 0;
  220341. int format = 0;
  220342. ScopedXLock xlock;
  220343. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220344. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220345. &format, &count, &remaining, &data) == Success)
  220346. {
  220347. dropData.append (data, count * format / 8);
  220348. XFree (data);
  220349. if (remaining == 0)
  220350. break;
  220351. }
  220352. else
  220353. {
  220354. XFree (data);
  220355. break;
  220356. }
  220357. }
  220358. lines.addLines (dropData.toString());
  220359. }
  220360. for (int i = 0; i < lines.size(); ++i)
  220361. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220362. dragAndDropFiles.trim();
  220363. dragAndDropFiles.removeEmptyStrings();
  220364. }
  220365. }
  220366. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220367. {
  220368. dragAndDropFiles.clear();
  220369. if (dragAndDropSourceWindow != None
  220370. && dragAndDropCurrentMimeType != 0)
  220371. {
  220372. dragAndDropTimestamp = clientMsg->data.l[2];
  220373. ScopedXLock xlock;
  220374. XConvertSelection (display,
  220375. Atoms::XdndSelection,
  220376. dragAndDropCurrentMimeType,
  220377. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220378. windowH,
  220379. dragAndDropTimestamp);
  220380. }
  220381. }
  220382. StringArray dragAndDropFiles;
  220383. int dragAndDropTimestamp;
  220384. Point<int> lastDropPos;
  220385. Atom dragAndDropCurrentMimeType;
  220386. Window dragAndDropSourceWindow;
  220387. Array <Atom> srcMimeTypeAtomList;
  220388. static int pointerMap[5];
  220389. static Point<int> lastMousePos;
  220390. static void clearLastMousePos() throw()
  220391. {
  220392. lastMousePos = Point<int> (0x100000, 0x100000);
  220393. }
  220394. };
  220395. ModifierKeys LinuxComponentPeer::currentModifiers;
  220396. bool LinuxComponentPeer::isActiveApplication = false;
  220397. int LinuxComponentPeer::pointerMap[5];
  220398. Point<int> LinuxComponentPeer::lastMousePos;
  220399. bool Process::isForegroundProcess()
  220400. {
  220401. return LinuxComponentPeer::isActiveApplication;
  220402. }
  220403. void ModifierKeys::updateCurrentModifiers() throw()
  220404. {
  220405. currentModifiers = LinuxComponentPeer::currentModifiers;
  220406. }
  220407. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220408. {
  220409. Window root, child;
  220410. int x, y, winx, winy;
  220411. unsigned int mask;
  220412. int mouseMods = 0;
  220413. ScopedXLock xlock;
  220414. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220415. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220416. {
  220417. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220418. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220419. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220420. }
  220421. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220422. return LinuxComponentPeer::currentModifiers;
  220423. }
  220424. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220425. {
  220426. if (enableOrDisable)
  220427. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220428. }
  220429. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220430. {
  220431. return new LinuxComponentPeer (this, styleFlags);
  220432. }
  220433. // (this callback is hooked up in the messaging code)
  220434. void juce_windowMessageReceive (XEvent* event)
  220435. {
  220436. if (event->xany.window != None)
  220437. {
  220438. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220439. if (ComponentPeer::isValidPeer (peer))
  220440. peer->handleWindowMessage (event);
  220441. }
  220442. else
  220443. {
  220444. switch (event->xany.type)
  220445. {
  220446. case KeymapNotify:
  220447. {
  220448. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220449. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220450. break;
  220451. }
  220452. default:
  220453. break;
  220454. }
  220455. }
  220456. }
  220457. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220458. {
  220459. if (display == 0)
  220460. return;
  220461. #if JUCE_USE_XINERAMA
  220462. int major_opcode, first_event, first_error;
  220463. ScopedXLock xlock;
  220464. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220465. {
  220466. typedef Bool (*tXineramaIsActive) (Display*);
  220467. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220468. static tXineramaIsActive xXineramaIsActive = 0;
  220469. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220470. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220471. {
  220472. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220473. if (h == 0)
  220474. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220475. if (h != 0)
  220476. {
  220477. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220478. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220479. }
  220480. }
  220481. if (xXineramaIsActive != 0
  220482. && xXineramaQueryScreens != 0
  220483. && xXineramaIsActive (display))
  220484. {
  220485. int numMonitors = 0;
  220486. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220487. if (screens != 0)
  220488. {
  220489. for (int i = numMonitors; --i >= 0;)
  220490. {
  220491. int index = screens[i].screen_number;
  220492. if (index >= 0)
  220493. {
  220494. while (monitorCoords.size() < index)
  220495. monitorCoords.add (Rectangle<int>());
  220496. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220497. screens[i].y_org,
  220498. screens[i].width,
  220499. screens[i].height));
  220500. }
  220501. }
  220502. XFree (screens);
  220503. }
  220504. }
  220505. }
  220506. if (monitorCoords.size() == 0)
  220507. #endif
  220508. {
  220509. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220510. if (hints != None)
  220511. {
  220512. const int numMonitors = ScreenCount (display);
  220513. for (int i = 0; i < numMonitors; ++i)
  220514. {
  220515. Window root = RootWindow (display, i);
  220516. unsigned long nitems, bytesLeft;
  220517. Atom actualType;
  220518. int actualFormat;
  220519. unsigned char* data = 0;
  220520. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220521. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220522. &data) == Success)
  220523. {
  220524. const long* const position = (const long*) data;
  220525. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220526. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220527. position[2], position[3]));
  220528. XFree (data);
  220529. }
  220530. }
  220531. }
  220532. if (monitorCoords.size() == 0)
  220533. {
  220534. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220535. DisplayHeight (display, DefaultScreen (display))));
  220536. }
  220537. }
  220538. }
  220539. void Desktop::createMouseInputSources()
  220540. {
  220541. mouseSources.add (new MouseInputSource (0, true));
  220542. }
  220543. bool Desktop::canUseSemiTransparentWindows() throw()
  220544. {
  220545. int matchedDepth = 0;
  220546. const int desiredDepth = 32;
  220547. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220548. && (matchedDepth == desiredDepth);
  220549. }
  220550. const Point<int> Desktop::getMousePosition()
  220551. {
  220552. Window root, child;
  220553. int x, y, winx, winy;
  220554. unsigned int mask;
  220555. ScopedXLock xlock;
  220556. if (XQueryPointer (display,
  220557. RootWindow (display, DefaultScreen (display)),
  220558. &root, &child,
  220559. &x, &y, &winx, &winy, &mask) == False)
  220560. {
  220561. // Pointer not on the default screen
  220562. x = y = -1;
  220563. }
  220564. return Point<int> (x, y);
  220565. }
  220566. void Desktop::setMousePosition (const Point<int>& newPosition)
  220567. {
  220568. ScopedXLock xlock;
  220569. Window root = RootWindow (display, DefaultScreen (display));
  220570. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220571. }
  220572. static bool screenSaverAllowed = true;
  220573. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220574. {
  220575. if (screenSaverAllowed != isEnabled)
  220576. {
  220577. screenSaverAllowed = isEnabled;
  220578. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220579. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220580. if (xScreenSaverSuspend == 0)
  220581. {
  220582. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220583. if (h != 0)
  220584. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220585. }
  220586. ScopedXLock xlock;
  220587. if (xScreenSaverSuspend != 0)
  220588. xScreenSaverSuspend (display, ! isEnabled);
  220589. }
  220590. }
  220591. bool Desktop::isScreenSaverEnabled()
  220592. {
  220593. return screenSaverAllowed;
  220594. }
  220595. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220596. {
  220597. ScopedXLock xlock;
  220598. const unsigned int imageW = image.getWidth();
  220599. const unsigned int imageH = image.getHeight();
  220600. #if JUCE_USE_XCURSOR
  220601. {
  220602. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220603. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220604. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220605. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220606. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220607. static tXcursorImageCreate xXcursorImageCreate = 0;
  220608. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220609. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220610. static bool hasBeenLoaded = false;
  220611. if (! hasBeenLoaded)
  220612. {
  220613. hasBeenLoaded = true;
  220614. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220615. if (h != 0)
  220616. {
  220617. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220618. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220619. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220620. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220621. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220622. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220623. || ! xXcursorSupportsARGB (display))
  220624. xXcursorSupportsARGB = 0;
  220625. }
  220626. }
  220627. if (xXcursorSupportsARGB != 0)
  220628. {
  220629. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220630. if (xcImage != 0)
  220631. {
  220632. xcImage->xhot = hotspotX;
  220633. xcImage->yhot = hotspotY;
  220634. XcursorPixel* dest = xcImage->pixels;
  220635. for (int y = 0; y < (int) imageH; ++y)
  220636. for (int x = 0; x < (int) imageW; ++x)
  220637. *dest++ = image.getPixelAt (x, y).getARGB();
  220638. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220639. xXcursorImageDestroy (xcImage);
  220640. if (result != 0)
  220641. return result;
  220642. }
  220643. }
  220644. }
  220645. #endif
  220646. Window root = RootWindow (display, DefaultScreen (display));
  220647. unsigned int cursorW, cursorH;
  220648. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220649. return 0;
  220650. Image im (Image::ARGB, cursorW, cursorH, true);
  220651. {
  220652. Graphics g (im);
  220653. if (imageW > cursorW || imageH > cursorH)
  220654. {
  220655. hotspotX = (hotspotX * cursorW) / imageW;
  220656. hotspotY = (hotspotY * cursorH) / imageH;
  220657. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220658. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220659. false);
  220660. }
  220661. else
  220662. {
  220663. g.drawImageAt (image, 0, 0);
  220664. }
  220665. }
  220666. const int stride = (cursorW + 7) >> 3;
  220667. HeapBlock <char> maskPlane, sourcePlane;
  220668. maskPlane.calloc (stride * cursorH);
  220669. sourcePlane.calloc (stride * cursorH);
  220670. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220671. for (int y = cursorH; --y >= 0;)
  220672. {
  220673. for (int x = cursorW; --x >= 0;)
  220674. {
  220675. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220676. const int offset = y * stride + (x >> 3);
  220677. const Colour c (im.getPixelAt (x, y));
  220678. if (c.getAlpha() >= 128)
  220679. maskPlane[offset] |= mask;
  220680. if (c.getBrightness() >= 0.5f)
  220681. sourcePlane[offset] |= mask;
  220682. }
  220683. }
  220684. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220685. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220686. XColor white, black;
  220687. black.red = black.green = black.blue = 0;
  220688. white.red = white.green = white.blue = 0xffff;
  220689. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220690. XFreePixmap (display, sourcePixmap);
  220691. XFreePixmap (display, maskPixmap);
  220692. return result;
  220693. }
  220694. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220695. {
  220696. ScopedXLock xlock;
  220697. if (cursorHandle != 0)
  220698. XFreeCursor (display, (Cursor) cursorHandle);
  220699. }
  220700. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220701. {
  220702. unsigned int shape;
  220703. switch (type)
  220704. {
  220705. case NormalCursor: return None; // Use parent cursor
  220706. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220707. case WaitCursor: shape = XC_watch; break;
  220708. case IBeamCursor: shape = XC_xterm; break;
  220709. case PointingHandCursor: shape = XC_hand2; break;
  220710. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220711. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220712. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220713. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220714. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220715. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220716. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220717. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220718. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220719. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220720. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220721. case CrosshairCursor: shape = XC_crosshair; break;
  220722. case DraggingHandCursor:
  220723. {
  220724. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220725. 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,
  220726. 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 };
  220727. const int dragHandDataSize = 99;
  220728. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220729. }
  220730. case CopyingCursor:
  220731. {
  220732. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220733. 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,
  220734. 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,
  220735. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220736. const int copyCursorSize = 119;
  220737. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220738. }
  220739. default:
  220740. jassertfalse;
  220741. return None;
  220742. }
  220743. ScopedXLock xlock;
  220744. return (void*) XCreateFontCursor (display, shape);
  220745. }
  220746. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220747. {
  220748. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220749. if (lp != 0)
  220750. lp->showMouseCursor ((Cursor) getHandle());
  220751. }
  220752. void MouseCursor::showInAllWindows() const
  220753. {
  220754. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220755. showInWindow (ComponentPeer::getPeer (i));
  220756. }
  220757. const Image juce_createIconForFile (const File& file)
  220758. {
  220759. return Image::null;
  220760. }
  220761. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220762. {
  220763. return createSoftwareImage (format, width, height, clearImage);
  220764. }
  220765. #if JUCE_OPENGL
  220766. class WindowedGLContext : public OpenGLContext
  220767. {
  220768. public:
  220769. WindowedGLContext (Component* const component,
  220770. const OpenGLPixelFormat& pixelFormat_,
  220771. GLXContext sharedContext)
  220772. : renderContext (0),
  220773. embeddedWindow (0),
  220774. pixelFormat (pixelFormat_),
  220775. swapInterval (0)
  220776. {
  220777. jassert (component != 0);
  220778. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220779. if (peer == 0)
  220780. return;
  220781. ScopedXLock xlock;
  220782. XSync (display, False);
  220783. GLint attribs [64];
  220784. int n = 0;
  220785. attribs[n++] = GLX_RGBA;
  220786. attribs[n++] = GLX_DOUBLEBUFFER;
  220787. attribs[n++] = GLX_RED_SIZE;
  220788. attribs[n++] = pixelFormat.redBits;
  220789. attribs[n++] = GLX_GREEN_SIZE;
  220790. attribs[n++] = pixelFormat.greenBits;
  220791. attribs[n++] = GLX_BLUE_SIZE;
  220792. attribs[n++] = pixelFormat.blueBits;
  220793. attribs[n++] = GLX_ALPHA_SIZE;
  220794. attribs[n++] = pixelFormat.alphaBits;
  220795. attribs[n++] = GLX_DEPTH_SIZE;
  220796. attribs[n++] = pixelFormat.depthBufferBits;
  220797. attribs[n++] = GLX_STENCIL_SIZE;
  220798. attribs[n++] = pixelFormat.stencilBufferBits;
  220799. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220800. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220801. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220802. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220803. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220804. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220805. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220806. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220807. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220808. attribs[n++] = None;
  220809. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220810. if (bestVisual == 0)
  220811. return;
  220812. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220813. Window windowH = (Window) peer->getNativeHandle();
  220814. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220815. XSetWindowAttributes swa;
  220816. swa.colormap = colourMap;
  220817. swa.border_pixel = 0;
  220818. swa.event_mask = ExposureMask | StructureNotifyMask;
  220819. embeddedWindow = XCreateWindow (display, windowH,
  220820. 0, 0, 1, 1, 0,
  220821. bestVisual->depth,
  220822. InputOutput,
  220823. bestVisual->visual,
  220824. CWBorderPixel | CWColormap | CWEventMask,
  220825. &swa);
  220826. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220827. XMapWindow (display, embeddedWindow);
  220828. XFreeColormap (display, colourMap);
  220829. XFree (bestVisual);
  220830. XSync (display, False);
  220831. }
  220832. ~WindowedGLContext()
  220833. {
  220834. ScopedXLock xlock;
  220835. deleteContext();
  220836. XUnmapWindow (display, embeddedWindow);
  220837. XDestroyWindow (display, embeddedWindow);
  220838. }
  220839. void deleteContext()
  220840. {
  220841. makeInactive();
  220842. if (renderContext != 0)
  220843. {
  220844. ScopedXLock xlock;
  220845. glXDestroyContext (display, renderContext);
  220846. renderContext = 0;
  220847. }
  220848. }
  220849. bool makeActive() const throw()
  220850. {
  220851. jassert (renderContext != 0);
  220852. ScopedXLock xlock;
  220853. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220854. && XSync (display, False);
  220855. }
  220856. bool makeInactive() const throw()
  220857. {
  220858. ScopedXLock xlock;
  220859. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220860. }
  220861. bool isActive() const throw()
  220862. {
  220863. ScopedXLock xlock;
  220864. return glXGetCurrentContext() == renderContext;
  220865. }
  220866. const OpenGLPixelFormat getPixelFormat() const
  220867. {
  220868. return pixelFormat;
  220869. }
  220870. void* getRawContext() const throw()
  220871. {
  220872. return renderContext;
  220873. }
  220874. void updateWindowPosition (int x, int y, int w, int h, int)
  220875. {
  220876. ScopedXLock xlock;
  220877. XMoveResizeWindow (display, embeddedWindow,
  220878. x, y, jmax (1, w), jmax (1, h));
  220879. }
  220880. void swapBuffers()
  220881. {
  220882. ScopedXLock xlock;
  220883. glXSwapBuffers (display, embeddedWindow);
  220884. }
  220885. bool setSwapInterval (const int numFramesPerSwap)
  220886. {
  220887. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  220888. if (GLXSwapIntervalSGI != 0)
  220889. {
  220890. swapInterval = numFramesPerSwap;
  220891. GLXSwapIntervalSGI (numFramesPerSwap);
  220892. return true;
  220893. }
  220894. return false;
  220895. }
  220896. int getSwapInterval() const
  220897. {
  220898. return swapInterval;
  220899. }
  220900. void repaint()
  220901. {
  220902. }
  220903. juce_UseDebuggingNewOperator
  220904. GLXContext renderContext;
  220905. private:
  220906. Window embeddedWindow;
  220907. OpenGLPixelFormat pixelFormat;
  220908. int swapInterval;
  220909. WindowedGLContext (const WindowedGLContext&);
  220910. WindowedGLContext& operator= (const WindowedGLContext&);
  220911. };
  220912. OpenGLContext* OpenGLComponent::createContext()
  220913. {
  220914. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220915. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220916. return (c->renderContext != 0) ? c.release() : 0;
  220917. }
  220918. void juce_glViewport (const int w, const int h)
  220919. {
  220920. glViewport (0, 0, w, h);
  220921. }
  220922. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220923. OwnedArray <OpenGLPixelFormat>& results)
  220924. {
  220925. results.add (new OpenGLPixelFormat()); // xxx
  220926. }
  220927. #endif
  220928. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220929. {
  220930. jassertfalse; // not implemented!
  220931. return false;
  220932. }
  220933. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220934. {
  220935. jassertfalse; // not implemented!
  220936. return false;
  220937. }
  220938. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220939. {
  220940. if (! isOnDesktop ())
  220941. addToDesktop (0);
  220942. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220943. if (wp != 0)
  220944. {
  220945. wp->setTaskBarIcon (newImage);
  220946. setVisible (true);
  220947. toFront (false);
  220948. repaint();
  220949. }
  220950. }
  220951. void SystemTrayIconComponent::paint (Graphics& g)
  220952. {
  220953. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220954. if (wp != 0)
  220955. {
  220956. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220957. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220958. false);
  220959. }
  220960. }
  220961. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220962. {
  220963. // xxx not yet implemented!
  220964. }
  220965. void PlatformUtilities::beep()
  220966. {
  220967. std::cout << "\a" << std::flush;
  220968. }
  220969. bool AlertWindow::showNativeDialogBox (const String& title,
  220970. const String& bodyText,
  220971. bool isOkCancel)
  220972. {
  220973. // use a non-native one for the time being..
  220974. if (isOkCancel)
  220975. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220976. else
  220977. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220978. return true;
  220979. }
  220980. const int KeyPress::spaceKey = XK_space & 0xff;
  220981. const int KeyPress::returnKey = XK_Return & 0xff;
  220982. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220983. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220984. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  220985. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  220986. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  220987. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  220988. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  220989. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  220990. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  220991. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  220992. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  220993. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  220994. const int KeyPress::tabKey = XK_Tab & 0xff;
  220995. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  220996. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  220997. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  220998. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  220999. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221000. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221001. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221002. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221003. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221004. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221005. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221006. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221007. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221008. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221009. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221010. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221011. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221012. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221013. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221014. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221015. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221016. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221017. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221018. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221019. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221020. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221021. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221022. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221023. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221024. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221025. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221026. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221027. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221028. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221029. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221030. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221031. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221032. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221033. #endif
  221034. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221035. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221036. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221037. // compiled on its own).
  221038. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221039. static const int maxNumChans = 64;
  221040. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221041. {
  221042. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221043. snd_pcm_hw_params_t* hwParams;
  221044. snd_pcm_hw_params_alloca (&hwParams);
  221045. for (int i = 0; ratesToTry[i] != 0; ++i)
  221046. {
  221047. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221048. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221049. {
  221050. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221051. }
  221052. }
  221053. }
  221054. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221055. {
  221056. snd_pcm_hw_params_t *params;
  221057. snd_pcm_hw_params_alloca (&params);
  221058. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221059. {
  221060. snd_pcm_hw_params_get_channels_min (params, minChans);
  221061. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221062. }
  221063. }
  221064. static void getDeviceProperties (const String& deviceID,
  221065. unsigned int& minChansOut,
  221066. unsigned int& maxChansOut,
  221067. unsigned int& minChansIn,
  221068. unsigned int& maxChansIn,
  221069. Array <int>& rates)
  221070. {
  221071. if (deviceID.isEmpty())
  221072. return;
  221073. snd_ctl_t* handle;
  221074. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221075. {
  221076. snd_pcm_info_t* info;
  221077. snd_pcm_info_alloca (&info);
  221078. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221079. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221080. snd_pcm_info_set_subdevice (info, 0);
  221081. if (snd_ctl_pcm_info (handle, info) >= 0)
  221082. {
  221083. snd_pcm_t* pcmHandle;
  221084. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  221085. {
  221086. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221087. getDeviceSampleRates (pcmHandle, rates);
  221088. snd_pcm_close (pcmHandle);
  221089. }
  221090. }
  221091. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221092. if (snd_ctl_pcm_info (handle, info) >= 0)
  221093. {
  221094. snd_pcm_t* pcmHandle;
  221095. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  221096. {
  221097. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221098. if (rates.size() == 0)
  221099. getDeviceSampleRates (pcmHandle, rates);
  221100. snd_pcm_close (pcmHandle);
  221101. }
  221102. }
  221103. snd_ctl_close (handle);
  221104. }
  221105. }
  221106. class ALSADevice
  221107. {
  221108. public:
  221109. ALSADevice (const String& deviceID,
  221110. const bool forInput)
  221111. : handle (0),
  221112. bitDepth (16),
  221113. numChannelsRunning (0),
  221114. isInput (forInput),
  221115. sampleFormat (AudioDataConverters::int16LE)
  221116. {
  221117. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221118. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221119. SND_PCM_ASYNC));
  221120. }
  221121. ~ALSADevice()
  221122. {
  221123. if (handle != 0)
  221124. snd_pcm_close (handle);
  221125. }
  221126. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221127. {
  221128. if (handle == 0)
  221129. return false;
  221130. snd_pcm_hw_params_t* hwParams;
  221131. snd_pcm_hw_params_alloca (&hwParams);
  221132. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221133. return false;
  221134. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221135. isInterleaved = false;
  221136. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221137. isInterleaved = true;
  221138. else
  221139. {
  221140. jassertfalse;
  221141. return false;
  221142. }
  221143. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  221144. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  221145. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  221146. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  221147. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  221148. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  221149. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  221150. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  221151. bitDepth = 0;
  221152. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  221153. {
  221154. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221155. {
  221156. bitDepth = formatsToTry [i + 1];
  221157. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  221158. break;
  221159. }
  221160. }
  221161. if (bitDepth == 0)
  221162. {
  221163. error = "device doesn't support a compatible PCM format";
  221164. DBG ("ALSA error: " + error + "\n");
  221165. return false;
  221166. }
  221167. int dir = 0;
  221168. unsigned int periods = 4;
  221169. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221170. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221171. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221172. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221173. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221174. || failed (snd_pcm_hw_params (handle, hwParams)))
  221175. {
  221176. return false;
  221177. }
  221178. snd_pcm_sw_params_t* swParams;
  221179. snd_pcm_sw_params_alloca (&swParams);
  221180. snd_pcm_uframes_t boundary;
  221181. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221182. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221183. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221184. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221185. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221186. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221187. || failed (snd_pcm_sw_params (handle, swParams)))
  221188. {
  221189. return false;
  221190. }
  221191. /*
  221192. #if JUCE_DEBUG
  221193. // enable this to dump the config of the devices that get opened
  221194. snd_output_t* out;
  221195. snd_output_stdio_attach (&out, stderr, 0);
  221196. snd_pcm_hw_params_dump (hwParams, out);
  221197. snd_pcm_sw_params_dump (swParams, out);
  221198. #endif
  221199. */
  221200. numChannelsRunning = numChannels;
  221201. return true;
  221202. }
  221203. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221204. {
  221205. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221206. float** const data = outputChannelBuffer.getArrayOfChannels();
  221207. if (isInterleaved)
  221208. {
  221209. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221210. float* interleaved = static_cast <float*> (scratch.getData());
  221211. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  221212. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221213. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  221214. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221215. return false;
  221216. }
  221217. else
  221218. {
  221219. for (int i = 0; i < numChannelsRunning; ++i)
  221220. if (data[i] != 0)
  221221. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  221222. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  221223. if (failed (num))
  221224. {
  221225. if (num == -EPIPE)
  221226. {
  221227. if (failed (snd_pcm_prepare (handle)))
  221228. return false;
  221229. }
  221230. else if (num != -ESTRPIPE)
  221231. return false;
  221232. }
  221233. }
  221234. return true;
  221235. }
  221236. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221237. {
  221238. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221239. float** const data = inputChannelBuffer.getArrayOfChannels();
  221240. if (isInterleaved)
  221241. {
  221242. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221243. float* interleaved = static_cast <float*> (scratch.getData());
  221244. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  221245. if (failed (num))
  221246. {
  221247. if (num == -EPIPE)
  221248. {
  221249. if (failed (snd_pcm_prepare (handle)))
  221250. return false;
  221251. }
  221252. else if (num != -ESTRPIPE)
  221253. return false;
  221254. }
  221255. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221256. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  221257. }
  221258. else
  221259. {
  221260. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221261. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221262. return false;
  221263. for (int i = 0; i < numChannelsRunning; ++i)
  221264. if (data[i] != 0)
  221265. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  221266. }
  221267. return true;
  221268. }
  221269. juce_UseDebuggingNewOperator
  221270. snd_pcm_t* handle;
  221271. String error;
  221272. int bitDepth, numChannelsRunning;
  221273. private:
  221274. const bool isInput;
  221275. bool isInterleaved;
  221276. MemoryBlock scratch;
  221277. AudioDataConverters::DataFormat sampleFormat;
  221278. bool failed (const int errorNum)
  221279. {
  221280. if (errorNum >= 0)
  221281. return false;
  221282. error = snd_strerror (errorNum);
  221283. DBG ("ALSA error: " + error + "\n");
  221284. return true;
  221285. }
  221286. };
  221287. class ALSAThread : public Thread
  221288. {
  221289. public:
  221290. ALSAThread (const String& inputId_,
  221291. const String& outputId_)
  221292. : Thread ("Juce ALSA"),
  221293. sampleRate (0),
  221294. bufferSize (0),
  221295. callback (0),
  221296. inputId (inputId_),
  221297. outputId (outputId_),
  221298. numCallbacks (0),
  221299. inputChannelBuffer (1, 1),
  221300. outputChannelBuffer (1, 1)
  221301. {
  221302. initialiseRatesAndChannels();
  221303. }
  221304. ~ALSAThread()
  221305. {
  221306. close();
  221307. }
  221308. void open (BigInteger inputChannels,
  221309. BigInteger outputChannels,
  221310. const double sampleRate_,
  221311. const int bufferSize_)
  221312. {
  221313. close();
  221314. error = String::empty;
  221315. sampleRate = sampleRate_;
  221316. bufferSize = bufferSize_;
  221317. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221318. inputChannelBuffer.clear();
  221319. inputChannelDataForCallback.clear();
  221320. currentInputChans.clear();
  221321. if (inputChannels.getHighestBit() >= 0)
  221322. {
  221323. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221324. {
  221325. if (inputChannels[i])
  221326. {
  221327. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221328. currentInputChans.setBit (i);
  221329. }
  221330. }
  221331. }
  221332. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221333. outputChannelBuffer.clear();
  221334. outputChannelDataForCallback.clear();
  221335. currentOutputChans.clear();
  221336. if (outputChannels.getHighestBit() >= 0)
  221337. {
  221338. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221339. {
  221340. if (outputChannels[i])
  221341. {
  221342. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221343. currentOutputChans.setBit (i);
  221344. }
  221345. }
  221346. }
  221347. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221348. {
  221349. outputDevice = new ALSADevice (outputId, false);
  221350. if (outputDevice->error.isNotEmpty())
  221351. {
  221352. error = outputDevice->error;
  221353. outputDevice = 0;
  221354. return;
  221355. }
  221356. currentOutputChans.setRange (0, minChansOut, true);
  221357. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221358. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221359. bufferSize))
  221360. {
  221361. error = outputDevice->error;
  221362. outputDevice = 0;
  221363. return;
  221364. }
  221365. }
  221366. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221367. {
  221368. inputDevice = new ALSADevice (inputId, true);
  221369. if (inputDevice->error.isNotEmpty())
  221370. {
  221371. error = inputDevice->error;
  221372. inputDevice = 0;
  221373. return;
  221374. }
  221375. currentInputChans.setRange (0, minChansIn, true);
  221376. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221377. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221378. bufferSize))
  221379. {
  221380. error = inputDevice->error;
  221381. inputDevice = 0;
  221382. return;
  221383. }
  221384. }
  221385. if (outputDevice == 0 && inputDevice == 0)
  221386. {
  221387. error = "no channels";
  221388. return;
  221389. }
  221390. if (outputDevice != 0 && inputDevice != 0)
  221391. {
  221392. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221393. }
  221394. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221395. return;
  221396. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221397. return;
  221398. startThread (9);
  221399. int count = 1000;
  221400. while (numCallbacks == 0)
  221401. {
  221402. sleep (5);
  221403. if (--count < 0 || ! isThreadRunning())
  221404. {
  221405. error = "device didn't start";
  221406. break;
  221407. }
  221408. }
  221409. }
  221410. void close()
  221411. {
  221412. stopThread (6000);
  221413. inputDevice = 0;
  221414. outputDevice = 0;
  221415. inputChannelBuffer.setSize (1, 1);
  221416. outputChannelBuffer.setSize (1, 1);
  221417. numCallbacks = 0;
  221418. }
  221419. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221420. {
  221421. const ScopedLock sl (callbackLock);
  221422. callback = newCallback;
  221423. }
  221424. void run()
  221425. {
  221426. while (! threadShouldExit())
  221427. {
  221428. if (inputDevice != 0)
  221429. {
  221430. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221431. {
  221432. DBG ("ALSA: read failure");
  221433. break;
  221434. }
  221435. }
  221436. if (threadShouldExit())
  221437. break;
  221438. {
  221439. const ScopedLock sl (callbackLock);
  221440. ++numCallbacks;
  221441. if (callback != 0)
  221442. {
  221443. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221444. inputChannelDataForCallback.size(),
  221445. outputChannelDataForCallback.getRawDataPointer(),
  221446. outputChannelDataForCallback.size(),
  221447. bufferSize);
  221448. }
  221449. else
  221450. {
  221451. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221452. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221453. }
  221454. }
  221455. if (outputDevice != 0)
  221456. {
  221457. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221458. if (threadShouldExit())
  221459. break;
  221460. failed (snd_pcm_avail_update (outputDevice->handle));
  221461. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221462. {
  221463. DBG ("ALSA: write failure");
  221464. break;
  221465. }
  221466. }
  221467. }
  221468. }
  221469. int getBitDepth() const throw()
  221470. {
  221471. if (outputDevice != 0)
  221472. return outputDevice->bitDepth;
  221473. if (inputDevice != 0)
  221474. return inputDevice->bitDepth;
  221475. return 16;
  221476. }
  221477. juce_UseDebuggingNewOperator
  221478. String error;
  221479. double sampleRate;
  221480. int bufferSize;
  221481. BigInteger currentInputChans, currentOutputChans;
  221482. Array <int> sampleRates;
  221483. StringArray channelNamesOut, channelNamesIn;
  221484. AudioIODeviceCallback* callback;
  221485. private:
  221486. const String inputId, outputId;
  221487. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221488. int numCallbacks;
  221489. CriticalSection callbackLock;
  221490. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221491. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221492. unsigned int minChansOut, maxChansOut;
  221493. unsigned int minChansIn, maxChansIn;
  221494. bool failed (const int errorNum)
  221495. {
  221496. if (errorNum >= 0)
  221497. return false;
  221498. error = snd_strerror (errorNum);
  221499. DBG ("ALSA error: " + error + "\n");
  221500. return true;
  221501. }
  221502. void initialiseRatesAndChannels()
  221503. {
  221504. sampleRates.clear();
  221505. channelNamesOut.clear();
  221506. channelNamesIn.clear();
  221507. minChansOut = 0;
  221508. maxChansOut = 0;
  221509. minChansIn = 0;
  221510. maxChansIn = 0;
  221511. unsigned int dummy = 0;
  221512. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221513. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221514. unsigned int i;
  221515. for (i = 0; i < maxChansOut; ++i)
  221516. channelNamesOut.add ("channel " + String ((int) i + 1));
  221517. for (i = 0; i < maxChansIn; ++i)
  221518. channelNamesIn.add ("channel " + String ((int) i + 1));
  221519. }
  221520. };
  221521. class ALSAAudioIODevice : public AudioIODevice
  221522. {
  221523. public:
  221524. ALSAAudioIODevice (const String& deviceName,
  221525. const String& inputId_,
  221526. const String& outputId_)
  221527. : AudioIODevice (deviceName, "ALSA"),
  221528. inputId (inputId_),
  221529. outputId (outputId_),
  221530. isOpen_ (false),
  221531. isStarted (false),
  221532. internal (inputId_, outputId_)
  221533. {
  221534. }
  221535. ~ALSAAudioIODevice()
  221536. {
  221537. }
  221538. const StringArray getOutputChannelNames()
  221539. {
  221540. return internal.channelNamesOut;
  221541. }
  221542. const StringArray getInputChannelNames()
  221543. {
  221544. return internal.channelNamesIn;
  221545. }
  221546. int getNumSampleRates()
  221547. {
  221548. return internal.sampleRates.size();
  221549. }
  221550. double getSampleRate (int index)
  221551. {
  221552. return internal.sampleRates [index];
  221553. }
  221554. int getNumBufferSizesAvailable()
  221555. {
  221556. return 50;
  221557. }
  221558. int getBufferSizeSamples (int index)
  221559. {
  221560. int n = 16;
  221561. for (int i = 0; i < index; ++i)
  221562. n += n < 64 ? 16
  221563. : (n < 512 ? 32
  221564. : (n < 1024 ? 64
  221565. : (n < 2048 ? 128 : 256)));
  221566. return n;
  221567. }
  221568. int getDefaultBufferSize()
  221569. {
  221570. return 512;
  221571. }
  221572. const String open (const BigInteger& inputChannels,
  221573. const BigInteger& outputChannels,
  221574. double sampleRate,
  221575. int bufferSizeSamples)
  221576. {
  221577. close();
  221578. if (bufferSizeSamples <= 0)
  221579. bufferSizeSamples = getDefaultBufferSize();
  221580. if (sampleRate <= 0)
  221581. {
  221582. for (int i = 0; i < getNumSampleRates(); ++i)
  221583. {
  221584. if (getSampleRate (i) >= 44100)
  221585. {
  221586. sampleRate = getSampleRate (i);
  221587. break;
  221588. }
  221589. }
  221590. }
  221591. internal.open (inputChannels, outputChannels,
  221592. sampleRate, bufferSizeSamples);
  221593. isOpen_ = internal.error.isEmpty();
  221594. return internal.error;
  221595. }
  221596. void close()
  221597. {
  221598. stop();
  221599. internal.close();
  221600. isOpen_ = false;
  221601. }
  221602. bool isOpen()
  221603. {
  221604. return isOpen_;
  221605. }
  221606. int getCurrentBufferSizeSamples()
  221607. {
  221608. return internal.bufferSize;
  221609. }
  221610. double getCurrentSampleRate()
  221611. {
  221612. return internal.sampleRate;
  221613. }
  221614. int getCurrentBitDepth()
  221615. {
  221616. return internal.getBitDepth();
  221617. }
  221618. const BigInteger getActiveOutputChannels() const
  221619. {
  221620. return internal.currentOutputChans;
  221621. }
  221622. const BigInteger getActiveInputChannels() const
  221623. {
  221624. return internal.currentInputChans;
  221625. }
  221626. int getOutputLatencyInSamples()
  221627. {
  221628. return 0;
  221629. }
  221630. int getInputLatencyInSamples()
  221631. {
  221632. return 0;
  221633. }
  221634. void start (AudioIODeviceCallback* callback)
  221635. {
  221636. if (! isOpen_)
  221637. callback = 0;
  221638. if (callback != 0)
  221639. callback->audioDeviceAboutToStart (this);
  221640. internal.setCallback (callback);
  221641. isStarted = (callback != 0);
  221642. }
  221643. void stop()
  221644. {
  221645. AudioIODeviceCallback* const oldCallback = internal.callback;
  221646. start (0);
  221647. if (oldCallback != 0)
  221648. oldCallback->audioDeviceStopped();
  221649. }
  221650. bool isPlaying()
  221651. {
  221652. return isStarted && internal.error.isEmpty();
  221653. }
  221654. const String getLastError()
  221655. {
  221656. return internal.error;
  221657. }
  221658. String inputId, outputId;
  221659. private:
  221660. bool isOpen_, isStarted;
  221661. ALSAThread internal;
  221662. };
  221663. class ALSAAudioIODeviceType : public AudioIODeviceType
  221664. {
  221665. public:
  221666. ALSAAudioIODeviceType()
  221667. : AudioIODeviceType ("ALSA"),
  221668. hasScanned (false)
  221669. {
  221670. }
  221671. ~ALSAAudioIODeviceType()
  221672. {
  221673. }
  221674. void scanForDevices()
  221675. {
  221676. if (hasScanned)
  221677. return;
  221678. hasScanned = true;
  221679. inputNames.clear();
  221680. inputIds.clear();
  221681. outputNames.clear();
  221682. outputIds.clear();
  221683. snd_ctl_t* handle;
  221684. snd_ctl_card_info_t* info;
  221685. snd_ctl_card_info_alloca (&info);
  221686. int cardNum = -1;
  221687. while (outputIds.size() + inputIds.size() <= 32)
  221688. {
  221689. snd_card_next (&cardNum);
  221690. if (cardNum < 0)
  221691. break;
  221692. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221693. {
  221694. if (snd_ctl_card_info (handle, info) >= 0)
  221695. {
  221696. String cardId (snd_ctl_card_info_get_id (info));
  221697. if (cardId.removeCharacters ("0123456789").isEmpty())
  221698. cardId = String (cardNum);
  221699. int device = -1;
  221700. for (;;)
  221701. {
  221702. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221703. break;
  221704. String id, name;
  221705. id << "hw:" << cardId << ',' << device;
  221706. bool isInput, isOutput;
  221707. if (testDevice (id, isInput, isOutput))
  221708. {
  221709. name << snd_ctl_card_info_get_name (info);
  221710. if (name.isEmpty())
  221711. name = id;
  221712. if (isInput)
  221713. {
  221714. inputNames.add (name);
  221715. inputIds.add (id);
  221716. }
  221717. if (isOutput)
  221718. {
  221719. outputNames.add (name);
  221720. outputIds.add (id);
  221721. }
  221722. }
  221723. }
  221724. }
  221725. snd_ctl_close (handle);
  221726. }
  221727. }
  221728. inputNames.appendNumbersToDuplicates (false, true);
  221729. outputNames.appendNumbersToDuplicates (false, true);
  221730. }
  221731. const StringArray getDeviceNames (bool wantInputNames) const
  221732. {
  221733. jassert (hasScanned); // need to call scanForDevices() before doing this
  221734. return wantInputNames ? inputNames : outputNames;
  221735. }
  221736. int getDefaultDeviceIndex (bool forInput) const
  221737. {
  221738. jassert (hasScanned); // need to call scanForDevices() before doing this
  221739. return 0;
  221740. }
  221741. bool hasSeparateInputsAndOutputs() const { return true; }
  221742. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221743. {
  221744. jassert (hasScanned); // need to call scanForDevices() before doing this
  221745. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221746. if (d == 0)
  221747. return -1;
  221748. return asInput ? inputIds.indexOf (d->inputId)
  221749. : outputIds.indexOf (d->outputId);
  221750. }
  221751. AudioIODevice* createDevice (const String& outputDeviceName,
  221752. const String& inputDeviceName)
  221753. {
  221754. jassert (hasScanned); // need to call scanForDevices() before doing this
  221755. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221756. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221757. String deviceName (outputIndex >= 0 ? outputDeviceName
  221758. : inputDeviceName);
  221759. if (inputIndex >= 0 || outputIndex >= 0)
  221760. return new ALSAAudioIODevice (deviceName,
  221761. inputIds [inputIndex],
  221762. outputIds [outputIndex]);
  221763. return 0;
  221764. }
  221765. juce_UseDebuggingNewOperator
  221766. private:
  221767. StringArray inputNames, outputNames, inputIds, outputIds;
  221768. bool hasScanned;
  221769. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221770. {
  221771. unsigned int minChansOut = 0, maxChansOut = 0;
  221772. unsigned int minChansIn = 0, maxChansIn = 0;
  221773. Array <int> rates;
  221774. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221775. DBG ("ALSA device: " + id
  221776. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221777. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221778. + " rates=" + String (rates.size()));
  221779. isInput = maxChansIn > 0;
  221780. isOutput = maxChansOut > 0;
  221781. return (isInput || isOutput) && rates.size() > 0;
  221782. }
  221783. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221784. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221785. };
  221786. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221787. {
  221788. return new ALSAAudioIODeviceType();
  221789. }
  221790. #endif
  221791. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221792. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221793. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221794. // compiled on its own).
  221795. #ifdef JUCE_INCLUDED_FILE
  221796. #if JUCE_JACK
  221797. static void* juce_libjack_handle = 0;
  221798. void* juce_load_jack_function (const char* const name)
  221799. {
  221800. if (juce_libjack_handle == 0)
  221801. return 0;
  221802. return dlsym (juce_libjack_handle, name);
  221803. }
  221804. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221805. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221806. return_type fn_name argument_types { \
  221807. static fn_name##_ptr_t fn = 0; \
  221808. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221809. if (fn) return (*fn)arguments; \
  221810. else return 0; \
  221811. }
  221812. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221813. typedef void (*fn_name##_ptr_t)argument_types; \
  221814. void fn_name argument_types { \
  221815. static fn_name##_ptr_t fn = 0; \
  221816. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221817. if (fn) (*fn)arguments; \
  221818. }
  221819. 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));
  221820. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221821. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221822. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221823. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221824. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221825. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221826. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221827. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221828. 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));
  221829. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221830. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221831. 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));
  221832. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221833. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221834. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221835. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221836. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221837. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221838. #if JUCE_DEBUG
  221839. #define JACK_LOGGING_ENABLED 1
  221840. #endif
  221841. #if JACK_LOGGING_ENABLED
  221842. static void jack_Log (const String& s)
  221843. {
  221844. std::cerr << s << std::endl;
  221845. }
  221846. static void dumpJackErrorMessage (const jack_status_t status)
  221847. {
  221848. if (status & JackServerFailed || status & JackServerError)
  221849. jack_Log ("Unable to connect to JACK server");
  221850. if (status & JackVersionError)
  221851. jack_Log ("Client's protocol version does not match");
  221852. if (status & JackInvalidOption)
  221853. jack_Log ("The operation contained an invalid or unsupported option");
  221854. if (status & JackNameNotUnique)
  221855. jack_Log ("The desired client name was not unique");
  221856. if (status & JackNoSuchClient)
  221857. jack_Log ("Requested client does not exist");
  221858. if (status & JackInitFailure)
  221859. jack_Log ("Unable to initialize client");
  221860. }
  221861. #else
  221862. #define dumpJackErrorMessage(a) {}
  221863. #define jack_Log(...) {}
  221864. #endif
  221865. #ifndef JUCE_JACK_CLIENT_NAME
  221866. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221867. #endif
  221868. class JackAudioIODevice : public AudioIODevice
  221869. {
  221870. public:
  221871. JackAudioIODevice (const String& deviceName,
  221872. const String& inputId_,
  221873. const String& outputId_)
  221874. : AudioIODevice (deviceName, "JACK"),
  221875. inputId (inputId_),
  221876. outputId (outputId_),
  221877. isOpen_ (false),
  221878. callback (0),
  221879. totalNumberOfInputChannels (0),
  221880. totalNumberOfOutputChannels (0)
  221881. {
  221882. jassert (deviceName.isNotEmpty());
  221883. jack_status_t status;
  221884. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221885. if (client == 0)
  221886. {
  221887. dumpJackErrorMessage (status);
  221888. }
  221889. else
  221890. {
  221891. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221892. // open input ports
  221893. const StringArray inputChannels (getInputChannelNames());
  221894. for (int i = 0; i < inputChannels.size(); i++)
  221895. {
  221896. String inputName;
  221897. inputName << "in_" << ++totalNumberOfInputChannels;
  221898. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221899. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221900. }
  221901. // open output ports
  221902. const StringArray outputChannels (getOutputChannelNames());
  221903. for (int i = 0; i < outputChannels.size (); i++)
  221904. {
  221905. String outputName;
  221906. outputName << "out_" << ++totalNumberOfOutputChannels;
  221907. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221908. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221909. }
  221910. inChans.calloc (totalNumberOfInputChannels + 2);
  221911. outChans.calloc (totalNumberOfOutputChannels + 2);
  221912. }
  221913. }
  221914. ~JackAudioIODevice()
  221915. {
  221916. close();
  221917. if (client != 0)
  221918. {
  221919. JUCE_NAMESPACE::jack_client_close (client);
  221920. client = 0;
  221921. }
  221922. }
  221923. const StringArray getChannelNames (bool forInput) const
  221924. {
  221925. StringArray names;
  221926. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221927. forInput ? JackPortIsInput : JackPortIsOutput);
  221928. if (ports != 0)
  221929. {
  221930. int j = 0;
  221931. while (ports[j] != 0)
  221932. {
  221933. const String portName (ports [j++]);
  221934. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221935. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221936. }
  221937. free (ports);
  221938. }
  221939. return names;
  221940. }
  221941. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221942. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221943. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221944. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221945. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221946. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221947. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221948. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221949. double sampleRate, int bufferSizeSamples)
  221950. {
  221951. if (client == 0)
  221952. {
  221953. lastError = "No JACK client running";
  221954. return lastError;
  221955. }
  221956. lastError = String::empty;
  221957. close();
  221958. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221959. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221960. JUCE_NAMESPACE::jack_activate (client);
  221961. isOpen_ = true;
  221962. if (! inputChannels.isZero())
  221963. {
  221964. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221965. if (ports != 0)
  221966. {
  221967. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221968. for (int i = 0; i < numInputChannels; ++i)
  221969. {
  221970. const String portName (ports[i]);
  221971. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221972. {
  221973. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221974. if (error != 0)
  221975. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221976. }
  221977. }
  221978. free (ports);
  221979. }
  221980. }
  221981. if (! outputChannels.isZero())
  221982. {
  221983. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221984. if (ports != 0)
  221985. {
  221986. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  221987. for (int i = 0; i < numOutputChannels; ++i)
  221988. {
  221989. const String portName (ports[i]);
  221990. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221991. {
  221992. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  221993. if (error != 0)
  221994. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221995. }
  221996. }
  221997. free (ports);
  221998. }
  221999. }
  222000. return lastError;
  222001. }
  222002. void close()
  222003. {
  222004. stop();
  222005. if (client != 0)
  222006. {
  222007. JUCE_NAMESPACE::jack_deactivate (client);
  222008. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222009. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222010. }
  222011. isOpen_ = false;
  222012. }
  222013. void start (AudioIODeviceCallback* newCallback)
  222014. {
  222015. if (isOpen_ && newCallback != callback)
  222016. {
  222017. if (newCallback != 0)
  222018. newCallback->audioDeviceAboutToStart (this);
  222019. AudioIODeviceCallback* const oldCallback = callback;
  222020. {
  222021. const ScopedLock sl (callbackLock);
  222022. callback = newCallback;
  222023. }
  222024. if (oldCallback != 0)
  222025. oldCallback->audioDeviceStopped();
  222026. }
  222027. }
  222028. void stop()
  222029. {
  222030. start (0);
  222031. }
  222032. bool isOpen() { return isOpen_; }
  222033. bool isPlaying() { return callback != 0; }
  222034. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222035. double getCurrentSampleRate() { return getSampleRate (0); }
  222036. int getCurrentBitDepth() { return 32; }
  222037. const String getLastError() { return lastError; }
  222038. const BigInteger getActiveOutputChannels() const
  222039. {
  222040. BigInteger outputBits;
  222041. for (int i = 0; i < outputPorts.size(); i++)
  222042. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222043. outputBits.setBit (i);
  222044. return outputBits;
  222045. }
  222046. const BigInteger getActiveInputChannels() const
  222047. {
  222048. BigInteger inputBits;
  222049. for (int i = 0; i < inputPorts.size(); i++)
  222050. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222051. inputBits.setBit (i);
  222052. return inputBits;
  222053. }
  222054. int getOutputLatencyInSamples()
  222055. {
  222056. int latency = 0;
  222057. for (int i = 0; i < outputPorts.size(); i++)
  222058. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222059. return latency;
  222060. }
  222061. int getInputLatencyInSamples()
  222062. {
  222063. int latency = 0;
  222064. for (int i = 0; i < inputPorts.size(); i++)
  222065. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222066. return latency;
  222067. }
  222068. String inputId, outputId;
  222069. private:
  222070. void process (const int numSamples)
  222071. {
  222072. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222073. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222074. {
  222075. jack_default_audio_sample_t* in
  222076. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222077. if (in != 0)
  222078. inChans [numActiveInChans++] = (float*) in;
  222079. }
  222080. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222081. {
  222082. jack_default_audio_sample_t* out
  222083. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222084. if (out != 0)
  222085. outChans [numActiveOutChans++] = (float*) out;
  222086. }
  222087. const ScopedLock sl (callbackLock);
  222088. if (callback != 0)
  222089. {
  222090. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222091. outChans, numActiveOutChans, numSamples);
  222092. }
  222093. else
  222094. {
  222095. for (i = 0; i < numActiveOutChans; ++i)
  222096. zeromem (outChans[i], sizeof (float) * numSamples);
  222097. }
  222098. }
  222099. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222100. {
  222101. if (callbackArgument != 0)
  222102. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222103. return 0;
  222104. }
  222105. static void threadInitCallback (void* callbackArgument)
  222106. {
  222107. jack_Log ("JackAudioIODevice::initialise");
  222108. }
  222109. static void shutdownCallback (void* callbackArgument)
  222110. {
  222111. jack_Log ("JackAudioIODevice::shutdown");
  222112. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222113. if (device != 0)
  222114. {
  222115. device->client = 0;
  222116. device->close();
  222117. }
  222118. }
  222119. static void errorCallback (const char* msg)
  222120. {
  222121. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222122. }
  222123. bool isOpen_;
  222124. jack_client_t* client;
  222125. String lastError;
  222126. AudioIODeviceCallback* callback;
  222127. CriticalSection callbackLock;
  222128. HeapBlock <float*> inChans, outChans;
  222129. int totalNumberOfInputChannels;
  222130. int totalNumberOfOutputChannels;
  222131. Array<void*> inputPorts, outputPorts;
  222132. };
  222133. class JackAudioIODeviceType : public AudioIODeviceType
  222134. {
  222135. public:
  222136. JackAudioIODeviceType()
  222137. : AudioIODeviceType ("JACK"),
  222138. hasScanned (false)
  222139. {
  222140. }
  222141. ~JackAudioIODeviceType()
  222142. {
  222143. }
  222144. void scanForDevices()
  222145. {
  222146. hasScanned = true;
  222147. inputNames.clear();
  222148. inputIds.clear();
  222149. outputNames.clear();
  222150. outputIds.clear();
  222151. if (juce_libjack_handle == 0)
  222152. {
  222153. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222154. if (juce_libjack_handle == 0)
  222155. return;
  222156. }
  222157. // open a dummy client
  222158. jack_status_t status;
  222159. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222160. if (client == 0)
  222161. {
  222162. dumpJackErrorMessage (status);
  222163. }
  222164. else
  222165. {
  222166. // scan for output devices
  222167. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222168. if (ports != 0)
  222169. {
  222170. int j = 0;
  222171. while (ports[j] != 0)
  222172. {
  222173. String clientName (ports[j]);
  222174. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222175. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222176. && ! inputNames.contains (clientName))
  222177. {
  222178. inputNames.add (clientName);
  222179. inputIds.add (ports [j]);
  222180. }
  222181. ++j;
  222182. }
  222183. free (ports);
  222184. }
  222185. // scan for input devices
  222186. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222187. if (ports != 0)
  222188. {
  222189. int j = 0;
  222190. while (ports[j] != 0)
  222191. {
  222192. String clientName (ports[j]);
  222193. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222194. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222195. && ! outputNames.contains (clientName))
  222196. {
  222197. outputNames.add (clientName);
  222198. outputIds.add (ports [j]);
  222199. }
  222200. ++j;
  222201. }
  222202. free (ports);
  222203. }
  222204. JUCE_NAMESPACE::jack_client_close (client);
  222205. }
  222206. }
  222207. const StringArray getDeviceNames (bool wantInputNames) const
  222208. {
  222209. jassert (hasScanned); // need to call scanForDevices() before doing this
  222210. return wantInputNames ? inputNames : outputNames;
  222211. }
  222212. int getDefaultDeviceIndex (bool forInput) const
  222213. {
  222214. jassert (hasScanned); // need to call scanForDevices() before doing this
  222215. return 0;
  222216. }
  222217. bool hasSeparateInputsAndOutputs() const { return true; }
  222218. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222219. {
  222220. jassert (hasScanned); // need to call scanForDevices() before doing this
  222221. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222222. if (d == 0)
  222223. return -1;
  222224. return asInput ? inputIds.indexOf (d->inputId)
  222225. : outputIds.indexOf (d->outputId);
  222226. }
  222227. AudioIODevice* createDevice (const String& outputDeviceName,
  222228. const String& inputDeviceName)
  222229. {
  222230. jassert (hasScanned); // need to call scanForDevices() before doing this
  222231. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222232. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222233. if (inputIndex >= 0 || outputIndex >= 0)
  222234. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222235. : inputDeviceName,
  222236. inputIds [inputIndex],
  222237. outputIds [outputIndex]);
  222238. return 0;
  222239. }
  222240. juce_UseDebuggingNewOperator
  222241. private:
  222242. StringArray inputNames, outputNames, inputIds, outputIds;
  222243. bool hasScanned;
  222244. JackAudioIODeviceType (const JackAudioIODeviceType&);
  222245. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  222246. };
  222247. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222248. {
  222249. return new JackAudioIODeviceType();
  222250. }
  222251. #else // if JACK is turned off..
  222252. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222253. #endif
  222254. #endif
  222255. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222256. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222257. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222258. // compiled on its own).
  222259. #if JUCE_INCLUDED_FILE
  222260. #if JUCE_ALSA
  222261. static snd_seq_t* iterateDevices (const bool forInput,
  222262. StringArray& deviceNamesFound,
  222263. const int deviceIndexToOpen)
  222264. {
  222265. snd_seq_t* returnedHandle = 0;
  222266. snd_seq_t* seqHandle;
  222267. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222268. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222269. {
  222270. snd_seq_system_info_t* systemInfo;
  222271. snd_seq_client_info_t* clientInfo;
  222272. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222273. {
  222274. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222275. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222276. {
  222277. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222278. while (--numClients >= 0 && returnedHandle == 0)
  222279. {
  222280. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222281. {
  222282. snd_seq_port_info_t* portInfo;
  222283. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222284. {
  222285. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222286. const int client = snd_seq_client_info_get_client (clientInfo);
  222287. snd_seq_port_info_set_client (portInfo, client);
  222288. snd_seq_port_info_set_port (portInfo, -1);
  222289. while (--numPorts >= 0)
  222290. {
  222291. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222292. && (snd_seq_port_info_get_capability (portInfo)
  222293. & (forInput ? SND_SEQ_PORT_CAP_READ
  222294. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222295. {
  222296. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222297. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222298. {
  222299. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222300. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222301. if (sourcePort != -1)
  222302. {
  222303. snd_seq_set_client_name (seqHandle,
  222304. forInput ? "Juce Midi Input"
  222305. : "Juce Midi Output");
  222306. const int portId
  222307. = snd_seq_create_simple_port (seqHandle,
  222308. forInput ? "Juce Midi In Port"
  222309. : "Juce Midi Out Port",
  222310. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222311. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222312. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222313. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222314. returnedHandle = seqHandle;
  222315. }
  222316. }
  222317. }
  222318. }
  222319. snd_seq_port_info_free (portInfo);
  222320. }
  222321. }
  222322. }
  222323. snd_seq_client_info_free (clientInfo);
  222324. }
  222325. snd_seq_system_info_free (systemInfo);
  222326. }
  222327. if (returnedHandle == 0)
  222328. snd_seq_close (seqHandle);
  222329. }
  222330. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222331. return returnedHandle;
  222332. }
  222333. static snd_seq_t* createDevice (const bool forInput,
  222334. const String& deviceNameToOpen)
  222335. {
  222336. snd_seq_t* seqHandle = 0;
  222337. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222338. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222339. {
  222340. snd_seq_set_client_name (seqHandle,
  222341. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222342. const int portId
  222343. = snd_seq_create_simple_port (seqHandle,
  222344. forInput ? "in"
  222345. : "out",
  222346. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222347. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222348. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222349. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222350. if (portId < 0)
  222351. {
  222352. snd_seq_close (seqHandle);
  222353. seqHandle = 0;
  222354. }
  222355. }
  222356. return seqHandle;
  222357. }
  222358. class MidiOutputDevice
  222359. {
  222360. public:
  222361. MidiOutputDevice (MidiOutput* const midiOutput_,
  222362. snd_seq_t* const seqHandle_)
  222363. :
  222364. midiOutput (midiOutput_),
  222365. seqHandle (seqHandle_),
  222366. maxEventSize (16 * 1024)
  222367. {
  222368. jassert (seqHandle != 0 && midiOutput != 0);
  222369. snd_midi_event_new (maxEventSize, &midiParser);
  222370. }
  222371. ~MidiOutputDevice()
  222372. {
  222373. snd_midi_event_free (midiParser);
  222374. snd_seq_close (seqHandle);
  222375. }
  222376. void sendMessageNow (const MidiMessage& message)
  222377. {
  222378. if (message.getRawDataSize() > maxEventSize)
  222379. {
  222380. maxEventSize = message.getRawDataSize();
  222381. snd_midi_event_free (midiParser);
  222382. snd_midi_event_new (maxEventSize, &midiParser);
  222383. }
  222384. snd_seq_event_t event;
  222385. snd_seq_ev_clear (&event);
  222386. snd_midi_event_encode (midiParser,
  222387. message.getRawData(),
  222388. message.getRawDataSize(),
  222389. &event);
  222390. snd_midi_event_reset_encode (midiParser);
  222391. snd_seq_ev_set_source (&event, 0);
  222392. snd_seq_ev_set_subs (&event);
  222393. snd_seq_ev_set_direct (&event);
  222394. snd_seq_event_output (seqHandle, &event);
  222395. snd_seq_drain_output (seqHandle);
  222396. }
  222397. juce_UseDebuggingNewOperator
  222398. private:
  222399. MidiOutput* const midiOutput;
  222400. snd_seq_t* const seqHandle;
  222401. snd_midi_event_t* midiParser;
  222402. int maxEventSize;
  222403. };
  222404. const StringArray MidiOutput::getDevices()
  222405. {
  222406. StringArray devices;
  222407. iterateDevices (false, devices, -1);
  222408. return devices;
  222409. }
  222410. int MidiOutput::getDefaultDeviceIndex()
  222411. {
  222412. return 0;
  222413. }
  222414. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222415. {
  222416. MidiOutput* newDevice = 0;
  222417. StringArray devices;
  222418. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222419. if (handle != 0)
  222420. {
  222421. newDevice = new MidiOutput();
  222422. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222423. }
  222424. return newDevice;
  222425. }
  222426. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222427. {
  222428. MidiOutput* newDevice = 0;
  222429. snd_seq_t* const handle = createDevice (false, deviceName);
  222430. if (handle != 0)
  222431. {
  222432. newDevice = new MidiOutput();
  222433. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222434. }
  222435. return newDevice;
  222436. }
  222437. MidiOutput::~MidiOutput()
  222438. {
  222439. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222440. delete device;
  222441. }
  222442. void MidiOutput::reset()
  222443. {
  222444. }
  222445. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222446. {
  222447. return false;
  222448. }
  222449. void MidiOutput::setVolume (float leftVol, float rightVol)
  222450. {
  222451. }
  222452. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222453. {
  222454. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222455. }
  222456. class MidiInputThread : public Thread
  222457. {
  222458. public:
  222459. MidiInputThread (MidiInput* const midiInput_,
  222460. snd_seq_t* const seqHandle_,
  222461. MidiInputCallback* const callback_)
  222462. : Thread ("Juce MIDI Input"),
  222463. midiInput (midiInput_),
  222464. seqHandle (seqHandle_),
  222465. callback (callback_)
  222466. {
  222467. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222468. }
  222469. ~MidiInputThread()
  222470. {
  222471. snd_seq_close (seqHandle);
  222472. }
  222473. void run()
  222474. {
  222475. const int maxEventSize = 16 * 1024;
  222476. snd_midi_event_t* midiParser;
  222477. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222478. {
  222479. HeapBlock <uint8> buffer (maxEventSize);
  222480. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222481. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222482. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222483. while (! threadShouldExit())
  222484. {
  222485. if (poll (pfd, numPfds, 500) > 0)
  222486. {
  222487. snd_seq_event_t* inputEvent = 0;
  222488. snd_seq_nonblock (seqHandle, 1);
  222489. do
  222490. {
  222491. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222492. {
  222493. // xxx what about SYSEXes that are too big for the buffer?
  222494. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222495. snd_midi_event_reset_decode (midiParser);
  222496. if (numBytes > 0)
  222497. {
  222498. const MidiMessage message ((const uint8*) buffer,
  222499. numBytes,
  222500. Time::getMillisecondCounter() * 0.001);
  222501. callback->handleIncomingMidiMessage (midiInput, message);
  222502. }
  222503. snd_seq_free_event (inputEvent);
  222504. }
  222505. }
  222506. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222507. snd_seq_free_event (inputEvent);
  222508. }
  222509. }
  222510. snd_midi_event_free (midiParser);
  222511. }
  222512. };
  222513. juce_UseDebuggingNewOperator
  222514. private:
  222515. MidiInput* const midiInput;
  222516. snd_seq_t* const seqHandle;
  222517. MidiInputCallback* const callback;
  222518. };
  222519. MidiInput::MidiInput (const String& name_)
  222520. : name (name_),
  222521. internal (0)
  222522. {
  222523. }
  222524. MidiInput::~MidiInput()
  222525. {
  222526. stop();
  222527. MidiInputThread* const thread = (MidiInputThread*) internal;
  222528. delete thread;
  222529. }
  222530. void MidiInput::start()
  222531. {
  222532. ((MidiInputThread*) internal)->startThread();
  222533. }
  222534. void MidiInput::stop()
  222535. {
  222536. ((MidiInputThread*) internal)->stopThread (3000);
  222537. }
  222538. int MidiInput::getDefaultDeviceIndex()
  222539. {
  222540. return 0;
  222541. }
  222542. const StringArray MidiInput::getDevices()
  222543. {
  222544. StringArray devices;
  222545. iterateDevices (true, devices, -1);
  222546. return devices;
  222547. }
  222548. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222549. {
  222550. MidiInput* newDevice = 0;
  222551. StringArray devices;
  222552. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222553. if (handle != 0)
  222554. {
  222555. newDevice = new MidiInput (devices [deviceIndex]);
  222556. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222557. }
  222558. return newDevice;
  222559. }
  222560. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222561. {
  222562. MidiInput* newDevice = 0;
  222563. snd_seq_t* const handle = createDevice (true, deviceName);
  222564. if (handle != 0)
  222565. {
  222566. newDevice = new MidiInput (deviceName);
  222567. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222568. }
  222569. return newDevice;
  222570. }
  222571. #else
  222572. // (These are just stub functions if ALSA is unavailable...)
  222573. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222574. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222575. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222576. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222577. MidiOutput::~MidiOutput() {}
  222578. void MidiOutput::reset() {}
  222579. bool MidiOutput::getVolume (float&, float&) { return false; }
  222580. void MidiOutput::setVolume (float, float) {}
  222581. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222582. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222583. MidiInput::~MidiInput() {}
  222584. void MidiInput::start() {}
  222585. void MidiInput::stop() {}
  222586. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222587. const StringArray MidiInput::getDevices() { return StringArray(); }
  222588. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222589. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222590. #endif
  222591. #endif
  222592. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222593. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222594. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222595. // compiled on its own).
  222596. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222597. AudioCDReader::AudioCDReader()
  222598. : AudioFormatReader (0, "CD Audio")
  222599. {
  222600. }
  222601. const StringArray AudioCDReader::getAvailableCDNames()
  222602. {
  222603. StringArray names;
  222604. return names;
  222605. }
  222606. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222607. {
  222608. return 0;
  222609. }
  222610. AudioCDReader::~AudioCDReader()
  222611. {
  222612. }
  222613. void AudioCDReader::refreshTrackLengths()
  222614. {
  222615. }
  222616. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222617. int64 startSampleInFile, int numSamples)
  222618. {
  222619. return false;
  222620. }
  222621. bool AudioCDReader::isCDStillPresent() const
  222622. {
  222623. return false;
  222624. }
  222625. bool AudioCDReader::isTrackAudio (int trackNum) const
  222626. {
  222627. return false;
  222628. }
  222629. void AudioCDReader::enableIndexScanning (bool b)
  222630. {
  222631. }
  222632. int AudioCDReader::getLastIndex() const
  222633. {
  222634. return 0;
  222635. }
  222636. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222637. {
  222638. return Array<int>();
  222639. }
  222640. #endif
  222641. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222642. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222643. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222644. // compiled on its own).
  222645. #if JUCE_INCLUDED_FILE
  222646. void FileChooser::showPlatformDialog (Array<File>& results,
  222647. const String& title,
  222648. const File& file,
  222649. const String& filters,
  222650. bool isDirectory,
  222651. bool selectsFiles,
  222652. bool isSave,
  222653. bool warnAboutOverwritingExistingFiles,
  222654. bool selectMultipleFiles,
  222655. FilePreviewComponent* previewComponent)
  222656. {
  222657. const String separator (":");
  222658. String command ("zenity --file-selection");
  222659. if (title.isNotEmpty())
  222660. command << " --title=\"" << title << "\"";
  222661. if (file != File::nonexistent)
  222662. command << " --filename=\"" << file.getFullPathName () << "\"";
  222663. if (isDirectory)
  222664. command << " --directory";
  222665. if (isSave)
  222666. command << " --save";
  222667. if (selectMultipleFiles)
  222668. command << " --multiple --separator=\"" << separator << "\"";
  222669. command << " 2>&1";
  222670. MemoryOutputStream result;
  222671. int status = -1;
  222672. FILE* stream = popen (command.toUTF8(), "r");
  222673. if (stream != 0)
  222674. {
  222675. for (;;)
  222676. {
  222677. char buffer [1024];
  222678. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222679. if (bytesRead <= 0)
  222680. break;
  222681. result.write (buffer, bytesRead);
  222682. }
  222683. status = pclose (stream);
  222684. }
  222685. if (status == 0)
  222686. {
  222687. StringArray tokens;
  222688. if (selectMultipleFiles)
  222689. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222690. else
  222691. tokens.add (result.toUTF8());
  222692. for (int i = 0; i < tokens.size(); i++)
  222693. results.add (File (tokens[i]));
  222694. return;
  222695. }
  222696. //xxx ain't got one!
  222697. jassertfalse;
  222698. }
  222699. #endif
  222700. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222701. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222702. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222703. // compiled on its own).
  222704. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222705. /*
  222706. Sorry.. This class isn't implemented on Linux!
  222707. */
  222708. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222709. : browser (0),
  222710. blankPageShown (false),
  222711. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222712. {
  222713. setOpaque (true);
  222714. }
  222715. WebBrowserComponent::~WebBrowserComponent()
  222716. {
  222717. }
  222718. void WebBrowserComponent::goToURL (const String& url,
  222719. const StringArray* headers,
  222720. const MemoryBlock* postData)
  222721. {
  222722. lastURL = url;
  222723. lastHeaders.clear();
  222724. if (headers != 0)
  222725. lastHeaders = *headers;
  222726. lastPostData.setSize (0);
  222727. if (postData != 0)
  222728. lastPostData = *postData;
  222729. blankPageShown = false;
  222730. }
  222731. void WebBrowserComponent::stop()
  222732. {
  222733. }
  222734. void WebBrowserComponent::goBack()
  222735. {
  222736. lastURL = String::empty;
  222737. blankPageShown = false;
  222738. }
  222739. void WebBrowserComponent::goForward()
  222740. {
  222741. lastURL = String::empty;
  222742. }
  222743. void WebBrowserComponent::refresh()
  222744. {
  222745. }
  222746. void WebBrowserComponent::paint (Graphics& g)
  222747. {
  222748. g.fillAll (Colours::white);
  222749. }
  222750. void WebBrowserComponent::checkWindowAssociation()
  222751. {
  222752. }
  222753. void WebBrowserComponent::reloadLastURL()
  222754. {
  222755. if (lastURL.isNotEmpty())
  222756. {
  222757. goToURL (lastURL, &lastHeaders, &lastPostData);
  222758. lastURL = String::empty;
  222759. }
  222760. }
  222761. void WebBrowserComponent::parentHierarchyChanged()
  222762. {
  222763. checkWindowAssociation();
  222764. }
  222765. void WebBrowserComponent::resized()
  222766. {
  222767. }
  222768. void WebBrowserComponent::visibilityChanged()
  222769. {
  222770. checkWindowAssociation();
  222771. }
  222772. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222773. {
  222774. return true;
  222775. }
  222776. #endif
  222777. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222778. #endif
  222779. END_JUCE_NAMESPACE
  222780. #endif
  222781. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222782. #endif
  222783. #if JUCE_MAC || JUCE_IPHONE
  222784. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222785. /*
  222786. This file wraps together all the mac-specific code, so that
  222787. we can include all the native headers just once, and compile all our
  222788. platform-specific stuff in one big lump, keeping it out of the way of
  222789. the rest of the codebase.
  222790. */
  222791. #if JUCE_MAC || JUCE_IOS
  222792. BEGIN_JUCE_NAMESPACE
  222793. #undef Point
  222794. #define JUCE_INCLUDED_FILE 1
  222795. // Now include the actual code files..
  222796. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222797. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222798. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222799. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222800. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222801. actually calling into a similarly named class in the other module's address space.
  222802. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222803. have unique names, and should avoid this problem.
  222804. If you're using the amalgamated version, you can just set this macro to something unique before
  222805. you include juce_amalgamated.cpp.
  222806. */
  222807. #ifndef JUCE_ObjCExtraSuffix
  222808. #define JUCE_ObjCExtraSuffix 3
  222809. #endif
  222810. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222811. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222812. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222813. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222814. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222815. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222816. // compiled on its own).
  222817. #if JUCE_INCLUDED_FILE
  222818. static const String nsStringToJuce (NSString* s)
  222819. {
  222820. return String::fromUTF8 ([s UTF8String]);
  222821. }
  222822. static NSString* juceStringToNS (const String& s)
  222823. {
  222824. return [NSString stringWithUTF8String: s.toUTF8()];
  222825. }
  222826. static const String convertUTF16ToString (const UniChar* utf16)
  222827. {
  222828. String s;
  222829. while (*utf16 != 0)
  222830. s += (juce_wchar) *utf16++;
  222831. return s;
  222832. }
  222833. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222834. {
  222835. String result;
  222836. if (cfString != 0)
  222837. {
  222838. CFRange range = { 0, CFStringGetLength (cfString) };
  222839. HeapBlock <UniChar> u (range.length + 1);
  222840. CFStringGetCharacters (cfString, range, u);
  222841. u[range.length] = 0;
  222842. result = convertUTF16ToString (u);
  222843. }
  222844. return result;
  222845. }
  222846. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222847. {
  222848. const int len = s.length();
  222849. HeapBlock <UniChar> temp (len + 2);
  222850. for (int i = 0; i <= len; ++i)
  222851. temp[i] = s[i];
  222852. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222853. }
  222854. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222855. {
  222856. #if JUCE_IOS
  222857. const ScopedAutoReleasePool pool;
  222858. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222859. #else
  222860. UnicodeMapping map;
  222861. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222862. kUnicodeNoSubset,
  222863. kTextEncodingDefaultFormat);
  222864. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222865. kUnicodeCanonicalCompVariant,
  222866. kTextEncodingDefaultFormat);
  222867. map.mappingVersion = kUnicodeUseLatestMapping;
  222868. UnicodeToTextInfo conversionInfo = 0;
  222869. String result;
  222870. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222871. {
  222872. const int len = s.length();
  222873. HeapBlock <UniChar> tempIn, tempOut;
  222874. tempIn.calloc (len + 2);
  222875. tempOut.calloc (len + 2);
  222876. for (int i = 0; i <= len; ++i)
  222877. tempIn[i] = s[i];
  222878. ByteCount bytesRead = 0;
  222879. ByteCount outputBufferSize = 0;
  222880. if (ConvertFromUnicodeToText (conversionInfo,
  222881. len * sizeof (UniChar), tempIn,
  222882. kUnicodeDefaultDirectionMask,
  222883. 0, 0, 0, 0,
  222884. len * sizeof (UniChar), &bytesRead,
  222885. &outputBufferSize, tempOut) == noErr)
  222886. {
  222887. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222888. juce_wchar* t = result;
  222889. unsigned int i;
  222890. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222891. t[i] = (juce_wchar) tempOut[i];
  222892. t[i] = 0;
  222893. }
  222894. DisposeUnicodeToTextInfo (&conversionInfo);
  222895. }
  222896. return result;
  222897. #endif
  222898. }
  222899. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222900. void SystemClipboard::copyTextToClipboard (const String& text)
  222901. {
  222902. #if JUCE_IOS
  222903. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222904. forPasteboardType: @"public.text"];
  222905. #else
  222906. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222907. owner: nil];
  222908. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222909. forType: NSStringPboardType];
  222910. #endif
  222911. }
  222912. const String SystemClipboard::getTextFromClipboard()
  222913. {
  222914. #if JUCE_IOS
  222915. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222916. #else
  222917. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222918. #endif
  222919. return text == 0 ? String::empty
  222920. : nsStringToJuce (text);
  222921. }
  222922. #endif
  222923. #endif
  222924. /*** End of inlined file: juce_mac_Strings.mm ***/
  222925. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222926. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222927. // compiled on its own).
  222928. #if JUCE_INCLUDED_FILE
  222929. namespace SystemStatsHelpers
  222930. {
  222931. static int64 highResTimerFrequency = 0;
  222932. static double highResTimerToMillisecRatio = 0;
  222933. #if JUCE_INTEL
  222934. static void juce_getCpuVendor (char* const v) throw()
  222935. {
  222936. int vendor[4];
  222937. zerostruct (vendor);
  222938. int dummy = 0;
  222939. asm ("mov %%ebx, %%esi \n\t"
  222940. "cpuid \n\t"
  222941. "xchg %%esi, %%ebx"
  222942. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222943. memcpy (v, vendor, 16);
  222944. }
  222945. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222946. {
  222947. unsigned int cpu = 0;
  222948. unsigned int ext = 0;
  222949. unsigned int family = 0;
  222950. unsigned int dummy = 0;
  222951. asm ("mov %%ebx, %%esi \n\t"
  222952. "cpuid \n\t"
  222953. "xchg %%esi, %%ebx"
  222954. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222955. familyModel = family;
  222956. extFeatures = ext;
  222957. return cpu;
  222958. }
  222959. #endif
  222960. }
  222961. void SystemStats::initialiseStats()
  222962. {
  222963. using namespace SystemStatsHelpers;
  222964. static bool initialised = false;
  222965. if (! initialised)
  222966. {
  222967. initialised = true;
  222968. #if JUCE_MAC
  222969. [NSApplication sharedApplication];
  222970. #endif
  222971. #if JUCE_INTEL
  222972. unsigned int familyModel, extFeatures;
  222973. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  222974. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  222975. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  222976. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  222977. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  222978. #else
  222979. cpuFlags.hasMMX = false;
  222980. cpuFlags.hasSSE = false;
  222981. cpuFlags.hasSSE2 = false;
  222982. cpuFlags.has3DNow = false;
  222983. #endif
  222984. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  222985. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  222986. #else
  222987. cpuFlags.numCpus = (int) MPProcessors();
  222988. #endif
  222989. mach_timebase_info_data_t timebase;
  222990. (void) mach_timebase_info (&timebase);
  222991. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  222992. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  222993. String s (SystemStats::getJUCEVersion());
  222994. rlimit lim;
  222995. getrlimit (RLIMIT_NOFILE, &lim);
  222996. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  222997. setrlimit (RLIMIT_NOFILE, &lim);
  222998. }
  222999. }
  223000. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223001. {
  223002. return MacOSX;
  223003. }
  223004. const String SystemStats::getOperatingSystemName()
  223005. {
  223006. return "Mac OS X";
  223007. }
  223008. #if ! JUCE_IOS
  223009. int PlatformUtilities::getOSXMinorVersionNumber()
  223010. {
  223011. SInt32 versionMinor = 0;
  223012. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223013. (void) err;
  223014. jassert (err == noErr);
  223015. return (int) versionMinor;
  223016. }
  223017. #endif
  223018. bool SystemStats::isOperatingSystem64Bit()
  223019. {
  223020. #if JUCE_IOS
  223021. return false;
  223022. #elif JUCE_64BIT
  223023. return true;
  223024. #else
  223025. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223026. #endif
  223027. }
  223028. int SystemStats::getMemorySizeInMegabytes()
  223029. {
  223030. uint64 mem = 0;
  223031. size_t memSize = sizeof (mem);
  223032. int mib[] = { CTL_HW, HW_MEMSIZE };
  223033. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223034. return (int) (mem / (1024 * 1024));
  223035. }
  223036. const String SystemStats::getCpuVendor()
  223037. {
  223038. #if JUCE_INTEL
  223039. char v [16];
  223040. SystemStatsHelpers::juce_getCpuVendor (v);
  223041. return String (v, 16);
  223042. #else
  223043. return String::empty;
  223044. #endif
  223045. }
  223046. int SystemStats::getCpuSpeedInMegaherz()
  223047. {
  223048. uint64 speedHz = 0;
  223049. size_t speedSize = sizeof (speedHz);
  223050. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223051. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223052. #if JUCE_BIG_ENDIAN
  223053. if (speedSize == 4)
  223054. speedHz >>= 32;
  223055. #endif
  223056. return (int) (speedHz / 1000000);
  223057. }
  223058. const String SystemStats::getLogonName()
  223059. {
  223060. return nsStringToJuce (NSUserName());
  223061. }
  223062. const String SystemStats::getFullUserName()
  223063. {
  223064. return nsStringToJuce (NSFullUserName());
  223065. }
  223066. uint32 juce_millisecondsSinceStartup() throw()
  223067. {
  223068. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223069. }
  223070. double Time::getMillisecondCounterHiRes() throw()
  223071. {
  223072. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223073. }
  223074. int64 Time::getHighResolutionTicks() throw()
  223075. {
  223076. return (int64) mach_absolute_time();
  223077. }
  223078. int64 Time::getHighResolutionTicksPerSecond() throw()
  223079. {
  223080. return SystemStatsHelpers::highResTimerFrequency;
  223081. }
  223082. bool Time::setSystemTimeToThisTime() const
  223083. {
  223084. jassertfalse;
  223085. return false;
  223086. }
  223087. int SystemStats::getPageSize()
  223088. {
  223089. return (int) NSPageSize();
  223090. }
  223091. void PlatformUtilities::fpuReset()
  223092. {
  223093. }
  223094. #endif
  223095. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223096. /*** Start of inlined file: juce_mac_Network.mm ***/
  223097. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223098. // compiled on its own).
  223099. #if JUCE_INCLUDED_FILE
  223100. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  223101. {
  223102. #ifndef IFT_ETHER
  223103. #define IFT_ETHER 6
  223104. #endif
  223105. ifaddrs* addrs = 0;
  223106. int numResults = 0;
  223107. if (getifaddrs (&addrs) == 0)
  223108. {
  223109. const ifaddrs* cursor = addrs;
  223110. while (cursor != 0 && numResults < maxNum)
  223111. {
  223112. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223113. if (sto->ss_family == AF_LINK)
  223114. {
  223115. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223116. if (sadd->sdl_type == IFT_ETHER)
  223117. {
  223118. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  223119. uint64 a = 0;
  223120. for (int i = 6; --i >= 0;)
  223121. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  223122. *addresses++ = (int64) a;
  223123. ++numResults;
  223124. }
  223125. }
  223126. cursor = cursor->ifa_next;
  223127. }
  223128. freeifaddrs (addrs);
  223129. }
  223130. return numResults;
  223131. }
  223132. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223133. const String& emailSubject,
  223134. const String& bodyText,
  223135. const StringArray& filesToAttach)
  223136. {
  223137. #if JUCE_IOS
  223138. //xxx probably need to use MFMailComposeViewController
  223139. jassertfalse;
  223140. return false;
  223141. #else
  223142. const ScopedAutoReleasePool pool;
  223143. String script;
  223144. script << "tell application \"Mail\"\r\n"
  223145. "set newMessage to make new outgoing message with properties {subject:\""
  223146. << emailSubject.replace ("\"", "\\\"")
  223147. << "\", content:\""
  223148. << bodyText.replace ("\"", "\\\"")
  223149. << "\" & return & return}\r\n"
  223150. "tell newMessage\r\n"
  223151. "set visible to true\r\n"
  223152. "set sender to \"sdfsdfsdfewf\"\r\n"
  223153. "make new to recipient at end of to recipients with properties {address:\""
  223154. << targetEmailAddress
  223155. << "\"}\r\n";
  223156. for (int i = 0; i < filesToAttach.size(); ++i)
  223157. {
  223158. script << "tell content\r\n"
  223159. "make new attachment with properties {file name:\""
  223160. << filesToAttach[i].replace ("\"", "\\\"")
  223161. << "\"} at after the last paragraph\r\n"
  223162. "end tell\r\n";
  223163. }
  223164. script << "end tell\r\n"
  223165. "end tell\r\n";
  223166. NSAppleScript* s = [[NSAppleScript alloc]
  223167. initWithSource: juceStringToNS (script)];
  223168. NSDictionary* error = 0;
  223169. const bool ok = [s executeAndReturnError: &error] != nil;
  223170. [s release];
  223171. return ok;
  223172. #endif
  223173. }
  223174. END_JUCE_NAMESPACE
  223175. using namespace JUCE_NAMESPACE;
  223176. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223177. @interface JuceURLConnection : NSObject
  223178. {
  223179. @public
  223180. NSURLRequest* request;
  223181. NSURLConnection* connection;
  223182. NSMutableData* data;
  223183. Thread* runLoopThread;
  223184. bool initialised, hasFailed, hasFinished;
  223185. int position;
  223186. int64 contentLength;
  223187. NSDictionary* headers;
  223188. NSLock* dataLock;
  223189. }
  223190. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223191. - (void) dealloc;
  223192. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223193. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223194. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223195. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223196. - (BOOL) isOpen;
  223197. - (int) read: (char*) dest numBytes: (int) num;
  223198. - (int) readPosition;
  223199. - (void) stop;
  223200. - (void) createConnection;
  223201. @end
  223202. class JuceURLConnectionMessageThread : public Thread
  223203. {
  223204. JuceURLConnection* owner;
  223205. public:
  223206. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223207. : Thread ("http connection"),
  223208. owner (owner_)
  223209. {
  223210. }
  223211. ~JuceURLConnectionMessageThread()
  223212. {
  223213. stopThread (10000);
  223214. }
  223215. void run()
  223216. {
  223217. [owner createConnection];
  223218. while (! threadShouldExit())
  223219. {
  223220. const ScopedAutoReleasePool pool;
  223221. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223222. }
  223223. }
  223224. };
  223225. @implementation JuceURLConnection
  223226. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223227. withCallback: (URL::OpenStreamProgressCallback*) callback
  223228. withContext: (void*) context;
  223229. {
  223230. [super init];
  223231. request = req;
  223232. [request retain];
  223233. data = [[NSMutableData data] retain];
  223234. dataLock = [[NSLock alloc] init];
  223235. connection = 0;
  223236. initialised = false;
  223237. hasFailed = false;
  223238. hasFinished = false;
  223239. contentLength = -1;
  223240. headers = 0;
  223241. runLoopThread = new JuceURLConnectionMessageThread (self);
  223242. runLoopThread->startThread();
  223243. while (runLoopThread->isThreadRunning() && ! initialised)
  223244. {
  223245. if (callback != 0)
  223246. callback (context, -1, (int) [[request HTTPBody] length]);
  223247. Thread::sleep (1);
  223248. }
  223249. return self;
  223250. }
  223251. - (void) dealloc
  223252. {
  223253. [self stop];
  223254. deleteAndZero (runLoopThread);
  223255. [connection release];
  223256. [data release];
  223257. [dataLock release];
  223258. [request release];
  223259. [headers release];
  223260. [super dealloc];
  223261. }
  223262. - (void) createConnection
  223263. {
  223264. NSUInteger oldRetainCount = [self retainCount];
  223265. connection = [[NSURLConnection alloc] initWithRequest: request
  223266. delegate: self];
  223267. if (oldRetainCount == [self retainCount])
  223268. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223269. if (connection == nil)
  223270. runLoopThread->signalThreadShouldExit();
  223271. }
  223272. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223273. {
  223274. (void) conn;
  223275. [dataLock lock];
  223276. [data setLength: 0];
  223277. [dataLock unlock];
  223278. initialised = true;
  223279. contentLength = [response expectedContentLength];
  223280. [headers release];
  223281. headers = 0;
  223282. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223283. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223284. }
  223285. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223286. {
  223287. (void) conn;
  223288. DBG (nsStringToJuce ([error description]));
  223289. hasFailed = true;
  223290. initialised = true;
  223291. if (runLoopThread != 0)
  223292. runLoopThread->signalThreadShouldExit();
  223293. }
  223294. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223295. {
  223296. (void) conn;
  223297. [dataLock lock];
  223298. [data appendData: newData];
  223299. [dataLock unlock];
  223300. initialised = true;
  223301. }
  223302. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223303. {
  223304. (void) conn;
  223305. hasFinished = true;
  223306. initialised = true;
  223307. if (runLoopThread != 0)
  223308. runLoopThread->signalThreadShouldExit();
  223309. }
  223310. - (BOOL) isOpen
  223311. {
  223312. return connection != 0 && ! hasFailed;
  223313. }
  223314. - (int) readPosition
  223315. {
  223316. return position;
  223317. }
  223318. - (int) read: (char*) dest numBytes: (int) numNeeded
  223319. {
  223320. int numDone = 0;
  223321. while (numNeeded > 0)
  223322. {
  223323. int available = jmin (numNeeded, (int) [data length]);
  223324. if (available > 0)
  223325. {
  223326. [dataLock lock];
  223327. [data getBytes: dest length: available];
  223328. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223329. [dataLock unlock];
  223330. numDone += available;
  223331. numNeeded -= available;
  223332. dest += available;
  223333. }
  223334. else
  223335. {
  223336. if (hasFailed || hasFinished)
  223337. break;
  223338. Thread::sleep (1);
  223339. }
  223340. }
  223341. position += numDone;
  223342. return numDone;
  223343. }
  223344. - (void) stop
  223345. {
  223346. [connection cancel];
  223347. if (runLoopThread != 0)
  223348. runLoopThread->stopThread (10000);
  223349. }
  223350. @end
  223351. BEGIN_JUCE_NAMESPACE
  223352. void* juce_openInternetFile (const String& url,
  223353. const String& headers,
  223354. const MemoryBlock& postData,
  223355. const bool isPost,
  223356. URL::OpenStreamProgressCallback* callback,
  223357. void* callbackContext,
  223358. int timeOutMs)
  223359. {
  223360. const ScopedAutoReleasePool pool;
  223361. NSMutableURLRequest* req = [NSMutableURLRequest
  223362. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223363. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223364. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223365. if (req == nil)
  223366. return 0;
  223367. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223368. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223369. StringArray headerLines;
  223370. headerLines.addLines (headers);
  223371. headerLines.removeEmptyStrings (true);
  223372. for (int i = 0; i < headerLines.size(); ++i)
  223373. {
  223374. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223375. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223376. if (key.isNotEmpty() && value.isNotEmpty())
  223377. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223378. }
  223379. if (isPost && postData.getSize() > 0)
  223380. {
  223381. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223382. length: postData.getSize()]];
  223383. }
  223384. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223385. withCallback: callback
  223386. withContext: callbackContext];
  223387. if ([s isOpen])
  223388. return s;
  223389. [s release];
  223390. return 0;
  223391. }
  223392. void juce_closeInternetFile (void* handle)
  223393. {
  223394. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223395. if (s != 0)
  223396. {
  223397. const ScopedAutoReleasePool pool;
  223398. [s stop];
  223399. [s release];
  223400. }
  223401. }
  223402. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223403. {
  223404. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223405. if (s != 0)
  223406. {
  223407. const ScopedAutoReleasePool pool;
  223408. return [s read: (char*) buffer numBytes: bytesToRead];
  223409. }
  223410. return 0;
  223411. }
  223412. int64 juce_getInternetFileContentLength (void* handle)
  223413. {
  223414. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223415. if (s != 0)
  223416. return s->contentLength;
  223417. return -1;
  223418. }
  223419. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223420. {
  223421. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223422. if (s != 0 && s->headers != 0)
  223423. {
  223424. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223425. NSString* key;
  223426. while ((key = [enumerator nextObject]) != nil)
  223427. headers.set (nsStringToJuce (key),
  223428. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223429. }
  223430. }
  223431. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223432. {
  223433. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223434. if (s != 0)
  223435. return [s readPosition];
  223436. return 0;
  223437. }
  223438. #endif
  223439. /*** End of inlined file: juce_mac_Network.mm ***/
  223440. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223441. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223442. // compiled on its own).
  223443. #if JUCE_INCLUDED_FILE
  223444. struct NamedPipeInternal
  223445. {
  223446. String pipeInName, pipeOutName;
  223447. int pipeIn, pipeOut;
  223448. bool volatile createdPipe, blocked, stopReadOperation;
  223449. static void signalHandler (int) {}
  223450. };
  223451. void NamedPipe::cancelPendingReads()
  223452. {
  223453. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223454. {
  223455. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223456. intern->stopReadOperation = true;
  223457. char buffer [1] = { 0 };
  223458. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223459. (void) bytesWritten;
  223460. int timeout = 2000;
  223461. while (intern->blocked && --timeout >= 0)
  223462. Thread::sleep (2);
  223463. intern->stopReadOperation = false;
  223464. }
  223465. }
  223466. void NamedPipe::close()
  223467. {
  223468. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223469. if (intern != 0)
  223470. {
  223471. internal = 0;
  223472. if (intern->pipeIn != -1)
  223473. ::close (intern->pipeIn);
  223474. if (intern->pipeOut != -1)
  223475. ::close (intern->pipeOut);
  223476. if (intern->createdPipe)
  223477. {
  223478. unlink (intern->pipeInName.toUTF8());
  223479. unlink (intern->pipeOutName.toUTF8());
  223480. }
  223481. delete intern;
  223482. }
  223483. }
  223484. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223485. {
  223486. close();
  223487. NamedPipeInternal* const intern = new NamedPipeInternal();
  223488. internal = intern;
  223489. intern->createdPipe = createPipe;
  223490. intern->blocked = false;
  223491. intern->stopReadOperation = false;
  223492. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223493. siginterrupt (SIGPIPE, 1);
  223494. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223495. intern->pipeInName = pipePath + "_in";
  223496. intern->pipeOutName = pipePath + "_out";
  223497. intern->pipeIn = -1;
  223498. intern->pipeOut = -1;
  223499. if (createPipe)
  223500. {
  223501. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223502. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223503. {
  223504. delete intern;
  223505. internal = 0;
  223506. return false;
  223507. }
  223508. }
  223509. return true;
  223510. }
  223511. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223512. {
  223513. int bytesRead = -1;
  223514. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223515. if (intern != 0)
  223516. {
  223517. intern->blocked = true;
  223518. if (intern->pipeIn == -1)
  223519. {
  223520. if (intern->createdPipe)
  223521. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223522. else
  223523. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223524. if (intern->pipeIn == -1)
  223525. {
  223526. intern->blocked = false;
  223527. return -1;
  223528. }
  223529. }
  223530. bytesRead = 0;
  223531. char* p = (char*) destBuffer;
  223532. while (bytesRead < maxBytesToRead)
  223533. {
  223534. const int bytesThisTime = maxBytesToRead - bytesRead;
  223535. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223536. if (numRead <= 0 || intern->stopReadOperation)
  223537. {
  223538. bytesRead = -1;
  223539. break;
  223540. }
  223541. bytesRead += numRead;
  223542. p += bytesRead;
  223543. }
  223544. intern->blocked = false;
  223545. }
  223546. return bytesRead;
  223547. }
  223548. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223549. {
  223550. int bytesWritten = -1;
  223551. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223552. if (intern != 0)
  223553. {
  223554. if (intern->pipeOut == -1)
  223555. {
  223556. if (intern->createdPipe)
  223557. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223558. else
  223559. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223560. if (intern->pipeOut == -1)
  223561. {
  223562. return -1;
  223563. }
  223564. }
  223565. const char* p = (const char*) sourceBuffer;
  223566. bytesWritten = 0;
  223567. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223568. while (bytesWritten < numBytesToWrite
  223569. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223570. {
  223571. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223572. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223573. if (numWritten <= 0)
  223574. {
  223575. bytesWritten = -1;
  223576. break;
  223577. }
  223578. bytesWritten += numWritten;
  223579. p += bytesWritten;
  223580. }
  223581. }
  223582. return bytesWritten;
  223583. }
  223584. #endif
  223585. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223586. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223587. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223588. // compiled on its own).
  223589. #if JUCE_INCLUDED_FILE
  223590. /*
  223591. Note that a lot of methods that you'd expect to find in this file actually
  223592. live in juce_posix_SharedCode.h!
  223593. */
  223594. void JUCE_API juce_threadEntryPoint (void*);
  223595. void* threadEntryProc (void* userData)
  223596. {
  223597. const ScopedAutoReleasePool pool;
  223598. juce_threadEntryPoint (userData);
  223599. return 0;
  223600. }
  223601. void* juce_createThread (void* userData)
  223602. {
  223603. pthread_t handle = 0;
  223604. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223605. {
  223606. pthread_detach (handle);
  223607. return (void*) handle;
  223608. }
  223609. return 0;
  223610. }
  223611. void juce_killThread (void* handle)
  223612. {
  223613. if (handle != 0)
  223614. pthread_cancel ((pthread_t) handle);
  223615. }
  223616. void juce_setCurrentThreadName (const String& /*name*/)
  223617. {
  223618. }
  223619. bool juce_setThreadPriority (void* handle, int priority)
  223620. {
  223621. if (handle == 0)
  223622. handle = (void*) pthread_self();
  223623. struct sched_param param;
  223624. int policy;
  223625. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223626. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223627. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223628. }
  223629. Thread::ThreadID Thread::getCurrentThreadId()
  223630. {
  223631. return static_cast <ThreadID> (pthread_self());
  223632. }
  223633. void Thread::yield()
  223634. {
  223635. sched_yield();
  223636. }
  223637. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223638. {
  223639. // xxx
  223640. jassertfalse;
  223641. }
  223642. bool Process::isForegroundProcess()
  223643. {
  223644. #if JUCE_MAC
  223645. return [NSApp isActive];
  223646. #else
  223647. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223648. #endif
  223649. }
  223650. void Process::raisePrivilege()
  223651. {
  223652. jassertfalse;
  223653. }
  223654. void Process::lowerPrivilege()
  223655. {
  223656. jassertfalse;
  223657. }
  223658. void Process::terminate()
  223659. {
  223660. exit (0);
  223661. }
  223662. void Process::setPriority (ProcessPriority)
  223663. {
  223664. // xxx
  223665. }
  223666. #endif
  223667. /*** End of inlined file: juce_mac_Threads.mm ***/
  223668. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223669. /*
  223670. This file contains posix routines that are common to both the Linux and Mac builds.
  223671. It gets included directly in the cpp files for these platforms.
  223672. */
  223673. CriticalSection::CriticalSection() throw()
  223674. {
  223675. pthread_mutexattr_t atts;
  223676. pthread_mutexattr_init (&atts);
  223677. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223678. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223679. pthread_mutex_init (&internal, &atts);
  223680. }
  223681. CriticalSection::~CriticalSection() throw()
  223682. {
  223683. pthread_mutex_destroy (&internal);
  223684. }
  223685. void CriticalSection::enter() const throw()
  223686. {
  223687. pthread_mutex_lock (&internal);
  223688. }
  223689. bool CriticalSection::tryEnter() const throw()
  223690. {
  223691. return pthread_mutex_trylock (&internal) == 0;
  223692. }
  223693. void CriticalSection::exit() const throw()
  223694. {
  223695. pthread_mutex_unlock (&internal);
  223696. }
  223697. class WaitableEventImpl
  223698. {
  223699. public:
  223700. WaitableEventImpl (const bool manualReset_)
  223701. : triggered (false),
  223702. manualReset (manualReset_)
  223703. {
  223704. pthread_cond_init (&condition, 0);
  223705. pthread_mutexattr_t atts;
  223706. pthread_mutexattr_init (&atts);
  223707. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223708. pthread_mutex_init (&mutex, &atts);
  223709. }
  223710. ~WaitableEventImpl()
  223711. {
  223712. pthread_cond_destroy (&condition);
  223713. pthread_mutex_destroy (&mutex);
  223714. }
  223715. bool wait (const int timeOutMillisecs) throw()
  223716. {
  223717. pthread_mutex_lock (&mutex);
  223718. if (! triggered)
  223719. {
  223720. if (timeOutMillisecs < 0)
  223721. {
  223722. do
  223723. {
  223724. pthread_cond_wait (&condition, &mutex);
  223725. }
  223726. while (! triggered);
  223727. }
  223728. else
  223729. {
  223730. struct timeval now;
  223731. gettimeofday (&now, 0);
  223732. struct timespec time;
  223733. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223734. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223735. if (time.tv_nsec >= 1000000000)
  223736. {
  223737. time.tv_nsec -= 1000000000;
  223738. time.tv_sec++;
  223739. }
  223740. do
  223741. {
  223742. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223743. {
  223744. pthread_mutex_unlock (&mutex);
  223745. return false;
  223746. }
  223747. }
  223748. while (! triggered);
  223749. }
  223750. }
  223751. if (! manualReset)
  223752. triggered = false;
  223753. pthread_mutex_unlock (&mutex);
  223754. return true;
  223755. }
  223756. void signal() throw()
  223757. {
  223758. pthread_mutex_lock (&mutex);
  223759. triggered = true;
  223760. pthread_cond_broadcast (&condition);
  223761. pthread_mutex_unlock (&mutex);
  223762. }
  223763. void reset() throw()
  223764. {
  223765. pthread_mutex_lock (&mutex);
  223766. triggered = false;
  223767. pthread_mutex_unlock (&mutex);
  223768. }
  223769. private:
  223770. pthread_cond_t condition;
  223771. pthread_mutex_t mutex;
  223772. bool triggered;
  223773. const bool manualReset;
  223774. WaitableEventImpl (const WaitableEventImpl&);
  223775. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223776. };
  223777. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223778. : internal (new WaitableEventImpl (manualReset))
  223779. {
  223780. }
  223781. WaitableEvent::~WaitableEvent() throw()
  223782. {
  223783. delete static_cast <WaitableEventImpl*> (internal);
  223784. }
  223785. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223786. {
  223787. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223788. }
  223789. void WaitableEvent::signal() const throw()
  223790. {
  223791. static_cast <WaitableEventImpl*> (internal)->signal();
  223792. }
  223793. void WaitableEvent::reset() const throw()
  223794. {
  223795. static_cast <WaitableEventImpl*> (internal)->reset();
  223796. }
  223797. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223798. {
  223799. struct timespec time;
  223800. time.tv_sec = millisecs / 1000;
  223801. time.tv_nsec = (millisecs % 1000) * 1000000;
  223802. nanosleep (&time, 0);
  223803. }
  223804. const juce_wchar File::separator = '/';
  223805. const String File::separatorString ("/");
  223806. const File File::getCurrentWorkingDirectory()
  223807. {
  223808. HeapBlock<char> heapBuffer;
  223809. char localBuffer [1024];
  223810. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223811. int bufferSize = 4096;
  223812. while (cwd == 0 && errno == ERANGE)
  223813. {
  223814. heapBuffer.malloc (bufferSize);
  223815. cwd = getcwd (heapBuffer, bufferSize - 1);
  223816. bufferSize += 1024;
  223817. }
  223818. return File (String::fromUTF8 (cwd));
  223819. }
  223820. bool File::setAsCurrentWorkingDirectory() const
  223821. {
  223822. return chdir (getFullPathName().toUTF8()) == 0;
  223823. }
  223824. static bool juce_stat (const String& fileName, struct stat& info)
  223825. {
  223826. return fileName.isNotEmpty()
  223827. && (stat (fileName.toUTF8(), &info) == 0);
  223828. }
  223829. bool File::isDirectory() const
  223830. {
  223831. struct stat info;
  223832. return fullPath.isEmpty()
  223833. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223834. }
  223835. bool File::exists() const
  223836. {
  223837. return fullPath.isNotEmpty()
  223838. && access (fullPath.toUTF8(), F_OK) == 0;
  223839. }
  223840. bool File::existsAsFile() const
  223841. {
  223842. return exists() && ! isDirectory();
  223843. }
  223844. int64 File::getSize() const
  223845. {
  223846. struct stat info;
  223847. return juce_stat (fullPath, info) ? info.st_size : 0;
  223848. }
  223849. bool File::hasWriteAccess() const
  223850. {
  223851. if (exists())
  223852. return access (fullPath.toUTF8(), W_OK) == 0;
  223853. if ((! isDirectory()) && fullPath.containsChar (separator))
  223854. return getParentDirectory().hasWriteAccess();
  223855. return false;
  223856. }
  223857. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223858. {
  223859. struct stat info;
  223860. const int res = stat (fullPath.toUTF8(), &info);
  223861. if (res != 0)
  223862. return false;
  223863. info.st_mode &= 0777; // Just permissions
  223864. if (shouldBeReadOnly)
  223865. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223866. else
  223867. // Give everybody write permission?
  223868. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223869. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223870. }
  223871. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223872. {
  223873. modificationTime = 0;
  223874. accessTime = 0;
  223875. creationTime = 0;
  223876. struct stat info;
  223877. const int res = stat (fullPath.toUTF8(), &info);
  223878. if (res == 0)
  223879. {
  223880. modificationTime = (int64) info.st_mtime * 1000;
  223881. accessTime = (int64) info.st_atime * 1000;
  223882. creationTime = (int64) info.st_ctime * 1000;
  223883. }
  223884. }
  223885. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223886. {
  223887. struct utimbuf times;
  223888. times.actime = (time_t) (accessTime / 1000);
  223889. times.modtime = (time_t) (modificationTime / 1000);
  223890. return utime (fullPath.toUTF8(), &times) == 0;
  223891. }
  223892. bool File::deleteFile() const
  223893. {
  223894. if (! exists())
  223895. return true;
  223896. else if (isDirectory())
  223897. return rmdir (fullPath.toUTF8()) == 0;
  223898. else
  223899. return remove (fullPath.toUTF8()) == 0;
  223900. }
  223901. bool File::moveInternal (const File& dest) const
  223902. {
  223903. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223904. return true;
  223905. if (hasWriteAccess() && copyInternal (dest))
  223906. {
  223907. if (deleteFile())
  223908. return true;
  223909. dest.deleteFile();
  223910. }
  223911. return false;
  223912. }
  223913. void File::createDirectoryInternal (const String& fileName) const
  223914. {
  223915. mkdir (fileName.toUTF8(), 0777);
  223916. }
  223917. void* juce_fileOpen (const File& file, bool forWriting)
  223918. {
  223919. int flags = O_RDONLY;
  223920. if (forWriting)
  223921. {
  223922. if (file.exists())
  223923. {
  223924. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223925. if (f != -1)
  223926. lseek (f, 0, SEEK_END);
  223927. return (void*) f;
  223928. }
  223929. else
  223930. {
  223931. flags = O_RDWR + O_CREAT;
  223932. }
  223933. }
  223934. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223935. }
  223936. void juce_fileClose (void* handle)
  223937. {
  223938. if (handle != 0)
  223939. close ((int) (pointer_sized_int) handle);
  223940. }
  223941. int juce_fileRead (void* handle, void* buffer, int size)
  223942. {
  223943. if (handle != 0)
  223944. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223945. return 0;
  223946. }
  223947. int juce_fileWrite (void* handle, const void* buffer, int size)
  223948. {
  223949. if (handle != 0)
  223950. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223951. return 0;
  223952. }
  223953. int64 juce_fileSetPosition (void* handle, int64 pos)
  223954. {
  223955. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223956. return pos;
  223957. return -1;
  223958. }
  223959. int64 FileOutputStream::getPositionInternal() const
  223960. {
  223961. if (fileHandle != 0)
  223962. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223963. return -1;
  223964. }
  223965. void FileOutputStream::flushInternal()
  223966. {
  223967. if (fileHandle != 0)
  223968. fsync ((int) (pointer_sized_int) fileHandle);
  223969. }
  223970. const File juce_getExecutableFile()
  223971. {
  223972. Dl_info exeInfo;
  223973. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223974. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223975. }
  223976. // if this file doesn't exist, find a parent of it that does..
  223977. static bool juce_doStatFS (File f, struct statfs& result)
  223978. {
  223979. for (int i = 5; --i >= 0;)
  223980. {
  223981. if (f.exists())
  223982. break;
  223983. f = f.getParentDirectory();
  223984. }
  223985. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  223986. }
  223987. int64 File::getBytesFreeOnVolume() const
  223988. {
  223989. struct statfs buf;
  223990. if (juce_doStatFS (*this, buf))
  223991. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  223992. return 0;
  223993. }
  223994. int64 File::getVolumeTotalSize() const
  223995. {
  223996. struct statfs buf;
  223997. if (juce_doStatFS (*this, buf))
  223998. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  223999. return 0;
  224000. }
  224001. const String File::getVolumeLabel() const
  224002. {
  224003. #if JUCE_MAC
  224004. struct VolAttrBuf
  224005. {
  224006. u_int32_t length;
  224007. attrreference_t mountPointRef;
  224008. char mountPointSpace [MAXPATHLEN];
  224009. } attrBuf;
  224010. struct attrlist attrList;
  224011. zerostruct (attrList);
  224012. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224013. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224014. File f (*this);
  224015. for (;;)
  224016. {
  224017. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224018. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224019. (int) attrBuf.mountPointRef.attr_length);
  224020. const File parent (f.getParentDirectory());
  224021. if (f == parent)
  224022. break;
  224023. f = parent;
  224024. }
  224025. #endif
  224026. return String::empty;
  224027. }
  224028. int File::getVolumeSerialNumber() const
  224029. {
  224030. return 0; // xxx
  224031. }
  224032. void juce_runSystemCommand (const String& command)
  224033. {
  224034. int result = system (command.toUTF8());
  224035. (void) result;
  224036. }
  224037. const String juce_getOutputFromCommand (const String& command)
  224038. {
  224039. // slight bodge here, as we just pipe the output into a temp file and read it...
  224040. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224041. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224042. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224043. String result (tempFile.loadFileAsString());
  224044. tempFile.deleteFile();
  224045. return result;
  224046. }
  224047. class InterProcessLock::Pimpl
  224048. {
  224049. public:
  224050. Pimpl (const String& name, const int timeOutMillisecs)
  224051. : handle (0), refCount (1)
  224052. {
  224053. #if JUCE_MAC
  224054. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224055. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224056. #else
  224057. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224058. #endif
  224059. temp.create();
  224060. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224061. if (handle != 0)
  224062. {
  224063. struct flock fl;
  224064. zerostruct (fl);
  224065. fl.l_whence = SEEK_SET;
  224066. fl.l_type = F_WRLCK;
  224067. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224068. for (;;)
  224069. {
  224070. const int result = fcntl (handle, F_SETLK, &fl);
  224071. if (result >= 0)
  224072. return;
  224073. if (errno != EINTR)
  224074. {
  224075. if (timeOutMillisecs == 0
  224076. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224077. break;
  224078. Thread::sleep (10);
  224079. }
  224080. }
  224081. }
  224082. closeFile();
  224083. }
  224084. ~Pimpl()
  224085. {
  224086. closeFile();
  224087. }
  224088. void closeFile()
  224089. {
  224090. if (handle != 0)
  224091. {
  224092. struct flock fl;
  224093. zerostruct (fl);
  224094. fl.l_whence = SEEK_SET;
  224095. fl.l_type = F_UNLCK;
  224096. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224097. {}
  224098. close (handle);
  224099. handle = 0;
  224100. }
  224101. }
  224102. int handle, refCount;
  224103. };
  224104. InterProcessLock::InterProcessLock (const String& name_)
  224105. : name (name_)
  224106. {
  224107. }
  224108. InterProcessLock::~InterProcessLock()
  224109. {
  224110. }
  224111. bool InterProcessLock::enter (const int timeOutMillisecs)
  224112. {
  224113. const ScopedLock sl (lock);
  224114. if (pimpl == 0)
  224115. {
  224116. pimpl = new Pimpl (name, timeOutMillisecs);
  224117. if (pimpl->handle == 0)
  224118. pimpl = 0;
  224119. }
  224120. else
  224121. {
  224122. pimpl->refCount++;
  224123. }
  224124. return pimpl != 0;
  224125. }
  224126. void InterProcessLock::exit()
  224127. {
  224128. const ScopedLock sl (lock);
  224129. // Trying to release the lock too many times!
  224130. jassert (pimpl != 0);
  224131. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224132. pimpl = 0;
  224133. }
  224134. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224135. /*** Start of inlined file: juce_mac_Files.mm ***/
  224136. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224137. // compiled on its own).
  224138. #if JUCE_INCLUDED_FILE
  224139. /*
  224140. Note that a lot of methods that you'd expect to find in this file actually
  224141. live in juce_posix_SharedCode.h!
  224142. */
  224143. bool File::copyInternal (const File& dest) const
  224144. {
  224145. const ScopedAutoReleasePool pool;
  224146. NSFileManager* fm = [NSFileManager defaultManager];
  224147. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224148. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224149. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224150. toPath: juceStringToNS (dest.getFullPathName())
  224151. error: nil];
  224152. #else
  224153. && [fm copyPath: juceStringToNS (fullPath)
  224154. toPath: juceStringToNS (dest.getFullPathName())
  224155. handler: nil];
  224156. #endif
  224157. }
  224158. void File::findFileSystemRoots (Array<File>& destArray)
  224159. {
  224160. destArray.add (File ("/"));
  224161. }
  224162. static bool isFileOnDriveType (const File& f, const char* const* types)
  224163. {
  224164. struct statfs buf;
  224165. if (juce_doStatFS (f, buf))
  224166. {
  224167. const String type (buf.f_fstypename);
  224168. while (*types != 0)
  224169. if (type.equalsIgnoreCase (*types++))
  224170. return true;
  224171. }
  224172. return false;
  224173. }
  224174. bool File::isOnCDRomDrive() const
  224175. {
  224176. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224177. return isFileOnDriveType (*this, cdTypes);
  224178. }
  224179. bool File::isOnHardDisk() const
  224180. {
  224181. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224182. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  224183. }
  224184. bool File::isOnRemovableDrive() const
  224185. {
  224186. #if JUCE_IOS
  224187. return false; // xxx is this possible?
  224188. #else
  224189. const ScopedAutoReleasePool pool;
  224190. BOOL removable = false;
  224191. [[NSWorkspace sharedWorkspace]
  224192. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224193. isRemovable: &removable
  224194. isWritable: nil
  224195. isUnmountable: nil
  224196. description: nil
  224197. type: nil];
  224198. return removable;
  224199. #endif
  224200. }
  224201. static bool juce_isHiddenFile (const String& path)
  224202. {
  224203. #if JUCE_IOS
  224204. return File (path).getFileName().startsWithChar ('.');
  224205. #else
  224206. FSRef ref;
  224207. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  224208. return false;
  224209. FSCatalogInfo info;
  224210. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  224211. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  224212. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224213. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224214. #endif
  224215. }
  224216. bool File::isHidden() const
  224217. {
  224218. return juce_isHiddenFile (getFullPathName());
  224219. }
  224220. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224221. const File File::getSpecialLocation (const SpecialLocationType type)
  224222. {
  224223. const ScopedAutoReleasePool pool;
  224224. String resultPath;
  224225. switch (type)
  224226. {
  224227. case userHomeDirectory:
  224228. resultPath = nsStringToJuce (NSHomeDirectory());
  224229. break;
  224230. case userDocumentsDirectory:
  224231. resultPath = "~/Documents";
  224232. break;
  224233. case userDesktopDirectory:
  224234. resultPath = "~/Desktop";
  224235. break;
  224236. case userApplicationDataDirectory:
  224237. resultPath = "~/Library";
  224238. break;
  224239. case commonApplicationDataDirectory:
  224240. resultPath = "/Library";
  224241. break;
  224242. case globalApplicationsDirectory:
  224243. resultPath = "/Applications";
  224244. break;
  224245. case userMusicDirectory:
  224246. resultPath = "~/Music";
  224247. break;
  224248. case userMoviesDirectory:
  224249. resultPath = "~/Movies";
  224250. break;
  224251. case tempDirectory:
  224252. {
  224253. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224254. tmp.createDirectory();
  224255. return tmp.getFullPathName();
  224256. }
  224257. case invokedExecutableFile:
  224258. if (juce_Argv0 != 0)
  224259. return File (String::fromUTF8 (juce_Argv0));
  224260. // deliberate fall-through...
  224261. case currentExecutableFile:
  224262. return juce_getExecutableFile();
  224263. case currentApplicationFile:
  224264. {
  224265. const File exe (juce_getExecutableFile());
  224266. const File parent (exe.getParentDirectory());
  224267. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224268. ? parent.getParentDirectory().getParentDirectory()
  224269. : exe;
  224270. }
  224271. case hostApplicationPath:
  224272. {
  224273. unsigned int size = 8192;
  224274. HeapBlock<char> buffer;
  224275. buffer.calloc (size + 8);
  224276. _NSGetExecutablePath (buffer.getData(), &size);
  224277. return String::fromUTF8 (buffer, size);
  224278. }
  224279. default:
  224280. jassertfalse; // unknown type?
  224281. break;
  224282. }
  224283. if (resultPath.isNotEmpty())
  224284. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224285. return File::nonexistent;
  224286. }
  224287. const String File::getVersion() const
  224288. {
  224289. const ScopedAutoReleasePool pool;
  224290. String result;
  224291. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224292. if (bundle != 0)
  224293. {
  224294. NSDictionary* info = [bundle infoDictionary];
  224295. if (info != 0)
  224296. {
  224297. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224298. if (name != nil)
  224299. result = nsStringToJuce (name);
  224300. }
  224301. }
  224302. return result;
  224303. }
  224304. const File File::getLinkedTarget() const
  224305. {
  224306. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224307. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224308. #else
  224309. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224310. #endif
  224311. if (dest != nil)
  224312. return File (nsStringToJuce (dest));
  224313. return *this;
  224314. }
  224315. bool File::moveToTrash() const
  224316. {
  224317. if (! exists())
  224318. return true;
  224319. #if JUCE_IOS
  224320. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224321. #else
  224322. const ScopedAutoReleasePool pool;
  224323. NSString* p = juceStringToNS (getFullPathName());
  224324. return [[NSWorkspace sharedWorkspace]
  224325. performFileOperation: NSWorkspaceRecycleOperation
  224326. source: [p stringByDeletingLastPathComponent]
  224327. destination: @""
  224328. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224329. tag: nil ];
  224330. #endif
  224331. }
  224332. class DirectoryIterator::NativeIterator::Pimpl
  224333. {
  224334. public:
  224335. Pimpl (const File& directory, const String& wildCard_)
  224336. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224337. wildCard (wildCard_),
  224338. enumerator (0)
  224339. {
  224340. ScopedAutoReleasePool pool;
  224341. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224342. wildcardUTF8 = wildCard.toUTF8();
  224343. }
  224344. ~Pimpl()
  224345. {
  224346. [enumerator release];
  224347. }
  224348. bool next (String& filenameFound,
  224349. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224350. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224351. {
  224352. ScopedAutoReleasePool pool;
  224353. for (;;)
  224354. {
  224355. NSString* file;
  224356. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224357. return false;
  224358. [enumerator skipDescendents];
  224359. filenameFound = nsStringToJuce (file);
  224360. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224361. continue;
  224362. const String path (parentDir + filenameFound);
  224363. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224364. {
  224365. struct stat info;
  224366. const bool statOk = juce_stat (path, info);
  224367. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224368. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224369. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  224370. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  224371. }
  224372. if (isHidden != 0)
  224373. *isHidden = juce_isHiddenFile (path);
  224374. if (isReadOnly != 0)
  224375. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224376. return true;
  224377. }
  224378. }
  224379. private:
  224380. String parentDir, wildCard;
  224381. const char* wildcardUTF8;
  224382. NSDirectoryEnumerator* enumerator;
  224383. Pimpl (const Pimpl&);
  224384. Pimpl& operator= (const Pimpl&);
  224385. };
  224386. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224387. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224388. {
  224389. }
  224390. DirectoryIterator::NativeIterator::~NativeIterator()
  224391. {
  224392. }
  224393. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224394. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224395. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224396. {
  224397. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224398. }
  224399. bool juce_launchExecutable (const String& pathAndArguments)
  224400. {
  224401. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224402. const int cpid = fork();
  224403. if (cpid == 0)
  224404. {
  224405. // Child process
  224406. if (execve (argv[0], (char**) argv, 0) < 0)
  224407. exit (0);
  224408. }
  224409. else
  224410. {
  224411. if (cpid < 0)
  224412. return false;
  224413. }
  224414. return true;
  224415. }
  224416. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224417. {
  224418. #if JUCE_IOS
  224419. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224420. #else
  224421. const ScopedAutoReleasePool pool;
  224422. if (parameters.isEmpty())
  224423. {
  224424. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224425. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224426. }
  224427. bool ok = false;
  224428. FSRef ref;
  224429. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224430. {
  224431. if (PlatformUtilities::isBundle (fileName))
  224432. {
  224433. NSMutableArray* urls = [NSMutableArray array];
  224434. StringArray docs;
  224435. docs.addTokens (parameters, true);
  224436. for (int i = 0; i < docs.size(); ++i)
  224437. [urls addObject: juceStringToNS (docs[i])];
  224438. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224439. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224440. options: 0
  224441. additionalEventParamDescriptor: nil
  224442. launchIdentifiers: nil];
  224443. }
  224444. else
  224445. {
  224446. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224447. }
  224448. }
  224449. return ok;
  224450. #endif
  224451. }
  224452. void File::revealToUser() const
  224453. {
  224454. #if ! JUCE_IOS
  224455. if (exists())
  224456. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224457. else if (getParentDirectory().exists())
  224458. getParentDirectory().revealToUser();
  224459. #endif
  224460. }
  224461. #if ! JUCE_IOS
  224462. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224463. {
  224464. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224465. }
  224466. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224467. {
  224468. char path [2048];
  224469. zerostruct (path);
  224470. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224471. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224472. return String::empty;
  224473. }
  224474. #endif
  224475. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224476. {
  224477. const ScopedAutoReleasePool pool;
  224478. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224479. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224480. #else
  224481. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224482. #endif
  224483. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224484. return [fileDict fileHFSTypeCode];
  224485. }
  224486. bool PlatformUtilities::isBundle (const String& filename)
  224487. {
  224488. #if JUCE_IOS
  224489. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224490. #else
  224491. const ScopedAutoReleasePool pool;
  224492. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224493. #endif
  224494. }
  224495. #endif
  224496. /*** End of inlined file: juce_mac_Files.mm ***/
  224497. #if JUCE_IOS
  224498. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224499. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224500. // compiled on its own).
  224501. #if JUCE_INCLUDED_FILE
  224502. END_JUCE_NAMESPACE
  224503. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224504. {
  224505. }
  224506. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224507. - (void) applicationWillTerminate: (UIApplication*) application;
  224508. @end
  224509. @implementation JuceAppStartupDelegate
  224510. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224511. {
  224512. initialiseJuce_GUI();
  224513. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  224514. exit (0);
  224515. }
  224516. - (void) applicationWillTerminate: (UIApplication*) application
  224517. {
  224518. jassert (JUCEApplication::getInstance() != 0);
  224519. JUCEApplication::getInstance()->shutdownApp();
  224520. delete JUCEApplication::getInstance();
  224521. shutdownJuce_GUI();
  224522. }
  224523. @end
  224524. BEGIN_JUCE_NAMESPACE
  224525. int juce_iOSMain (int argc, const char* argv[])
  224526. {
  224527. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224528. }
  224529. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224530. {
  224531. pool = [[NSAutoreleasePool alloc] init];
  224532. }
  224533. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224534. {
  224535. [((NSAutoreleasePool*) pool) release];
  224536. }
  224537. void PlatformUtilities::beep()
  224538. {
  224539. //xxx
  224540. //AudioServicesPlaySystemSound ();
  224541. }
  224542. void PlatformUtilities::addItemToDock (const File& file)
  224543. {
  224544. }
  224545. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224546. END_JUCE_NAMESPACE
  224547. @interface JuceAlertBoxDelegate : NSObject
  224548. {
  224549. @public
  224550. bool clickedOk;
  224551. }
  224552. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224553. @end
  224554. @implementation JuceAlertBoxDelegate
  224555. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224556. {
  224557. clickedOk = (buttonIndex == 0);
  224558. alertView.hidden = true;
  224559. }
  224560. @end
  224561. BEGIN_JUCE_NAMESPACE
  224562. // (This function is used directly by other bits of code)
  224563. bool juce_iPhoneShowModalAlert (const String& title,
  224564. const String& bodyText,
  224565. NSString* okButtonText,
  224566. NSString* cancelButtonText)
  224567. {
  224568. const ScopedAutoReleasePool pool;
  224569. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224570. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224571. message: juceStringToNS (bodyText)
  224572. delegate: callback
  224573. cancelButtonTitle: okButtonText
  224574. otherButtonTitles: cancelButtonText, nil];
  224575. [alert retain];
  224576. [alert show];
  224577. while (! alert.hidden && alert.superview != nil)
  224578. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224579. const bool result = callback->clickedOk;
  224580. [alert release];
  224581. [callback release];
  224582. return result;
  224583. }
  224584. bool AlertWindow::showNativeDialogBox (const String& title,
  224585. const String& bodyText,
  224586. bool isOkCancel)
  224587. {
  224588. return juce_iPhoneShowModalAlert (title, bodyText,
  224589. @"OK",
  224590. isOkCancel ? @"Cancel" : nil);
  224591. }
  224592. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224593. {
  224594. jassertfalse; // no such thing on the iphone!
  224595. return false;
  224596. }
  224597. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224598. {
  224599. jassertfalse; // no such thing on the iphone!
  224600. return false;
  224601. }
  224602. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224603. {
  224604. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224605. }
  224606. bool Desktop::isScreenSaverEnabled()
  224607. {
  224608. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224609. }
  224610. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224611. {
  224612. const ScopedAutoReleasePool pool;
  224613. monitorCoords.clear();
  224614. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224615. : [[UIScreen mainScreen] bounds];
  224616. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224617. (int) r.origin.y,
  224618. (int) r.size.width,
  224619. (int) r.size.height));
  224620. }
  224621. #endif
  224622. #endif
  224623. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224624. #else
  224625. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224626. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224627. // compiled on its own).
  224628. #if JUCE_INCLUDED_FILE
  224629. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224630. {
  224631. pool = [[NSAutoreleasePool alloc] init];
  224632. }
  224633. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224634. {
  224635. [((NSAutoreleasePool*) pool) release];
  224636. }
  224637. void PlatformUtilities::beep()
  224638. {
  224639. NSBeep();
  224640. }
  224641. void PlatformUtilities::addItemToDock (const File& file)
  224642. {
  224643. // check that it's not already there...
  224644. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224645. .containsIgnoreCase (file.getFullPathName()))
  224646. {
  224647. 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>"
  224648. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224649. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224650. }
  224651. }
  224652. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224653. bool AlertWindow::showNativeDialogBox (const String& title,
  224654. const String& bodyText,
  224655. bool isOkCancel)
  224656. {
  224657. const ScopedAutoReleasePool pool;
  224658. return NSRunAlertPanel (juceStringToNS (title),
  224659. juceStringToNS (bodyText),
  224660. @"Ok",
  224661. isOkCancel ? @"Cancel" : nil,
  224662. nil) == NSAlertDefaultReturn;
  224663. }
  224664. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224665. {
  224666. if (files.size() == 0)
  224667. return false;
  224668. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224669. if (draggingSource == 0)
  224670. {
  224671. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224672. return false;
  224673. }
  224674. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224675. if (sourceComp == 0)
  224676. {
  224677. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224678. return false;
  224679. }
  224680. const ScopedAutoReleasePool pool;
  224681. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224682. if (view == 0)
  224683. return false;
  224684. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224685. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224686. owner: nil];
  224687. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224688. for (int i = 0; i < files.size(); ++i)
  224689. [filesArray addObject: juceStringToNS (files[i])];
  224690. [pboard setPropertyList: filesArray
  224691. forType: NSFilenamesPboardType];
  224692. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224693. fromView: nil];
  224694. dragPosition.x -= 16;
  224695. dragPosition.y -= 16;
  224696. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224697. at: dragPosition
  224698. offset: NSMakeSize (0, 0)
  224699. event: [[view window] currentEvent]
  224700. pasteboard: pboard
  224701. source: view
  224702. slideBack: YES];
  224703. return true;
  224704. }
  224705. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224706. {
  224707. jassertfalse; // not implemented!
  224708. return false;
  224709. }
  224710. bool Desktop::canUseSemiTransparentWindows() throw()
  224711. {
  224712. return true;
  224713. }
  224714. const Point<int> Desktop::getMousePosition()
  224715. {
  224716. const ScopedAutoReleasePool pool;
  224717. const NSPoint p ([NSEvent mouseLocation]);
  224718. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224719. }
  224720. void Desktop::setMousePosition (const Point<int>& newPosition)
  224721. {
  224722. // this rubbish needs to be done around the warp call, to avoid causing a
  224723. // bizarre glitch..
  224724. CGAssociateMouseAndMouseCursorPosition (false);
  224725. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224726. CGAssociateMouseAndMouseCursorPosition (true);
  224727. }
  224728. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224729. class ScreenSaverDefeater : public Timer,
  224730. public DeletedAtShutdown
  224731. {
  224732. public:
  224733. ScreenSaverDefeater()
  224734. {
  224735. startTimer (10000);
  224736. timerCallback();
  224737. }
  224738. ~ScreenSaverDefeater() {}
  224739. void timerCallback()
  224740. {
  224741. if (Process::isForegroundProcess())
  224742. UpdateSystemActivity (UsrActivity);
  224743. }
  224744. };
  224745. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224746. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224747. {
  224748. if (isEnabled)
  224749. deleteAndZero (screenSaverDefeater);
  224750. else if (screenSaverDefeater == 0)
  224751. screenSaverDefeater = new ScreenSaverDefeater();
  224752. }
  224753. bool Desktop::isScreenSaverEnabled()
  224754. {
  224755. return screenSaverDefeater == 0;
  224756. }
  224757. #else
  224758. static IOPMAssertionID screenSaverDisablerID = 0;
  224759. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224760. {
  224761. if (isEnabled)
  224762. {
  224763. if (screenSaverDisablerID != 0)
  224764. {
  224765. IOPMAssertionRelease (screenSaverDisablerID);
  224766. screenSaverDisablerID = 0;
  224767. }
  224768. }
  224769. else
  224770. {
  224771. if (screenSaverDisablerID == 0)
  224772. {
  224773. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224774. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224775. CFSTR ("Juce"), &screenSaverDisablerID);
  224776. #else
  224777. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224778. &screenSaverDisablerID);
  224779. #endif
  224780. }
  224781. }
  224782. }
  224783. bool Desktop::isScreenSaverEnabled()
  224784. {
  224785. return screenSaverDisablerID == 0;
  224786. }
  224787. #endif
  224788. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224789. {
  224790. const ScopedAutoReleasePool pool;
  224791. monitorCoords.clear();
  224792. NSArray* screens = [NSScreen screens];
  224793. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224794. for (unsigned int i = 0; i < [screens count]; ++i)
  224795. {
  224796. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224797. NSRect r = clipToWorkArea ? [s visibleFrame]
  224798. : [s frame];
  224799. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224800. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224801. (int) r.size.width,
  224802. (int) r.size.height));
  224803. }
  224804. jassert (monitorCoords.size() > 0);
  224805. }
  224806. #endif
  224807. #endif
  224808. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224809. #endif
  224810. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224811. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224812. // compiled on its own).
  224813. #if JUCE_INCLUDED_FILE
  224814. void Logger::outputDebugString (const String& text)
  224815. {
  224816. std::cerr << text << std::endl;
  224817. }
  224818. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224819. {
  224820. static char testResult = 0;
  224821. if (testResult == 0)
  224822. {
  224823. struct kinfo_proc info;
  224824. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224825. size_t sz = sizeof (info);
  224826. sysctl (m, 4, &info, &sz, 0, 0);
  224827. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224828. }
  224829. return testResult > 0;
  224830. }
  224831. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224832. {
  224833. return juce_isRunningUnderDebugger();
  224834. }
  224835. #endif
  224836. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224837. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224838. #if JUCE_IOS
  224839. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224840. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224841. // compiled on its own).
  224842. #if JUCE_INCLUDED_FILE
  224843. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224844. #define SUPPORT_10_4_FONTS 1
  224845. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224846. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224847. #define SUPPORT_ONLY_10_4_FONTS 1
  224848. #endif
  224849. END_JUCE_NAMESPACE
  224850. @interface NSFont (PrivateHack)
  224851. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224852. @end
  224853. BEGIN_JUCE_NAMESPACE
  224854. #endif
  224855. class MacTypeface : public Typeface
  224856. {
  224857. public:
  224858. MacTypeface (const Font& font)
  224859. : Typeface (font.getTypefaceName())
  224860. {
  224861. const ScopedAutoReleasePool pool;
  224862. renderingTransform = CGAffineTransformIdentity;
  224863. bool needsItalicTransform = false;
  224864. #if JUCE_IOS
  224865. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224866. if (font.isItalic() || font.isBold())
  224867. {
  224868. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224869. for (NSString* i in familyFonts)
  224870. {
  224871. const String fn (nsStringToJuce (i));
  224872. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224873. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224874. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224875. || afterDash.containsIgnoreCase ("italic")
  224876. || fn.endsWithIgnoreCase ("oblique")
  224877. || fn.endsWithIgnoreCase ("italic");
  224878. if (probablyBold == font.isBold()
  224879. && probablyItalic == font.isItalic())
  224880. {
  224881. fontName = i;
  224882. needsItalicTransform = false;
  224883. break;
  224884. }
  224885. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224886. {
  224887. fontName = i;
  224888. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224889. }
  224890. }
  224891. if (needsItalicTransform)
  224892. renderingTransform.c = 0.15f;
  224893. }
  224894. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224895. const int ascender = abs (CGFontGetAscent (fontRef));
  224896. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224897. ascent = ascender / totalHeight;
  224898. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224899. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224900. #else
  224901. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224902. if (font.isItalic())
  224903. {
  224904. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224905. toHaveTrait: NSItalicFontMask];
  224906. if (newFont == nsFont)
  224907. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224908. nsFont = newFont;
  224909. }
  224910. if (font.isBold())
  224911. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224912. [nsFont retain];
  224913. ascent = std::abs ((float) [nsFont ascender]);
  224914. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224915. ascent /= totalSize;
  224916. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224917. if (needsItalicTransform)
  224918. {
  224919. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224920. renderingTransform.c = 0.15f;
  224921. }
  224922. #if SUPPORT_ONLY_10_4_FONTS
  224923. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224924. if (atsFont == 0)
  224925. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224926. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224927. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224928. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224929. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224930. #else
  224931. #if SUPPORT_10_4_FONTS
  224932. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224933. {
  224934. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224935. if (atsFont == 0)
  224936. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224937. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224938. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224939. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224940. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224941. }
  224942. else
  224943. #endif
  224944. {
  224945. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224946. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224947. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224948. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224949. }
  224950. #endif
  224951. #endif
  224952. }
  224953. ~MacTypeface()
  224954. {
  224955. #if ! JUCE_IOS
  224956. [nsFont release];
  224957. #endif
  224958. if (fontRef != 0)
  224959. CGFontRelease (fontRef);
  224960. }
  224961. float getAscent() const
  224962. {
  224963. return ascent;
  224964. }
  224965. float getDescent() const
  224966. {
  224967. return 1.0f - ascent;
  224968. }
  224969. float getStringWidth (const String& text)
  224970. {
  224971. if (fontRef == 0 || text.isEmpty())
  224972. return 0;
  224973. const int length = text.length();
  224974. HeapBlock <CGGlyph> glyphs;
  224975. createGlyphsForString (text, length, glyphs);
  224976. float x = 0;
  224977. #if SUPPORT_ONLY_10_4_FONTS
  224978. HeapBlock <NSSize> advances (length);
  224979. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224980. for (int i = 0; i < length; ++i)
  224981. x += advances[i].width;
  224982. #else
  224983. #if SUPPORT_10_4_FONTS
  224984. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224985. {
  224986. HeapBlock <NSSize> advances (length);
  224987. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  224988. for (int i = 0; i < length; ++i)
  224989. x += advances[i].width;
  224990. }
  224991. else
  224992. #endif
  224993. {
  224994. HeapBlock <int> advances (length);
  224995. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224996. for (int i = 0; i < length; ++i)
  224997. x += advances[i];
  224998. }
  224999. #endif
  225000. return x * unitsToHeightScaleFactor;
  225001. }
  225002. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225003. {
  225004. xOffsets.add (0);
  225005. if (fontRef == 0 || text.isEmpty())
  225006. return;
  225007. const int length = text.length();
  225008. HeapBlock <CGGlyph> glyphs;
  225009. createGlyphsForString (text, length, glyphs);
  225010. #if SUPPORT_ONLY_10_4_FONTS
  225011. HeapBlock <NSSize> advances (length);
  225012. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225013. int x = 0;
  225014. for (int i = 0; i < length; ++i)
  225015. {
  225016. x += advances[i].width;
  225017. xOffsets.add (x * unitsToHeightScaleFactor);
  225018. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225019. }
  225020. #else
  225021. #if SUPPORT_10_4_FONTS
  225022. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225023. {
  225024. HeapBlock <NSSize> advances (length);
  225025. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225026. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225027. float x = 0;
  225028. for (int i = 0; i < length; ++i)
  225029. {
  225030. x += advances[i].width;
  225031. xOffsets.add (x * unitsToHeightScaleFactor);
  225032. resultGlyphs.add (nsGlyphs[i]);
  225033. }
  225034. }
  225035. else
  225036. #endif
  225037. {
  225038. HeapBlock <int> advances (length);
  225039. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225040. {
  225041. int x = 0;
  225042. for (int i = 0; i < length; ++i)
  225043. {
  225044. x += advances [i];
  225045. xOffsets.add (x * unitsToHeightScaleFactor);
  225046. resultGlyphs.add (glyphs[i]);
  225047. }
  225048. }
  225049. }
  225050. #endif
  225051. }
  225052. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225053. {
  225054. #if JUCE_IOS
  225055. return false;
  225056. #else
  225057. if (nsFont == 0)
  225058. return false;
  225059. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225060. jassert (path.isEmpty());
  225061. const ScopedAutoReleasePool pool;
  225062. NSBezierPath* bez = [NSBezierPath bezierPath];
  225063. [bez moveToPoint: NSMakePoint (0, 0)];
  225064. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225065. inFont: nsFont];
  225066. for (int i = 0; i < [bez elementCount]; ++i)
  225067. {
  225068. NSPoint p[3];
  225069. switch ([bez elementAtIndex: i associatedPoints: p])
  225070. {
  225071. case NSMoveToBezierPathElement:
  225072. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  225073. break;
  225074. case NSLineToBezierPathElement:
  225075. path.lineTo ((float) p[0].x, (float) -p[0].y);
  225076. break;
  225077. case NSCurveToBezierPathElement:
  225078. 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);
  225079. break;
  225080. case NSClosePathBezierPathElement:
  225081. path.closeSubPath();
  225082. break;
  225083. default:
  225084. jassertfalse;
  225085. break;
  225086. }
  225087. }
  225088. path.applyTransform (pathTransform);
  225089. return true;
  225090. #endif
  225091. }
  225092. juce_UseDebuggingNewOperator
  225093. CGFontRef fontRef;
  225094. float fontHeightToCGSizeFactor;
  225095. CGAffineTransform renderingTransform;
  225096. private:
  225097. float ascent, unitsToHeightScaleFactor;
  225098. #if JUCE_IOS
  225099. #else
  225100. NSFont* nsFont;
  225101. AffineTransform pathTransform;
  225102. #endif
  225103. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225104. {
  225105. #if SUPPORT_10_4_FONTS
  225106. #if ! SUPPORT_ONLY_10_4_FONTS
  225107. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225108. #endif
  225109. {
  225110. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225111. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225112. for (int i = 0; i < length; ++i)
  225113. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225114. return;
  225115. }
  225116. #endif
  225117. #if ! SUPPORT_ONLY_10_4_FONTS
  225118. if (charToGlyphMapper == 0)
  225119. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225120. glyphs.malloc (length);
  225121. for (int i = 0; i < length; ++i)
  225122. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225123. #endif
  225124. }
  225125. #if ! SUPPORT_ONLY_10_4_FONTS
  225126. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225127. class CharToGlyphMapper
  225128. {
  225129. public:
  225130. CharToGlyphMapper (CGFontRef fontRef)
  225131. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225132. idRangeOffset (0), glyphIndexes (0)
  225133. {
  225134. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225135. if (cmapTable != 0)
  225136. {
  225137. const int numSubtables = getValue16 (cmapTable, 2);
  225138. for (int i = 0; i < numSubtables; ++i)
  225139. {
  225140. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225141. {
  225142. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225143. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225144. {
  225145. const int length = getValue16 (cmapTable, offset + 2);
  225146. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225147. segCount = segCountX2 / 2;
  225148. const int endCodeOffset = offset + 14;
  225149. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225150. const int idDeltaOffset = startCodeOffset + segCountX2;
  225151. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225152. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225153. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225154. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225155. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225156. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225157. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225158. }
  225159. break;
  225160. }
  225161. }
  225162. CFRelease (cmapTable);
  225163. }
  225164. }
  225165. ~CharToGlyphMapper()
  225166. {
  225167. if (endCode != 0)
  225168. {
  225169. CFRelease (endCode);
  225170. CFRelease (startCode);
  225171. CFRelease (idDelta);
  225172. CFRelease (idRangeOffset);
  225173. CFRelease (glyphIndexes);
  225174. }
  225175. }
  225176. int getGlyphForCharacter (const juce_wchar c) const
  225177. {
  225178. for (int i = 0; i < segCount; ++i)
  225179. {
  225180. if (getValue16 (endCode, i * 2) >= c)
  225181. {
  225182. const int start = getValue16 (startCode, i * 2);
  225183. if (start > c)
  225184. break;
  225185. const int delta = getValue16 (idDelta, i * 2);
  225186. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225187. if (rangeOffset == 0)
  225188. return delta + c;
  225189. else
  225190. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225191. }
  225192. }
  225193. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225194. return jmax (-1, c - 29);
  225195. }
  225196. private:
  225197. int segCount;
  225198. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225199. static uint16 getValue16 (CFDataRef data, const int index)
  225200. {
  225201. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225202. }
  225203. static uint32 getValue32 (CFDataRef data, const int index)
  225204. {
  225205. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225206. }
  225207. };
  225208. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225209. #endif
  225210. MacTypeface (const MacTypeface&);
  225211. MacTypeface& operator= (const MacTypeface&);
  225212. };
  225213. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225214. {
  225215. return new MacTypeface (font);
  225216. }
  225217. const StringArray Font::findAllTypefaceNames()
  225218. {
  225219. StringArray names;
  225220. const ScopedAutoReleasePool pool;
  225221. #if JUCE_IOS
  225222. NSArray* fonts = [UIFont familyNames];
  225223. #else
  225224. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225225. #endif
  225226. for (unsigned int i = 0; i < [fonts count]; ++i)
  225227. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225228. names.sort (true);
  225229. return names;
  225230. }
  225231. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  225232. {
  225233. #if JUCE_IOS
  225234. defaultSans = "Helvetica";
  225235. defaultSerif = "Times New Roman";
  225236. defaultFixed = "Courier New";
  225237. #else
  225238. defaultSans = "Lucida Grande";
  225239. defaultSerif = "Times New Roman";
  225240. defaultFixed = "Monaco";
  225241. #endif
  225242. }
  225243. #endif
  225244. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225245. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225246. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225247. // compiled on its own).
  225248. #if JUCE_INCLUDED_FILE
  225249. class CoreGraphicsImage : public Image::SharedImage
  225250. {
  225251. public:
  225252. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225253. : Image::SharedImage (format_, width_, height_)
  225254. {
  225255. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225256. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225257. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225258. imageData = imageDataAllocated;
  225259. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225260. : CGColorSpaceCreateDeviceRGB();
  225261. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225262. colourSpace, getCGImageFlags (format_));
  225263. CGColorSpaceRelease (colourSpace);
  225264. }
  225265. ~CoreGraphicsImage()
  225266. {
  225267. CGContextRelease (context);
  225268. }
  225269. Image::ImageType getType() const { return Image::NativeImage; }
  225270. LowLevelGraphicsContext* createLowLevelContext();
  225271. SharedImage* clone()
  225272. {
  225273. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225274. memcpy (im->imageData, imageData, lineStride * height);
  225275. return im;
  225276. }
  225277. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  225278. {
  225279. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225280. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225281. {
  225282. return CGBitmapContextCreateImage (nativeImage->context);
  225283. }
  225284. else
  225285. {
  225286. const Image::BitmapData srcData (juceImage, false);
  225287. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225288. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225289. 8, srcData.pixelStride * 8, srcData.lineStride,
  225290. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225291. 0, true, kCGRenderingIntentDefault);
  225292. CGDataProviderRelease (provider);
  225293. return imageRef;
  225294. }
  225295. }
  225296. #if JUCE_MAC
  225297. static NSImage* createNSImage (const Image& image)
  225298. {
  225299. const ScopedAutoReleasePool pool;
  225300. NSImage* im = [[NSImage alloc] init];
  225301. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225302. [im lockFocus];
  225303. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225304. CGImageRef imageRef = createImage (image, false, colourSpace);
  225305. CGColorSpaceRelease (colourSpace);
  225306. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225307. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225308. CGImageRelease (imageRef);
  225309. [im unlockFocus];
  225310. return im;
  225311. }
  225312. #endif
  225313. CGContextRef context;
  225314. HeapBlock<uint8> imageDataAllocated;
  225315. private:
  225316. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225317. {
  225318. #if JUCE_BIG_ENDIAN
  225319. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225320. #else
  225321. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225322. #endif
  225323. }
  225324. };
  225325. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225326. {
  225327. #if USE_COREGRAPHICS_RENDERING
  225328. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225329. #else
  225330. return createSoftwareImage (format, width, height, clearImage);
  225331. #endif
  225332. }
  225333. class CoreGraphicsContext : public LowLevelGraphicsContext
  225334. {
  225335. public:
  225336. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225337. : context (context_),
  225338. flipHeight (flipHeight_),
  225339. state (new SavedState()),
  225340. numGradientLookupEntries (0),
  225341. lastClipRectIsValid (false)
  225342. {
  225343. CGContextRetain (context);
  225344. CGContextSaveGState(context);
  225345. CGContextSetShouldSmoothFonts (context, true);
  225346. CGContextSetShouldAntialias (context, true);
  225347. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225348. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225349. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225350. gradientCallbacks.version = 0;
  225351. gradientCallbacks.evaluate = gradientCallback;
  225352. gradientCallbacks.releaseInfo = 0;
  225353. setFont (Font());
  225354. }
  225355. ~CoreGraphicsContext()
  225356. {
  225357. CGContextRestoreGState (context);
  225358. CGContextRelease (context);
  225359. CGColorSpaceRelease (rgbColourSpace);
  225360. CGColorSpaceRelease (greyColourSpace);
  225361. }
  225362. bool isVectorDevice() const { return false; }
  225363. void setOrigin (int x, int y)
  225364. {
  225365. CGContextTranslateCTM (context, x, -y);
  225366. if (lastClipRectIsValid)
  225367. lastClipRect.translate (-x, -y);
  225368. }
  225369. bool clipToRectangle (const Rectangle<int>& r)
  225370. {
  225371. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225372. if (lastClipRectIsValid)
  225373. {
  225374. lastClipRect = lastClipRect.getIntersection (r);
  225375. return ! lastClipRect.isEmpty();
  225376. }
  225377. return ! isClipEmpty();
  225378. }
  225379. bool clipToRectangleList (const RectangleList& clipRegion)
  225380. {
  225381. if (clipRegion.isEmpty())
  225382. {
  225383. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225384. lastClipRectIsValid = true;
  225385. lastClipRect = Rectangle<int>();
  225386. return false;
  225387. }
  225388. else
  225389. {
  225390. const int numRects = clipRegion.getNumRectangles();
  225391. HeapBlock <CGRect> rects (numRects);
  225392. for (int i = 0; i < numRects; ++i)
  225393. {
  225394. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225395. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225396. }
  225397. CGContextClipToRects (context, rects, numRects);
  225398. lastClipRectIsValid = false;
  225399. return ! isClipEmpty();
  225400. }
  225401. }
  225402. void excludeClipRectangle (const Rectangle<int>& r)
  225403. {
  225404. RectangleList remaining (getClipBounds());
  225405. remaining.subtract (r);
  225406. clipToRectangleList (remaining);
  225407. lastClipRectIsValid = false;
  225408. }
  225409. void clipToPath (const Path& path, const AffineTransform& transform)
  225410. {
  225411. createPath (path, transform);
  225412. CGContextClip (context);
  225413. lastClipRectIsValid = false;
  225414. }
  225415. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225416. {
  225417. if (! transform.isSingularity())
  225418. {
  225419. Image singleChannelImage (sourceImage);
  225420. if (sourceImage.getFormat() != Image::SingleChannel)
  225421. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225422. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225423. flip();
  225424. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225425. applyTransform (t);
  225426. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225427. CGContextClipToMask (context, r, image);
  225428. applyTransform (t.inverted());
  225429. flip();
  225430. CGImageRelease (image);
  225431. lastClipRectIsValid = false;
  225432. }
  225433. }
  225434. bool clipRegionIntersects (const Rectangle<int>& r)
  225435. {
  225436. return getClipBounds().intersects (r);
  225437. }
  225438. const Rectangle<int> getClipBounds() const
  225439. {
  225440. if (! lastClipRectIsValid)
  225441. {
  225442. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225443. lastClipRectIsValid = true;
  225444. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225445. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225446. roundToInt (bounds.size.width),
  225447. roundToInt (bounds.size.height));
  225448. }
  225449. return lastClipRect;
  225450. }
  225451. bool isClipEmpty() const
  225452. {
  225453. return getClipBounds().isEmpty();
  225454. }
  225455. void saveState()
  225456. {
  225457. CGContextSaveGState (context);
  225458. stateStack.add (new SavedState (*state));
  225459. }
  225460. void restoreState()
  225461. {
  225462. CGContextRestoreGState (context);
  225463. SavedState* const top = stateStack.getLast();
  225464. if (top != 0)
  225465. {
  225466. state = top;
  225467. stateStack.removeLast (1, false);
  225468. lastClipRectIsValid = false;
  225469. }
  225470. else
  225471. {
  225472. jassertfalse; // trying to pop with an empty stack!
  225473. }
  225474. }
  225475. void setFill (const FillType& fillType)
  225476. {
  225477. state->fillType = fillType;
  225478. if (fillType.isColour())
  225479. {
  225480. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225481. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225482. CGContextSetAlpha (context, 1.0f);
  225483. }
  225484. }
  225485. void setOpacity (float newOpacity)
  225486. {
  225487. state->fillType.setOpacity (newOpacity);
  225488. setFill (state->fillType);
  225489. }
  225490. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225491. {
  225492. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225493. ? kCGInterpolationLow
  225494. : kCGInterpolationHigh);
  225495. }
  225496. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225497. {
  225498. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225499. if (replaceExistingContents)
  225500. {
  225501. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225502. CGContextClearRect (context, cgRect);
  225503. #else
  225504. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225505. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225506. CGContextClearRect (context, cgRect);
  225507. else
  225508. #endif
  225509. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225510. #endif
  225511. fillRect (r, false);
  225512. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225513. }
  225514. else
  225515. {
  225516. if (state->fillType.isColour())
  225517. {
  225518. CGContextFillRect (context, cgRect);
  225519. }
  225520. else if (state->fillType.isGradient())
  225521. {
  225522. CGContextSaveGState (context);
  225523. CGContextClipToRect (context, cgRect);
  225524. drawGradient();
  225525. CGContextRestoreGState (context);
  225526. }
  225527. else
  225528. {
  225529. CGContextSaveGState (context);
  225530. CGContextClipToRect (context, cgRect);
  225531. drawImage (state->fillType.image, state->fillType.transform, true);
  225532. CGContextRestoreGState (context);
  225533. }
  225534. }
  225535. }
  225536. void fillPath (const Path& path, const AffineTransform& transform)
  225537. {
  225538. CGContextSaveGState (context);
  225539. if (state->fillType.isColour())
  225540. {
  225541. flip();
  225542. applyTransform (transform);
  225543. createPath (path);
  225544. if (path.isUsingNonZeroWinding())
  225545. CGContextFillPath (context);
  225546. else
  225547. CGContextEOFillPath (context);
  225548. }
  225549. else
  225550. {
  225551. createPath (path, transform);
  225552. if (path.isUsingNonZeroWinding())
  225553. CGContextClip (context);
  225554. else
  225555. CGContextEOClip (context);
  225556. if (state->fillType.isGradient())
  225557. drawGradient();
  225558. else
  225559. drawImage (state->fillType.image, state->fillType.transform, true);
  225560. }
  225561. CGContextRestoreGState (context);
  225562. }
  225563. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225564. {
  225565. const int iw = sourceImage.getWidth();
  225566. const int ih = sourceImage.getHeight();
  225567. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225568. CGContextSaveGState (context);
  225569. CGContextSetAlpha (context, state->fillType.getOpacity());
  225570. flip();
  225571. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  225572. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  225573. if (fillEntireClipAsTiles)
  225574. {
  225575. #if JUCE_IOS
  225576. CGContextDrawTiledImage (context, imageRect, image);
  225577. #else
  225578. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225579. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225580. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225581. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225582. CGContextDrawTiledImage (context, imageRect, image);
  225583. else
  225584. #endif
  225585. {
  225586. // Fallback to manually doing a tiled fill on 10.4
  225587. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225588. int x = 0, y = 0;
  225589. while (x > clip.origin.x) x -= iw;
  225590. while (y > clip.origin.y) y -= ih;
  225591. const int right = (int) (clip.origin.x + clip.size.width);
  225592. const int bottom = (int) (clip.origin.y + clip.size.height);
  225593. while (y < bottom)
  225594. {
  225595. for (int x2 = x; x2 < right; x2 += iw)
  225596. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225597. y += ih;
  225598. }
  225599. }
  225600. #endif
  225601. }
  225602. else
  225603. {
  225604. CGContextDrawImage (context, imageRect, image);
  225605. }
  225606. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225607. CGContextRestoreGState (context);
  225608. }
  225609. void drawLine (const Line<float>& line)
  225610. {
  225611. CGContextSetLineCap (context, kCGLineCapSquare);
  225612. CGContextSetLineWidth (context, 1.0f);
  225613. CGContextSetRGBStrokeColor (context,
  225614. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225615. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225616. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225617. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225618. CGContextStrokeLineSegments (context, cgLine, 1);
  225619. }
  225620. void drawVerticalLine (const int x, float top, float bottom)
  225621. {
  225622. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225623. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225624. #else
  225625. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225626. // the x co-ord slightly to trick it..
  225627. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225628. #endif
  225629. }
  225630. void drawHorizontalLine (const int y, float left, float right)
  225631. {
  225632. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225633. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225634. #else
  225635. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225636. // the x co-ord slightly to trick it..
  225637. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225638. #endif
  225639. }
  225640. void setFont (const Font& newFont)
  225641. {
  225642. if (state->font != newFont)
  225643. {
  225644. state->fontRef = 0;
  225645. state->font = newFont;
  225646. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225647. if (mf != 0)
  225648. {
  225649. state->fontRef = mf->fontRef;
  225650. CGContextSetFont (context, state->fontRef);
  225651. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225652. state->fontTransform = mf->renderingTransform;
  225653. state->fontTransform.a *= state->font.getHorizontalScale();
  225654. CGContextSetTextMatrix (context, state->fontTransform);
  225655. }
  225656. }
  225657. }
  225658. const Font getFont()
  225659. {
  225660. return state->font;
  225661. }
  225662. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225663. {
  225664. if (state->fontRef != 0 && state->fillType.isColour())
  225665. {
  225666. if (transform.isOnlyTranslation())
  225667. {
  225668. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225669. CGGlyph g = glyphNumber;
  225670. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225671. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225672. }
  225673. else
  225674. {
  225675. CGContextSaveGState (context);
  225676. flip();
  225677. applyTransform (transform);
  225678. CGAffineTransform t = state->fontTransform;
  225679. t.d = -t.d;
  225680. CGContextSetTextMatrix (context, t);
  225681. CGGlyph g = glyphNumber;
  225682. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225683. CGContextRestoreGState (context);
  225684. }
  225685. }
  225686. else
  225687. {
  225688. Path p;
  225689. Font& f = state->font;
  225690. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225691. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225692. .followedBy (transform));
  225693. }
  225694. }
  225695. private:
  225696. CGContextRef context;
  225697. const CGFloat flipHeight;
  225698. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225699. CGFunctionCallbacks gradientCallbacks;
  225700. mutable Rectangle<int> lastClipRect;
  225701. mutable bool lastClipRectIsValid;
  225702. struct SavedState
  225703. {
  225704. SavedState()
  225705. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225706. {
  225707. }
  225708. SavedState (const SavedState& other)
  225709. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225710. fontTransform (other.fontTransform)
  225711. {
  225712. }
  225713. ~SavedState()
  225714. {
  225715. }
  225716. FillType fillType;
  225717. Font font;
  225718. CGFontRef fontRef;
  225719. CGAffineTransform fontTransform;
  225720. };
  225721. ScopedPointer <SavedState> state;
  225722. OwnedArray <SavedState> stateStack;
  225723. HeapBlock <PixelARGB> gradientLookupTable;
  225724. int numGradientLookupEntries;
  225725. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225726. {
  225727. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225728. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225729. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225730. colour.unpremultiply();
  225731. outData[0] = colour.getRed() / 255.0f;
  225732. outData[1] = colour.getGreen() / 255.0f;
  225733. outData[2] = colour.getBlue() / 255.0f;
  225734. outData[3] = colour.getAlpha() / 255.0f;
  225735. }
  225736. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225737. {
  225738. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225739. --numGradientLookupEntries;
  225740. CGShadingRef result = 0;
  225741. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225742. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225743. if (gradient.isRadial)
  225744. {
  225745. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225746. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225747. function, true, true);
  225748. }
  225749. else
  225750. {
  225751. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225752. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225753. function, true, true);
  225754. }
  225755. CGFunctionRelease (function);
  225756. return result;
  225757. }
  225758. void drawGradient()
  225759. {
  225760. flip();
  225761. applyTransform (state->fillType.transform);
  225762. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225763. // you draw a gradient with high quality interp enabled).
  225764. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225765. CGContextSetAlpha (context, state->fillType.getOpacity());
  225766. CGContextDrawShading (context, shading);
  225767. CGShadingRelease (shading);
  225768. }
  225769. void createPath (const Path& path) const
  225770. {
  225771. CGContextBeginPath (context);
  225772. Path::Iterator i (path);
  225773. while (i.next())
  225774. {
  225775. switch (i.elementType)
  225776. {
  225777. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225778. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225779. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225780. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225781. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225782. default: jassertfalse; break;
  225783. }
  225784. }
  225785. }
  225786. void createPath (const Path& path, const AffineTransform& transform) const
  225787. {
  225788. CGContextBeginPath (context);
  225789. Path::Iterator i (path);
  225790. while (i.next())
  225791. {
  225792. switch (i.elementType)
  225793. {
  225794. case Path::Iterator::startNewSubPath:
  225795. transform.transformPoint (i.x1, i.y1);
  225796. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225797. break;
  225798. case Path::Iterator::lineTo:
  225799. transform.transformPoint (i.x1, i.y1);
  225800. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225801. break;
  225802. case Path::Iterator::quadraticTo:
  225803. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  225804. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225805. break;
  225806. case Path::Iterator::cubicTo:
  225807. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  225808. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225809. break;
  225810. case Path::Iterator::closePath:
  225811. CGContextClosePath (context); break;
  225812. default:
  225813. jassertfalse;
  225814. break;
  225815. }
  225816. }
  225817. }
  225818. void flip() const
  225819. {
  225820. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225821. }
  225822. void applyTransform (const AffineTransform& transform) const
  225823. {
  225824. CGAffineTransform t;
  225825. t.a = transform.mat00;
  225826. t.b = transform.mat10;
  225827. t.c = transform.mat01;
  225828. t.d = transform.mat11;
  225829. t.tx = transform.mat02;
  225830. t.ty = transform.mat12;
  225831. CGContextConcatCTM (context, t);
  225832. }
  225833. CoreGraphicsContext (const CoreGraphicsContext&);
  225834. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225835. };
  225836. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225837. {
  225838. return new CoreGraphicsContext (context, height);
  225839. }
  225840. #endif
  225841. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225842. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225843. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225844. // compiled on its own).
  225845. #if JUCE_INCLUDED_FILE
  225846. class UIViewComponentPeer;
  225847. END_JUCE_NAMESPACE
  225848. #define JuceUIView MakeObjCClassName(JuceUIView)
  225849. @interface JuceUIView : UIView <UITextViewDelegate>
  225850. {
  225851. @public
  225852. UIViewComponentPeer* owner;
  225853. UITextView* hiddenTextView;
  225854. }
  225855. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225856. - (void) dealloc;
  225857. - (void) drawRect: (CGRect) r;
  225858. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225859. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225860. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225861. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225862. - (BOOL) becomeFirstResponder;
  225863. - (BOOL) resignFirstResponder;
  225864. - (BOOL) canBecomeFirstResponder;
  225865. - (void) asyncRepaint: (id) rect;
  225866. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  225867. @end
  225868. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225869. @interface JuceUIWindow : UIWindow
  225870. {
  225871. @private
  225872. UIViewComponentPeer* owner;
  225873. bool isZooming;
  225874. }
  225875. - (void) setOwner: (UIViewComponentPeer*) owner;
  225876. - (void) becomeKeyWindow;
  225877. @end
  225878. BEGIN_JUCE_NAMESPACE
  225879. class UIViewComponentPeer : public ComponentPeer,
  225880. public FocusChangeListener
  225881. {
  225882. public:
  225883. UIViewComponentPeer (Component* const component,
  225884. const int windowStyleFlags,
  225885. UIView* viewToAttachTo);
  225886. ~UIViewComponentPeer();
  225887. void* getNativeHandle() const;
  225888. void setVisible (bool shouldBeVisible);
  225889. void setTitle (const String& title);
  225890. void setPosition (int x, int y);
  225891. void setSize (int w, int h);
  225892. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225893. const Rectangle<int> getBounds() const;
  225894. const Rectangle<int> getBounds (const bool global) const;
  225895. const Point<int> getScreenPosition() const;
  225896. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225897. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225898. void setMinimised (bool shouldBeMinimised);
  225899. bool isMinimised() const;
  225900. void setFullScreen (bool shouldBeFullScreen);
  225901. bool isFullScreen() const;
  225902. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225903. const BorderSize getFrameSize() const;
  225904. bool setAlwaysOnTop (bool alwaysOnTop);
  225905. void toFront (bool makeActiveWindow);
  225906. void toBehind (ComponentPeer* other);
  225907. void setIcon (const Image& newIcon);
  225908. virtual void drawRect (CGRect r);
  225909. virtual bool canBecomeKeyWindow();
  225910. virtual bool windowShouldClose();
  225911. virtual void redirectMovedOrResized();
  225912. virtual CGRect constrainRect (CGRect r);
  225913. virtual void viewFocusGain();
  225914. virtual void viewFocusLoss();
  225915. bool isFocused() const;
  225916. void grabFocus();
  225917. void textInputRequired (const Point<int>& position);
  225918. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  225919. void updateHiddenTextContent (TextInputTarget* target);
  225920. void globalFocusChanged (Component*);
  225921. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225922. void repaint (const Rectangle<int>& area);
  225923. void performAnyPendingRepaintsNow();
  225924. juce_UseDebuggingNewOperator
  225925. UIWindow* window;
  225926. JuceUIView* view;
  225927. bool isSharedWindow, fullScreen, insideDrawRect;
  225928. static ModifierKeys currentModifiers;
  225929. static int64 getMouseTime (UIEvent* e)
  225930. {
  225931. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225932. + (int64) ([e timestamp] * 1000.0);
  225933. }
  225934. Array <UITouch*> currentTouches;
  225935. };
  225936. END_JUCE_NAMESPACE
  225937. @implementation JuceUIView
  225938. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225939. withFrame: (CGRect) frame
  225940. {
  225941. [super initWithFrame: frame];
  225942. owner = owner_;
  225943. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225944. [self addSubview: hiddenTextView];
  225945. hiddenTextView.delegate = self;
  225946. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  225947. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  225948. return self;
  225949. }
  225950. - (void) dealloc
  225951. {
  225952. [hiddenTextView removeFromSuperview];
  225953. [hiddenTextView release];
  225954. [super dealloc];
  225955. }
  225956. - (void) drawRect: (CGRect) r
  225957. {
  225958. if (owner != 0)
  225959. owner->drawRect (r);
  225960. }
  225961. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225962. {
  225963. return false;
  225964. }
  225965. ModifierKeys UIViewComponentPeer::currentModifiers;
  225966. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225967. {
  225968. return UIViewComponentPeer::currentModifiers;
  225969. }
  225970. void ModifierKeys::updateCurrentModifiers() throw()
  225971. {
  225972. currentModifiers = UIViewComponentPeer::currentModifiers;
  225973. }
  225974. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225975. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225976. {
  225977. if (owner != 0)
  225978. owner->handleTouches (event, true, false, false);
  225979. }
  225980. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  225981. {
  225982. if (owner != 0)
  225983. owner->handleTouches (event, false, false, false);
  225984. }
  225985. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  225986. {
  225987. if (owner != 0)
  225988. owner->handleTouches (event, false, true, false);
  225989. }
  225990. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  225991. {
  225992. if (owner != 0)
  225993. owner->handleTouches (event, false, true, true);
  225994. [self touchesEnded: touches withEvent: event];
  225995. }
  225996. - (BOOL) becomeFirstResponder
  225997. {
  225998. if (owner != 0)
  225999. owner->viewFocusGain();
  226000. return true;
  226001. }
  226002. - (BOOL) resignFirstResponder
  226003. {
  226004. if (owner != 0)
  226005. owner->viewFocusLoss();
  226006. return true;
  226007. }
  226008. - (BOOL) canBecomeFirstResponder
  226009. {
  226010. return owner != 0 && owner->canBecomeKeyWindow();
  226011. }
  226012. - (void) asyncRepaint: (id) rect
  226013. {
  226014. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226015. [self setNeedsDisplayInRect: *r];
  226016. }
  226017. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226018. {
  226019. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226020. nsStringToJuce (text));
  226021. }
  226022. @end
  226023. @implementation JuceUIWindow
  226024. - (void) setOwner: (UIViewComponentPeer*) owner_
  226025. {
  226026. owner = owner_;
  226027. isZooming = false;
  226028. }
  226029. - (void) becomeKeyWindow
  226030. {
  226031. [super becomeKeyWindow];
  226032. if (owner != 0)
  226033. owner->grabFocus();
  226034. }
  226035. @end
  226036. BEGIN_JUCE_NAMESPACE
  226037. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226038. const int windowStyleFlags,
  226039. UIView* viewToAttachTo)
  226040. : ComponentPeer (component, windowStyleFlags),
  226041. window (0),
  226042. view (0),
  226043. isSharedWindow (viewToAttachTo != 0),
  226044. fullScreen (false),
  226045. insideDrawRect (false)
  226046. {
  226047. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  226048. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226049. if (isSharedWindow)
  226050. {
  226051. window = [viewToAttachTo window];
  226052. [viewToAttachTo addSubview: view];
  226053. setVisible (component->isVisible());
  226054. }
  226055. else
  226056. {
  226057. r.origin.x = (float) component->getX();
  226058. r.origin.y = (float) component->getY();
  226059. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226060. window = [[JuceUIWindow alloc] init];
  226061. window.frame = r;
  226062. window.opaque = component->isOpaque();
  226063. view.opaque = component->isOpaque();
  226064. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226065. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226066. [((JuceUIWindow*) window) setOwner: this];
  226067. if (component->isAlwaysOnTop())
  226068. window.windowLevel = UIWindowLevelAlert;
  226069. [window addSubview: view];
  226070. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226071. view.hidden = ! component->isVisible();
  226072. window.hidden = ! component->isVisible();
  226073. view.multipleTouchEnabled = YES;
  226074. }
  226075. setTitle (component->getName());
  226076. Desktop::getInstance().addFocusChangeListener (this);
  226077. }
  226078. UIViewComponentPeer::~UIViewComponentPeer()
  226079. {
  226080. Desktop::getInstance().removeFocusChangeListener (this);
  226081. view->owner = 0;
  226082. [view removeFromSuperview];
  226083. [view release];
  226084. if (! isSharedWindow)
  226085. {
  226086. [((JuceUIWindow*) window) setOwner: 0];
  226087. [window release];
  226088. }
  226089. }
  226090. void* UIViewComponentPeer::getNativeHandle() const
  226091. {
  226092. return view;
  226093. }
  226094. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226095. {
  226096. view.hidden = ! shouldBeVisible;
  226097. if (! isSharedWindow)
  226098. window.hidden = ! shouldBeVisible;
  226099. }
  226100. void UIViewComponentPeer::setTitle (const String& title)
  226101. {
  226102. // xxx is this possible?
  226103. }
  226104. void UIViewComponentPeer::setPosition (int x, int y)
  226105. {
  226106. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226107. }
  226108. void UIViewComponentPeer::setSize (int w, int h)
  226109. {
  226110. setBounds (component->getX(), component->getY(), w, h, false);
  226111. }
  226112. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226113. {
  226114. fullScreen = isNowFullScreen;
  226115. w = jmax (0, w);
  226116. h = jmax (0, h);
  226117. CGRect r;
  226118. r.origin.x = (float) x;
  226119. r.origin.y = (float) y;
  226120. r.size.width = (float) w;
  226121. r.size.height = (float) h;
  226122. if (isSharedWindow)
  226123. {
  226124. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  226125. if ([view frame].size.width != r.size.width
  226126. || [view frame].size.height != r.size.height)
  226127. [view setNeedsDisplay];
  226128. view.frame = r;
  226129. }
  226130. else
  226131. {
  226132. window.frame = r;
  226133. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226134. }
  226135. }
  226136. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226137. {
  226138. CGRect r = [view frame];
  226139. if (global && [view window] != 0)
  226140. {
  226141. r = [view convertRect: r toView: nil];
  226142. CGRect wr = [[view window] frame];
  226143. r.origin.x += wr.origin.x;
  226144. r.origin.y += wr.origin.y;
  226145. }
  226146. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  226147. (int) r.size.width, (int) r.size.height);
  226148. }
  226149. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226150. {
  226151. return getBounds (! isSharedWindow);
  226152. }
  226153. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226154. {
  226155. return getBounds (true).getPosition();
  226156. }
  226157. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  226158. {
  226159. return relativePosition + getScreenPosition();
  226160. }
  226161. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  226162. {
  226163. return screenPosition - getScreenPosition();
  226164. }
  226165. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226166. {
  226167. if (constrainer != 0)
  226168. {
  226169. CGRect current = [window frame];
  226170. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226171. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226172. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  226173. (int) r.size.width, (int) r.size.height);
  226174. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  226175. (int) current.size.width, (int) current.size.height);
  226176. constrainer->checkBounds (pos, original,
  226177. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226178. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226179. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226180. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226181. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226182. r.origin.x = pos.getX();
  226183. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226184. r.size.width = pos.getWidth();
  226185. r.size.height = pos.getHeight();
  226186. }
  226187. return r;
  226188. }
  226189. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226190. {
  226191. // xxx
  226192. }
  226193. bool UIViewComponentPeer::isMinimised() const
  226194. {
  226195. return false;
  226196. }
  226197. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226198. {
  226199. if (! isSharedWindow)
  226200. {
  226201. Rectangle<int> r (lastNonFullscreenBounds);
  226202. setMinimised (false);
  226203. if (fullScreen != shouldBeFullScreen)
  226204. {
  226205. if (shouldBeFullScreen)
  226206. r = Desktop::getInstance().getMainMonitorArea();
  226207. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226208. if (r != getComponent()->getBounds() && ! r.isEmpty())
  226209. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226210. }
  226211. }
  226212. }
  226213. bool UIViewComponentPeer::isFullScreen() const
  226214. {
  226215. return fullScreen;
  226216. }
  226217. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226218. {
  226219. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  226220. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  226221. return false;
  226222. CGPoint p;
  226223. p.x = (float) position.getX();
  226224. p.y = (float) position.getY();
  226225. UIView* v = [view hitTest: p withEvent: nil];
  226226. if (trueIfInAChildWindow)
  226227. return v != nil;
  226228. return v == view;
  226229. }
  226230. const BorderSize UIViewComponentPeer::getFrameSize() const
  226231. {
  226232. BorderSize b;
  226233. if (! isSharedWindow)
  226234. {
  226235. CGRect v = [view convertRect: [view frame] toView: nil];
  226236. CGRect w = [window frame];
  226237. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  226238. b.setBottom ((int) v.origin.y);
  226239. b.setLeft ((int) v.origin.x);
  226240. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  226241. }
  226242. return b;
  226243. }
  226244. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226245. {
  226246. if (! isSharedWindow)
  226247. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226248. return true;
  226249. }
  226250. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226251. {
  226252. if (isSharedWindow)
  226253. [[view superview] bringSubviewToFront: view];
  226254. if (window != 0 && component->isVisible())
  226255. [window makeKeyAndVisible];
  226256. }
  226257. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226258. {
  226259. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226260. jassert (otherPeer != 0); // wrong type of window?
  226261. if (otherPeer != 0)
  226262. {
  226263. if (isSharedWindow)
  226264. {
  226265. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226266. }
  226267. else
  226268. {
  226269. jassertfalse; // don't know how to do this
  226270. }
  226271. }
  226272. }
  226273. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226274. {
  226275. // to do..
  226276. }
  226277. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226278. {
  226279. NSArray* touches = [[event touchesForView: view] allObjects];
  226280. for (unsigned int i = 0; i < [touches count]; ++i)
  226281. {
  226282. UITouch* touch = [touches objectAtIndex: i];
  226283. CGPoint p = [touch locationInView: view];
  226284. const Point<int> pos ((int) p.x, (int) p.y);
  226285. juce_lastMousePos = pos + getScreenPosition();
  226286. const int64 time = getMouseTime (event);
  226287. int touchIndex = currentTouches.indexOf (touch);
  226288. if (touchIndex < 0)
  226289. {
  226290. touchIndex = currentTouches.size();
  226291. currentTouches.add (touch);
  226292. }
  226293. if (isDown)
  226294. {
  226295. currentModifiers = currentModifiers.withoutMouseButtons();
  226296. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226297. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226298. }
  226299. else if (isUp)
  226300. {
  226301. currentModifiers = currentModifiers.withoutMouseButtons();
  226302. currentTouches.remove (touchIndex);
  226303. }
  226304. if (isCancel)
  226305. currentTouches.clear();
  226306. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226307. }
  226308. }
  226309. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226310. void UIViewComponentPeer::viewFocusGain()
  226311. {
  226312. if (currentlyFocusedPeer != this)
  226313. {
  226314. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226315. currentlyFocusedPeer->handleFocusLoss();
  226316. currentlyFocusedPeer = this;
  226317. handleFocusGain();
  226318. }
  226319. }
  226320. void UIViewComponentPeer::viewFocusLoss()
  226321. {
  226322. if (currentlyFocusedPeer == this)
  226323. {
  226324. currentlyFocusedPeer = 0;
  226325. handleFocusLoss();
  226326. }
  226327. }
  226328. void juce_HandleProcessFocusChange()
  226329. {
  226330. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226331. {
  226332. if (Process::isForegroundProcess())
  226333. {
  226334. currentlyFocusedPeer->handleFocusGain();
  226335. ComponentPeer::bringModalComponentToFront();
  226336. }
  226337. else
  226338. {
  226339. currentlyFocusedPeer->handleFocusLoss();
  226340. // turn kiosk mode off if we lose focus..
  226341. Desktop::getInstance().setKioskModeComponent (0);
  226342. }
  226343. }
  226344. }
  226345. bool UIViewComponentPeer::isFocused() const
  226346. {
  226347. return isSharedWindow ? this == currentlyFocusedPeer
  226348. : (window != 0 && [window isKeyWindow]);
  226349. }
  226350. void UIViewComponentPeer::grabFocus()
  226351. {
  226352. if (window != 0)
  226353. {
  226354. [window makeKeyWindow];
  226355. viewFocusGain();
  226356. }
  226357. }
  226358. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226359. {
  226360. }
  226361. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226362. {
  226363. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226364. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  226365. }
  226366. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  226367. {
  226368. TextInputTarget* const target = findCurrentTextInputTarget();
  226369. if (target != 0)
  226370. {
  226371. const Range<int> currentSelection (target->getHighlightedRegion());
  226372. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226373. if (currentSelection.isEmpty())
  226374. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226375. target->insertTextAtCaret (text);
  226376. updateHiddenTextContent (target);
  226377. }
  226378. return NO;
  226379. }
  226380. void UIViewComponentPeer::globalFocusChanged (Component*)
  226381. {
  226382. TextInputTarget* const target = findCurrentTextInputTarget();
  226383. if (target != 0)
  226384. {
  226385. Component* comp = dynamic_cast<Component*> (target);
  226386. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226387. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226388. updateHiddenTextContent (target);
  226389. [view->hiddenTextView becomeFirstResponder];
  226390. }
  226391. else
  226392. {
  226393. [view->hiddenTextView resignFirstResponder];
  226394. }
  226395. }
  226396. void UIViewComponentPeer::drawRect (CGRect r)
  226397. {
  226398. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226399. return;
  226400. CGContextRef cg = UIGraphicsGetCurrentContext();
  226401. if (! component->isOpaque())
  226402. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226403. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226404. CoreGraphicsContext g (cg, view.bounds.size.height);
  226405. insideDrawRect = true;
  226406. handlePaint (g);
  226407. insideDrawRect = false;
  226408. }
  226409. bool UIViewComponentPeer::canBecomeKeyWindow()
  226410. {
  226411. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226412. }
  226413. bool UIViewComponentPeer::windowShouldClose()
  226414. {
  226415. if (! isValidPeer (this))
  226416. return YES;
  226417. handleUserClosingWindow();
  226418. return NO;
  226419. }
  226420. void UIViewComponentPeer::redirectMovedOrResized()
  226421. {
  226422. handleMovedOrResized();
  226423. }
  226424. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226425. {
  226426. }
  226427. class AsyncRepaintMessage : public CallbackMessage
  226428. {
  226429. public:
  226430. UIViewComponentPeer* const peer;
  226431. const Rectangle<int> rect;
  226432. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226433. : peer (peer_), rect (rect_)
  226434. {
  226435. }
  226436. void messageCallback()
  226437. {
  226438. if (ComponentPeer::isValidPeer (peer))
  226439. peer->repaint (rect);
  226440. }
  226441. };
  226442. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226443. {
  226444. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226445. {
  226446. (new AsyncRepaintMessage (this, area))->post();
  226447. }
  226448. else
  226449. {
  226450. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226451. (float) area.getWidth(), (float) area.getHeight())];
  226452. }
  226453. }
  226454. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226455. {
  226456. }
  226457. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226458. {
  226459. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226460. }
  226461. const Image juce_createIconForFile (const File& file)
  226462. {
  226463. return Image::null;
  226464. }
  226465. void Desktop::createMouseInputSources()
  226466. {
  226467. for (int i = 0; i < 10; ++i)
  226468. mouseSources.add (new MouseInputSource (i, false));
  226469. }
  226470. bool Desktop::canUseSemiTransparentWindows() throw()
  226471. {
  226472. return true;
  226473. }
  226474. const Point<int> Desktop::getMousePosition()
  226475. {
  226476. return juce_lastMousePos;
  226477. }
  226478. void Desktop::setMousePosition (const Point<int>&)
  226479. {
  226480. }
  226481. const int KeyPress::spaceKey = ' ';
  226482. const int KeyPress::returnKey = 0x0d;
  226483. const int KeyPress::escapeKey = 0x1b;
  226484. const int KeyPress::backspaceKey = 0x7f;
  226485. const int KeyPress::leftKey = 0x1000;
  226486. const int KeyPress::rightKey = 0x1001;
  226487. const int KeyPress::upKey = 0x1002;
  226488. const int KeyPress::downKey = 0x1003;
  226489. const int KeyPress::pageUpKey = 0x1004;
  226490. const int KeyPress::pageDownKey = 0x1005;
  226491. const int KeyPress::endKey = 0x1006;
  226492. const int KeyPress::homeKey = 0x1007;
  226493. const int KeyPress::deleteKey = 0x1008;
  226494. const int KeyPress::insertKey = -1;
  226495. const int KeyPress::tabKey = 9;
  226496. const int KeyPress::F1Key = 0x2001;
  226497. const int KeyPress::F2Key = 0x2002;
  226498. const int KeyPress::F3Key = 0x2003;
  226499. const int KeyPress::F4Key = 0x2004;
  226500. const int KeyPress::F5Key = 0x2005;
  226501. const int KeyPress::F6Key = 0x2006;
  226502. const int KeyPress::F7Key = 0x2007;
  226503. const int KeyPress::F8Key = 0x2008;
  226504. const int KeyPress::F9Key = 0x2009;
  226505. const int KeyPress::F10Key = 0x200a;
  226506. const int KeyPress::F11Key = 0x200b;
  226507. const int KeyPress::F12Key = 0x200c;
  226508. const int KeyPress::F13Key = 0x200d;
  226509. const int KeyPress::F14Key = 0x200e;
  226510. const int KeyPress::F15Key = 0x200f;
  226511. const int KeyPress::F16Key = 0x2010;
  226512. const int KeyPress::numberPad0 = 0x30020;
  226513. const int KeyPress::numberPad1 = 0x30021;
  226514. const int KeyPress::numberPad2 = 0x30022;
  226515. const int KeyPress::numberPad3 = 0x30023;
  226516. const int KeyPress::numberPad4 = 0x30024;
  226517. const int KeyPress::numberPad5 = 0x30025;
  226518. const int KeyPress::numberPad6 = 0x30026;
  226519. const int KeyPress::numberPad7 = 0x30027;
  226520. const int KeyPress::numberPad8 = 0x30028;
  226521. const int KeyPress::numberPad9 = 0x30029;
  226522. const int KeyPress::numberPadAdd = 0x3002a;
  226523. const int KeyPress::numberPadSubtract = 0x3002b;
  226524. const int KeyPress::numberPadMultiply = 0x3002c;
  226525. const int KeyPress::numberPadDivide = 0x3002d;
  226526. const int KeyPress::numberPadSeparator = 0x3002e;
  226527. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226528. const int KeyPress::numberPadEquals = 0x30030;
  226529. const int KeyPress::numberPadDelete = 0x30031;
  226530. const int KeyPress::playKey = 0x30000;
  226531. const int KeyPress::stopKey = 0x30001;
  226532. const int KeyPress::fastForwardKey = 0x30002;
  226533. const int KeyPress::rewindKey = 0x30003;
  226534. #endif
  226535. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226536. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226537. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226538. // compiled on its own).
  226539. #if JUCE_INCLUDED_FILE
  226540. struct CallbackMessagePayload
  226541. {
  226542. MessageCallbackFunction* function;
  226543. void* parameter;
  226544. void* volatile result;
  226545. bool volatile hasBeenExecuted;
  226546. };
  226547. END_JUCE_NAMESPACE
  226548. @interface JuceCustomMessageHandler : NSObject
  226549. {
  226550. }
  226551. - (void) performCallback: (id) info;
  226552. @end
  226553. @implementation JuceCustomMessageHandler
  226554. - (void) performCallback: (id) info
  226555. {
  226556. if ([info isKindOfClass: [NSData class]])
  226557. {
  226558. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226559. if (pl != 0)
  226560. {
  226561. pl->result = (*pl->function) (pl->parameter);
  226562. pl->hasBeenExecuted = true;
  226563. }
  226564. }
  226565. else
  226566. {
  226567. jassertfalse; // should never get here!
  226568. }
  226569. }
  226570. @end
  226571. BEGIN_JUCE_NAMESPACE
  226572. void MessageManager::runDispatchLoop()
  226573. {
  226574. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226575. runDispatchLoopUntil (-1);
  226576. }
  226577. void MessageManager::stopDispatchLoop()
  226578. {
  226579. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  226580. exit (0); // iPhone apps get no mercy..
  226581. }
  226582. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226583. {
  226584. const ScopedAutoReleasePool pool;
  226585. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226586. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226587. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226588. while (! quitMessagePosted)
  226589. {
  226590. const ScopedAutoReleasePool pool;
  226591. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226592. beforeDate: endDate];
  226593. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226594. break;
  226595. }
  226596. return ! quitMessagePosted;
  226597. }
  226598. static CFRunLoopRef runLoop = 0;
  226599. static CFRunLoopSourceRef runLoopSource = 0;
  226600. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  226601. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226602. static void runLoopSourceCallback (void*)
  226603. {
  226604. if (pendingMessages != 0)
  226605. {
  226606. int numDispatched = 0;
  226607. do
  226608. {
  226609. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  226610. if (nextMessage == 0)
  226611. return;
  226612. const ScopedAutoReleasePool pool;
  226613. MessageManager::getInstance()->deliverMessage (nextMessage);
  226614. } while (++numDispatched <= 4);
  226615. CFRunLoopSourceSignal (runLoopSource);
  226616. CFRunLoopWakeUp (runLoop);
  226617. }
  226618. }
  226619. void MessageManager::doPlatformSpecificInitialisation()
  226620. {
  226621. pendingMessages = new OwnedArray <Message, CriticalSection>();
  226622. runLoop = CFRunLoopGetCurrent();
  226623. CFRunLoopSourceContext sourceContext;
  226624. zerostruct (sourceContext);
  226625. sourceContext.perform = runLoopSourceCallback;
  226626. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226627. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226628. if (juceCustomMessageHandler == 0)
  226629. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226630. }
  226631. void MessageManager::doPlatformSpecificShutdown()
  226632. {
  226633. CFRunLoopSourceInvalidate (runLoopSource);
  226634. CFRelease (runLoopSource);
  226635. runLoopSource = 0;
  226636. deleteAndZero (pendingMessages);
  226637. if (juceCustomMessageHandler != 0)
  226638. {
  226639. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226640. [juceCustomMessageHandler release];
  226641. juceCustomMessageHandler = 0;
  226642. }
  226643. }
  226644. bool juce_postMessageToSystemQueue (Message* message)
  226645. {
  226646. if (pendingMessages != 0)
  226647. {
  226648. pendingMessages->add (message);
  226649. CFRunLoopSourceSignal (runLoopSource);
  226650. CFRunLoopWakeUp (runLoop);
  226651. }
  226652. return true;
  226653. }
  226654. void MessageManager::broadcastMessage (const String& value) throw()
  226655. {
  226656. }
  226657. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226658. void* data)
  226659. {
  226660. if (isThisTheMessageThread())
  226661. {
  226662. return (*callback) (data);
  226663. }
  226664. else
  226665. {
  226666. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226667. // deadlock because the message manager is blocked from running, so can never
  226668. // call your function..
  226669. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226670. const ScopedAutoReleasePool pool;
  226671. CallbackMessagePayload cmp;
  226672. cmp.function = callback;
  226673. cmp.parameter = data;
  226674. cmp.result = 0;
  226675. cmp.hasBeenExecuted = false;
  226676. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226677. withObject: [NSData dataWithBytesNoCopy: &cmp
  226678. length: sizeof (cmp)
  226679. freeWhenDone: NO]
  226680. waitUntilDone: YES];
  226681. return cmp.result;
  226682. }
  226683. }
  226684. #endif
  226685. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226686. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226687. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226688. // compiled on its own).
  226689. #if JUCE_INCLUDED_FILE
  226690. #if JUCE_MAC
  226691. END_JUCE_NAMESPACE
  226692. using namespace JUCE_NAMESPACE;
  226693. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226694. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226695. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226696. #else
  226697. @interface JuceFileChooserDelegate : NSObject
  226698. #endif
  226699. {
  226700. StringArray* filters;
  226701. }
  226702. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226703. - (void) dealloc;
  226704. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226705. @end
  226706. @implementation JuceFileChooserDelegate
  226707. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226708. {
  226709. [super init];
  226710. filters = filters_;
  226711. return self;
  226712. }
  226713. - (void) dealloc
  226714. {
  226715. delete filters;
  226716. [super dealloc];
  226717. }
  226718. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226719. {
  226720. (void) sender;
  226721. const File f (nsStringToJuce (filename));
  226722. for (int i = filters->size(); --i >= 0;)
  226723. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226724. return true;
  226725. return f.isDirectory();
  226726. }
  226727. @end
  226728. BEGIN_JUCE_NAMESPACE
  226729. void FileChooser::showPlatformDialog (Array<File>& results,
  226730. const String& title,
  226731. const File& currentFileOrDirectory,
  226732. const String& filter,
  226733. bool selectsDirectory,
  226734. bool selectsFiles,
  226735. bool isSaveDialogue,
  226736. bool warnAboutOverwritingExistingFiles,
  226737. bool selectMultipleFiles,
  226738. FilePreviewComponent* extraInfoComponent)
  226739. {
  226740. const ScopedAutoReleasePool pool;
  226741. StringArray* filters = new StringArray();
  226742. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226743. filters->trim();
  226744. filters->removeEmptyStrings();
  226745. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226746. [delegate autorelease];
  226747. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226748. : [NSOpenPanel openPanel];
  226749. [panel setTitle: juceStringToNS (title)];
  226750. if (! isSaveDialogue)
  226751. {
  226752. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226753. [openPanel setCanChooseDirectories: selectsDirectory];
  226754. [openPanel setCanChooseFiles: selectsFiles];
  226755. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226756. }
  226757. [panel setDelegate: delegate];
  226758. if (isSaveDialogue || selectsDirectory)
  226759. [panel setCanCreateDirectories: YES];
  226760. String directory, filename;
  226761. if (currentFileOrDirectory.isDirectory())
  226762. {
  226763. directory = currentFileOrDirectory.getFullPathName();
  226764. }
  226765. else
  226766. {
  226767. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226768. filename = currentFileOrDirectory.getFileName();
  226769. }
  226770. if ([panel runModalForDirectory: juceStringToNS (directory)
  226771. file: juceStringToNS (filename)]
  226772. == NSOKButton)
  226773. {
  226774. if (isSaveDialogue)
  226775. {
  226776. results.add (File (nsStringToJuce ([panel filename])));
  226777. }
  226778. else
  226779. {
  226780. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226781. NSArray* urls = [openPanel filenames];
  226782. for (unsigned int i = 0; i < [urls count]; ++i)
  226783. {
  226784. NSString* f = [urls objectAtIndex: i];
  226785. results.add (File (nsStringToJuce (f)));
  226786. }
  226787. }
  226788. }
  226789. [panel setDelegate: nil];
  226790. }
  226791. #else
  226792. void FileChooser::showPlatformDialog (Array<File>& results,
  226793. const String& title,
  226794. const File& currentFileOrDirectory,
  226795. const String& filter,
  226796. bool selectsDirectory,
  226797. bool selectsFiles,
  226798. bool isSaveDialogue,
  226799. bool warnAboutOverwritingExistingFiles,
  226800. bool selectMultipleFiles,
  226801. FilePreviewComponent* extraInfoComponent)
  226802. {
  226803. const ScopedAutoReleasePool pool;
  226804. jassertfalse; //xxx to do
  226805. }
  226806. #endif
  226807. #endif
  226808. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226809. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226810. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226811. // compiled on its own).
  226812. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226813. #if JUCE_MAC
  226814. END_JUCE_NAMESPACE
  226815. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226816. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226817. {
  226818. CriticalSection* contextLock;
  226819. bool needsUpdate;
  226820. }
  226821. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226822. - (bool) makeActive;
  226823. - (void) makeInactive;
  226824. - (void) reshape;
  226825. @end
  226826. @implementation ThreadSafeNSOpenGLView
  226827. - (id) initWithFrame: (NSRect) frameRect
  226828. pixelFormat: (NSOpenGLPixelFormat*) format
  226829. {
  226830. contextLock = new CriticalSection();
  226831. self = [super initWithFrame: frameRect pixelFormat: format];
  226832. if (self != nil)
  226833. [[NSNotificationCenter defaultCenter] addObserver: self
  226834. selector: @selector (_surfaceNeedsUpdate:)
  226835. name: NSViewGlobalFrameDidChangeNotification
  226836. object: self];
  226837. return self;
  226838. }
  226839. - (void) dealloc
  226840. {
  226841. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226842. delete contextLock;
  226843. [super dealloc];
  226844. }
  226845. - (bool) makeActive
  226846. {
  226847. const ScopedLock sl (*contextLock);
  226848. if ([self openGLContext] == 0)
  226849. return false;
  226850. [[self openGLContext] makeCurrentContext];
  226851. if (needsUpdate)
  226852. {
  226853. [super update];
  226854. needsUpdate = false;
  226855. }
  226856. return true;
  226857. }
  226858. - (void) makeInactive
  226859. {
  226860. const ScopedLock sl (*contextLock);
  226861. [NSOpenGLContext clearCurrentContext];
  226862. }
  226863. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226864. {
  226865. const ScopedLock sl (*contextLock);
  226866. needsUpdate = true;
  226867. }
  226868. - (void) update
  226869. {
  226870. const ScopedLock sl (*contextLock);
  226871. needsUpdate = true;
  226872. }
  226873. - (void) reshape
  226874. {
  226875. const ScopedLock sl (*contextLock);
  226876. needsUpdate = true;
  226877. }
  226878. @end
  226879. BEGIN_JUCE_NAMESPACE
  226880. class WindowedGLContext : public OpenGLContext
  226881. {
  226882. public:
  226883. WindowedGLContext (Component* const component,
  226884. const OpenGLPixelFormat& pixelFormat_,
  226885. NSOpenGLContext* sharedContext)
  226886. : renderContext (0),
  226887. pixelFormat (pixelFormat_)
  226888. {
  226889. jassert (component != 0);
  226890. NSOpenGLPixelFormatAttribute attribs [64];
  226891. int n = 0;
  226892. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226893. attribs[n++] = NSOpenGLPFAAccelerated;
  226894. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226895. attribs[n++] = NSOpenGLPFAColorSize;
  226896. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226897. pixelFormat.greenBits,
  226898. pixelFormat.blueBits);
  226899. attribs[n++] = NSOpenGLPFAAlphaSize;
  226900. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226901. attribs[n++] = NSOpenGLPFADepthSize;
  226902. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226903. attribs[n++] = NSOpenGLPFAStencilSize;
  226904. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226905. attribs[n++] = NSOpenGLPFAAccumSize;
  226906. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226907. pixelFormat.accumulationBufferGreenBits,
  226908. pixelFormat.accumulationBufferBlueBits,
  226909. pixelFormat.accumulationBufferAlphaBits);
  226910. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226911. attribs[n++] = NSOpenGLPFASampleBuffers;
  226912. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226913. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226914. attribs[n++] = NSOpenGLPFANoRecovery;
  226915. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226916. NSOpenGLPixelFormat* format
  226917. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226918. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226919. pixelFormat: format];
  226920. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226921. shareContext: sharedContext] autorelease];
  226922. const GLint swapInterval = 1;
  226923. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226924. [view setOpenGLContext: renderContext];
  226925. [renderContext setView: view];
  226926. [format release];
  226927. viewHolder = new NSViewComponentInternal (view, component);
  226928. }
  226929. ~WindowedGLContext()
  226930. {
  226931. deleteContext();
  226932. viewHolder = 0;
  226933. }
  226934. void deleteContext()
  226935. {
  226936. makeInactive();
  226937. [renderContext clearDrawable];
  226938. [renderContext setView: nil];
  226939. [view setOpenGLContext: nil];
  226940. renderContext = nil;
  226941. }
  226942. bool makeActive() const throw()
  226943. {
  226944. jassert (renderContext != 0);
  226945. [view makeActive];
  226946. return isActive();
  226947. }
  226948. bool makeInactive() const throw()
  226949. {
  226950. [view makeInactive];
  226951. return true;
  226952. }
  226953. bool isActive() const throw()
  226954. {
  226955. return [NSOpenGLContext currentContext] == renderContext;
  226956. }
  226957. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226958. void* getRawContext() const throw() { return renderContext; }
  226959. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226960. {
  226961. }
  226962. void swapBuffers()
  226963. {
  226964. [renderContext flushBuffer];
  226965. }
  226966. bool setSwapInterval (const int numFramesPerSwap)
  226967. {
  226968. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226969. forParameter: NSOpenGLCPSwapInterval];
  226970. return true;
  226971. }
  226972. int getSwapInterval() const
  226973. {
  226974. GLint numFrames = 0;
  226975. [renderContext getValues: &numFrames
  226976. forParameter: NSOpenGLCPSwapInterval];
  226977. return numFrames;
  226978. }
  226979. void repaint()
  226980. {
  226981. // we need to invalidate the juce view that holds this gl view, to make it
  226982. // cause a repaint callback
  226983. NSView* v = (NSView*) viewHolder->view;
  226984. NSRect r = [v frame];
  226985. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226986. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226987. // repaint message, thus never causing our paint() callback, and never repainting
  226988. // the comp. So invalidating just a little bit around the edge helps..
  226989. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226990. }
  226991. void* getNativeWindowHandle() const { return viewHolder->view; }
  226992. juce_UseDebuggingNewOperator
  226993. NSOpenGLContext* renderContext;
  226994. ThreadSafeNSOpenGLView* view;
  226995. private:
  226996. OpenGLPixelFormat pixelFormat;
  226997. ScopedPointer <NSViewComponentInternal> viewHolder;
  226998. WindowedGLContext (const WindowedGLContext&);
  226999. WindowedGLContext& operator= (const WindowedGLContext&);
  227000. };
  227001. OpenGLContext* OpenGLComponent::createContext()
  227002. {
  227003. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  227004. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227005. return (c->renderContext != 0) ? c.release() : 0;
  227006. }
  227007. void* OpenGLComponent::getNativeWindowHandle() const
  227008. {
  227009. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227010. : 0;
  227011. }
  227012. void juce_glViewport (const int w, const int h)
  227013. {
  227014. glViewport (0, 0, w, h);
  227015. }
  227016. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227017. OwnedArray <OpenGLPixelFormat>& results)
  227018. {
  227019. /* GLint attribs [64];
  227020. int n = 0;
  227021. attribs[n++] = AGL_RGBA;
  227022. attribs[n++] = AGL_DOUBLEBUFFER;
  227023. attribs[n++] = AGL_ACCELERATED;
  227024. attribs[n++] = AGL_NO_RECOVERY;
  227025. attribs[n++] = AGL_NONE;
  227026. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227027. while (p != 0)
  227028. {
  227029. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227030. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227031. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227032. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227033. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227034. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227035. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227036. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227037. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227038. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227039. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227040. results.add (pf);
  227041. p = aglNextPixelFormat (p);
  227042. }*/
  227043. //jassertfalse // can't see how you do this in cocoa!
  227044. }
  227045. #else
  227046. END_JUCE_NAMESPACE
  227047. @interface JuceGLView : UIView
  227048. {
  227049. }
  227050. + (Class) layerClass;
  227051. @end
  227052. @implementation JuceGLView
  227053. + (Class) layerClass
  227054. {
  227055. return [CAEAGLLayer class];
  227056. }
  227057. @end
  227058. BEGIN_JUCE_NAMESPACE
  227059. class GLESContext : public OpenGLContext
  227060. {
  227061. public:
  227062. GLESContext (UIViewComponentPeer* peer,
  227063. Component* const component_,
  227064. const OpenGLPixelFormat& pixelFormat_,
  227065. const GLESContext* const sharedContext,
  227066. NSUInteger apiType)
  227067. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227068. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227069. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227070. {
  227071. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227072. view.opaque = YES;
  227073. view.hidden = NO;
  227074. view.backgroundColor = [UIColor blackColor];
  227075. view.userInteractionEnabled = NO;
  227076. glLayer = (CAEAGLLayer*) [view layer];
  227077. [peer->view addSubview: view];
  227078. if (sharedContext != 0)
  227079. context = [[EAGLContext alloc] initWithAPI: apiType
  227080. sharegroup: [sharedContext->context sharegroup]];
  227081. else
  227082. context = [[EAGLContext alloc] initWithAPI: apiType];
  227083. createGLBuffers();
  227084. }
  227085. ~GLESContext()
  227086. {
  227087. deleteContext();
  227088. [view removeFromSuperview];
  227089. [view release];
  227090. freeGLBuffers();
  227091. }
  227092. void deleteContext()
  227093. {
  227094. makeInactive();
  227095. [context release];
  227096. context = nil;
  227097. }
  227098. bool makeActive() const throw()
  227099. {
  227100. jassert (context != 0);
  227101. [EAGLContext setCurrentContext: context];
  227102. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227103. return true;
  227104. }
  227105. void swapBuffers()
  227106. {
  227107. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227108. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227109. }
  227110. bool makeInactive() const throw()
  227111. {
  227112. return [EAGLContext setCurrentContext: nil];
  227113. }
  227114. bool isActive() const throw()
  227115. {
  227116. return [EAGLContext currentContext] == context;
  227117. }
  227118. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227119. void* getRawContext() const throw() { return glLayer; }
  227120. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227121. {
  227122. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227123. if (lastWidth != w || lastHeight != h)
  227124. {
  227125. lastWidth = w;
  227126. lastHeight = h;
  227127. freeGLBuffers();
  227128. createGLBuffers();
  227129. }
  227130. }
  227131. bool setSwapInterval (const int numFramesPerSwap)
  227132. {
  227133. numFrames = numFramesPerSwap;
  227134. return true;
  227135. }
  227136. int getSwapInterval() const
  227137. {
  227138. return numFrames;
  227139. }
  227140. void repaint()
  227141. {
  227142. }
  227143. void createGLBuffers()
  227144. {
  227145. makeActive();
  227146. glGenFramebuffersOES (1, &frameBufferHandle);
  227147. glGenRenderbuffersOES (1, &colorBufferHandle);
  227148. glGenRenderbuffersOES (1, &depthBufferHandle);
  227149. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227150. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227151. GLint width, height;
  227152. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227153. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227154. if (useDepthBuffer)
  227155. {
  227156. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227157. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227158. }
  227159. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227160. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227161. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227162. if (useDepthBuffer)
  227163. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227164. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227165. }
  227166. void freeGLBuffers()
  227167. {
  227168. if (frameBufferHandle != 0)
  227169. {
  227170. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227171. frameBufferHandle = 0;
  227172. }
  227173. if (colorBufferHandle != 0)
  227174. {
  227175. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227176. colorBufferHandle = 0;
  227177. }
  227178. if (depthBufferHandle != 0)
  227179. {
  227180. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227181. depthBufferHandle = 0;
  227182. }
  227183. }
  227184. juce_UseDebuggingNewOperator
  227185. private:
  227186. Component::SafePointer<Component> component;
  227187. OpenGLPixelFormat pixelFormat;
  227188. JuceGLView* view;
  227189. CAEAGLLayer* glLayer;
  227190. EAGLContext* context;
  227191. bool useDepthBuffer;
  227192. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227193. int numFrames;
  227194. int lastWidth, lastHeight;
  227195. GLESContext (const GLESContext&);
  227196. GLESContext& operator= (const GLESContext&);
  227197. };
  227198. OpenGLContext* OpenGLComponent::createContext()
  227199. {
  227200. ScopedAutoReleasePool pool;
  227201. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227202. if (peer != 0)
  227203. return new GLESContext (peer, this, preferredPixelFormat,
  227204. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227205. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227206. return 0;
  227207. }
  227208. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227209. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227210. {
  227211. }
  227212. void juce_glViewport (const int w, const int h)
  227213. {
  227214. glViewport (0, 0, w, h);
  227215. }
  227216. #endif
  227217. #endif
  227218. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227219. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227220. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227221. // compiled on its own).
  227222. #if JUCE_INCLUDED_FILE
  227223. #if JUCE_MAC
  227224. namespace MouseCursorHelpers
  227225. {
  227226. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227227. {
  227228. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227229. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227230. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227231. [im release];
  227232. return c;
  227233. }
  227234. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227235. {
  227236. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227237. BufferedInputStream buf (&fileStream, 4096, false);
  227238. PNGImageFormat pngFormat;
  227239. Image im (pngFormat.decodeImage (buf));
  227240. if (im.isValid())
  227241. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227242. jassertfalse;
  227243. return 0;
  227244. }
  227245. }
  227246. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227247. {
  227248. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227249. }
  227250. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227251. {
  227252. const ScopedAutoReleasePool pool;
  227253. NSCursor* c = 0;
  227254. switch (type)
  227255. {
  227256. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227257. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227258. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227259. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227260. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227261. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227262. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227263. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227264. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227265. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227266. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227267. case UpDownResizeCursor:
  227268. case TopEdgeResizeCursor:
  227269. case BottomEdgeResizeCursor:
  227270. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227271. case TopLeftCornerResizeCursor:
  227272. case BottomRightCornerResizeCursor:
  227273. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227274. case TopRightCornerResizeCursor:
  227275. case BottomLeftCornerResizeCursor:
  227276. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227277. case UpDownLeftRightResizeCursor:
  227278. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227279. default:
  227280. jassertfalse;
  227281. break;
  227282. }
  227283. [c retain];
  227284. return c;
  227285. }
  227286. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227287. {
  227288. [((NSCursor*) cursorHandle) release];
  227289. }
  227290. void MouseCursor::showInAllWindows() const
  227291. {
  227292. showInWindow (0);
  227293. }
  227294. void MouseCursor::showInWindow (ComponentPeer*) const
  227295. {
  227296. [((NSCursor*) getHandle()) set];
  227297. }
  227298. #else
  227299. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227300. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227301. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227302. void MouseCursor::showInAllWindows() const {}
  227303. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227304. #endif
  227305. #endif
  227306. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227307. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227308. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227309. // compiled on its own).
  227310. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227311. #if JUCE_MAC
  227312. END_JUCE_NAMESPACE
  227313. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227314. @interface DownloadClickDetector : NSObject
  227315. {
  227316. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227317. }
  227318. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227319. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227320. request: (NSURLRequest*) request
  227321. frame: (WebFrame*) frame
  227322. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227323. @end
  227324. @implementation DownloadClickDetector
  227325. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227326. {
  227327. [super init];
  227328. ownerComponent = ownerComponent_;
  227329. return self;
  227330. }
  227331. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227332. request: (NSURLRequest*) request
  227333. frame: (WebFrame*) frame
  227334. decisionListener: (id <WebPolicyDecisionListener>) listener
  227335. {
  227336. (void) sender;
  227337. (void) request;
  227338. (void) frame;
  227339. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227340. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227341. [listener use];
  227342. else
  227343. [listener ignore];
  227344. }
  227345. @end
  227346. BEGIN_JUCE_NAMESPACE
  227347. class WebBrowserComponentInternal : public NSViewComponent
  227348. {
  227349. public:
  227350. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227351. {
  227352. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227353. frameName: @""
  227354. groupName: @""];
  227355. setView (webView);
  227356. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227357. [webView setPolicyDelegate: clickListener];
  227358. }
  227359. ~WebBrowserComponentInternal()
  227360. {
  227361. [webView setPolicyDelegate: nil];
  227362. [clickListener release];
  227363. setView (0);
  227364. }
  227365. void goToURL (const String& url,
  227366. const StringArray* headers,
  227367. const MemoryBlock* postData)
  227368. {
  227369. NSMutableURLRequest* r
  227370. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227371. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227372. timeoutInterval: 30.0];
  227373. if (postData != 0 && postData->getSize() > 0)
  227374. {
  227375. [r setHTTPMethod: @"POST"];
  227376. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227377. length: postData->getSize()]];
  227378. }
  227379. if (headers != 0)
  227380. {
  227381. for (int i = 0; i < headers->size(); ++i)
  227382. {
  227383. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227384. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227385. [r setValue: juceStringToNS (headerValue)
  227386. forHTTPHeaderField: juceStringToNS (headerName)];
  227387. }
  227388. }
  227389. stop();
  227390. [[webView mainFrame] loadRequest: r];
  227391. }
  227392. void goBack()
  227393. {
  227394. [webView goBack];
  227395. }
  227396. void goForward()
  227397. {
  227398. [webView goForward];
  227399. }
  227400. void stop()
  227401. {
  227402. [webView stopLoading: nil];
  227403. }
  227404. void refresh()
  227405. {
  227406. [webView reload: nil];
  227407. }
  227408. private:
  227409. WebView* webView;
  227410. DownloadClickDetector* clickListener;
  227411. };
  227412. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227413. : browser (0),
  227414. blankPageShown (false),
  227415. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227416. {
  227417. setOpaque (true);
  227418. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227419. }
  227420. WebBrowserComponent::~WebBrowserComponent()
  227421. {
  227422. deleteAndZero (browser);
  227423. }
  227424. void WebBrowserComponent::goToURL (const String& url,
  227425. const StringArray* headers,
  227426. const MemoryBlock* postData)
  227427. {
  227428. lastURL = url;
  227429. lastHeaders.clear();
  227430. if (headers != 0)
  227431. lastHeaders = *headers;
  227432. lastPostData.setSize (0);
  227433. if (postData != 0)
  227434. lastPostData = *postData;
  227435. blankPageShown = false;
  227436. browser->goToURL (url, headers, postData);
  227437. }
  227438. void WebBrowserComponent::stop()
  227439. {
  227440. browser->stop();
  227441. }
  227442. void WebBrowserComponent::goBack()
  227443. {
  227444. lastURL = String::empty;
  227445. blankPageShown = false;
  227446. browser->goBack();
  227447. }
  227448. void WebBrowserComponent::goForward()
  227449. {
  227450. lastURL = String::empty;
  227451. browser->goForward();
  227452. }
  227453. void WebBrowserComponent::refresh()
  227454. {
  227455. browser->refresh();
  227456. }
  227457. void WebBrowserComponent::paint (Graphics&)
  227458. {
  227459. }
  227460. void WebBrowserComponent::checkWindowAssociation()
  227461. {
  227462. if (isShowing())
  227463. {
  227464. if (blankPageShown)
  227465. goBack();
  227466. }
  227467. else
  227468. {
  227469. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227470. {
  227471. // when the component becomes invisible, some stuff like flash
  227472. // carries on playing audio, so we need to force it onto a blank
  227473. // page to avoid this, (and send it back when it's made visible again).
  227474. blankPageShown = true;
  227475. browser->goToURL ("about:blank", 0, 0);
  227476. }
  227477. }
  227478. }
  227479. void WebBrowserComponent::reloadLastURL()
  227480. {
  227481. if (lastURL.isNotEmpty())
  227482. {
  227483. goToURL (lastURL, &lastHeaders, &lastPostData);
  227484. lastURL = String::empty;
  227485. }
  227486. }
  227487. void WebBrowserComponent::parentHierarchyChanged()
  227488. {
  227489. checkWindowAssociation();
  227490. }
  227491. void WebBrowserComponent::resized()
  227492. {
  227493. browser->setSize (getWidth(), getHeight());
  227494. }
  227495. void WebBrowserComponent::visibilityChanged()
  227496. {
  227497. checkWindowAssociation();
  227498. }
  227499. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227500. {
  227501. return true;
  227502. }
  227503. #else
  227504. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227505. {
  227506. }
  227507. WebBrowserComponent::~WebBrowserComponent()
  227508. {
  227509. }
  227510. void WebBrowserComponent::goToURL (const String& url,
  227511. const StringArray* headers,
  227512. const MemoryBlock* postData)
  227513. {
  227514. }
  227515. void WebBrowserComponent::stop()
  227516. {
  227517. }
  227518. void WebBrowserComponent::goBack()
  227519. {
  227520. }
  227521. void WebBrowserComponent::goForward()
  227522. {
  227523. }
  227524. void WebBrowserComponent::refresh()
  227525. {
  227526. }
  227527. void WebBrowserComponent::paint (Graphics& g)
  227528. {
  227529. }
  227530. void WebBrowserComponent::checkWindowAssociation()
  227531. {
  227532. }
  227533. void WebBrowserComponent::reloadLastURL()
  227534. {
  227535. }
  227536. void WebBrowserComponent::parentHierarchyChanged()
  227537. {
  227538. }
  227539. void WebBrowserComponent::resized()
  227540. {
  227541. }
  227542. void WebBrowserComponent::visibilityChanged()
  227543. {
  227544. }
  227545. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227546. {
  227547. return true;
  227548. }
  227549. #endif
  227550. #endif
  227551. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227552. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227553. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227554. // compiled on its own).
  227555. #if JUCE_INCLUDED_FILE
  227556. class IPhoneAudioIODevice : public AudioIODevice
  227557. {
  227558. public:
  227559. IPhoneAudioIODevice (const String& deviceName)
  227560. : AudioIODevice (deviceName, "Audio"),
  227561. audioUnit (0),
  227562. isRunning (false),
  227563. callback (0),
  227564. actualBufferSize (0),
  227565. floatData (1, 2)
  227566. {
  227567. numInputChannels = 2;
  227568. numOutputChannels = 2;
  227569. preferredBufferSize = 0;
  227570. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227571. updateDeviceInfo();
  227572. }
  227573. ~IPhoneAudioIODevice()
  227574. {
  227575. close();
  227576. }
  227577. const StringArray getOutputChannelNames()
  227578. {
  227579. StringArray s;
  227580. s.add ("Left");
  227581. s.add ("Right");
  227582. return s;
  227583. }
  227584. const StringArray getInputChannelNames()
  227585. {
  227586. StringArray s;
  227587. if (audioInputIsAvailable)
  227588. {
  227589. s.add ("Left");
  227590. s.add ("Right");
  227591. }
  227592. return s;
  227593. }
  227594. int getNumSampleRates()
  227595. {
  227596. return 1;
  227597. }
  227598. double getSampleRate (int index)
  227599. {
  227600. return sampleRate;
  227601. }
  227602. int getNumBufferSizesAvailable()
  227603. {
  227604. return 1;
  227605. }
  227606. int getBufferSizeSamples (int index)
  227607. {
  227608. return getDefaultBufferSize();
  227609. }
  227610. int getDefaultBufferSize()
  227611. {
  227612. return 1024;
  227613. }
  227614. const String open (const BigInteger& inputChannels,
  227615. const BigInteger& outputChannels,
  227616. double sampleRate,
  227617. int bufferSize)
  227618. {
  227619. close();
  227620. lastError = String::empty;
  227621. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227622. // xxx set up channel mapping
  227623. activeOutputChans = outputChannels;
  227624. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227625. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227626. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227627. activeInputChans = inputChannels;
  227628. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227629. numInputChannels = activeInputChans.countNumberOfSetBits();
  227630. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227631. AudioSessionSetActive (true);
  227632. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  227633. : kAudioSessionCategory_MediaPlayback;
  227634. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227635. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227636. fixAudioRouteIfSetToReceiver();
  227637. updateDeviceInfo();
  227638. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227639. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227640. actualBufferSize = preferredBufferSize;
  227641. prepareFloatBuffers();
  227642. isRunning = true;
  227643. propertyChanged (0, 0, 0); // creates and starts the AU
  227644. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227645. return lastError;
  227646. }
  227647. void close()
  227648. {
  227649. if (isRunning)
  227650. {
  227651. isRunning = false;
  227652. AudioSessionSetActive (false);
  227653. if (audioUnit != 0)
  227654. {
  227655. AudioComponentInstanceDispose (audioUnit);
  227656. audioUnit = 0;
  227657. }
  227658. }
  227659. }
  227660. bool isOpen()
  227661. {
  227662. return isRunning;
  227663. }
  227664. int getCurrentBufferSizeSamples()
  227665. {
  227666. return actualBufferSize;
  227667. }
  227668. double getCurrentSampleRate()
  227669. {
  227670. return sampleRate;
  227671. }
  227672. int getCurrentBitDepth()
  227673. {
  227674. return 16;
  227675. }
  227676. const BigInteger getActiveOutputChannels() const
  227677. {
  227678. return activeOutputChans;
  227679. }
  227680. const BigInteger getActiveInputChannels() const
  227681. {
  227682. return activeInputChans;
  227683. }
  227684. int getOutputLatencyInSamples()
  227685. {
  227686. return 0; //xxx
  227687. }
  227688. int getInputLatencyInSamples()
  227689. {
  227690. return 0; //xxx
  227691. }
  227692. void start (AudioIODeviceCallback* callback_)
  227693. {
  227694. if (isRunning && callback != callback_)
  227695. {
  227696. if (callback_ != 0)
  227697. callback_->audioDeviceAboutToStart (this);
  227698. const ScopedLock sl (callbackLock);
  227699. callback = callback_;
  227700. }
  227701. }
  227702. void stop()
  227703. {
  227704. if (isRunning)
  227705. {
  227706. AudioIODeviceCallback* lastCallback;
  227707. {
  227708. const ScopedLock sl (callbackLock);
  227709. lastCallback = callback;
  227710. callback = 0;
  227711. }
  227712. if (lastCallback != 0)
  227713. lastCallback->audioDeviceStopped();
  227714. }
  227715. }
  227716. bool isPlaying()
  227717. {
  227718. return isRunning && callback != 0;
  227719. }
  227720. const String getLastError()
  227721. {
  227722. return lastError;
  227723. }
  227724. private:
  227725. CriticalSection callbackLock;
  227726. Float64 sampleRate;
  227727. int numInputChannels, numOutputChannels;
  227728. int preferredBufferSize;
  227729. int actualBufferSize;
  227730. bool isRunning;
  227731. String lastError;
  227732. AudioStreamBasicDescription format;
  227733. AudioUnit audioUnit;
  227734. UInt32 audioInputIsAvailable;
  227735. AudioIODeviceCallback* callback;
  227736. BigInteger activeOutputChans, activeInputChans;
  227737. AudioSampleBuffer floatData;
  227738. float* inputChannels[3];
  227739. float* outputChannels[3];
  227740. bool monoInputChannelNumber, monoOutputChannelNumber;
  227741. void prepareFloatBuffers()
  227742. {
  227743. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227744. zerostruct (inputChannels);
  227745. zerostruct (outputChannels);
  227746. for (int i = 0; i < numInputChannels; ++i)
  227747. inputChannels[i] = floatData.getSampleData (i);
  227748. for (int i = 0; i < numOutputChannels; ++i)
  227749. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227750. }
  227751. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227752. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227753. {
  227754. OSStatus err = noErr;
  227755. if (audioInputIsAvailable)
  227756. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227757. const ScopedLock sl (callbackLock);
  227758. if (callback != 0)
  227759. {
  227760. if (audioInputIsAvailable && numInputChannels > 0)
  227761. {
  227762. short* shortData = (short*) ioData->mBuffers[0].mData;
  227763. if (numInputChannels >= 2)
  227764. {
  227765. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227766. {
  227767. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227768. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227769. }
  227770. }
  227771. else
  227772. {
  227773. if (monoInputChannelNumber > 0)
  227774. ++shortData;
  227775. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227776. {
  227777. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227778. ++shortData;
  227779. }
  227780. }
  227781. }
  227782. else
  227783. {
  227784. for (int i = numInputChannels; --i >= 0;)
  227785. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227786. }
  227787. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227788. outputChannels, numOutputChannels,
  227789. (int) inNumberFrames);
  227790. short* shortData = (short*) ioData->mBuffers[0].mData;
  227791. int n = 0;
  227792. if (numOutputChannels >= 2)
  227793. {
  227794. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227795. {
  227796. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227797. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227798. }
  227799. }
  227800. else if (numOutputChannels == 1)
  227801. {
  227802. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227803. {
  227804. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227805. shortData [n++] = s;
  227806. shortData [n++] = s;
  227807. }
  227808. }
  227809. else
  227810. {
  227811. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227812. }
  227813. }
  227814. else
  227815. {
  227816. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227817. }
  227818. return err;
  227819. }
  227820. void updateDeviceInfo()
  227821. {
  227822. UInt32 size = sizeof (sampleRate);
  227823. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227824. size = sizeof (audioInputIsAvailable);
  227825. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227826. }
  227827. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227828. {
  227829. if (! isRunning)
  227830. return;
  227831. if (inPropertyValue != 0)
  227832. {
  227833. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227834. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227835. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227836. SInt32 routeChangeReason;
  227837. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227838. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227839. fixAudioRouteIfSetToReceiver();
  227840. }
  227841. updateDeviceInfo();
  227842. createAudioUnit();
  227843. AudioSessionSetActive (true);
  227844. if (audioUnit != 0)
  227845. {
  227846. UInt32 formatSize = sizeof (format);
  227847. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227848. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227849. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227850. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227851. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227852. AudioOutputUnitStart (audioUnit);
  227853. }
  227854. }
  227855. void interruptionListener (UInt32 inInterruption)
  227856. {
  227857. /*if (inInterruption == kAudioSessionBeginInterruption)
  227858. {
  227859. isRunning = false;
  227860. AudioOutputUnitStop (audioUnit);
  227861. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227862. "This could have been interrupted by another application or by unplugging a headset",
  227863. @"Resume",
  227864. @"Cancel"))
  227865. {
  227866. isRunning = true;
  227867. propertyChanged (0, 0, 0);
  227868. }
  227869. }*/
  227870. if (inInterruption == kAudioSessionEndInterruption)
  227871. {
  227872. isRunning = true;
  227873. AudioSessionSetActive (true);
  227874. AudioOutputUnitStart (audioUnit);
  227875. }
  227876. }
  227877. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227878. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227879. {
  227880. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227881. }
  227882. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227883. {
  227884. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227885. }
  227886. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227887. {
  227888. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227889. }
  227890. void resetFormat (const int numChannels)
  227891. {
  227892. memset (&format, 0, sizeof (format));
  227893. format.mFormatID = kAudioFormatLinearPCM;
  227894. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227895. format.mBitsPerChannel = 8 * sizeof (short);
  227896. format.mChannelsPerFrame = 2;
  227897. format.mFramesPerPacket = 1;
  227898. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227899. }
  227900. bool createAudioUnit()
  227901. {
  227902. if (audioUnit != 0)
  227903. {
  227904. AudioComponentInstanceDispose (audioUnit);
  227905. audioUnit = 0;
  227906. }
  227907. resetFormat (2);
  227908. AudioComponentDescription desc;
  227909. desc.componentType = kAudioUnitType_Output;
  227910. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227911. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227912. desc.componentFlags = 0;
  227913. desc.componentFlagsMask = 0;
  227914. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227915. AudioComponentInstanceNew (comp, &audioUnit);
  227916. if (audioUnit == 0)
  227917. return false;
  227918. const UInt32 one = 1;
  227919. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227920. AudioChannelLayout layout;
  227921. layout.mChannelBitmap = 0;
  227922. layout.mNumberChannelDescriptions = 0;
  227923. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227924. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227925. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227926. AURenderCallbackStruct inputProc;
  227927. inputProc.inputProc = processStatic;
  227928. inputProc.inputProcRefCon = this;
  227929. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227930. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227931. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227932. AudioUnitInitialize (audioUnit);
  227933. return true;
  227934. }
  227935. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227936. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227937. static void fixAudioRouteIfSetToReceiver()
  227938. {
  227939. CFStringRef audioRoute = 0;
  227940. UInt32 propertySize = sizeof (audioRoute);
  227941. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227942. {
  227943. NSString* route = (NSString*) audioRoute;
  227944. //DBG ("audio route: " + nsStringToJuce (route));
  227945. if ([route hasPrefix: @"Receiver"])
  227946. {
  227947. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227948. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227949. }
  227950. CFRelease (audioRoute);
  227951. }
  227952. }
  227953. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  227954. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  227955. };
  227956. class IPhoneAudioIODeviceType : public AudioIODeviceType
  227957. {
  227958. public:
  227959. IPhoneAudioIODeviceType()
  227960. : AudioIODeviceType ("iPhone Audio")
  227961. {
  227962. }
  227963. ~IPhoneAudioIODeviceType()
  227964. {
  227965. }
  227966. void scanForDevices()
  227967. {
  227968. }
  227969. const StringArray getDeviceNames (bool wantInputNames) const
  227970. {
  227971. StringArray s;
  227972. s.add ("iPhone Audio");
  227973. return s;
  227974. }
  227975. int getDefaultDeviceIndex (bool forInput) const
  227976. {
  227977. return 0;
  227978. }
  227979. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  227980. {
  227981. return device != 0 ? 0 : -1;
  227982. }
  227983. bool hasSeparateInputsAndOutputs() const { return false; }
  227984. AudioIODevice* createDevice (const String& outputDeviceName,
  227985. const String& inputDeviceName)
  227986. {
  227987. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  227988. {
  227989. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  227990. : inputDeviceName);
  227991. }
  227992. return 0;
  227993. }
  227994. juce_UseDebuggingNewOperator
  227995. private:
  227996. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  227997. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  227998. };
  227999. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228000. {
  228001. return new IPhoneAudioIODeviceType();
  228002. }
  228003. #endif
  228004. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  228005. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228006. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228007. // compiled on its own).
  228008. #if JUCE_INCLUDED_FILE
  228009. #if JUCE_MAC
  228010. #undef log
  228011. #define log(a) Logger::writeToLog(a)
  228012. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  228013. {
  228014. if (err == noErr)
  228015. return true;
  228016. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228017. jassertfalse;
  228018. return false;
  228019. }
  228020. #undef OK
  228021. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  228022. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228023. {
  228024. String result;
  228025. CFStringRef str = 0;
  228026. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228027. if (str != 0)
  228028. {
  228029. result = PlatformUtilities::cfStringToJuceString (str);
  228030. CFRelease (str);
  228031. str = 0;
  228032. }
  228033. MIDIEntityRef entity = 0;
  228034. MIDIEndpointGetEntity (endpoint, &entity);
  228035. if (entity == 0)
  228036. return result; // probably virtual
  228037. if (result.isEmpty())
  228038. {
  228039. // endpoint name has zero length - try the entity
  228040. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228041. if (str != 0)
  228042. {
  228043. result += PlatformUtilities::cfStringToJuceString (str);
  228044. CFRelease (str);
  228045. str = 0;
  228046. }
  228047. }
  228048. // now consider the device's name
  228049. MIDIDeviceRef device = 0;
  228050. MIDIEntityGetDevice (entity, &device);
  228051. if (device == 0)
  228052. return result;
  228053. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228054. if (str != 0)
  228055. {
  228056. const String s (PlatformUtilities::cfStringToJuceString (str));
  228057. CFRelease (str);
  228058. // if an external device has only one entity, throw away
  228059. // the endpoint name and just use the device name
  228060. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228061. {
  228062. result = s;
  228063. }
  228064. else if (! result.startsWithIgnoreCase (s))
  228065. {
  228066. // prepend the device name to the entity name
  228067. result = (s + " " + result).trimEnd();
  228068. }
  228069. }
  228070. return result;
  228071. }
  228072. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228073. {
  228074. String result;
  228075. // Does the endpoint have connections?
  228076. CFDataRef connections = 0;
  228077. int numConnections = 0;
  228078. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228079. if (connections != 0)
  228080. {
  228081. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228082. if (numConnections > 0)
  228083. {
  228084. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228085. for (int i = 0; i < numConnections; ++i, ++pid)
  228086. {
  228087. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228088. MIDIObjectRef connObject;
  228089. MIDIObjectType connObjectType;
  228090. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228091. if (err == noErr)
  228092. {
  228093. String s;
  228094. if (connObjectType == kMIDIObjectType_ExternalSource
  228095. || connObjectType == kMIDIObjectType_ExternalDestination)
  228096. {
  228097. // Connected to an external device's endpoint (10.3 and later).
  228098. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228099. }
  228100. else
  228101. {
  228102. // Connected to an external device (10.2) (or something else, catch-all)
  228103. CFStringRef str = 0;
  228104. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228105. if (str != 0)
  228106. {
  228107. s = PlatformUtilities::cfStringToJuceString (str);
  228108. CFRelease (str);
  228109. }
  228110. }
  228111. if (s.isNotEmpty())
  228112. {
  228113. if (result.isNotEmpty())
  228114. result += ", ";
  228115. result += s;
  228116. }
  228117. }
  228118. }
  228119. }
  228120. CFRelease (connections);
  228121. }
  228122. if (result.isNotEmpty())
  228123. return result;
  228124. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228125. return getEndpointName (endpoint, false);
  228126. }
  228127. const StringArray MidiOutput::getDevices()
  228128. {
  228129. StringArray s;
  228130. const ItemCount num = MIDIGetNumberOfDestinations();
  228131. for (ItemCount i = 0; i < num; ++i)
  228132. {
  228133. MIDIEndpointRef dest = MIDIGetDestination (i);
  228134. if (dest != 0)
  228135. {
  228136. String name (getConnectedEndpointName (dest));
  228137. if (name.isEmpty())
  228138. name = "<error>";
  228139. s.add (name);
  228140. }
  228141. else
  228142. {
  228143. s.add ("<error>");
  228144. }
  228145. }
  228146. return s;
  228147. }
  228148. int MidiOutput::getDefaultDeviceIndex()
  228149. {
  228150. return 0;
  228151. }
  228152. static MIDIClientRef globalMidiClient;
  228153. static bool hasGlobalClientBeenCreated = false;
  228154. static bool makeSureClientExists()
  228155. {
  228156. if (! hasGlobalClientBeenCreated)
  228157. {
  228158. String name ("JUCE");
  228159. if (JUCEApplication::getInstance() != 0)
  228160. name = JUCEApplication::getInstance()->getApplicationName();
  228161. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228162. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228163. CFRelease (appName);
  228164. }
  228165. return hasGlobalClientBeenCreated;
  228166. }
  228167. class MidiPortAndEndpoint
  228168. {
  228169. public:
  228170. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228171. : port (port_), endPoint (endPoint_)
  228172. {
  228173. }
  228174. ~MidiPortAndEndpoint()
  228175. {
  228176. if (port != 0)
  228177. MIDIPortDispose (port);
  228178. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228179. MIDIEndpointDispose (endPoint);
  228180. }
  228181. MIDIPortRef port;
  228182. MIDIEndpointRef endPoint;
  228183. };
  228184. MidiOutput* MidiOutput::openDevice (int index)
  228185. {
  228186. MidiOutput* mo = 0;
  228187. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  228188. {
  228189. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228190. CFStringRef pname;
  228191. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228192. {
  228193. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  228194. if (makeSureClientExists())
  228195. {
  228196. MIDIPortRef port;
  228197. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  228198. {
  228199. mo = new MidiOutput();
  228200. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  228201. }
  228202. }
  228203. CFRelease (pname);
  228204. }
  228205. }
  228206. return mo;
  228207. }
  228208. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228209. {
  228210. MidiOutput* mo = 0;
  228211. if (makeSureClientExists())
  228212. {
  228213. MIDIEndpointRef endPoint;
  228214. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228215. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  228216. {
  228217. mo = new MidiOutput();
  228218. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  228219. }
  228220. CFRelease (name);
  228221. }
  228222. return mo;
  228223. }
  228224. MidiOutput::~MidiOutput()
  228225. {
  228226. delete (MidiPortAndEndpoint*) internal;
  228227. }
  228228. void MidiOutput::reset()
  228229. {
  228230. }
  228231. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228232. {
  228233. return false;
  228234. }
  228235. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228236. {
  228237. }
  228238. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228239. {
  228240. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  228241. if (message.isSysEx())
  228242. {
  228243. const int maxPacketSize = 256;
  228244. int pos = 0, bytesLeft = message.getRawDataSize();
  228245. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228246. HeapBlock <MIDIPacketList> packets;
  228247. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  228248. packets->numPackets = numPackets;
  228249. MIDIPacket* p = packets->packet;
  228250. for (int i = 0; i < numPackets; ++i)
  228251. {
  228252. p->timeStamp = 0;
  228253. p->length = jmin (maxPacketSize, bytesLeft);
  228254. memcpy (p->data, message.getRawData() + pos, p->length);
  228255. pos += p->length;
  228256. bytesLeft -= p->length;
  228257. p = MIDIPacketNext (p);
  228258. }
  228259. if (mpe->port != 0)
  228260. MIDISend (mpe->port, mpe->endPoint, packets);
  228261. else
  228262. MIDIReceived (mpe->endPoint, packets);
  228263. }
  228264. else
  228265. {
  228266. MIDIPacketList packets;
  228267. packets.numPackets = 1;
  228268. packets.packet[0].timeStamp = 0;
  228269. packets.packet[0].length = message.getRawDataSize();
  228270. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228271. if (mpe->port != 0)
  228272. MIDISend (mpe->port, mpe->endPoint, &packets);
  228273. else
  228274. MIDIReceived (mpe->endPoint, &packets);
  228275. }
  228276. }
  228277. const StringArray MidiInput::getDevices()
  228278. {
  228279. StringArray s;
  228280. const ItemCount num = MIDIGetNumberOfSources();
  228281. for (ItemCount i = 0; i < num; ++i)
  228282. {
  228283. MIDIEndpointRef source = MIDIGetSource (i);
  228284. if (source != 0)
  228285. {
  228286. String name (getConnectedEndpointName (source));
  228287. if (name.isEmpty())
  228288. name = "<error>";
  228289. s.add (name);
  228290. }
  228291. else
  228292. {
  228293. s.add ("<error>");
  228294. }
  228295. }
  228296. return s;
  228297. }
  228298. int MidiInput::getDefaultDeviceIndex()
  228299. {
  228300. return 0;
  228301. }
  228302. struct MidiPortAndCallback
  228303. {
  228304. MidiInput* input;
  228305. MidiPortAndEndpoint* portAndEndpoint;
  228306. MidiInputCallback* callback;
  228307. MemoryBlock pendingData;
  228308. int pendingBytes;
  228309. double pendingDataTime;
  228310. bool active;
  228311. void processSysex (const uint8*& d, int& size, const double time)
  228312. {
  228313. if (*d == 0xf0)
  228314. {
  228315. pendingBytes = 0;
  228316. pendingDataTime = time;
  228317. }
  228318. pendingData.ensureSize (pendingBytes + size, false);
  228319. uint8* totalMessage = (uint8*) pendingData.getData();
  228320. uint8* dest = totalMessage + pendingBytes;
  228321. while (size > 0)
  228322. {
  228323. if (pendingBytes > 0 && *d >= 0x80)
  228324. {
  228325. if (*d >= 0xfa || *d == 0xf8)
  228326. {
  228327. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228328. ++d;
  228329. --size;
  228330. }
  228331. else
  228332. {
  228333. if (*d == 0xf7)
  228334. {
  228335. *dest++ = *d++;
  228336. pendingBytes++;
  228337. --size;
  228338. }
  228339. break;
  228340. }
  228341. }
  228342. else
  228343. {
  228344. *dest++ = *d++;
  228345. pendingBytes++;
  228346. --size;
  228347. }
  228348. }
  228349. if (totalMessage [pendingBytes - 1] == 0xf7)
  228350. {
  228351. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228352. pendingBytes = 0;
  228353. }
  228354. else
  228355. {
  228356. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228357. }
  228358. }
  228359. };
  228360. namespace CoreMidiCallbacks
  228361. {
  228362. static CriticalSection callbackLock;
  228363. static Array<void*> activeCallbacks;
  228364. }
  228365. static void midiInputProc (const MIDIPacketList* pktlist,
  228366. void* readProcRefCon,
  228367. void* /*srcConnRefCon*/)
  228368. {
  228369. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228370. const double originalTime = time;
  228371. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228372. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228373. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228374. {
  228375. const MIDIPacket* packet = &pktlist->packet[0];
  228376. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228377. {
  228378. const uint8* d = (const uint8*) (packet->data);
  228379. int size = packet->length;
  228380. while (size > 0)
  228381. {
  228382. time = originalTime;
  228383. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228384. {
  228385. mpc->processSysex (d, size, time);
  228386. }
  228387. else
  228388. {
  228389. int used = 0;
  228390. const MidiMessage m (d, size, used, 0, time);
  228391. if (used <= 0)
  228392. {
  228393. jassertfalse; // malformed midi message
  228394. break;
  228395. }
  228396. else
  228397. {
  228398. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228399. }
  228400. size -= used;
  228401. d += used;
  228402. }
  228403. }
  228404. packet = MIDIPacketNext (packet);
  228405. }
  228406. }
  228407. }
  228408. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228409. {
  228410. MidiInput* mi = 0;
  228411. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228412. {
  228413. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228414. if (endPoint != 0)
  228415. {
  228416. CFStringRef pname;
  228417. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228418. {
  228419. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228420. if (makeSureClientExists())
  228421. {
  228422. MIDIPortRef port;
  228423. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228424. mpc->active = false;
  228425. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228426. {
  228427. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228428. {
  228429. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228430. mpc->callback = callback;
  228431. mpc->pendingBytes = 0;
  228432. mpc->pendingData.ensureSize (128);
  228433. mi = new MidiInput (getDevices() [index]);
  228434. mpc->input = mi;
  228435. mi->internal = mpc;
  228436. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228437. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228438. }
  228439. else
  228440. {
  228441. OK (MIDIPortDispose (port));
  228442. }
  228443. }
  228444. }
  228445. }
  228446. CFRelease (pname);
  228447. }
  228448. }
  228449. return mi;
  228450. }
  228451. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228452. {
  228453. MidiInput* mi = 0;
  228454. if (makeSureClientExists())
  228455. {
  228456. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228457. mpc->active = false;
  228458. MIDIEndpointRef endPoint;
  228459. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228460. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228461. {
  228462. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228463. mpc->callback = callback;
  228464. mpc->pendingBytes = 0;
  228465. mpc->pendingData.ensureSize (128);
  228466. mi = new MidiInput (deviceName);
  228467. mpc->input = mi;
  228468. mi->internal = mpc;
  228469. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228470. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228471. }
  228472. CFRelease (name);
  228473. }
  228474. return mi;
  228475. }
  228476. MidiInput::MidiInput (const String& name_)
  228477. : name (name_)
  228478. {
  228479. }
  228480. MidiInput::~MidiInput()
  228481. {
  228482. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228483. mpc->active = false;
  228484. {
  228485. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228486. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228487. }
  228488. if (mpc->portAndEndpoint->port != 0)
  228489. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228490. delete mpc->portAndEndpoint;
  228491. delete mpc;
  228492. }
  228493. void MidiInput::start()
  228494. {
  228495. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228496. ((MidiPortAndCallback*) internal)->active = true;
  228497. }
  228498. void MidiInput::stop()
  228499. {
  228500. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228501. ((MidiPortAndCallback*) internal)->active = false;
  228502. }
  228503. #undef log
  228504. #else
  228505. MidiOutput::~MidiOutput()
  228506. {
  228507. }
  228508. void MidiOutput::reset()
  228509. {
  228510. }
  228511. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228512. {
  228513. return false;
  228514. }
  228515. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228516. {
  228517. }
  228518. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228519. {
  228520. }
  228521. const StringArray MidiOutput::getDevices()
  228522. {
  228523. return StringArray();
  228524. }
  228525. MidiOutput* MidiOutput::openDevice (int index)
  228526. {
  228527. return 0;
  228528. }
  228529. const StringArray MidiInput::getDevices()
  228530. {
  228531. return StringArray();
  228532. }
  228533. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228534. {
  228535. return 0;
  228536. }
  228537. #endif
  228538. #endif
  228539. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228540. #else
  228541. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228542. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228543. // compiled on its own).
  228544. #if JUCE_INCLUDED_FILE
  228545. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228546. #define SUPPORT_10_4_FONTS 1
  228547. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228548. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228549. #define SUPPORT_ONLY_10_4_FONTS 1
  228550. #endif
  228551. END_JUCE_NAMESPACE
  228552. @interface NSFont (PrivateHack)
  228553. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228554. @end
  228555. BEGIN_JUCE_NAMESPACE
  228556. #endif
  228557. class MacTypeface : public Typeface
  228558. {
  228559. public:
  228560. MacTypeface (const Font& font)
  228561. : Typeface (font.getTypefaceName())
  228562. {
  228563. const ScopedAutoReleasePool pool;
  228564. renderingTransform = CGAffineTransformIdentity;
  228565. bool needsItalicTransform = false;
  228566. #if JUCE_IOS
  228567. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228568. if (font.isItalic() || font.isBold())
  228569. {
  228570. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228571. for (NSString* i in familyFonts)
  228572. {
  228573. const String fn (nsStringToJuce (i));
  228574. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228575. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228576. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228577. || afterDash.containsIgnoreCase ("italic")
  228578. || fn.endsWithIgnoreCase ("oblique")
  228579. || fn.endsWithIgnoreCase ("italic");
  228580. if (probablyBold == font.isBold()
  228581. && probablyItalic == font.isItalic())
  228582. {
  228583. fontName = i;
  228584. needsItalicTransform = false;
  228585. break;
  228586. }
  228587. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228588. {
  228589. fontName = i;
  228590. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228591. }
  228592. }
  228593. if (needsItalicTransform)
  228594. renderingTransform.c = 0.15f;
  228595. }
  228596. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228597. const int ascender = abs (CGFontGetAscent (fontRef));
  228598. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228599. ascent = ascender / totalHeight;
  228600. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228601. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228602. #else
  228603. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228604. if (font.isItalic())
  228605. {
  228606. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228607. toHaveTrait: NSItalicFontMask];
  228608. if (newFont == nsFont)
  228609. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228610. nsFont = newFont;
  228611. }
  228612. if (font.isBold())
  228613. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228614. [nsFont retain];
  228615. ascent = std::abs ((float) [nsFont ascender]);
  228616. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228617. ascent /= totalSize;
  228618. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228619. if (needsItalicTransform)
  228620. {
  228621. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228622. renderingTransform.c = 0.15f;
  228623. }
  228624. #if SUPPORT_ONLY_10_4_FONTS
  228625. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228626. if (atsFont == 0)
  228627. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228628. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228629. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228630. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228631. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228632. #else
  228633. #if SUPPORT_10_4_FONTS
  228634. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228635. {
  228636. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228637. if (atsFont == 0)
  228638. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228639. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228640. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228641. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228642. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228643. }
  228644. else
  228645. #endif
  228646. {
  228647. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228648. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228649. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228650. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228651. }
  228652. #endif
  228653. #endif
  228654. }
  228655. ~MacTypeface()
  228656. {
  228657. #if ! JUCE_IOS
  228658. [nsFont release];
  228659. #endif
  228660. if (fontRef != 0)
  228661. CGFontRelease (fontRef);
  228662. }
  228663. float getAscent() const
  228664. {
  228665. return ascent;
  228666. }
  228667. float getDescent() const
  228668. {
  228669. return 1.0f - ascent;
  228670. }
  228671. float getStringWidth (const String& text)
  228672. {
  228673. if (fontRef == 0 || text.isEmpty())
  228674. return 0;
  228675. const int length = text.length();
  228676. HeapBlock <CGGlyph> glyphs;
  228677. createGlyphsForString (text, length, glyphs);
  228678. float x = 0;
  228679. #if SUPPORT_ONLY_10_4_FONTS
  228680. HeapBlock <NSSize> advances (length);
  228681. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228682. for (int i = 0; i < length; ++i)
  228683. x += advances[i].width;
  228684. #else
  228685. #if SUPPORT_10_4_FONTS
  228686. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228687. {
  228688. HeapBlock <NSSize> advances (length);
  228689. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228690. for (int i = 0; i < length; ++i)
  228691. x += advances[i].width;
  228692. }
  228693. else
  228694. #endif
  228695. {
  228696. HeapBlock <int> advances (length);
  228697. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228698. for (int i = 0; i < length; ++i)
  228699. x += advances[i];
  228700. }
  228701. #endif
  228702. return x * unitsToHeightScaleFactor;
  228703. }
  228704. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228705. {
  228706. xOffsets.add (0);
  228707. if (fontRef == 0 || text.isEmpty())
  228708. return;
  228709. const int length = text.length();
  228710. HeapBlock <CGGlyph> glyphs;
  228711. createGlyphsForString (text, length, glyphs);
  228712. #if SUPPORT_ONLY_10_4_FONTS
  228713. HeapBlock <NSSize> advances (length);
  228714. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228715. int x = 0;
  228716. for (int i = 0; i < length; ++i)
  228717. {
  228718. x += advances[i].width;
  228719. xOffsets.add (x * unitsToHeightScaleFactor);
  228720. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228721. }
  228722. #else
  228723. #if SUPPORT_10_4_FONTS
  228724. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228725. {
  228726. HeapBlock <NSSize> advances (length);
  228727. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228728. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228729. float x = 0;
  228730. for (int i = 0; i < length; ++i)
  228731. {
  228732. x += advances[i].width;
  228733. xOffsets.add (x * unitsToHeightScaleFactor);
  228734. resultGlyphs.add (nsGlyphs[i]);
  228735. }
  228736. }
  228737. else
  228738. #endif
  228739. {
  228740. HeapBlock <int> advances (length);
  228741. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228742. {
  228743. int x = 0;
  228744. for (int i = 0; i < length; ++i)
  228745. {
  228746. x += advances [i];
  228747. xOffsets.add (x * unitsToHeightScaleFactor);
  228748. resultGlyphs.add (glyphs[i]);
  228749. }
  228750. }
  228751. }
  228752. #endif
  228753. }
  228754. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228755. {
  228756. #if JUCE_IOS
  228757. return false;
  228758. #else
  228759. if (nsFont == 0)
  228760. return false;
  228761. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228762. jassert (path.isEmpty());
  228763. const ScopedAutoReleasePool pool;
  228764. NSBezierPath* bez = [NSBezierPath bezierPath];
  228765. [bez moveToPoint: NSMakePoint (0, 0)];
  228766. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228767. inFont: nsFont];
  228768. for (int i = 0; i < [bez elementCount]; ++i)
  228769. {
  228770. NSPoint p[3];
  228771. switch ([bez elementAtIndex: i associatedPoints: p])
  228772. {
  228773. case NSMoveToBezierPathElement:
  228774. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228775. break;
  228776. case NSLineToBezierPathElement:
  228777. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228778. break;
  228779. case NSCurveToBezierPathElement:
  228780. 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);
  228781. break;
  228782. case NSClosePathBezierPathElement:
  228783. path.closeSubPath();
  228784. break;
  228785. default:
  228786. jassertfalse;
  228787. break;
  228788. }
  228789. }
  228790. path.applyTransform (pathTransform);
  228791. return true;
  228792. #endif
  228793. }
  228794. juce_UseDebuggingNewOperator
  228795. CGFontRef fontRef;
  228796. float fontHeightToCGSizeFactor;
  228797. CGAffineTransform renderingTransform;
  228798. private:
  228799. float ascent, unitsToHeightScaleFactor;
  228800. #if JUCE_IOS
  228801. #else
  228802. NSFont* nsFont;
  228803. AffineTransform pathTransform;
  228804. #endif
  228805. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228806. {
  228807. #if SUPPORT_10_4_FONTS
  228808. #if ! SUPPORT_ONLY_10_4_FONTS
  228809. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228810. #endif
  228811. {
  228812. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228813. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228814. for (int i = 0; i < length; ++i)
  228815. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228816. return;
  228817. }
  228818. #endif
  228819. #if ! SUPPORT_ONLY_10_4_FONTS
  228820. if (charToGlyphMapper == 0)
  228821. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228822. glyphs.malloc (length);
  228823. for (int i = 0; i < length; ++i)
  228824. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228825. #endif
  228826. }
  228827. #if ! SUPPORT_ONLY_10_4_FONTS
  228828. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228829. class CharToGlyphMapper
  228830. {
  228831. public:
  228832. CharToGlyphMapper (CGFontRef fontRef)
  228833. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228834. idRangeOffset (0), glyphIndexes (0)
  228835. {
  228836. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228837. if (cmapTable != 0)
  228838. {
  228839. const int numSubtables = getValue16 (cmapTable, 2);
  228840. for (int i = 0; i < numSubtables; ++i)
  228841. {
  228842. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228843. {
  228844. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228845. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228846. {
  228847. const int length = getValue16 (cmapTable, offset + 2);
  228848. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228849. segCount = segCountX2 / 2;
  228850. const int endCodeOffset = offset + 14;
  228851. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228852. const int idDeltaOffset = startCodeOffset + segCountX2;
  228853. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228854. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228855. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228856. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228857. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228858. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228859. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228860. }
  228861. break;
  228862. }
  228863. }
  228864. CFRelease (cmapTable);
  228865. }
  228866. }
  228867. ~CharToGlyphMapper()
  228868. {
  228869. if (endCode != 0)
  228870. {
  228871. CFRelease (endCode);
  228872. CFRelease (startCode);
  228873. CFRelease (idDelta);
  228874. CFRelease (idRangeOffset);
  228875. CFRelease (glyphIndexes);
  228876. }
  228877. }
  228878. int getGlyphForCharacter (const juce_wchar c) const
  228879. {
  228880. for (int i = 0; i < segCount; ++i)
  228881. {
  228882. if (getValue16 (endCode, i * 2) >= c)
  228883. {
  228884. const int start = getValue16 (startCode, i * 2);
  228885. if (start > c)
  228886. break;
  228887. const int delta = getValue16 (idDelta, i * 2);
  228888. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228889. if (rangeOffset == 0)
  228890. return delta + c;
  228891. else
  228892. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228893. }
  228894. }
  228895. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228896. return jmax (-1, c - 29);
  228897. }
  228898. private:
  228899. int segCount;
  228900. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228901. static uint16 getValue16 (CFDataRef data, const int index)
  228902. {
  228903. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228904. }
  228905. static uint32 getValue32 (CFDataRef data, const int index)
  228906. {
  228907. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228908. }
  228909. };
  228910. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228911. #endif
  228912. MacTypeface (const MacTypeface&);
  228913. MacTypeface& operator= (const MacTypeface&);
  228914. };
  228915. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228916. {
  228917. return new MacTypeface (font);
  228918. }
  228919. const StringArray Font::findAllTypefaceNames()
  228920. {
  228921. StringArray names;
  228922. const ScopedAutoReleasePool pool;
  228923. #if JUCE_IOS
  228924. NSArray* fonts = [UIFont familyNames];
  228925. #else
  228926. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228927. #endif
  228928. for (unsigned int i = 0; i < [fonts count]; ++i)
  228929. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228930. names.sort (true);
  228931. return names;
  228932. }
  228933. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228934. {
  228935. #if JUCE_IOS
  228936. defaultSans = "Helvetica";
  228937. defaultSerif = "Times New Roman";
  228938. defaultFixed = "Courier New";
  228939. #else
  228940. defaultSans = "Lucida Grande";
  228941. defaultSerif = "Times New Roman";
  228942. defaultFixed = "Monaco";
  228943. #endif
  228944. }
  228945. #endif
  228946. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228947. // (must go before juce_mac_CoreGraphicsContext.mm)
  228948. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228949. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228950. // compiled on its own).
  228951. #if JUCE_INCLUDED_FILE
  228952. class CoreGraphicsImage : public Image::SharedImage
  228953. {
  228954. public:
  228955. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  228956. : Image::SharedImage (format_, width_, height_)
  228957. {
  228958. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  228959. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  228960. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  228961. imageData = imageDataAllocated;
  228962. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  228963. : CGColorSpaceCreateDeviceRGB();
  228964. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  228965. colourSpace, getCGImageFlags (format_));
  228966. CGColorSpaceRelease (colourSpace);
  228967. }
  228968. ~CoreGraphicsImage()
  228969. {
  228970. CGContextRelease (context);
  228971. }
  228972. Image::ImageType getType() const { return Image::NativeImage; }
  228973. LowLevelGraphicsContext* createLowLevelContext();
  228974. SharedImage* clone()
  228975. {
  228976. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  228977. memcpy (im->imageData, imageData, lineStride * height);
  228978. return im;
  228979. }
  228980. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  228981. {
  228982. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  228983. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  228984. {
  228985. return CGBitmapContextCreateImage (nativeImage->context);
  228986. }
  228987. else
  228988. {
  228989. const Image::BitmapData srcData (juceImage, false);
  228990. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  228991. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  228992. 8, srcData.pixelStride * 8, srcData.lineStride,
  228993. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  228994. 0, true, kCGRenderingIntentDefault);
  228995. CGDataProviderRelease (provider);
  228996. return imageRef;
  228997. }
  228998. }
  228999. #if JUCE_MAC
  229000. static NSImage* createNSImage (const Image& image)
  229001. {
  229002. const ScopedAutoReleasePool pool;
  229003. NSImage* im = [[NSImage alloc] init];
  229004. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229005. [im lockFocus];
  229006. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229007. CGImageRef imageRef = createImage (image, false, colourSpace);
  229008. CGColorSpaceRelease (colourSpace);
  229009. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229010. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229011. CGImageRelease (imageRef);
  229012. [im unlockFocus];
  229013. return im;
  229014. }
  229015. #endif
  229016. CGContextRef context;
  229017. HeapBlock<uint8> imageDataAllocated;
  229018. private:
  229019. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229020. {
  229021. #if JUCE_BIG_ENDIAN
  229022. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229023. #else
  229024. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229025. #endif
  229026. }
  229027. };
  229028. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229029. {
  229030. #if USE_COREGRAPHICS_RENDERING
  229031. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229032. #else
  229033. return createSoftwareImage (format, width, height, clearImage);
  229034. #endif
  229035. }
  229036. class CoreGraphicsContext : public LowLevelGraphicsContext
  229037. {
  229038. public:
  229039. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229040. : context (context_),
  229041. flipHeight (flipHeight_),
  229042. state (new SavedState()),
  229043. numGradientLookupEntries (0),
  229044. lastClipRectIsValid (false)
  229045. {
  229046. CGContextRetain (context);
  229047. CGContextSaveGState(context);
  229048. CGContextSetShouldSmoothFonts (context, true);
  229049. CGContextSetShouldAntialias (context, true);
  229050. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229051. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229052. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229053. gradientCallbacks.version = 0;
  229054. gradientCallbacks.evaluate = gradientCallback;
  229055. gradientCallbacks.releaseInfo = 0;
  229056. setFont (Font());
  229057. }
  229058. ~CoreGraphicsContext()
  229059. {
  229060. CGContextRestoreGState (context);
  229061. CGContextRelease (context);
  229062. CGColorSpaceRelease (rgbColourSpace);
  229063. CGColorSpaceRelease (greyColourSpace);
  229064. }
  229065. bool isVectorDevice() const { return false; }
  229066. void setOrigin (int x, int y)
  229067. {
  229068. CGContextTranslateCTM (context, x, -y);
  229069. if (lastClipRectIsValid)
  229070. lastClipRect.translate (-x, -y);
  229071. }
  229072. bool clipToRectangle (const Rectangle<int>& r)
  229073. {
  229074. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229075. if (lastClipRectIsValid)
  229076. {
  229077. lastClipRect = lastClipRect.getIntersection (r);
  229078. return ! lastClipRect.isEmpty();
  229079. }
  229080. return ! isClipEmpty();
  229081. }
  229082. bool clipToRectangleList (const RectangleList& clipRegion)
  229083. {
  229084. if (clipRegion.isEmpty())
  229085. {
  229086. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229087. lastClipRectIsValid = true;
  229088. lastClipRect = Rectangle<int>();
  229089. return false;
  229090. }
  229091. else
  229092. {
  229093. const int numRects = clipRegion.getNumRectangles();
  229094. HeapBlock <CGRect> rects (numRects);
  229095. for (int i = 0; i < numRects; ++i)
  229096. {
  229097. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229098. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229099. }
  229100. CGContextClipToRects (context, rects, numRects);
  229101. lastClipRectIsValid = false;
  229102. return ! isClipEmpty();
  229103. }
  229104. }
  229105. void excludeClipRectangle (const Rectangle<int>& r)
  229106. {
  229107. RectangleList remaining (getClipBounds());
  229108. remaining.subtract (r);
  229109. clipToRectangleList (remaining);
  229110. lastClipRectIsValid = false;
  229111. }
  229112. void clipToPath (const Path& path, const AffineTransform& transform)
  229113. {
  229114. createPath (path, transform);
  229115. CGContextClip (context);
  229116. lastClipRectIsValid = false;
  229117. }
  229118. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229119. {
  229120. if (! transform.isSingularity())
  229121. {
  229122. Image singleChannelImage (sourceImage);
  229123. if (sourceImage.getFormat() != Image::SingleChannel)
  229124. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229125. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  229126. flip();
  229127. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229128. applyTransform (t);
  229129. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229130. CGContextClipToMask (context, r, image);
  229131. applyTransform (t.inverted());
  229132. flip();
  229133. CGImageRelease (image);
  229134. lastClipRectIsValid = false;
  229135. }
  229136. }
  229137. bool clipRegionIntersects (const Rectangle<int>& r)
  229138. {
  229139. return getClipBounds().intersects (r);
  229140. }
  229141. const Rectangle<int> getClipBounds() const
  229142. {
  229143. if (! lastClipRectIsValid)
  229144. {
  229145. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229146. lastClipRectIsValid = true;
  229147. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229148. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229149. roundToInt (bounds.size.width),
  229150. roundToInt (bounds.size.height));
  229151. }
  229152. return lastClipRect;
  229153. }
  229154. bool isClipEmpty() const
  229155. {
  229156. return getClipBounds().isEmpty();
  229157. }
  229158. void saveState()
  229159. {
  229160. CGContextSaveGState (context);
  229161. stateStack.add (new SavedState (*state));
  229162. }
  229163. void restoreState()
  229164. {
  229165. CGContextRestoreGState (context);
  229166. SavedState* const top = stateStack.getLast();
  229167. if (top != 0)
  229168. {
  229169. state = top;
  229170. stateStack.removeLast (1, false);
  229171. lastClipRectIsValid = false;
  229172. }
  229173. else
  229174. {
  229175. jassertfalse; // trying to pop with an empty stack!
  229176. }
  229177. }
  229178. void setFill (const FillType& fillType)
  229179. {
  229180. state->fillType = fillType;
  229181. if (fillType.isColour())
  229182. {
  229183. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229184. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229185. CGContextSetAlpha (context, 1.0f);
  229186. }
  229187. }
  229188. void setOpacity (float newOpacity)
  229189. {
  229190. state->fillType.setOpacity (newOpacity);
  229191. setFill (state->fillType);
  229192. }
  229193. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229194. {
  229195. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229196. ? kCGInterpolationLow
  229197. : kCGInterpolationHigh);
  229198. }
  229199. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229200. {
  229201. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229202. if (replaceExistingContents)
  229203. {
  229204. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229205. CGContextClearRect (context, cgRect);
  229206. #else
  229207. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229208. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229209. CGContextClearRect (context, cgRect);
  229210. else
  229211. #endif
  229212. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229213. #endif
  229214. fillRect (r, false);
  229215. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229216. }
  229217. else
  229218. {
  229219. if (state->fillType.isColour())
  229220. {
  229221. CGContextFillRect (context, cgRect);
  229222. }
  229223. else if (state->fillType.isGradient())
  229224. {
  229225. CGContextSaveGState (context);
  229226. CGContextClipToRect (context, cgRect);
  229227. drawGradient();
  229228. CGContextRestoreGState (context);
  229229. }
  229230. else
  229231. {
  229232. CGContextSaveGState (context);
  229233. CGContextClipToRect (context, cgRect);
  229234. drawImage (state->fillType.image, state->fillType.transform, true);
  229235. CGContextRestoreGState (context);
  229236. }
  229237. }
  229238. }
  229239. void fillPath (const Path& path, const AffineTransform& transform)
  229240. {
  229241. CGContextSaveGState (context);
  229242. if (state->fillType.isColour())
  229243. {
  229244. flip();
  229245. applyTransform (transform);
  229246. createPath (path);
  229247. if (path.isUsingNonZeroWinding())
  229248. CGContextFillPath (context);
  229249. else
  229250. CGContextEOFillPath (context);
  229251. }
  229252. else
  229253. {
  229254. createPath (path, transform);
  229255. if (path.isUsingNonZeroWinding())
  229256. CGContextClip (context);
  229257. else
  229258. CGContextEOClip (context);
  229259. if (state->fillType.isGradient())
  229260. drawGradient();
  229261. else
  229262. drawImage (state->fillType.image, state->fillType.transform, true);
  229263. }
  229264. CGContextRestoreGState (context);
  229265. }
  229266. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229267. {
  229268. const int iw = sourceImage.getWidth();
  229269. const int ih = sourceImage.getHeight();
  229270. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  229271. CGContextSaveGState (context);
  229272. CGContextSetAlpha (context, state->fillType.getOpacity());
  229273. flip();
  229274. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229275. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229276. if (fillEntireClipAsTiles)
  229277. {
  229278. #if JUCE_IOS
  229279. CGContextDrawTiledImage (context, imageRect, image);
  229280. #else
  229281. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229282. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229283. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229284. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229285. CGContextDrawTiledImage (context, imageRect, image);
  229286. else
  229287. #endif
  229288. {
  229289. // Fallback to manually doing a tiled fill on 10.4
  229290. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229291. int x = 0, y = 0;
  229292. while (x > clip.origin.x) x -= iw;
  229293. while (y > clip.origin.y) y -= ih;
  229294. const int right = (int) (clip.origin.x + clip.size.width);
  229295. const int bottom = (int) (clip.origin.y + clip.size.height);
  229296. while (y < bottom)
  229297. {
  229298. for (int x2 = x; x2 < right; x2 += iw)
  229299. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229300. y += ih;
  229301. }
  229302. }
  229303. #endif
  229304. }
  229305. else
  229306. {
  229307. CGContextDrawImage (context, imageRect, image);
  229308. }
  229309. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229310. CGContextRestoreGState (context);
  229311. }
  229312. void drawLine (const Line<float>& line)
  229313. {
  229314. CGContextSetLineCap (context, kCGLineCapSquare);
  229315. CGContextSetLineWidth (context, 1.0f);
  229316. CGContextSetRGBStrokeColor (context,
  229317. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229318. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229319. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229320. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229321. CGContextStrokeLineSegments (context, cgLine, 1);
  229322. }
  229323. void drawVerticalLine (const int x, float top, float bottom)
  229324. {
  229325. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229326. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229327. #else
  229328. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229329. // the x co-ord slightly to trick it..
  229330. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229331. #endif
  229332. }
  229333. void drawHorizontalLine (const int y, float left, float right)
  229334. {
  229335. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229336. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229337. #else
  229338. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229339. // the x co-ord slightly to trick it..
  229340. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229341. #endif
  229342. }
  229343. void setFont (const Font& newFont)
  229344. {
  229345. if (state->font != newFont)
  229346. {
  229347. state->fontRef = 0;
  229348. state->font = newFont;
  229349. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229350. if (mf != 0)
  229351. {
  229352. state->fontRef = mf->fontRef;
  229353. CGContextSetFont (context, state->fontRef);
  229354. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229355. state->fontTransform = mf->renderingTransform;
  229356. state->fontTransform.a *= state->font.getHorizontalScale();
  229357. CGContextSetTextMatrix (context, state->fontTransform);
  229358. }
  229359. }
  229360. }
  229361. const Font getFont()
  229362. {
  229363. return state->font;
  229364. }
  229365. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229366. {
  229367. if (state->fontRef != 0 && state->fillType.isColour())
  229368. {
  229369. if (transform.isOnlyTranslation())
  229370. {
  229371. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229372. CGGlyph g = glyphNumber;
  229373. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229374. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229375. }
  229376. else
  229377. {
  229378. CGContextSaveGState (context);
  229379. flip();
  229380. applyTransform (transform);
  229381. CGAffineTransform t = state->fontTransform;
  229382. t.d = -t.d;
  229383. CGContextSetTextMatrix (context, t);
  229384. CGGlyph g = glyphNumber;
  229385. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229386. CGContextRestoreGState (context);
  229387. }
  229388. }
  229389. else
  229390. {
  229391. Path p;
  229392. Font& f = state->font;
  229393. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229394. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229395. .followedBy (transform));
  229396. }
  229397. }
  229398. private:
  229399. CGContextRef context;
  229400. const CGFloat flipHeight;
  229401. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229402. CGFunctionCallbacks gradientCallbacks;
  229403. mutable Rectangle<int> lastClipRect;
  229404. mutable bool lastClipRectIsValid;
  229405. struct SavedState
  229406. {
  229407. SavedState()
  229408. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229409. {
  229410. }
  229411. SavedState (const SavedState& other)
  229412. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229413. fontTransform (other.fontTransform)
  229414. {
  229415. }
  229416. ~SavedState()
  229417. {
  229418. }
  229419. FillType fillType;
  229420. Font font;
  229421. CGFontRef fontRef;
  229422. CGAffineTransform fontTransform;
  229423. };
  229424. ScopedPointer <SavedState> state;
  229425. OwnedArray <SavedState> stateStack;
  229426. HeapBlock <PixelARGB> gradientLookupTable;
  229427. int numGradientLookupEntries;
  229428. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229429. {
  229430. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229431. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229432. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229433. colour.unpremultiply();
  229434. outData[0] = colour.getRed() / 255.0f;
  229435. outData[1] = colour.getGreen() / 255.0f;
  229436. outData[2] = colour.getBlue() / 255.0f;
  229437. outData[3] = colour.getAlpha() / 255.0f;
  229438. }
  229439. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229440. {
  229441. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229442. --numGradientLookupEntries;
  229443. CGShadingRef result = 0;
  229444. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229445. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229446. if (gradient.isRadial)
  229447. {
  229448. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229449. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229450. function, true, true);
  229451. }
  229452. else
  229453. {
  229454. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229455. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229456. function, true, true);
  229457. }
  229458. CGFunctionRelease (function);
  229459. return result;
  229460. }
  229461. void drawGradient()
  229462. {
  229463. flip();
  229464. applyTransform (state->fillType.transform);
  229465. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229466. // you draw a gradient with high quality interp enabled).
  229467. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229468. CGContextSetAlpha (context, state->fillType.getOpacity());
  229469. CGContextDrawShading (context, shading);
  229470. CGShadingRelease (shading);
  229471. }
  229472. void createPath (const Path& path) const
  229473. {
  229474. CGContextBeginPath (context);
  229475. Path::Iterator i (path);
  229476. while (i.next())
  229477. {
  229478. switch (i.elementType)
  229479. {
  229480. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229481. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229482. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229483. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229484. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229485. default: jassertfalse; break;
  229486. }
  229487. }
  229488. }
  229489. void createPath (const Path& path, const AffineTransform& transform) const
  229490. {
  229491. CGContextBeginPath (context);
  229492. Path::Iterator i (path);
  229493. while (i.next())
  229494. {
  229495. switch (i.elementType)
  229496. {
  229497. case Path::Iterator::startNewSubPath:
  229498. transform.transformPoint (i.x1, i.y1);
  229499. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229500. break;
  229501. case Path::Iterator::lineTo:
  229502. transform.transformPoint (i.x1, i.y1);
  229503. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229504. break;
  229505. case Path::Iterator::quadraticTo:
  229506. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  229507. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229508. break;
  229509. case Path::Iterator::cubicTo:
  229510. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  229511. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229512. break;
  229513. case Path::Iterator::closePath:
  229514. CGContextClosePath (context); break;
  229515. default:
  229516. jassertfalse;
  229517. break;
  229518. }
  229519. }
  229520. }
  229521. void flip() const
  229522. {
  229523. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229524. }
  229525. void applyTransform (const AffineTransform& transform) const
  229526. {
  229527. CGAffineTransform t;
  229528. t.a = transform.mat00;
  229529. t.b = transform.mat10;
  229530. t.c = transform.mat01;
  229531. t.d = transform.mat11;
  229532. t.tx = transform.mat02;
  229533. t.ty = transform.mat12;
  229534. CGContextConcatCTM (context, t);
  229535. }
  229536. CoreGraphicsContext (const CoreGraphicsContext&);
  229537. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229538. };
  229539. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229540. {
  229541. return new CoreGraphicsContext (context, height);
  229542. }
  229543. #endif
  229544. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229545. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229546. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229547. // compiled on its own).
  229548. #if JUCE_INCLUDED_FILE
  229549. class NSViewComponentPeer;
  229550. END_JUCE_NAMESPACE
  229551. @interface NSEvent (JuceDeviceDelta)
  229552. - (float) deviceDeltaX;
  229553. - (float) deviceDeltaY;
  229554. @end
  229555. #define JuceNSView MakeObjCClassName(JuceNSView)
  229556. @interface JuceNSView : NSView<NSTextInput>
  229557. {
  229558. @public
  229559. NSViewComponentPeer* owner;
  229560. NSNotificationCenter* notificationCenter;
  229561. String* stringBeingComposed;
  229562. bool textWasInserted;
  229563. }
  229564. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229565. - (void) dealloc;
  229566. - (BOOL) isOpaque;
  229567. - (void) drawRect: (NSRect) r;
  229568. - (void) mouseDown: (NSEvent*) ev;
  229569. - (void) asyncMouseDown: (NSEvent*) ev;
  229570. - (void) mouseUp: (NSEvent*) ev;
  229571. - (void) asyncMouseUp: (NSEvent*) ev;
  229572. - (void) mouseDragged: (NSEvent*) ev;
  229573. - (void) mouseMoved: (NSEvent*) ev;
  229574. - (void) mouseEntered: (NSEvent*) ev;
  229575. - (void) mouseExited: (NSEvent*) ev;
  229576. - (void) rightMouseDown: (NSEvent*) ev;
  229577. - (void) rightMouseDragged: (NSEvent*) ev;
  229578. - (void) rightMouseUp: (NSEvent*) ev;
  229579. - (void) otherMouseDown: (NSEvent*) ev;
  229580. - (void) otherMouseDragged: (NSEvent*) ev;
  229581. - (void) otherMouseUp: (NSEvent*) ev;
  229582. - (void) scrollWheel: (NSEvent*) ev;
  229583. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229584. - (void) frameChanged: (NSNotification*) n;
  229585. - (void) viewDidMoveToWindow;
  229586. - (void) keyDown: (NSEvent*) ev;
  229587. - (void) keyUp: (NSEvent*) ev;
  229588. // NSTextInput Methods
  229589. - (void) insertText: (id) aString;
  229590. - (void) doCommandBySelector: (SEL) aSelector;
  229591. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229592. - (void) unmarkText;
  229593. - (BOOL) hasMarkedText;
  229594. - (long) conversationIdentifier;
  229595. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229596. - (NSRange) markedRange;
  229597. - (NSRange) selectedRange;
  229598. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229599. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  229600. - (NSArray*) validAttributesForMarkedText;
  229601. - (void) flagsChanged: (NSEvent*) ev;
  229602. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229603. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229604. #endif
  229605. - (BOOL) becomeFirstResponder;
  229606. - (BOOL) resignFirstResponder;
  229607. - (BOOL) acceptsFirstResponder;
  229608. - (void) asyncRepaint: (id) rect;
  229609. - (NSArray*) getSupportedDragTypes;
  229610. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229611. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229612. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229613. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229614. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229615. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229616. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229617. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229618. @end
  229619. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229620. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229621. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229622. #else
  229623. @interface JuceNSWindow : NSWindow
  229624. #endif
  229625. {
  229626. @private
  229627. NSViewComponentPeer* owner;
  229628. bool isZooming;
  229629. }
  229630. - (void) setOwner: (NSViewComponentPeer*) owner;
  229631. - (BOOL) canBecomeKeyWindow;
  229632. - (void) becomeKeyWindow;
  229633. - (BOOL) windowShouldClose: (id) window;
  229634. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229635. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229636. - (void) zoom: (id) sender;
  229637. @end
  229638. BEGIN_JUCE_NAMESPACE
  229639. class NSViewComponentPeer : public ComponentPeer
  229640. {
  229641. public:
  229642. NSViewComponentPeer (Component* const component,
  229643. const int windowStyleFlags,
  229644. NSView* viewToAttachTo);
  229645. ~NSViewComponentPeer();
  229646. void* getNativeHandle() const;
  229647. void setVisible (bool shouldBeVisible);
  229648. void setTitle (const String& title);
  229649. void setPosition (int x, int y);
  229650. void setSize (int w, int h);
  229651. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229652. const Rectangle<int> getBounds (const bool global) const;
  229653. const Rectangle<int> getBounds() const;
  229654. const Point<int> getScreenPosition() const;
  229655. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229656. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229657. void setMinimised (bool shouldBeMinimised);
  229658. bool isMinimised() const;
  229659. void setFullScreen (bool shouldBeFullScreen);
  229660. bool isFullScreen() const;
  229661. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229662. const BorderSize getFrameSize() const;
  229663. bool setAlwaysOnTop (bool alwaysOnTop);
  229664. void toFront (bool makeActiveWindow);
  229665. void toBehind (ComponentPeer* other);
  229666. void setIcon (const Image& newIcon);
  229667. const StringArray getAvailableRenderingEngines() throw();
  229668. int getCurrentRenderingEngine() throw();
  229669. void setCurrentRenderingEngine (int index) throw();
  229670. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229671. for example having more than one juce plugin loaded into a host, then when a
  229672. method is called, the actual code that runs might actually be in a different module
  229673. than the one you expect... So any calls to library functions or statics that are
  229674. made inside obj-c methods will probably end up getting executed in a different DLL's
  229675. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229676. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229677. virtual methods of an object that's known to live inside the right module's space.
  229678. */
  229679. virtual void redirectMouseDown (NSEvent* ev);
  229680. virtual void redirectMouseUp (NSEvent* ev);
  229681. virtual void redirectMouseDrag (NSEvent* ev);
  229682. virtual void redirectMouseMove (NSEvent* ev);
  229683. virtual void redirectMouseEnter (NSEvent* ev);
  229684. virtual void redirectMouseExit (NSEvent* ev);
  229685. virtual void redirectMouseWheel (NSEvent* ev);
  229686. void sendMouseEvent (NSEvent* ev);
  229687. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229688. virtual bool redirectKeyDown (NSEvent* ev);
  229689. virtual bool redirectKeyUp (NSEvent* ev);
  229690. virtual void redirectModKeyChange (NSEvent* ev);
  229691. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229692. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229693. #endif
  229694. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229695. virtual bool isOpaque();
  229696. virtual void drawRect (NSRect r);
  229697. virtual bool canBecomeKeyWindow();
  229698. virtual bool windowShouldClose();
  229699. virtual void redirectMovedOrResized();
  229700. virtual void viewMovedToWindow();
  229701. virtual NSRect constrainRect (NSRect r);
  229702. static void showArrowCursorIfNeeded();
  229703. static void updateModifiers (NSEvent* e);
  229704. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229705. static int getKeyCodeFromEvent (NSEvent* ev)
  229706. {
  229707. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229708. int keyCode = unmodified[0];
  229709. if (keyCode == 0x19) // (backwards-tab)
  229710. keyCode = '\t';
  229711. else if (keyCode == 0x03) // (enter)
  229712. keyCode = '\r';
  229713. return keyCode;
  229714. }
  229715. static int64 getMouseTime (NSEvent* e)
  229716. {
  229717. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229718. + (int64) ([e timestamp] * 1000.0);
  229719. }
  229720. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229721. {
  229722. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229723. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229724. }
  229725. static int getModifierForButtonNumber (const NSInteger num)
  229726. {
  229727. return num == 0 ? ModifierKeys::leftButtonModifier
  229728. : (num == 1 ? ModifierKeys::rightButtonModifier
  229729. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229730. }
  229731. virtual void viewFocusGain();
  229732. virtual void viewFocusLoss();
  229733. bool isFocused() const;
  229734. void grabFocus();
  229735. void textInputRequired (const Point<int>& position);
  229736. void repaint (const Rectangle<int>& area);
  229737. void performAnyPendingRepaintsNow();
  229738. juce_UseDebuggingNewOperator
  229739. NSWindow* window;
  229740. JuceNSView* view;
  229741. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229742. static ModifierKeys currentModifiers;
  229743. static ComponentPeer* currentlyFocusedPeer;
  229744. static Array<int> keysCurrentlyDown;
  229745. };
  229746. END_JUCE_NAMESPACE
  229747. @implementation JuceNSView
  229748. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229749. withFrame: (NSRect) frame
  229750. {
  229751. [super initWithFrame: frame];
  229752. owner = owner_;
  229753. stringBeingComposed = 0;
  229754. textWasInserted = false;
  229755. notificationCenter = [NSNotificationCenter defaultCenter];
  229756. [notificationCenter addObserver: self
  229757. selector: @selector (frameChanged:)
  229758. name: NSViewFrameDidChangeNotification
  229759. object: self];
  229760. if (! owner_->isSharedWindow)
  229761. {
  229762. [notificationCenter addObserver: self
  229763. selector: @selector (frameChanged:)
  229764. name: NSWindowDidMoveNotification
  229765. object: owner_->window];
  229766. }
  229767. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229768. return self;
  229769. }
  229770. - (void) dealloc
  229771. {
  229772. [notificationCenter removeObserver: self];
  229773. delete stringBeingComposed;
  229774. [super dealloc];
  229775. }
  229776. - (void) drawRect: (NSRect) r
  229777. {
  229778. if (owner != 0)
  229779. owner->drawRect (r);
  229780. }
  229781. - (BOOL) isOpaque
  229782. {
  229783. return owner == 0 || owner->isOpaque();
  229784. }
  229785. - (void) mouseDown: (NSEvent*) ev
  229786. {
  229787. if (JUCEApplication::isStandaloneApp())
  229788. [self asyncMouseDown: ev];
  229789. else
  229790. // In some host situations, the host will stop modal loops from working
  229791. // correctly if they're called from a mouse event, so we'll trigger
  229792. // the event asynchronously..
  229793. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229794. withObject: ev
  229795. waitUntilDone: NO];
  229796. }
  229797. - (void) asyncMouseDown: (NSEvent*) ev
  229798. {
  229799. if (owner != 0)
  229800. owner->redirectMouseDown (ev);
  229801. }
  229802. - (void) mouseUp: (NSEvent*) ev
  229803. {
  229804. if (! JUCEApplication::isStandaloneApp())
  229805. [self asyncMouseUp: ev];
  229806. else
  229807. // In some host situations, the host will stop modal loops from working
  229808. // correctly if they're called from a mouse event, so we'll trigger
  229809. // the event asynchronously..
  229810. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229811. withObject: ev
  229812. waitUntilDone: NO];
  229813. }
  229814. - (void) asyncMouseUp: (NSEvent*) ev
  229815. {
  229816. if (owner != 0)
  229817. owner->redirectMouseUp (ev);
  229818. }
  229819. - (void) mouseDragged: (NSEvent*) ev
  229820. {
  229821. if (owner != 0)
  229822. owner->redirectMouseDrag (ev);
  229823. }
  229824. - (void) mouseMoved: (NSEvent*) ev
  229825. {
  229826. if (owner != 0)
  229827. owner->redirectMouseMove (ev);
  229828. }
  229829. - (void) mouseEntered: (NSEvent*) ev
  229830. {
  229831. if (owner != 0)
  229832. owner->redirectMouseEnter (ev);
  229833. }
  229834. - (void) mouseExited: (NSEvent*) ev
  229835. {
  229836. if (owner != 0)
  229837. owner->redirectMouseExit (ev);
  229838. }
  229839. - (void) rightMouseDown: (NSEvent*) ev
  229840. {
  229841. [self mouseDown: ev];
  229842. }
  229843. - (void) rightMouseDragged: (NSEvent*) ev
  229844. {
  229845. [self mouseDragged: ev];
  229846. }
  229847. - (void) rightMouseUp: (NSEvent*) ev
  229848. {
  229849. [self mouseUp: ev];
  229850. }
  229851. - (void) otherMouseDown: (NSEvent*) ev
  229852. {
  229853. [self mouseDown: ev];
  229854. }
  229855. - (void) otherMouseDragged: (NSEvent*) ev
  229856. {
  229857. [self mouseDragged: ev];
  229858. }
  229859. - (void) otherMouseUp: (NSEvent*) ev
  229860. {
  229861. [self mouseUp: ev];
  229862. }
  229863. - (void) scrollWheel: (NSEvent*) ev
  229864. {
  229865. if (owner != 0)
  229866. owner->redirectMouseWheel (ev);
  229867. }
  229868. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229869. {
  229870. (void) ev;
  229871. return YES;
  229872. }
  229873. - (void) frameChanged: (NSNotification*) n
  229874. {
  229875. (void) n;
  229876. if (owner != 0)
  229877. owner->redirectMovedOrResized();
  229878. }
  229879. - (void) viewDidMoveToWindow
  229880. {
  229881. if (owner != 0)
  229882. owner->viewMovedToWindow();
  229883. }
  229884. - (void) asyncRepaint: (id) rect
  229885. {
  229886. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229887. [self setNeedsDisplayInRect: *r];
  229888. }
  229889. - (void) keyDown: (NSEvent*) ev
  229890. {
  229891. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229892. textWasInserted = false;
  229893. if (target != 0)
  229894. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229895. else
  229896. deleteAndZero (stringBeingComposed);
  229897. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229898. [super keyDown: ev];
  229899. }
  229900. - (void) keyUp: (NSEvent*) ev
  229901. {
  229902. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229903. [super keyUp: ev];
  229904. }
  229905. - (void) insertText: (id) aString
  229906. {
  229907. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229908. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  229909. if ([newText length] > 0)
  229910. {
  229911. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229912. if (target != 0)
  229913. {
  229914. target->insertTextAtCaret (nsStringToJuce (newText));
  229915. textWasInserted = true;
  229916. }
  229917. }
  229918. deleteAndZero (stringBeingComposed);
  229919. }
  229920. - (void) doCommandBySelector: (SEL) aSelector
  229921. {
  229922. (void) aSelector;
  229923. }
  229924. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229925. {
  229926. (void) selectionRange;
  229927. if (stringBeingComposed == 0)
  229928. stringBeingComposed = new String();
  229929. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229930. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229931. if (target != 0)
  229932. {
  229933. const Range<int> currentHighlight (target->getHighlightedRegion());
  229934. target->insertTextAtCaret (*stringBeingComposed);
  229935. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229936. textWasInserted = true;
  229937. }
  229938. }
  229939. - (void) unmarkText
  229940. {
  229941. if (stringBeingComposed != 0)
  229942. {
  229943. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229944. if (target != 0)
  229945. {
  229946. target->insertTextAtCaret (*stringBeingComposed);
  229947. textWasInserted = true;
  229948. }
  229949. }
  229950. deleteAndZero (stringBeingComposed);
  229951. }
  229952. - (BOOL) hasMarkedText
  229953. {
  229954. return stringBeingComposed != 0;
  229955. }
  229956. - (long) conversationIdentifier
  229957. {
  229958. return (long) (pointer_sized_int) self;
  229959. }
  229960. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  229961. {
  229962. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229963. if (target != 0)
  229964. {
  229965. const Range<int> r ((int) theRange.location,
  229966. (int) (theRange.location + theRange.length));
  229967. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  229968. }
  229969. return nil;
  229970. }
  229971. - (NSRange) markedRange
  229972. {
  229973. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  229974. : NSMakeRange (NSNotFound, 0);
  229975. }
  229976. - (NSRange) selectedRange
  229977. {
  229978. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229979. if (target != 0)
  229980. {
  229981. const Range<int> highlight (target->getHighlightedRegion());
  229982. if (! highlight.isEmpty())
  229983. return NSMakeRange (highlight.getStart(), highlight.getLength());
  229984. }
  229985. return NSMakeRange (NSNotFound, 0);
  229986. }
  229987. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  229988. {
  229989. (void) theRange;
  229990. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  229991. if (comp == 0)
  229992. return NSMakeRect (0, 0, 0, 0);
  229993. const Rectangle<int> bounds (comp->getScreenBounds());
  229994. return NSMakeRect (bounds.getX(),
  229995. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  229996. bounds.getWidth(),
  229997. bounds.getHeight());
  229998. }
  229999. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230000. {
  230001. (void) thePoint;
  230002. return NSNotFound;
  230003. }
  230004. - (NSArray*) validAttributesForMarkedText
  230005. {
  230006. return [NSArray array];
  230007. }
  230008. - (void) flagsChanged: (NSEvent*) ev
  230009. {
  230010. if (owner != 0)
  230011. owner->redirectModKeyChange (ev);
  230012. }
  230013. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230014. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230015. {
  230016. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230017. return true;
  230018. return [super performKeyEquivalent: ev];
  230019. }
  230020. #endif
  230021. - (BOOL) becomeFirstResponder
  230022. {
  230023. if (owner != 0)
  230024. owner->viewFocusGain();
  230025. return true;
  230026. }
  230027. - (BOOL) resignFirstResponder
  230028. {
  230029. if (owner != 0)
  230030. owner->viewFocusLoss();
  230031. return true;
  230032. }
  230033. - (BOOL) acceptsFirstResponder
  230034. {
  230035. return owner != 0 && owner->canBecomeKeyWindow();
  230036. }
  230037. - (NSArray*) getSupportedDragTypes
  230038. {
  230039. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230040. }
  230041. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230042. {
  230043. return owner != 0 && owner->sendDragCallback (type, sender);
  230044. }
  230045. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230046. {
  230047. if ([self sendDragCallback: 0 sender: sender])
  230048. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230049. else
  230050. return NSDragOperationNone;
  230051. }
  230052. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230053. {
  230054. if ([self sendDragCallback: 0 sender: sender])
  230055. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230056. else
  230057. return NSDragOperationNone;
  230058. }
  230059. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230060. {
  230061. [self sendDragCallback: 1 sender: sender];
  230062. }
  230063. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230064. {
  230065. [self sendDragCallback: 1 sender: sender];
  230066. }
  230067. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230068. {
  230069. (void) sender;
  230070. return YES;
  230071. }
  230072. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230073. {
  230074. return [self sendDragCallback: 2 sender: sender];
  230075. }
  230076. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230077. {
  230078. (void) sender;
  230079. }
  230080. @end
  230081. @implementation JuceNSWindow
  230082. - (void) setOwner: (NSViewComponentPeer*) owner_
  230083. {
  230084. owner = owner_;
  230085. isZooming = false;
  230086. }
  230087. - (BOOL) canBecomeKeyWindow
  230088. {
  230089. return owner != 0 && owner->canBecomeKeyWindow();
  230090. }
  230091. - (void) becomeKeyWindow
  230092. {
  230093. [super becomeKeyWindow];
  230094. if (owner != 0)
  230095. owner->grabFocus();
  230096. }
  230097. - (BOOL) windowShouldClose: (id) window
  230098. {
  230099. (void) window;
  230100. return owner == 0 || owner->windowShouldClose();
  230101. }
  230102. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230103. {
  230104. (void) screen;
  230105. if (owner != 0)
  230106. frameRect = owner->constrainRect (frameRect);
  230107. return frameRect;
  230108. }
  230109. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230110. {
  230111. (void) window;
  230112. if (isZooming)
  230113. return proposedFrameSize;
  230114. NSRect frameRect = [self frame];
  230115. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230116. frameRect.size = proposedFrameSize;
  230117. if (owner != 0)
  230118. frameRect = owner->constrainRect (frameRect);
  230119. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230120. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230121. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230122. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230123. return frameRect.size;
  230124. }
  230125. - (void) zoom: (id) sender
  230126. {
  230127. isZooming = true;
  230128. [super zoom: sender];
  230129. isZooming = false;
  230130. }
  230131. - (void) windowWillMove: (NSNotification*) notification
  230132. {
  230133. (void) notification;
  230134. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230135. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230136. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230137. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230138. }
  230139. @end
  230140. BEGIN_JUCE_NAMESPACE
  230141. ModifierKeys NSViewComponentPeer::currentModifiers;
  230142. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230143. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230144. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230145. {
  230146. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230147. return true;
  230148. if (keyCode >= 'A' && keyCode <= 'Z'
  230149. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230150. return true;
  230151. if (keyCode >= 'a' && keyCode <= 'z'
  230152. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230153. return true;
  230154. return false;
  230155. }
  230156. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230157. {
  230158. int m = 0;
  230159. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230160. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230161. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230162. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230163. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230164. }
  230165. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230166. {
  230167. updateModifiers (ev);
  230168. int keyCode = getKeyCodeFromEvent (ev);
  230169. if (keyCode != 0)
  230170. {
  230171. if (isKeyDown)
  230172. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230173. else
  230174. keysCurrentlyDown.removeValue (keyCode);
  230175. }
  230176. }
  230177. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230178. {
  230179. return NSViewComponentPeer::currentModifiers;
  230180. }
  230181. void ModifierKeys::updateCurrentModifiers() throw()
  230182. {
  230183. currentModifiers = NSViewComponentPeer::currentModifiers;
  230184. }
  230185. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230186. const int windowStyleFlags,
  230187. NSView* viewToAttachTo)
  230188. : ComponentPeer (component_, windowStyleFlags),
  230189. window (0),
  230190. view (0),
  230191. isSharedWindow (viewToAttachTo != 0),
  230192. fullScreen (false),
  230193. insideDrawRect (false),
  230194. #if USE_COREGRAPHICS_RENDERING
  230195. usingCoreGraphics (true),
  230196. #else
  230197. usingCoreGraphics (false),
  230198. #endif
  230199. recursiveToFrontCall (false)
  230200. {
  230201. NSRect r;
  230202. r.origin.x = 0;
  230203. r.origin.y = 0;
  230204. r.size.width = (float) component->getWidth();
  230205. r.size.height = (float) component->getHeight();
  230206. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230207. [view setPostsFrameChangedNotifications: YES];
  230208. if (isSharedWindow)
  230209. {
  230210. window = [viewToAttachTo window];
  230211. [viewToAttachTo addSubview: view];
  230212. setVisible (component->isVisible());
  230213. }
  230214. else
  230215. {
  230216. r.origin.x = (float) component->getX();
  230217. r.origin.y = (float) component->getY();
  230218. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230219. unsigned int style = 0;
  230220. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230221. style = NSBorderlessWindowMask;
  230222. else
  230223. style = NSTitledWindowMask;
  230224. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230225. style |= NSMiniaturizableWindowMask;
  230226. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230227. style |= NSClosableWindowMask;
  230228. if ((windowStyleFlags & windowIsResizable) != 0)
  230229. style |= NSResizableWindowMask;
  230230. window = [[JuceNSWindow alloc] initWithContentRect: r
  230231. styleMask: style
  230232. backing: NSBackingStoreBuffered
  230233. defer: YES];
  230234. [((JuceNSWindow*) window) setOwner: this];
  230235. [window orderOut: nil];
  230236. [window setDelegate: (JuceNSWindow*) window];
  230237. [window setOpaque: component->isOpaque()];
  230238. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230239. if (component->isAlwaysOnTop())
  230240. [window setLevel: NSFloatingWindowLevel];
  230241. [window setContentView: view];
  230242. [window setAutodisplay: YES];
  230243. [window setAcceptsMouseMovedEvents: YES];
  230244. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230245. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230246. [window setReleasedWhenClosed: YES];
  230247. [window retain];
  230248. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230249. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230250. }
  230251. setTitle (component->getName());
  230252. }
  230253. NSViewComponentPeer::~NSViewComponentPeer()
  230254. {
  230255. view->owner = 0;
  230256. [view removeFromSuperview];
  230257. [view release];
  230258. if (! isSharedWindow)
  230259. {
  230260. [((JuceNSWindow*) window) setOwner: 0];
  230261. [window close];
  230262. [window release];
  230263. }
  230264. }
  230265. void* NSViewComponentPeer::getNativeHandle() const
  230266. {
  230267. return view;
  230268. }
  230269. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230270. {
  230271. if (isSharedWindow)
  230272. {
  230273. [view setHidden: ! shouldBeVisible];
  230274. }
  230275. else
  230276. {
  230277. if (shouldBeVisible)
  230278. {
  230279. [window orderFront: nil];
  230280. handleBroughtToFront();
  230281. }
  230282. else
  230283. {
  230284. [window orderOut: nil];
  230285. }
  230286. }
  230287. }
  230288. void NSViewComponentPeer::setTitle (const String& title)
  230289. {
  230290. const ScopedAutoReleasePool pool;
  230291. if (! isSharedWindow)
  230292. [window setTitle: juceStringToNS (title)];
  230293. }
  230294. void NSViewComponentPeer::setPosition (int x, int y)
  230295. {
  230296. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230297. }
  230298. void NSViewComponentPeer::setSize (int w, int h)
  230299. {
  230300. setBounds (component->getX(), component->getY(), w, h, false);
  230301. }
  230302. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230303. {
  230304. fullScreen = isNowFullScreen;
  230305. w = jmax (0, w);
  230306. h = jmax (0, h);
  230307. NSRect r;
  230308. r.origin.x = (float) x;
  230309. r.origin.y = (float) y;
  230310. r.size.width = (float) w;
  230311. r.size.height = (float) h;
  230312. if (isSharedWindow)
  230313. {
  230314. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230315. if ([view frame].size.width != r.size.width
  230316. || [view frame].size.height != r.size.height)
  230317. [view setNeedsDisplay: true];
  230318. [view setFrame: r];
  230319. }
  230320. else
  230321. {
  230322. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230323. [window setFrame: [window frameRectForContentRect: r]
  230324. display: true];
  230325. }
  230326. }
  230327. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230328. {
  230329. NSRect r = [view frame];
  230330. if (global && [view window] != 0)
  230331. {
  230332. r = [view convertRect: r toView: nil];
  230333. NSRect wr = [[view window] frame];
  230334. r.origin.x += wr.origin.x;
  230335. r.origin.y += wr.origin.y;
  230336. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230337. }
  230338. else
  230339. {
  230340. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230341. }
  230342. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230343. }
  230344. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230345. {
  230346. return getBounds (! isSharedWindow);
  230347. }
  230348. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230349. {
  230350. return getBounds (true).getPosition();
  230351. }
  230352. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230353. {
  230354. return relativePosition + getScreenPosition();
  230355. }
  230356. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230357. {
  230358. return screenPosition - getScreenPosition();
  230359. }
  230360. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230361. {
  230362. if (constrainer != 0)
  230363. {
  230364. NSRect current = [window frame];
  230365. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230366. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230367. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230368. (int) r.size.width, (int) r.size.height);
  230369. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230370. (int) current.size.width, (int) current.size.height);
  230371. constrainer->checkBounds (pos, original,
  230372. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230373. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230374. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230375. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230376. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230377. r.origin.x = pos.getX();
  230378. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230379. r.size.width = pos.getWidth();
  230380. r.size.height = pos.getHeight();
  230381. }
  230382. return r;
  230383. }
  230384. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230385. {
  230386. if (! isSharedWindow)
  230387. {
  230388. if (shouldBeMinimised)
  230389. [window miniaturize: nil];
  230390. else
  230391. [window deminiaturize: nil];
  230392. }
  230393. }
  230394. bool NSViewComponentPeer::isMinimised() const
  230395. {
  230396. return window != 0 && [window isMiniaturized];
  230397. }
  230398. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230399. {
  230400. if (! isSharedWindow)
  230401. {
  230402. Rectangle<int> r (lastNonFullscreenBounds);
  230403. setMinimised (false);
  230404. if (fullScreen != shouldBeFullScreen)
  230405. {
  230406. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230407. {
  230408. fullScreen = true;
  230409. [window performZoom: nil];
  230410. }
  230411. else
  230412. {
  230413. if (shouldBeFullScreen)
  230414. r = Desktop::getInstance().getMainMonitorArea();
  230415. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230416. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230417. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230418. }
  230419. }
  230420. }
  230421. }
  230422. bool NSViewComponentPeer::isFullScreen() const
  230423. {
  230424. return fullScreen;
  230425. }
  230426. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230427. {
  230428. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230429. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230430. return false;
  230431. NSPoint p;
  230432. p.x = (float) position.getX();
  230433. p.y = (float) position.getY();
  230434. NSView* v = [view hitTest: p];
  230435. if (trueIfInAChildWindow)
  230436. return v != nil;
  230437. return v == view;
  230438. }
  230439. const BorderSize NSViewComponentPeer::getFrameSize() const
  230440. {
  230441. BorderSize b;
  230442. if (! isSharedWindow)
  230443. {
  230444. NSRect v = [view convertRect: [view frame] toView: nil];
  230445. NSRect w = [window frame];
  230446. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230447. b.setBottom ((int) v.origin.y);
  230448. b.setLeft ((int) v.origin.x);
  230449. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230450. }
  230451. return b;
  230452. }
  230453. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230454. {
  230455. if (! isSharedWindow)
  230456. {
  230457. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230458. : NSNormalWindowLevel];
  230459. }
  230460. return true;
  230461. }
  230462. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230463. {
  230464. if (isSharedWindow)
  230465. {
  230466. [[view superview] addSubview: view
  230467. positioned: NSWindowAbove
  230468. relativeTo: nil];
  230469. }
  230470. if (window != 0 && component->isVisible())
  230471. {
  230472. if (makeActiveWindow)
  230473. [window makeKeyAndOrderFront: nil];
  230474. else
  230475. [window orderFront: nil];
  230476. if (! recursiveToFrontCall)
  230477. {
  230478. recursiveToFrontCall = true;
  230479. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230480. handleBroughtToFront();
  230481. recursiveToFrontCall = false;
  230482. }
  230483. }
  230484. }
  230485. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230486. {
  230487. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230488. jassert (otherPeer != 0); // wrong type of window?
  230489. if (otherPeer != 0)
  230490. {
  230491. if (isSharedWindow)
  230492. {
  230493. [[view superview] addSubview: view
  230494. positioned: NSWindowBelow
  230495. relativeTo: otherPeer->view];
  230496. }
  230497. else
  230498. {
  230499. [window orderWindow: NSWindowBelow
  230500. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230501. : nil ];
  230502. }
  230503. }
  230504. }
  230505. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230506. {
  230507. // to do..
  230508. }
  230509. void NSViewComponentPeer::viewFocusGain()
  230510. {
  230511. if (currentlyFocusedPeer != this)
  230512. {
  230513. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230514. currentlyFocusedPeer->handleFocusLoss();
  230515. currentlyFocusedPeer = this;
  230516. handleFocusGain();
  230517. }
  230518. }
  230519. void NSViewComponentPeer::viewFocusLoss()
  230520. {
  230521. if (currentlyFocusedPeer == this)
  230522. {
  230523. currentlyFocusedPeer = 0;
  230524. handleFocusLoss();
  230525. }
  230526. }
  230527. void juce_HandleProcessFocusChange()
  230528. {
  230529. NSViewComponentPeer::keysCurrentlyDown.clear();
  230530. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230531. {
  230532. if (Process::isForegroundProcess())
  230533. {
  230534. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230535. ComponentPeer::bringModalComponentToFront();
  230536. }
  230537. else
  230538. {
  230539. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230540. // turn kiosk mode off if we lose focus..
  230541. Desktop::getInstance().setKioskModeComponent (0);
  230542. }
  230543. }
  230544. }
  230545. bool NSViewComponentPeer::isFocused() const
  230546. {
  230547. return isSharedWindow ? this == currentlyFocusedPeer
  230548. : (window != 0 && [window isKeyWindow]);
  230549. }
  230550. void NSViewComponentPeer::grabFocus()
  230551. {
  230552. if (window != 0)
  230553. {
  230554. [window makeKeyWindow];
  230555. [window makeFirstResponder: view];
  230556. viewFocusGain();
  230557. }
  230558. }
  230559. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230560. {
  230561. }
  230562. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230563. {
  230564. String unicode (nsStringToJuce ([ev characters]));
  230565. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230566. int keyCode = getKeyCodeFromEvent (ev);
  230567. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230568. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230569. if (unicode.isNotEmpty() || keyCode != 0)
  230570. {
  230571. if (isKeyDown)
  230572. {
  230573. bool used = false;
  230574. while (unicode.length() > 0)
  230575. {
  230576. juce_wchar textCharacter = unicode[0];
  230577. unicode = unicode.substring (1);
  230578. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230579. textCharacter = 0;
  230580. used = handleKeyUpOrDown (true) || used;
  230581. used = handleKeyPress (keyCode, textCharacter) || used;
  230582. }
  230583. return used;
  230584. }
  230585. else
  230586. {
  230587. if (handleKeyUpOrDown (false))
  230588. return true;
  230589. }
  230590. }
  230591. return false;
  230592. }
  230593. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230594. {
  230595. updateKeysDown (ev, true);
  230596. bool used = handleKeyEvent (ev, true);
  230597. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230598. {
  230599. // for command keys, the key-up event is thrown away, so simulate one..
  230600. updateKeysDown (ev, false);
  230601. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230602. }
  230603. // (If we're running modally, don't allow unused keystrokes to be passed
  230604. // along to other blocked views..)
  230605. if (Component::getCurrentlyModalComponent() != 0)
  230606. used = true;
  230607. return used;
  230608. }
  230609. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230610. {
  230611. updateKeysDown (ev, false);
  230612. return handleKeyEvent (ev, false)
  230613. || Component::getCurrentlyModalComponent() != 0;
  230614. }
  230615. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230616. {
  230617. keysCurrentlyDown.clear();
  230618. handleKeyUpOrDown (true);
  230619. updateModifiers (ev);
  230620. handleModifierKeysChange();
  230621. }
  230622. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230623. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230624. {
  230625. if ([ev type] == NSKeyDown)
  230626. return redirectKeyDown (ev);
  230627. else if ([ev type] == NSKeyUp)
  230628. return redirectKeyUp (ev);
  230629. return false;
  230630. }
  230631. #endif
  230632. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230633. {
  230634. updateModifiers (ev);
  230635. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230636. }
  230637. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230638. {
  230639. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230640. sendMouseEvent (ev);
  230641. }
  230642. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230643. {
  230644. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230645. sendMouseEvent (ev);
  230646. showArrowCursorIfNeeded();
  230647. }
  230648. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230649. {
  230650. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230651. sendMouseEvent (ev);
  230652. }
  230653. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230654. {
  230655. currentModifiers = currentModifiers.withoutMouseButtons();
  230656. sendMouseEvent (ev);
  230657. showArrowCursorIfNeeded();
  230658. }
  230659. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230660. {
  230661. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230662. currentModifiers = currentModifiers.withoutMouseButtons();
  230663. sendMouseEvent (ev);
  230664. }
  230665. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230666. {
  230667. currentModifiers = currentModifiers.withoutMouseButtons();
  230668. sendMouseEvent (ev);
  230669. }
  230670. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230671. {
  230672. updateModifiers (ev);
  230673. float x = 0, y = 0;
  230674. @try
  230675. {
  230676. x = [ev deviceDeltaX] * 0.5f;
  230677. y = [ev deviceDeltaY] * 0.5f;
  230678. }
  230679. @catch (...)
  230680. {}
  230681. if (x == 0 && y == 0)
  230682. {
  230683. x = [ev deltaX] * 10.0f;
  230684. y = [ev deltaY] * 10.0f;
  230685. }
  230686. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  230687. }
  230688. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230689. {
  230690. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230691. if (mouse.getComponentUnderMouse() == 0
  230692. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230693. {
  230694. [[NSCursor arrowCursor] set];
  230695. }
  230696. }
  230697. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230698. {
  230699. NSString* bestType
  230700. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230701. if (bestType == nil)
  230702. return false;
  230703. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230704. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230705. StringArray files;
  230706. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230707. if (list == nil)
  230708. return false;
  230709. if ([list isKindOfClass: [NSArray class]])
  230710. {
  230711. NSArray* items = (NSArray*) list;
  230712. for (unsigned int i = 0; i < [items count]; ++i)
  230713. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230714. }
  230715. if (files.size() == 0)
  230716. return false;
  230717. if (type == 0)
  230718. handleFileDragMove (files, pos);
  230719. else if (type == 1)
  230720. handleFileDragExit (files);
  230721. else if (type == 2)
  230722. handleFileDragDrop (files, pos);
  230723. return true;
  230724. }
  230725. bool NSViewComponentPeer::isOpaque()
  230726. {
  230727. return component == 0 || component->isOpaque();
  230728. }
  230729. void NSViewComponentPeer::drawRect (NSRect r)
  230730. {
  230731. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230732. return;
  230733. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230734. if (! component->isOpaque())
  230735. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230736. #if USE_COREGRAPHICS_RENDERING
  230737. if (usingCoreGraphics)
  230738. {
  230739. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230740. insideDrawRect = true;
  230741. handlePaint (context);
  230742. insideDrawRect = false;
  230743. }
  230744. else
  230745. #endif
  230746. {
  230747. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230748. (int) (r.size.width + 0.5f),
  230749. (int) (r.size.height + 0.5f),
  230750. ! getComponent()->isOpaque());
  230751. const int xOffset = -roundToInt (r.origin.x);
  230752. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230753. const NSRect* rects = 0;
  230754. NSInteger numRects = 0;
  230755. [view getRectsBeingDrawn: &rects count: &numRects];
  230756. const Rectangle<int> clipBounds (temp.getBounds());
  230757. RectangleList clip;
  230758. for (int i = 0; i < numRects; ++i)
  230759. {
  230760. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230761. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230762. roundToInt (rects[i].size.width),
  230763. roundToInt (rects[i].size.height))));
  230764. }
  230765. if (! clip.isEmpty())
  230766. {
  230767. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230768. insideDrawRect = true;
  230769. handlePaint (context);
  230770. insideDrawRect = false;
  230771. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230772. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230773. CGColorSpaceRelease (colourSpace);
  230774. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230775. CGImageRelease (image);
  230776. }
  230777. }
  230778. }
  230779. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230780. {
  230781. StringArray s;
  230782. s.add ("Software Renderer");
  230783. #if USE_COREGRAPHICS_RENDERING
  230784. s.add ("CoreGraphics Renderer");
  230785. #endif
  230786. return s;
  230787. }
  230788. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230789. {
  230790. return usingCoreGraphics ? 1 : 0;
  230791. }
  230792. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230793. {
  230794. #if USE_COREGRAPHICS_RENDERING
  230795. if (usingCoreGraphics != (index > 0))
  230796. {
  230797. usingCoreGraphics = index > 0;
  230798. [view setNeedsDisplay: true];
  230799. }
  230800. #endif
  230801. }
  230802. bool NSViewComponentPeer::canBecomeKeyWindow()
  230803. {
  230804. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230805. }
  230806. bool NSViewComponentPeer::windowShouldClose()
  230807. {
  230808. if (! isValidPeer (this))
  230809. return YES;
  230810. handleUserClosingWindow();
  230811. return NO;
  230812. }
  230813. void NSViewComponentPeer::redirectMovedOrResized()
  230814. {
  230815. handleMovedOrResized();
  230816. }
  230817. void NSViewComponentPeer::viewMovedToWindow()
  230818. {
  230819. if (isSharedWindow)
  230820. window = [view window];
  230821. }
  230822. void Desktop::createMouseInputSources()
  230823. {
  230824. mouseSources.add (new MouseInputSource (0, true));
  230825. }
  230826. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230827. {
  230828. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230829. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230830. // is apparently still available in 64-bit apps..
  230831. if (enableOrDisable)
  230832. {
  230833. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230834. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230835. }
  230836. else
  230837. {
  230838. SetSystemUIMode (kUIModeNormal, 0);
  230839. }
  230840. }
  230841. class AsyncRepaintMessage : public CallbackMessage
  230842. {
  230843. public:
  230844. NSViewComponentPeer* const peer;
  230845. const Rectangle<int> rect;
  230846. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230847. : peer (peer_), rect (rect_)
  230848. {
  230849. }
  230850. void messageCallback()
  230851. {
  230852. if (ComponentPeer::isValidPeer (peer))
  230853. peer->repaint (rect);
  230854. }
  230855. };
  230856. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230857. {
  230858. if (insideDrawRect)
  230859. {
  230860. (new AsyncRepaintMessage (this, area))->post();
  230861. }
  230862. else
  230863. {
  230864. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230865. (float) area.getWidth(), (float) area.getHeight())];
  230866. }
  230867. }
  230868. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230869. {
  230870. [view displayIfNeeded];
  230871. }
  230872. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230873. {
  230874. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230875. }
  230876. const Image juce_createIconForFile (const File& file)
  230877. {
  230878. const ScopedAutoReleasePool pool;
  230879. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230880. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230881. [NSGraphicsContext saveGraphicsState];
  230882. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230883. [image drawAtPoint: NSMakePoint (0, 0)
  230884. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230885. operation: NSCompositeSourceOver fraction: 1.0f];
  230886. [[NSGraphicsContext currentContext] flushGraphics];
  230887. [NSGraphicsContext restoreGraphicsState];
  230888. return Image (result);
  230889. }
  230890. const int KeyPress::spaceKey = ' ';
  230891. const int KeyPress::returnKey = 0x0d;
  230892. const int KeyPress::escapeKey = 0x1b;
  230893. const int KeyPress::backspaceKey = 0x7f;
  230894. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230895. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230896. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230897. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230898. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230899. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230900. const int KeyPress::endKey = NSEndFunctionKey;
  230901. const int KeyPress::homeKey = NSHomeFunctionKey;
  230902. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230903. const int KeyPress::insertKey = -1;
  230904. const int KeyPress::tabKey = 9;
  230905. const int KeyPress::F1Key = NSF1FunctionKey;
  230906. const int KeyPress::F2Key = NSF2FunctionKey;
  230907. const int KeyPress::F3Key = NSF3FunctionKey;
  230908. const int KeyPress::F4Key = NSF4FunctionKey;
  230909. const int KeyPress::F5Key = NSF5FunctionKey;
  230910. const int KeyPress::F6Key = NSF6FunctionKey;
  230911. const int KeyPress::F7Key = NSF7FunctionKey;
  230912. const int KeyPress::F8Key = NSF8FunctionKey;
  230913. const int KeyPress::F9Key = NSF9FunctionKey;
  230914. const int KeyPress::F10Key = NSF10FunctionKey;
  230915. const int KeyPress::F11Key = NSF1FunctionKey;
  230916. const int KeyPress::F12Key = NSF12FunctionKey;
  230917. const int KeyPress::F13Key = NSF13FunctionKey;
  230918. const int KeyPress::F14Key = NSF14FunctionKey;
  230919. const int KeyPress::F15Key = NSF15FunctionKey;
  230920. const int KeyPress::F16Key = NSF16FunctionKey;
  230921. const int KeyPress::numberPad0 = 0x30020;
  230922. const int KeyPress::numberPad1 = 0x30021;
  230923. const int KeyPress::numberPad2 = 0x30022;
  230924. const int KeyPress::numberPad3 = 0x30023;
  230925. const int KeyPress::numberPad4 = 0x30024;
  230926. const int KeyPress::numberPad5 = 0x30025;
  230927. const int KeyPress::numberPad6 = 0x30026;
  230928. const int KeyPress::numberPad7 = 0x30027;
  230929. const int KeyPress::numberPad8 = 0x30028;
  230930. const int KeyPress::numberPad9 = 0x30029;
  230931. const int KeyPress::numberPadAdd = 0x3002a;
  230932. const int KeyPress::numberPadSubtract = 0x3002b;
  230933. const int KeyPress::numberPadMultiply = 0x3002c;
  230934. const int KeyPress::numberPadDivide = 0x3002d;
  230935. const int KeyPress::numberPadSeparator = 0x3002e;
  230936. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230937. const int KeyPress::numberPadEquals = 0x30030;
  230938. const int KeyPress::numberPadDelete = 0x30031;
  230939. const int KeyPress::playKey = 0x30000;
  230940. const int KeyPress::stopKey = 0x30001;
  230941. const int KeyPress::fastForwardKey = 0x30002;
  230942. const int KeyPress::rewindKey = 0x30003;
  230943. #endif
  230944. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230945. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230946. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230947. // compiled on its own).
  230948. #if JUCE_INCLUDED_FILE
  230949. #if JUCE_MAC
  230950. namespace MouseCursorHelpers
  230951. {
  230952. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  230953. {
  230954. NSImage* im = CoreGraphicsImage::createNSImage (image);
  230955. NSCursor* c = [[NSCursor alloc] initWithImage: im
  230956. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  230957. [im release];
  230958. return c;
  230959. }
  230960. static void* fromWebKitFile (const char* filename, float hx, float hy)
  230961. {
  230962. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  230963. BufferedInputStream buf (&fileStream, 4096, false);
  230964. PNGImageFormat pngFormat;
  230965. Image im (pngFormat.decodeImage (buf));
  230966. if (im.isValid())
  230967. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  230968. jassertfalse;
  230969. return 0;
  230970. }
  230971. }
  230972. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  230973. {
  230974. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  230975. }
  230976. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  230977. {
  230978. const ScopedAutoReleasePool pool;
  230979. NSCursor* c = 0;
  230980. switch (type)
  230981. {
  230982. case NormalCursor: c = [NSCursor arrowCursor]; break;
  230983. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  230984. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  230985. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  230986. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  230987. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  230988. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  230989. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  230990. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  230991. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  230992. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  230993. case UpDownResizeCursor:
  230994. case TopEdgeResizeCursor:
  230995. case BottomEdgeResizeCursor:
  230996. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  230997. case TopLeftCornerResizeCursor:
  230998. case BottomRightCornerResizeCursor:
  230999. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231000. case TopRightCornerResizeCursor:
  231001. case BottomLeftCornerResizeCursor:
  231002. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231003. case UpDownLeftRightResizeCursor:
  231004. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231005. default:
  231006. jassertfalse;
  231007. break;
  231008. }
  231009. [c retain];
  231010. return c;
  231011. }
  231012. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231013. {
  231014. [((NSCursor*) cursorHandle) release];
  231015. }
  231016. void MouseCursor::showInAllWindows() const
  231017. {
  231018. showInWindow (0);
  231019. }
  231020. void MouseCursor::showInWindow (ComponentPeer*) const
  231021. {
  231022. [((NSCursor*) getHandle()) set];
  231023. }
  231024. #else
  231025. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231026. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231027. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231028. void MouseCursor::showInAllWindows() const {}
  231029. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231030. #endif
  231031. #endif
  231032. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231033. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231034. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231035. // compiled on its own).
  231036. #if JUCE_INCLUDED_FILE
  231037. class NSViewComponentInternal : public ComponentMovementWatcher
  231038. {
  231039. Component* const owner;
  231040. NSViewComponentPeer* currentPeer;
  231041. bool wasShowing;
  231042. public:
  231043. NSView* const view;
  231044. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  231045. : ComponentMovementWatcher (owner_),
  231046. owner (owner_),
  231047. currentPeer (0),
  231048. wasShowing (false),
  231049. view (view_)
  231050. {
  231051. [view_ retain];
  231052. if (owner_->isShowing())
  231053. componentPeerChanged();
  231054. }
  231055. ~NSViewComponentInternal()
  231056. {
  231057. [view removeFromSuperview];
  231058. [view release];
  231059. }
  231060. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231061. {
  231062. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231063. // The ComponentMovementWatcher version of this method avoids calling
  231064. // us when the top-level comp is resized, but for an NSView we need to know this
  231065. // because with inverted co-ords, we need to update the position even if the
  231066. // top-left pos hasn't changed
  231067. if (comp.isOnDesktop() && wasResized)
  231068. componentMovedOrResized (wasMoved, wasResized);
  231069. }
  231070. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231071. {
  231072. Component* const topComp = owner->getTopLevelComponent();
  231073. if (topComp->getPeer() != 0)
  231074. {
  231075. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  231076. NSRect r;
  231077. r.origin.x = (float) pos.getX();
  231078. r.origin.y = (float) pos.getY();
  231079. r.size.width = (float) owner->getWidth();
  231080. r.size.height = (float) owner->getHeight();
  231081. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231082. [view setFrame: r];
  231083. }
  231084. }
  231085. void componentPeerChanged()
  231086. {
  231087. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  231088. if (currentPeer != peer)
  231089. {
  231090. [view removeFromSuperview];
  231091. currentPeer = peer;
  231092. if (peer != 0)
  231093. {
  231094. [peer->view addSubview: view];
  231095. componentMovedOrResized (false, false);
  231096. }
  231097. }
  231098. [view setHidden: ! owner->isShowing()];
  231099. }
  231100. void componentVisibilityChanged (Component&)
  231101. {
  231102. componentPeerChanged();
  231103. }
  231104. juce_UseDebuggingNewOperator
  231105. private:
  231106. NSViewComponentInternal (const NSViewComponentInternal&);
  231107. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  231108. };
  231109. NSViewComponent::NSViewComponent()
  231110. {
  231111. }
  231112. NSViewComponent::~NSViewComponent()
  231113. {
  231114. }
  231115. void NSViewComponent::setView (void* view)
  231116. {
  231117. if (view != getView())
  231118. {
  231119. if (view != 0)
  231120. info = new NSViewComponentInternal ((NSView*) view, this);
  231121. else
  231122. info = 0;
  231123. }
  231124. }
  231125. void* NSViewComponent::getView() const
  231126. {
  231127. return info == 0 ? 0 : info->view;
  231128. }
  231129. void NSViewComponent::paint (Graphics&)
  231130. {
  231131. }
  231132. #endif
  231133. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231134. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231135. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231136. // compiled on its own).
  231137. #if JUCE_INCLUDED_FILE
  231138. AppleRemoteDevice::AppleRemoteDevice()
  231139. : device (0),
  231140. queue (0),
  231141. remoteId (0)
  231142. {
  231143. }
  231144. AppleRemoteDevice::~AppleRemoteDevice()
  231145. {
  231146. stop();
  231147. }
  231148. static io_object_t getAppleRemoteDevice()
  231149. {
  231150. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231151. io_iterator_t iter = 0;
  231152. io_object_t iod = 0;
  231153. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231154. && iter != 0)
  231155. {
  231156. iod = IOIteratorNext (iter);
  231157. }
  231158. IOObjectRelease (iter);
  231159. return iod;
  231160. }
  231161. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  231162. {
  231163. jassert (*device == 0);
  231164. io_name_t classname;
  231165. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231166. {
  231167. IOCFPlugInInterface** cfPlugInInterface = 0;
  231168. SInt32 score = 0;
  231169. if (IOCreatePlugInInterfaceForService (iod,
  231170. kIOHIDDeviceUserClientTypeID,
  231171. kIOCFPlugInInterfaceID,
  231172. &cfPlugInInterface,
  231173. &score) == kIOReturnSuccess)
  231174. {
  231175. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231176. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231177. device);
  231178. (void) hr;
  231179. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231180. }
  231181. }
  231182. return *device != 0;
  231183. }
  231184. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231185. {
  231186. if (queue != 0)
  231187. return true;
  231188. stop();
  231189. bool result = false;
  231190. io_object_t iod = getAppleRemoteDevice();
  231191. if (iod != 0)
  231192. {
  231193. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231194. result = true;
  231195. else
  231196. stop();
  231197. IOObjectRelease (iod);
  231198. }
  231199. return result;
  231200. }
  231201. void AppleRemoteDevice::stop()
  231202. {
  231203. if (queue != 0)
  231204. {
  231205. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231206. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231207. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231208. queue = 0;
  231209. }
  231210. if (device != 0)
  231211. {
  231212. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231213. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231214. device = 0;
  231215. }
  231216. }
  231217. bool AppleRemoteDevice::isActive() const
  231218. {
  231219. return queue != 0;
  231220. }
  231221. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231222. {
  231223. if (result == kIOReturnSuccess)
  231224. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231225. }
  231226. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231227. {
  231228. Array <int> cookies;
  231229. CFArrayRef elements;
  231230. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231231. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231232. return false;
  231233. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231234. {
  231235. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231236. // get the cookie
  231237. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231238. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231239. continue;
  231240. long number;
  231241. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231242. continue;
  231243. cookies.add ((int) number);
  231244. }
  231245. CFRelease (elements);
  231246. if ((*(IOHIDDeviceInterface**) device)
  231247. ->open ((IOHIDDeviceInterface**) device,
  231248. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  231249. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  231250. {
  231251. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231252. if (queue != 0)
  231253. {
  231254. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231255. for (int i = 0; i < cookies.size(); ++i)
  231256. {
  231257. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231258. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231259. }
  231260. CFRunLoopSourceRef eventSource;
  231261. if ((*(IOHIDQueueInterface**) queue)
  231262. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231263. {
  231264. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231265. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231266. {
  231267. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231268. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231269. return true;
  231270. }
  231271. }
  231272. }
  231273. }
  231274. return false;
  231275. }
  231276. void AppleRemoteDevice::handleCallbackInternal()
  231277. {
  231278. int totalValues = 0;
  231279. AbsoluteTime nullTime = { 0, 0 };
  231280. char cookies [12];
  231281. int numCookies = 0;
  231282. while (numCookies < numElementsInArray (cookies))
  231283. {
  231284. IOHIDEventStruct e;
  231285. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231286. break;
  231287. if ((int) e.elementCookie == 19)
  231288. {
  231289. remoteId = e.value;
  231290. buttonPressed (switched, false);
  231291. }
  231292. else
  231293. {
  231294. totalValues += e.value;
  231295. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231296. }
  231297. }
  231298. cookies [numCookies++] = 0;
  231299. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231300. static const char buttonPatterns[] =
  231301. {
  231302. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231303. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231304. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231305. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231306. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231307. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231308. 0x1f, 0x12, 0x04, 0x02, 0,
  231309. 0x1f, 0x12, 0x03, 0x02, 0,
  231310. 0x1f, 0x12, 0x1f, 0x12, 0,
  231311. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  231312. 19, 0
  231313. };
  231314. int buttonNum = (int) menuButton;
  231315. int i = 0;
  231316. while (i < numElementsInArray (buttonPatterns))
  231317. {
  231318. if (strcmp (cookies, buttonPatterns + i) == 0)
  231319. {
  231320. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  231321. break;
  231322. }
  231323. i += (int) strlen (buttonPatterns + i) + 1;
  231324. ++buttonNum;
  231325. }
  231326. }
  231327. #endif
  231328. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231329. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231330. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231331. // compiled on its own).
  231332. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231333. #if JUCE_MAC
  231334. END_JUCE_NAMESPACE
  231335. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231336. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231337. {
  231338. CriticalSection* contextLock;
  231339. bool needsUpdate;
  231340. }
  231341. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231342. - (bool) makeActive;
  231343. - (void) makeInactive;
  231344. - (void) reshape;
  231345. @end
  231346. @implementation ThreadSafeNSOpenGLView
  231347. - (id) initWithFrame: (NSRect) frameRect
  231348. pixelFormat: (NSOpenGLPixelFormat*) format
  231349. {
  231350. contextLock = new CriticalSection();
  231351. self = [super initWithFrame: frameRect pixelFormat: format];
  231352. if (self != nil)
  231353. [[NSNotificationCenter defaultCenter] addObserver: self
  231354. selector: @selector (_surfaceNeedsUpdate:)
  231355. name: NSViewGlobalFrameDidChangeNotification
  231356. object: self];
  231357. return self;
  231358. }
  231359. - (void) dealloc
  231360. {
  231361. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231362. delete contextLock;
  231363. [super dealloc];
  231364. }
  231365. - (bool) makeActive
  231366. {
  231367. const ScopedLock sl (*contextLock);
  231368. if ([self openGLContext] == 0)
  231369. return false;
  231370. [[self openGLContext] makeCurrentContext];
  231371. if (needsUpdate)
  231372. {
  231373. [super update];
  231374. needsUpdate = false;
  231375. }
  231376. return true;
  231377. }
  231378. - (void) makeInactive
  231379. {
  231380. const ScopedLock sl (*contextLock);
  231381. [NSOpenGLContext clearCurrentContext];
  231382. }
  231383. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231384. {
  231385. const ScopedLock sl (*contextLock);
  231386. needsUpdate = true;
  231387. }
  231388. - (void) update
  231389. {
  231390. const ScopedLock sl (*contextLock);
  231391. needsUpdate = true;
  231392. }
  231393. - (void) reshape
  231394. {
  231395. const ScopedLock sl (*contextLock);
  231396. needsUpdate = true;
  231397. }
  231398. @end
  231399. BEGIN_JUCE_NAMESPACE
  231400. class WindowedGLContext : public OpenGLContext
  231401. {
  231402. public:
  231403. WindowedGLContext (Component* const component,
  231404. const OpenGLPixelFormat& pixelFormat_,
  231405. NSOpenGLContext* sharedContext)
  231406. : renderContext (0),
  231407. pixelFormat (pixelFormat_)
  231408. {
  231409. jassert (component != 0);
  231410. NSOpenGLPixelFormatAttribute attribs [64];
  231411. int n = 0;
  231412. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231413. attribs[n++] = NSOpenGLPFAAccelerated;
  231414. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231415. attribs[n++] = NSOpenGLPFAColorSize;
  231416. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231417. pixelFormat.greenBits,
  231418. pixelFormat.blueBits);
  231419. attribs[n++] = NSOpenGLPFAAlphaSize;
  231420. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231421. attribs[n++] = NSOpenGLPFADepthSize;
  231422. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231423. attribs[n++] = NSOpenGLPFAStencilSize;
  231424. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231425. attribs[n++] = NSOpenGLPFAAccumSize;
  231426. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231427. pixelFormat.accumulationBufferGreenBits,
  231428. pixelFormat.accumulationBufferBlueBits,
  231429. pixelFormat.accumulationBufferAlphaBits);
  231430. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231431. attribs[n++] = NSOpenGLPFASampleBuffers;
  231432. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231433. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231434. attribs[n++] = NSOpenGLPFANoRecovery;
  231435. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231436. NSOpenGLPixelFormat* format
  231437. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231438. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231439. pixelFormat: format];
  231440. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231441. shareContext: sharedContext] autorelease];
  231442. const GLint swapInterval = 1;
  231443. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231444. [view setOpenGLContext: renderContext];
  231445. [renderContext setView: view];
  231446. [format release];
  231447. viewHolder = new NSViewComponentInternal (view, component);
  231448. }
  231449. ~WindowedGLContext()
  231450. {
  231451. deleteContext();
  231452. viewHolder = 0;
  231453. }
  231454. void deleteContext()
  231455. {
  231456. makeInactive();
  231457. [renderContext clearDrawable];
  231458. [renderContext setView: nil];
  231459. [view setOpenGLContext: nil];
  231460. renderContext = nil;
  231461. }
  231462. bool makeActive() const throw()
  231463. {
  231464. jassert (renderContext != 0);
  231465. [view makeActive];
  231466. return isActive();
  231467. }
  231468. bool makeInactive() const throw()
  231469. {
  231470. [view makeInactive];
  231471. return true;
  231472. }
  231473. bool isActive() const throw()
  231474. {
  231475. return [NSOpenGLContext currentContext] == renderContext;
  231476. }
  231477. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231478. void* getRawContext() const throw() { return renderContext; }
  231479. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231480. {
  231481. }
  231482. void swapBuffers()
  231483. {
  231484. [renderContext flushBuffer];
  231485. }
  231486. bool setSwapInterval (const int numFramesPerSwap)
  231487. {
  231488. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231489. forParameter: NSOpenGLCPSwapInterval];
  231490. return true;
  231491. }
  231492. int getSwapInterval() const
  231493. {
  231494. GLint numFrames = 0;
  231495. [renderContext getValues: &numFrames
  231496. forParameter: NSOpenGLCPSwapInterval];
  231497. return numFrames;
  231498. }
  231499. void repaint()
  231500. {
  231501. // we need to invalidate the juce view that holds this gl view, to make it
  231502. // cause a repaint callback
  231503. NSView* v = (NSView*) viewHolder->view;
  231504. NSRect r = [v frame];
  231505. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231506. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231507. // repaint message, thus never causing our paint() callback, and never repainting
  231508. // the comp. So invalidating just a little bit around the edge helps..
  231509. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231510. }
  231511. void* getNativeWindowHandle() const { return viewHolder->view; }
  231512. juce_UseDebuggingNewOperator
  231513. NSOpenGLContext* renderContext;
  231514. ThreadSafeNSOpenGLView* view;
  231515. private:
  231516. OpenGLPixelFormat pixelFormat;
  231517. ScopedPointer <NSViewComponentInternal> viewHolder;
  231518. WindowedGLContext (const WindowedGLContext&);
  231519. WindowedGLContext& operator= (const WindowedGLContext&);
  231520. };
  231521. OpenGLContext* OpenGLComponent::createContext()
  231522. {
  231523. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231524. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231525. return (c->renderContext != 0) ? c.release() : 0;
  231526. }
  231527. void* OpenGLComponent::getNativeWindowHandle() const
  231528. {
  231529. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231530. : 0;
  231531. }
  231532. void juce_glViewport (const int w, const int h)
  231533. {
  231534. glViewport (0, 0, w, h);
  231535. }
  231536. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231537. OwnedArray <OpenGLPixelFormat>& results)
  231538. {
  231539. /* GLint attribs [64];
  231540. int n = 0;
  231541. attribs[n++] = AGL_RGBA;
  231542. attribs[n++] = AGL_DOUBLEBUFFER;
  231543. attribs[n++] = AGL_ACCELERATED;
  231544. attribs[n++] = AGL_NO_RECOVERY;
  231545. attribs[n++] = AGL_NONE;
  231546. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231547. while (p != 0)
  231548. {
  231549. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231550. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231551. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231552. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231553. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231554. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231555. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231556. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231557. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231558. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231559. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231560. results.add (pf);
  231561. p = aglNextPixelFormat (p);
  231562. }*/
  231563. //jassertfalse // can't see how you do this in cocoa!
  231564. }
  231565. #else
  231566. END_JUCE_NAMESPACE
  231567. @interface JuceGLView : UIView
  231568. {
  231569. }
  231570. + (Class) layerClass;
  231571. @end
  231572. @implementation JuceGLView
  231573. + (Class) layerClass
  231574. {
  231575. return [CAEAGLLayer class];
  231576. }
  231577. @end
  231578. BEGIN_JUCE_NAMESPACE
  231579. class GLESContext : public OpenGLContext
  231580. {
  231581. public:
  231582. GLESContext (UIViewComponentPeer* peer,
  231583. Component* const component_,
  231584. const OpenGLPixelFormat& pixelFormat_,
  231585. const GLESContext* const sharedContext,
  231586. NSUInteger apiType)
  231587. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231588. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231589. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231590. {
  231591. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231592. view.opaque = YES;
  231593. view.hidden = NO;
  231594. view.backgroundColor = [UIColor blackColor];
  231595. view.userInteractionEnabled = NO;
  231596. glLayer = (CAEAGLLayer*) [view layer];
  231597. [peer->view addSubview: view];
  231598. if (sharedContext != 0)
  231599. context = [[EAGLContext alloc] initWithAPI: apiType
  231600. sharegroup: [sharedContext->context sharegroup]];
  231601. else
  231602. context = [[EAGLContext alloc] initWithAPI: apiType];
  231603. createGLBuffers();
  231604. }
  231605. ~GLESContext()
  231606. {
  231607. deleteContext();
  231608. [view removeFromSuperview];
  231609. [view release];
  231610. freeGLBuffers();
  231611. }
  231612. void deleteContext()
  231613. {
  231614. makeInactive();
  231615. [context release];
  231616. context = nil;
  231617. }
  231618. bool makeActive() const throw()
  231619. {
  231620. jassert (context != 0);
  231621. [EAGLContext setCurrentContext: context];
  231622. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231623. return true;
  231624. }
  231625. void swapBuffers()
  231626. {
  231627. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231628. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231629. }
  231630. bool makeInactive() const throw()
  231631. {
  231632. return [EAGLContext setCurrentContext: nil];
  231633. }
  231634. bool isActive() const throw()
  231635. {
  231636. return [EAGLContext currentContext] == context;
  231637. }
  231638. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231639. void* getRawContext() const throw() { return glLayer; }
  231640. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231641. {
  231642. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231643. if (lastWidth != w || lastHeight != h)
  231644. {
  231645. lastWidth = w;
  231646. lastHeight = h;
  231647. freeGLBuffers();
  231648. createGLBuffers();
  231649. }
  231650. }
  231651. bool setSwapInterval (const int numFramesPerSwap)
  231652. {
  231653. numFrames = numFramesPerSwap;
  231654. return true;
  231655. }
  231656. int getSwapInterval() const
  231657. {
  231658. return numFrames;
  231659. }
  231660. void repaint()
  231661. {
  231662. }
  231663. void createGLBuffers()
  231664. {
  231665. makeActive();
  231666. glGenFramebuffersOES (1, &frameBufferHandle);
  231667. glGenRenderbuffersOES (1, &colorBufferHandle);
  231668. glGenRenderbuffersOES (1, &depthBufferHandle);
  231669. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231670. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231671. GLint width, height;
  231672. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231673. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231674. if (useDepthBuffer)
  231675. {
  231676. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231677. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231678. }
  231679. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231680. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231681. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231682. if (useDepthBuffer)
  231683. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231684. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231685. }
  231686. void freeGLBuffers()
  231687. {
  231688. if (frameBufferHandle != 0)
  231689. {
  231690. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231691. frameBufferHandle = 0;
  231692. }
  231693. if (colorBufferHandle != 0)
  231694. {
  231695. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231696. colorBufferHandle = 0;
  231697. }
  231698. if (depthBufferHandle != 0)
  231699. {
  231700. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231701. depthBufferHandle = 0;
  231702. }
  231703. }
  231704. juce_UseDebuggingNewOperator
  231705. private:
  231706. Component::SafePointer<Component> component;
  231707. OpenGLPixelFormat pixelFormat;
  231708. JuceGLView* view;
  231709. CAEAGLLayer* glLayer;
  231710. EAGLContext* context;
  231711. bool useDepthBuffer;
  231712. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231713. int numFrames;
  231714. int lastWidth, lastHeight;
  231715. GLESContext (const GLESContext&);
  231716. GLESContext& operator= (const GLESContext&);
  231717. };
  231718. OpenGLContext* OpenGLComponent::createContext()
  231719. {
  231720. ScopedAutoReleasePool pool;
  231721. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231722. if (peer != 0)
  231723. return new GLESContext (peer, this, preferredPixelFormat,
  231724. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231725. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231726. return 0;
  231727. }
  231728. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231729. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231730. {
  231731. }
  231732. void juce_glViewport (const int w, const int h)
  231733. {
  231734. glViewport (0, 0, w, h);
  231735. }
  231736. #endif
  231737. #endif
  231738. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231739. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231740. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231741. // compiled on its own).
  231742. #if JUCE_INCLUDED_FILE
  231743. class JuceMainMenuHandler;
  231744. END_JUCE_NAMESPACE
  231745. using namespace JUCE_NAMESPACE;
  231746. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231747. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231748. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231749. #else
  231750. @interface JuceMenuCallback : NSObject
  231751. #endif
  231752. {
  231753. JuceMainMenuHandler* owner;
  231754. }
  231755. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231756. - (void) dealloc;
  231757. - (void) menuItemInvoked: (id) menu;
  231758. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231759. @end
  231760. BEGIN_JUCE_NAMESPACE
  231761. class JuceMainMenuHandler : private MenuBarModel::Listener,
  231762. private DeletedAtShutdown
  231763. {
  231764. public:
  231765. static JuceMainMenuHandler* instance;
  231766. JuceMainMenuHandler()
  231767. : currentModel (0),
  231768. lastUpdateTime (0)
  231769. {
  231770. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231771. }
  231772. ~JuceMainMenuHandler()
  231773. {
  231774. setMenu (0);
  231775. jassert (instance == this);
  231776. instance = 0;
  231777. [callback release];
  231778. }
  231779. void setMenu (MenuBarModel* const newMenuBarModel)
  231780. {
  231781. if (currentModel != newMenuBarModel)
  231782. {
  231783. if (currentModel != 0)
  231784. currentModel->removeListener (this);
  231785. currentModel = newMenuBarModel;
  231786. if (currentModel != 0)
  231787. currentModel->addListener (this);
  231788. menuBarItemsChanged (0);
  231789. }
  231790. }
  231791. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231792. const String& name, const int menuId, const int tag)
  231793. {
  231794. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231795. action: nil
  231796. keyEquivalent: @""];
  231797. [item setTag: tag];
  231798. NSMenu* sub = createMenu (child, name, menuId, tag);
  231799. [parent setSubmenu: sub forItem: item];
  231800. [sub setAutoenablesItems: false];
  231801. [sub release];
  231802. }
  231803. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231804. const String& name, const int menuId, const int tag)
  231805. {
  231806. [parentItem setTag: tag];
  231807. NSMenu* menu = [parentItem submenu];
  231808. [menu setTitle: juceStringToNS (name)];
  231809. while ([menu numberOfItems] > 0)
  231810. [menu removeItemAtIndex: 0];
  231811. PopupMenu::MenuItemIterator iter (menuToCopy);
  231812. while (iter.next())
  231813. addMenuItem (iter, menu, menuId, tag);
  231814. [menu setAutoenablesItems: false];
  231815. [menu update];
  231816. }
  231817. void menuBarItemsChanged (MenuBarModel*)
  231818. {
  231819. lastUpdateTime = Time::getMillisecondCounter();
  231820. StringArray menuNames;
  231821. if (currentModel != 0)
  231822. menuNames = currentModel->getMenuBarNames();
  231823. NSMenu* menuBar = [NSApp mainMenu];
  231824. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231825. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231826. int menuId = 1;
  231827. for (int i = 0; i < menuNames.size(); ++i)
  231828. {
  231829. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231830. if (i >= [menuBar numberOfItems] - 1)
  231831. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231832. else
  231833. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231834. }
  231835. }
  231836. static void flashMenuBar (NSMenu* menu)
  231837. {
  231838. if ([[menu title] isEqualToString: @"Apple"])
  231839. return;
  231840. [menu retain];
  231841. const unichar f35Key = NSF35FunctionKey;
  231842. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231843. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231844. action: nil
  231845. keyEquivalent: f35String];
  231846. [item setTarget: nil];
  231847. [menu insertItem: item atIndex: [menu numberOfItems]];
  231848. [item release];
  231849. if ([menu indexOfItem: item] >= 0)
  231850. {
  231851. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231852. location: NSZeroPoint
  231853. modifierFlags: NSCommandKeyMask
  231854. timestamp: 0
  231855. windowNumber: 0
  231856. context: [NSGraphicsContext currentContext]
  231857. characters: f35String
  231858. charactersIgnoringModifiers: f35String
  231859. isARepeat: NO
  231860. keyCode: 0];
  231861. [menu performKeyEquivalent: f35Event];
  231862. if ([menu indexOfItem: item] >= 0)
  231863. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231864. }
  231865. [menu release];
  231866. }
  231867. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231868. {
  231869. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231870. {
  231871. NSMenuItem* m = [menu itemAtIndex: i];
  231872. if ([m tag] == info.commandID)
  231873. return m;
  231874. if ([m submenu] != 0)
  231875. {
  231876. NSMenuItem* found = findMenuItem ([m submenu], info);
  231877. if (found != 0)
  231878. return found;
  231879. }
  231880. }
  231881. return 0;
  231882. }
  231883. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231884. {
  231885. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231886. if (item != 0)
  231887. flashMenuBar ([item menu]);
  231888. }
  231889. void updateMenus()
  231890. {
  231891. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231892. menuBarItemsChanged (0);
  231893. }
  231894. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231895. {
  231896. if (currentModel != 0)
  231897. {
  231898. if (commandManager != 0)
  231899. {
  231900. ApplicationCommandTarget::InvocationInfo info (commandId);
  231901. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231902. commandManager->invoke (info, true);
  231903. }
  231904. currentModel->menuItemSelected (commandId, topLevelIndex);
  231905. }
  231906. }
  231907. MenuBarModel* currentModel;
  231908. uint32 lastUpdateTime;
  231909. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231910. const int topLevelMenuId, const int topLevelIndex)
  231911. {
  231912. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231913. if (text == 0)
  231914. text = @"";
  231915. if (iter.isSeparator)
  231916. {
  231917. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231918. }
  231919. else if (iter.isSectionHeader)
  231920. {
  231921. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231922. action: nil
  231923. keyEquivalent: @""];
  231924. [item setEnabled: false];
  231925. }
  231926. else if (iter.subMenu != 0)
  231927. {
  231928. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231929. action: nil
  231930. keyEquivalent: @""];
  231931. [item setTag: iter.itemId];
  231932. [item setEnabled: iter.isEnabled];
  231933. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231934. [sub setDelegate: nil];
  231935. [menuToAddTo setSubmenu: sub forItem: item];
  231936. [sub release];
  231937. }
  231938. else
  231939. {
  231940. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231941. action: @selector (menuItemInvoked:)
  231942. keyEquivalent: @""];
  231943. [item setTag: iter.itemId];
  231944. [item setEnabled: iter.isEnabled];
  231945. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231946. [item setTarget: (id) callback];
  231947. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231948. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231949. [item setRepresentedObject: info];
  231950. if (iter.commandManager != 0)
  231951. {
  231952. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  231953. ->getKeyPressesAssignedToCommand (iter.itemId));
  231954. if (keyPresses.size() > 0)
  231955. {
  231956. const KeyPress& kp = keyPresses.getReference(0);
  231957. if (kp.getKeyCode() != KeyPress::backspaceKey
  231958. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  231959. // every time you press the key while editing text)
  231960. {
  231961. juce_wchar key = kp.getTextCharacter();
  231962. if (kp.getKeyCode() == KeyPress::backspaceKey)
  231963. key = NSBackspaceCharacter;
  231964. else if (kp.getKeyCode() == KeyPress::deleteKey)
  231965. key = NSDeleteCharacter;
  231966. else if (key == 0)
  231967. key = (juce_wchar) kp.getKeyCode();
  231968. unsigned int mods = 0;
  231969. if (kp.getModifiers().isShiftDown())
  231970. mods |= NSShiftKeyMask;
  231971. if (kp.getModifiers().isCtrlDown())
  231972. mods |= NSControlKeyMask;
  231973. if (kp.getModifiers().isAltDown())
  231974. mods |= NSAlternateKeyMask;
  231975. if (kp.getModifiers().isCommandDown())
  231976. mods |= NSCommandKeyMask;
  231977. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  231978. [item setKeyEquivalentModifierMask: mods];
  231979. }
  231980. }
  231981. }
  231982. }
  231983. }
  231984. JuceMenuCallback* callback;
  231985. private:
  231986. NSMenu* createMenu (const PopupMenu menu,
  231987. const String& menuName,
  231988. const int topLevelMenuId,
  231989. const int topLevelIndex)
  231990. {
  231991. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  231992. [m setAutoenablesItems: false];
  231993. [m setDelegate: callback];
  231994. PopupMenu::MenuItemIterator iter (menu);
  231995. while (iter.next())
  231996. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  231997. [m update];
  231998. return m;
  231999. }
  232000. };
  232001. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232002. END_JUCE_NAMESPACE
  232003. @implementation JuceMenuCallback
  232004. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232005. {
  232006. [super init];
  232007. owner = owner_;
  232008. return self;
  232009. }
  232010. - (void) dealloc
  232011. {
  232012. [super dealloc];
  232013. }
  232014. - (void) menuItemInvoked: (id) menu
  232015. {
  232016. NSMenuItem* item = (NSMenuItem*) menu;
  232017. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232018. {
  232019. // 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
  232020. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232021. // into the focused component and let it trigger the menu item indirectly.
  232022. NSEvent* e = [NSApp currentEvent];
  232023. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232024. {
  232025. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232026. {
  232027. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232028. if (peer != 0)
  232029. {
  232030. if ([e type] == NSKeyDown)
  232031. peer->redirectKeyDown (e);
  232032. else
  232033. peer->redirectKeyUp (e);
  232034. return;
  232035. }
  232036. }
  232037. }
  232038. NSArray* info = (NSArray*) [item representedObject];
  232039. owner->invoke ((int) [item tag],
  232040. (ApplicationCommandManager*) (pointer_sized_int)
  232041. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232042. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232043. }
  232044. }
  232045. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232046. {
  232047. (void) menu;
  232048. if (JuceMainMenuHandler::instance != 0)
  232049. JuceMainMenuHandler::instance->updateMenus();
  232050. }
  232051. @end
  232052. BEGIN_JUCE_NAMESPACE
  232053. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  232054. const PopupMenu* extraItems)
  232055. {
  232056. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232057. {
  232058. PopupMenu::MenuItemIterator iter (*extraItems);
  232059. while (iter.next())
  232060. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232061. [menu addItem: [NSMenuItem separatorItem]];
  232062. }
  232063. NSMenuItem* item;
  232064. // Services...
  232065. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232066. action: nil keyEquivalent: @""];
  232067. [menu addItem: item];
  232068. [item release];
  232069. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232070. [menu setSubmenu: servicesMenu forItem: item];
  232071. [NSApp setServicesMenu: servicesMenu];
  232072. [servicesMenu release];
  232073. [menu addItem: [NSMenuItem separatorItem]];
  232074. // Hide + Show stuff...
  232075. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232076. action: @selector (hide:) keyEquivalent: @"h"];
  232077. [item setTarget: NSApp];
  232078. [menu addItem: item];
  232079. [item release];
  232080. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232081. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232082. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232083. [item setTarget: NSApp];
  232084. [menu addItem: item];
  232085. [item release];
  232086. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232087. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232088. [item setTarget: NSApp];
  232089. [menu addItem: item];
  232090. [item release];
  232091. [menu addItem: [NSMenuItem separatorItem]];
  232092. // Quit item....
  232093. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232094. action: @selector (terminate:) keyEquivalent: @"q"];
  232095. [item setTarget: NSApp];
  232096. [menu addItem: item];
  232097. [item release];
  232098. return menu;
  232099. }
  232100. // Since our app has no NIB, this initialises a standard app menu...
  232101. static void rebuildMainMenu (const PopupMenu* extraItems)
  232102. {
  232103. // this can't be used in a plugin!
  232104. jassert (JUCEApplication::isStandaloneApp());
  232105. if (JUCEApplication::getInstance() != 0)
  232106. {
  232107. const ScopedAutoReleasePool pool;
  232108. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232109. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232110. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232111. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232112. [mainMenu setSubmenu: appMenu forItem: item];
  232113. [NSApp setMainMenu: mainMenu];
  232114. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232115. [appMenu release];
  232116. [mainMenu release];
  232117. }
  232118. }
  232119. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232120. const PopupMenu* extraAppleMenuItems)
  232121. {
  232122. if (getMacMainMenu() != newMenuBarModel)
  232123. {
  232124. const ScopedAutoReleasePool pool;
  232125. if (newMenuBarModel == 0)
  232126. {
  232127. delete JuceMainMenuHandler::instance;
  232128. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232129. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232130. extraAppleMenuItems = 0;
  232131. }
  232132. else
  232133. {
  232134. if (JuceMainMenuHandler::instance == 0)
  232135. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232136. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232137. }
  232138. }
  232139. rebuildMainMenu (extraAppleMenuItems);
  232140. if (newMenuBarModel != 0)
  232141. newMenuBarModel->menuItemsChanged();
  232142. }
  232143. MenuBarModel* MenuBarModel::getMacMainMenu()
  232144. {
  232145. return JuceMainMenuHandler::instance != 0
  232146. ? JuceMainMenuHandler::instance->currentModel : 0;
  232147. }
  232148. void juce_initialiseMacMainMenu()
  232149. {
  232150. if (JuceMainMenuHandler::instance == 0)
  232151. rebuildMainMenu (0);
  232152. }
  232153. #endif
  232154. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232155. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232156. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232157. // compiled on its own).
  232158. #if JUCE_INCLUDED_FILE
  232159. #if JUCE_MAC
  232160. END_JUCE_NAMESPACE
  232161. using namespace JUCE_NAMESPACE;
  232162. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232163. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232164. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232165. #else
  232166. @interface JuceFileChooserDelegate : NSObject
  232167. #endif
  232168. {
  232169. StringArray* filters;
  232170. }
  232171. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232172. - (void) dealloc;
  232173. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232174. @end
  232175. @implementation JuceFileChooserDelegate
  232176. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232177. {
  232178. [super init];
  232179. filters = filters_;
  232180. return self;
  232181. }
  232182. - (void) dealloc
  232183. {
  232184. delete filters;
  232185. [super dealloc];
  232186. }
  232187. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232188. {
  232189. (void) sender;
  232190. const File f (nsStringToJuce (filename));
  232191. for (int i = filters->size(); --i >= 0;)
  232192. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232193. return true;
  232194. return f.isDirectory();
  232195. }
  232196. @end
  232197. BEGIN_JUCE_NAMESPACE
  232198. void FileChooser::showPlatformDialog (Array<File>& results,
  232199. const String& title,
  232200. const File& currentFileOrDirectory,
  232201. const String& filter,
  232202. bool selectsDirectory,
  232203. bool selectsFiles,
  232204. bool isSaveDialogue,
  232205. bool warnAboutOverwritingExistingFiles,
  232206. bool selectMultipleFiles,
  232207. FilePreviewComponent* extraInfoComponent)
  232208. {
  232209. const ScopedAutoReleasePool pool;
  232210. StringArray* filters = new StringArray();
  232211. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232212. filters->trim();
  232213. filters->removeEmptyStrings();
  232214. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232215. [delegate autorelease];
  232216. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232217. : [NSOpenPanel openPanel];
  232218. [panel setTitle: juceStringToNS (title)];
  232219. if (! isSaveDialogue)
  232220. {
  232221. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232222. [openPanel setCanChooseDirectories: selectsDirectory];
  232223. [openPanel setCanChooseFiles: selectsFiles];
  232224. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232225. }
  232226. [panel setDelegate: delegate];
  232227. if (isSaveDialogue || selectsDirectory)
  232228. [panel setCanCreateDirectories: YES];
  232229. String directory, filename;
  232230. if (currentFileOrDirectory.isDirectory())
  232231. {
  232232. directory = currentFileOrDirectory.getFullPathName();
  232233. }
  232234. else
  232235. {
  232236. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232237. filename = currentFileOrDirectory.getFileName();
  232238. }
  232239. if ([panel runModalForDirectory: juceStringToNS (directory)
  232240. file: juceStringToNS (filename)]
  232241. == NSOKButton)
  232242. {
  232243. if (isSaveDialogue)
  232244. {
  232245. results.add (File (nsStringToJuce ([panel filename])));
  232246. }
  232247. else
  232248. {
  232249. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232250. NSArray* urls = [openPanel filenames];
  232251. for (unsigned int i = 0; i < [urls count]; ++i)
  232252. {
  232253. NSString* f = [urls objectAtIndex: i];
  232254. results.add (File (nsStringToJuce (f)));
  232255. }
  232256. }
  232257. }
  232258. [panel setDelegate: nil];
  232259. }
  232260. #else
  232261. void FileChooser::showPlatformDialog (Array<File>& results,
  232262. const String& title,
  232263. const File& currentFileOrDirectory,
  232264. const String& filter,
  232265. bool selectsDirectory,
  232266. bool selectsFiles,
  232267. bool isSaveDialogue,
  232268. bool warnAboutOverwritingExistingFiles,
  232269. bool selectMultipleFiles,
  232270. FilePreviewComponent* extraInfoComponent)
  232271. {
  232272. const ScopedAutoReleasePool pool;
  232273. jassertfalse; //xxx to do
  232274. }
  232275. #endif
  232276. #endif
  232277. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232278. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232279. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232280. // compiled on its own).
  232281. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232282. END_JUCE_NAMESPACE
  232283. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232284. @interface NonInterceptingQTMovieView : QTMovieView
  232285. {
  232286. }
  232287. - (id) initWithFrame: (NSRect) frame;
  232288. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232289. - (NSView*) hitTest: (NSPoint) p;
  232290. @end
  232291. @implementation NonInterceptingQTMovieView
  232292. - (id) initWithFrame: (NSRect) frame
  232293. {
  232294. self = [super initWithFrame: frame];
  232295. [self setNextResponder: [self superview]];
  232296. return self;
  232297. }
  232298. - (void) dealloc
  232299. {
  232300. [super dealloc];
  232301. }
  232302. - (NSView*) hitTest: (NSPoint) point
  232303. {
  232304. return [self isControllerVisible] ? [super hitTest: point] : nil;
  232305. }
  232306. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  232307. {
  232308. return YES;
  232309. }
  232310. @end
  232311. BEGIN_JUCE_NAMESPACE
  232312. #define theMovie (static_cast <QTMovie*> (movie))
  232313. QuickTimeMovieComponent::QuickTimeMovieComponent()
  232314. : movie (0)
  232315. {
  232316. setOpaque (true);
  232317. setVisible (true);
  232318. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  232319. setView (view);
  232320. [view release];
  232321. }
  232322. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  232323. {
  232324. closeMovie();
  232325. setView (0);
  232326. }
  232327. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  232328. {
  232329. return true;
  232330. }
  232331. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  232332. {
  232333. // unfortunately, QTMovie objects can only be created on the main thread..
  232334. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232335. QTMovie* movie = 0;
  232336. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232337. if (fin != 0)
  232338. {
  232339. movieFile = fin->getFile();
  232340. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232341. error: nil];
  232342. }
  232343. else
  232344. {
  232345. MemoryBlock temp;
  232346. movieStream->readIntoMemoryBlock (temp);
  232347. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232348. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232349. {
  232350. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232351. length: temp.getSize()]
  232352. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232353. MIMEType: @""]
  232354. error: nil];
  232355. if (movie != 0)
  232356. break;
  232357. }
  232358. }
  232359. return movie;
  232360. }
  232361. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232362. const bool isControllerVisible_)
  232363. {
  232364. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232365. }
  232366. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232367. const bool controllerVisible_)
  232368. {
  232369. closeMovie();
  232370. if (getPeer() == 0)
  232371. {
  232372. // To open a movie, this component must be visible inside a functioning window, so that
  232373. // the QT control can be assigned to the window.
  232374. jassertfalse;
  232375. return false;
  232376. }
  232377. movie = openMovieFromStream (movieStream, movieFile);
  232378. [theMovie retain];
  232379. QTMovieView* view = (QTMovieView*) getView();
  232380. [view setMovie: theMovie];
  232381. [view setControllerVisible: controllerVisible_];
  232382. setLooping (looping);
  232383. return movie != nil;
  232384. }
  232385. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232386. const bool isControllerVisible_)
  232387. {
  232388. // unfortunately, QTMovie objects can only be created on the main thread..
  232389. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232390. closeMovie();
  232391. if (getPeer() == 0)
  232392. {
  232393. // To open a movie, this component must be visible inside a functioning window, so that
  232394. // the QT control can be assigned to the window.
  232395. jassertfalse;
  232396. return false;
  232397. }
  232398. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232399. NSError* err;
  232400. if ([QTMovie canInitWithURL: url])
  232401. movie = [QTMovie movieWithURL: url error: &err];
  232402. [theMovie retain];
  232403. QTMovieView* view = (QTMovieView*) getView();
  232404. [view setMovie: theMovie];
  232405. [view setControllerVisible: controllerVisible];
  232406. setLooping (looping);
  232407. return movie != nil;
  232408. }
  232409. void QuickTimeMovieComponent::closeMovie()
  232410. {
  232411. stop();
  232412. QTMovieView* view = (QTMovieView*) getView();
  232413. [view setMovie: nil];
  232414. [theMovie release];
  232415. movie = 0;
  232416. movieFile = File::nonexistent;
  232417. }
  232418. bool QuickTimeMovieComponent::isMovieOpen() const
  232419. {
  232420. return movie != nil;
  232421. }
  232422. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232423. {
  232424. return movieFile;
  232425. }
  232426. void QuickTimeMovieComponent::play()
  232427. {
  232428. [theMovie play];
  232429. }
  232430. void QuickTimeMovieComponent::stop()
  232431. {
  232432. [theMovie stop];
  232433. }
  232434. bool QuickTimeMovieComponent::isPlaying() const
  232435. {
  232436. return movie != 0 && [theMovie rate] != 0;
  232437. }
  232438. void QuickTimeMovieComponent::setPosition (const double seconds)
  232439. {
  232440. if (movie != 0)
  232441. {
  232442. QTTime t;
  232443. t.timeValue = (uint64) (100000.0 * seconds);
  232444. t.timeScale = 100000;
  232445. t.flags = 0;
  232446. [theMovie setCurrentTime: t];
  232447. }
  232448. }
  232449. double QuickTimeMovieComponent::getPosition() const
  232450. {
  232451. if (movie == 0)
  232452. return 0.0;
  232453. QTTime t = [theMovie currentTime];
  232454. return t.timeValue / (double) t.timeScale;
  232455. }
  232456. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232457. {
  232458. [theMovie setRate: newSpeed];
  232459. }
  232460. double QuickTimeMovieComponent::getMovieDuration() const
  232461. {
  232462. if (movie == 0)
  232463. return 0.0;
  232464. QTTime t = [theMovie duration];
  232465. return t.timeValue / (double) t.timeScale;
  232466. }
  232467. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232468. {
  232469. looping = shouldLoop;
  232470. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232471. forKey: QTMovieLoopsAttribute];
  232472. }
  232473. bool QuickTimeMovieComponent::isLooping() const
  232474. {
  232475. return looping;
  232476. }
  232477. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232478. {
  232479. [theMovie setVolume: newVolume];
  232480. }
  232481. float QuickTimeMovieComponent::getMovieVolume() const
  232482. {
  232483. return movie != 0 ? [theMovie volume] : 0.0f;
  232484. }
  232485. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232486. {
  232487. width = 0;
  232488. height = 0;
  232489. if (movie != 0)
  232490. {
  232491. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232492. width = (int) s.width;
  232493. height = (int) s.height;
  232494. }
  232495. }
  232496. void QuickTimeMovieComponent::paint (Graphics& g)
  232497. {
  232498. if (movie == 0)
  232499. g.fillAll (Colours::black);
  232500. }
  232501. bool QuickTimeMovieComponent::isControllerVisible() const
  232502. {
  232503. return controllerVisible;
  232504. }
  232505. void QuickTimeMovieComponent::goToStart()
  232506. {
  232507. setPosition (0.0);
  232508. }
  232509. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232510. const RectanglePlacement& placement)
  232511. {
  232512. int normalWidth, normalHeight;
  232513. getMovieNormalSize (normalWidth, normalHeight);
  232514. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232515. {
  232516. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232517. placement.applyTo (x, y, w, h,
  232518. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232519. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232520. if (w > 0 && h > 0)
  232521. {
  232522. setBounds (roundToInt (x), roundToInt (y),
  232523. roundToInt (w), roundToInt (h));
  232524. }
  232525. }
  232526. else
  232527. {
  232528. setBounds (spaceToFitWithin);
  232529. }
  232530. }
  232531. #if ! (JUCE_MAC && JUCE_64BIT)
  232532. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232533. {
  232534. if (movieStream == 0)
  232535. return false;
  232536. File file;
  232537. QTMovie* movie = openMovieFromStream (movieStream, file);
  232538. if (movie != nil)
  232539. result = [movie quickTimeMovie];
  232540. return movie != nil;
  232541. }
  232542. #endif
  232543. #endif
  232544. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232545. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232546. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232547. // compiled on its own).
  232548. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232549. const int kilobytesPerSecond1x = 176;
  232550. END_JUCE_NAMESPACE
  232551. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232552. @interface OpenDiskDevice : NSObject
  232553. {
  232554. @public
  232555. DRDevice* device;
  232556. NSMutableArray* tracks;
  232557. bool underrunProtection;
  232558. }
  232559. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232560. - (void) dealloc;
  232561. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232562. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232563. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232564. @end
  232565. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232566. @interface AudioTrackProducer : NSObject
  232567. {
  232568. JUCE_NAMESPACE::AudioSource* source;
  232569. int readPosition, lengthInFrames;
  232570. }
  232571. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232572. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232573. - (void) dealloc;
  232574. - (void) setupTrackProperties: (DRTrack*) track;
  232575. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232576. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232577. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232578. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232579. toMedia:(NSDictionary*)mediaInfo;
  232580. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232581. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232582. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232583. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232584. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232585. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232586. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232587. ioFlags:(uint32_t*)flags;
  232588. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232589. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232590. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232591. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232592. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232593. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232594. ioFlags:(uint32_t*)flags;
  232595. @end
  232596. @implementation OpenDiskDevice
  232597. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232598. {
  232599. [super init];
  232600. device = device_;
  232601. tracks = [[NSMutableArray alloc] init];
  232602. underrunProtection = true;
  232603. return self;
  232604. }
  232605. - (void) dealloc
  232606. {
  232607. [tracks release];
  232608. [super dealloc];
  232609. }
  232610. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232611. {
  232612. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232613. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232614. [p setupTrackProperties: t];
  232615. [tracks addObject: t];
  232616. [t release];
  232617. [p release];
  232618. }
  232619. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232620. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232621. {
  232622. DRBurn* burn = [DRBurn burnForDevice: device];
  232623. if (! [device acquireExclusiveAccess])
  232624. {
  232625. *error = "Couldn't open or write to the CD device";
  232626. return;
  232627. }
  232628. [device acquireMediaReservation];
  232629. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232630. [d autorelease];
  232631. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232632. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232633. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232634. if (burnSpeed > 0)
  232635. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232636. if (! underrunProtection)
  232637. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232638. [burn setProperties: d];
  232639. [burn writeLayout: tracks];
  232640. for (;;)
  232641. {
  232642. JUCE_NAMESPACE::Thread::sleep (300);
  232643. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232644. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232645. {
  232646. [burn abort];
  232647. *error = "User cancelled the write operation";
  232648. break;
  232649. }
  232650. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232651. {
  232652. *error = "Write operation failed";
  232653. break;
  232654. }
  232655. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232656. {
  232657. break;
  232658. }
  232659. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232660. objectForKey: DRErrorStatusErrorStringKey];
  232661. if ([err length] > 0)
  232662. {
  232663. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232664. break;
  232665. }
  232666. }
  232667. [device releaseMediaReservation];
  232668. [device releaseExclusiveAccess];
  232669. }
  232670. @end
  232671. @implementation AudioTrackProducer
  232672. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232673. {
  232674. lengthInFrames = lengthInFrames_;
  232675. readPosition = 0;
  232676. return self;
  232677. }
  232678. - (void) setupTrackProperties: (DRTrack*) track
  232679. {
  232680. NSMutableDictionary* p = [[track properties] mutableCopy];
  232681. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232682. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232683. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232684. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232685. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232686. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232687. [track setProperties: p];
  232688. [p release];
  232689. }
  232690. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232691. {
  232692. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232693. if (s != nil)
  232694. s->source = source_;
  232695. return s;
  232696. }
  232697. - (void) dealloc
  232698. {
  232699. if (source != 0)
  232700. {
  232701. source->releaseResources();
  232702. delete source;
  232703. }
  232704. [super dealloc];
  232705. }
  232706. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232707. {
  232708. }
  232709. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232710. {
  232711. return true;
  232712. }
  232713. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232714. {
  232715. return lengthInFrames;
  232716. }
  232717. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232718. toMedia: (NSDictionary*) mediaInfo
  232719. {
  232720. if (source != 0)
  232721. source->prepareToPlay (44100 / 75, 44100);
  232722. readPosition = 0;
  232723. return true;
  232724. }
  232725. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232726. {
  232727. if (source != 0)
  232728. source->prepareToPlay (44100 / 75, 44100);
  232729. return true;
  232730. }
  232731. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232732. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232733. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232734. {
  232735. if (source != 0)
  232736. {
  232737. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232738. if (numSamples > 0)
  232739. {
  232740. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232741. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232742. info.buffer = &tempBuffer;
  232743. info.startSample = 0;
  232744. info.numSamples = numSamples;
  232745. source->getNextAudioBlock (info);
  232746. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232747. buffer, numSamples, 4);
  232748. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232749. buffer + 2, numSamples, 4);
  232750. readPosition += numSamples;
  232751. }
  232752. return numSamples * 4;
  232753. }
  232754. return 0;
  232755. }
  232756. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232757. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232758. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232759. ioFlags: (uint32_t*) flags
  232760. {
  232761. zeromem (buffer, bufferLength);
  232762. return bufferLength;
  232763. }
  232764. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232765. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232766. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232767. {
  232768. return true;
  232769. }
  232770. @end
  232771. BEGIN_JUCE_NAMESPACE
  232772. class AudioCDBurner::Pimpl : public Timer
  232773. {
  232774. public:
  232775. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232776. : device (0), owner (owner_)
  232777. {
  232778. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232779. if (dev != 0)
  232780. {
  232781. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232782. lastState = getDiskState();
  232783. startTimer (1000);
  232784. }
  232785. }
  232786. ~Pimpl()
  232787. {
  232788. stopTimer();
  232789. [device release];
  232790. }
  232791. void timerCallback()
  232792. {
  232793. const DiskState state = getDiskState();
  232794. if (state != lastState)
  232795. {
  232796. lastState = state;
  232797. owner.sendChangeMessage (&owner);
  232798. }
  232799. }
  232800. DiskState getDiskState() const
  232801. {
  232802. if ([device->device isValid])
  232803. {
  232804. NSDictionary* status = [device->device status];
  232805. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232806. if ([state isEqualTo: DRDeviceMediaStateNone])
  232807. {
  232808. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232809. return trayOpen;
  232810. return noDisc;
  232811. }
  232812. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232813. {
  232814. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232815. return writableDiskPresent;
  232816. else
  232817. return readOnlyDiskPresent;
  232818. }
  232819. }
  232820. return unknown;
  232821. }
  232822. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232823. const Array<int> getAvailableWriteSpeeds() const
  232824. {
  232825. Array<int> results;
  232826. if ([device->device isValid])
  232827. {
  232828. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232829. for (unsigned int i = 0; i < [speeds count]; ++i)
  232830. {
  232831. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232832. results.add (kbPerSec / kilobytesPerSecond1x);
  232833. }
  232834. }
  232835. return results;
  232836. }
  232837. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232838. {
  232839. if ([device->device isValid])
  232840. {
  232841. device->underrunProtection = shouldBeEnabled;
  232842. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232843. }
  232844. return false;
  232845. }
  232846. int getNumAvailableAudioBlocks() const
  232847. {
  232848. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232849. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232850. }
  232851. OpenDiskDevice* device;
  232852. private:
  232853. DiskState lastState;
  232854. AudioCDBurner& owner;
  232855. };
  232856. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232857. {
  232858. pimpl = new Pimpl (*this, deviceIndex);
  232859. }
  232860. AudioCDBurner::~AudioCDBurner()
  232861. {
  232862. }
  232863. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232864. {
  232865. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232866. if (b->pimpl->device == 0)
  232867. b = 0;
  232868. return b.release();
  232869. }
  232870. static NSArray* findDiskBurnerDevices()
  232871. {
  232872. NSMutableArray* results = [NSMutableArray array];
  232873. NSArray* devs = [DRDevice devices];
  232874. if (devs != 0)
  232875. {
  232876. int num = [devs count];
  232877. int i;
  232878. for (i = 0; i < num; ++i)
  232879. {
  232880. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232881. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232882. if (name != nil)
  232883. [results addObject: name];
  232884. }
  232885. }
  232886. return results;
  232887. }
  232888. const StringArray AudioCDBurner::findAvailableDevices()
  232889. {
  232890. NSArray* names = findDiskBurnerDevices();
  232891. StringArray s;
  232892. for (unsigned int i = 0; i < [names count]; ++i)
  232893. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232894. return s;
  232895. }
  232896. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232897. {
  232898. return pimpl->getDiskState();
  232899. }
  232900. bool AudioCDBurner::isDiskPresent() const
  232901. {
  232902. return getDiskState() == writableDiskPresent;
  232903. }
  232904. bool AudioCDBurner::openTray()
  232905. {
  232906. return pimpl->openTray();
  232907. }
  232908. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232909. {
  232910. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232911. DiskState oldState = getDiskState();
  232912. DiskState newState = oldState;
  232913. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232914. {
  232915. newState = getDiskState();
  232916. Thread::sleep (100);
  232917. }
  232918. return newState;
  232919. }
  232920. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232921. {
  232922. return pimpl->getAvailableWriteSpeeds();
  232923. }
  232924. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232925. {
  232926. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232927. }
  232928. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232929. {
  232930. return pimpl->getNumAvailableAudioBlocks();
  232931. }
  232932. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232933. {
  232934. if ([pimpl->device->device isValid])
  232935. {
  232936. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232937. return true;
  232938. }
  232939. return false;
  232940. }
  232941. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232942. bool ejectDiscAfterwards,
  232943. bool performFakeBurnForTesting,
  232944. int writeSpeed)
  232945. {
  232946. String error ("Couldn't open or write to the CD device");
  232947. if ([pimpl->device->device isValid])
  232948. {
  232949. error = String::empty;
  232950. [pimpl->device burn: listener
  232951. errorString: &error
  232952. ejectAfterwards: ejectDiscAfterwards
  232953. isFake: performFakeBurnForTesting
  232954. speed: writeSpeed];
  232955. }
  232956. return error;
  232957. }
  232958. #endif
  232959. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232960. void AudioCDReader::ejectDisk()
  232961. {
  232962. const ScopedAutoReleasePool p;
  232963. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  232964. }
  232965. #endif
  232966. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  232967. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  232968. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232969. // compiled on its own).
  232970. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232971. namespace CDReaderHelpers
  232972. {
  232973. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  232974. {
  232975. forEachXmlChildElementWithTagName (xml, child, "key")
  232976. if (child->getAllSubText() == key)
  232977. return child->getNextElement();
  232978. return 0;
  232979. }
  232980. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  232981. {
  232982. const XmlElement* const block = getElementForKey (xml, key);
  232983. return block != 0 ? block->getAllSubText().getIntValue() : defaultValue;
  232984. }
  232985. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  232986. // Returns NULL on success, otherwise a const char* representing an error.
  232987. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  232988. {
  232989. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  232990. if (xml == 0)
  232991. return "Couldn't parse XML in file";
  232992. const XmlElement* const dict = xml->getChildByName ("dict");
  232993. if (dict == 0)
  232994. return "Couldn't get top level dictionary";
  232995. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  232996. if (sessions == 0)
  232997. return "Couldn't find sessions key";
  232998. const XmlElement* const session = sessions->getFirstChildElement();
  232999. if (session == 0)
  233000. return "Couldn't find first session";
  233001. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233002. if (leadOut < 0)
  233003. return "Couldn't find Leadout Block";
  233004. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233005. if (trackArray == 0)
  233006. return "Couldn't find Track Array";
  233007. forEachXmlChildElement (*trackArray, track)
  233008. {
  233009. const int trackValue = getIntValueForKey (*track, "Start Block");
  233010. if (trackValue < 0)
  233011. return "Couldn't find Start Block in the track";
  233012. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233013. }
  233014. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233015. return 0;
  233016. }
  233017. static void findDevices (Array<File>& cds)
  233018. {
  233019. File volumes ("/Volumes");
  233020. volumes.findChildFiles (cds, File::findDirectories, false);
  233021. for (int i = cds.size(); --i >= 0;)
  233022. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233023. cds.remove (i);
  233024. }
  233025. struct TrackSorter
  233026. {
  233027. static int getCDTrackNumber (const File& file)
  233028. {
  233029. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233030. }
  233031. static int compareElements (const File& first, const File& second)
  233032. {
  233033. const int firstTrack = getCDTrackNumber (first);
  233034. const int secondTrack = getCDTrackNumber (second);
  233035. jassert (firstTrack > 0 && secondTrack > 0);
  233036. return firstTrack - secondTrack;
  233037. }
  233038. };
  233039. }
  233040. const StringArray AudioCDReader::getAvailableCDNames()
  233041. {
  233042. Array<File> cds;
  233043. CDReaderHelpers::findDevices (cds);
  233044. StringArray names;
  233045. for (int i = 0; i < cds.size(); ++i)
  233046. names.add (cds.getReference(i).getFileName());
  233047. return names;
  233048. }
  233049. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233050. {
  233051. Array<File> cds;
  233052. CDReaderHelpers::findDevices (cds);
  233053. if (cds[index].exists())
  233054. return new AudioCDReader (cds[index]);
  233055. return 0;
  233056. }
  233057. AudioCDReader::AudioCDReader (const File& volume)
  233058. : AudioFormatReader (0, "CD Audio"),
  233059. volumeDir (volume),
  233060. currentReaderTrack (-1),
  233061. reader (0)
  233062. {
  233063. sampleRate = 44100.0;
  233064. bitsPerSample = 16;
  233065. numChannels = 2;
  233066. usesFloatingPointData = false;
  233067. refreshTrackLengths();
  233068. }
  233069. AudioCDReader::~AudioCDReader()
  233070. {
  233071. }
  233072. void AudioCDReader::refreshTrackLengths()
  233073. {
  233074. tracks.clear();
  233075. trackStartSamples.clear();
  233076. lengthInSamples = 0;
  233077. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233078. CDReaderHelpers::TrackSorter sorter;
  233079. tracks.sort (sorter);
  233080. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233081. if (toc.exists())
  233082. {
  233083. XmlDocument doc (toc);
  233084. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233085. (void) error; // could be logged..
  233086. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  233087. }
  233088. }
  233089. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233090. int64 startSampleInFile, int numSamples)
  233091. {
  233092. while (numSamples > 0)
  233093. {
  233094. int track = -1;
  233095. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233096. {
  233097. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233098. {
  233099. track = i;
  233100. break;
  233101. }
  233102. }
  233103. if (track < 0)
  233104. return false;
  233105. if (track != currentReaderTrack)
  233106. {
  233107. reader = 0;
  233108. FileInputStream* const in = tracks [track].createInputStream();
  233109. if (in != 0)
  233110. {
  233111. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233112. AiffAudioFormat format;
  233113. reader = format.createReaderFor (bin, true);
  233114. if (reader == 0)
  233115. currentReaderTrack = -1;
  233116. else
  233117. currentReaderTrack = track;
  233118. }
  233119. }
  233120. if (reader == 0)
  233121. return false;
  233122. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233123. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233124. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233125. numSamples -= numAvailable;
  233126. startSampleInFile += numAvailable;
  233127. }
  233128. return true;
  233129. }
  233130. bool AudioCDReader::isCDStillPresent() const
  233131. {
  233132. return volumeDir.exists();
  233133. }
  233134. bool AudioCDReader::isTrackAudio (int trackNum) const
  233135. {
  233136. return tracks [trackNum].hasFileExtension (".aiff");
  233137. }
  233138. void AudioCDReader::enableIndexScanning (bool b)
  233139. {
  233140. // any way to do this on a Mac??
  233141. }
  233142. int AudioCDReader::getLastIndex() const
  233143. {
  233144. return 0;
  233145. }
  233146. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  233147. {
  233148. return Array <int>();
  233149. }
  233150. #endif
  233151. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233152. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233153. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233154. // compiled on its own).
  233155. #if JUCE_INCLUDED_FILE
  233156. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233157. for example having more than one juce plugin loaded into a host, then when a
  233158. method is called, the actual code that runs might actually be in a different module
  233159. than the one you expect... So any calls to library functions or statics that are
  233160. made inside obj-c methods will probably end up getting executed in a different DLL's
  233161. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233162. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233163. virtual methods of an object that's known to live inside the right module's space.
  233164. */
  233165. class AppDelegateRedirector
  233166. {
  233167. public:
  233168. AppDelegateRedirector()
  233169. {
  233170. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  233171. runLoop = CFRunLoopGetMain();
  233172. #else
  233173. runLoop = CFRunLoopGetCurrent();
  233174. #endif
  233175. CFRunLoopSourceContext sourceContext;
  233176. zerostruct (sourceContext);
  233177. sourceContext.info = this;
  233178. sourceContext.perform = runLoopSourceCallback;
  233179. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  233180. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233181. }
  233182. virtual ~AppDelegateRedirector()
  233183. {
  233184. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233185. CFRunLoopSourceInvalidate (runLoopSource);
  233186. CFRelease (runLoopSource);
  233187. }
  233188. virtual NSApplicationTerminateReply shouldTerminate()
  233189. {
  233190. if (JUCEApplication::getInstance() != 0)
  233191. {
  233192. JUCEApplication::getInstance()->systemRequestedQuit();
  233193. return NSTerminateCancel;
  233194. }
  233195. return NSTerminateNow;
  233196. }
  233197. virtual BOOL openFile (const NSString* filename)
  233198. {
  233199. if (JUCEApplication::getInstance() != 0)
  233200. {
  233201. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  233202. return YES;
  233203. }
  233204. return NO;
  233205. }
  233206. virtual void openFiles (NSArray* filenames)
  233207. {
  233208. StringArray files;
  233209. for (unsigned int i = 0; i < [filenames count]; ++i)
  233210. {
  233211. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  233212. if (filename.containsChar (' '))
  233213. filename = filename.quoted('"');
  233214. files.add (filename);
  233215. }
  233216. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233217. {
  233218. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233219. }
  233220. }
  233221. virtual void focusChanged()
  233222. {
  233223. juce_HandleProcessFocusChange();
  233224. }
  233225. struct CallbackMessagePayload
  233226. {
  233227. MessageCallbackFunction* function;
  233228. void* parameter;
  233229. void* volatile result;
  233230. bool volatile hasBeenExecuted;
  233231. };
  233232. virtual void performCallback (CallbackMessagePayload* pl)
  233233. {
  233234. pl->result = (*pl->function) (pl->parameter);
  233235. pl->hasBeenExecuted = true;
  233236. }
  233237. virtual void deleteSelf()
  233238. {
  233239. delete this;
  233240. }
  233241. void postMessage (Message* const m)
  233242. {
  233243. messages.add (m);
  233244. CFRunLoopSourceSignal (runLoopSource);
  233245. CFRunLoopWakeUp (runLoop);
  233246. }
  233247. private:
  233248. CFRunLoopRef runLoop;
  233249. CFRunLoopSourceRef runLoopSource;
  233250. OwnedArray <Message, CriticalSection> messages;
  233251. void runLoopCallback()
  233252. {
  233253. int numDispatched = 0;
  233254. do
  233255. {
  233256. Message* const nextMessage = messages.removeAndReturn (0);
  233257. if (nextMessage == 0)
  233258. return;
  233259. const ScopedAutoReleasePool pool;
  233260. MessageManager::getInstance()->deliverMessage (nextMessage);
  233261. } while (++numDispatched <= 4);
  233262. CFRunLoopSourceSignal (runLoopSource);
  233263. CFRunLoopWakeUp (runLoop);
  233264. }
  233265. static void runLoopSourceCallback (void* info)
  233266. {
  233267. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  233268. }
  233269. };
  233270. END_JUCE_NAMESPACE
  233271. using namespace JUCE_NAMESPACE;
  233272. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  233273. @interface JuceAppDelegate : NSObject
  233274. {
  233275. @private
  233276. id oldDelegate;
  233277. @public
  233278. AppDelegateRedirector* redirector;
  233279. }
  233280. - (JuceAppDelegate*) init;
  233281. - (void) dealloc;
  233282. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  233283. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  233284. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  233285. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  233286. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  233287. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  233288. - (void) performCallback: (id) info;
  233289. - (void) dummyMethod;
  233290. @end
  233291. @implementation JuceAppDelegate
  233292. - (JuceAppDelegate*) init
  233293. {
  233294. [super init];
  233295. redirector = new AppDelegateRedirector();
  233296. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  233297. if (JUCEApplication::isStandaloneApp())
  233298. {
  233299. oldDelegate = [NSApp delegate];
  233300. [NSApp setDelegate: self];
  233301. }
  233302. else
  233303. {
  233304. oldDelegate = 0;
  233305. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233306. name: NSApplicationDidResignActiveNotification object: NSApp];
  233307. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233308. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233309. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233310. name: NSApplicationWillUnhideNotification object: NSApp];
  233311. }
  233312. return self;
  233313. }
  233314. - (void) dealloc
  233315. {
  233316. if (oldDelegate != 0)
  233317. [NSApp setDelegate: oldDelegate];
  233318. redirector->deleteSelf();
  233319. [super dealloc];
  233320. }
  233321. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233322. {
  233323. (void) app;
  233324. return redirector->shouldTerminate();
  233325. }
  233326. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  233327. {
  233328. (void) app;
  233329. return redirector->openFile (filename);
  233330. }
  233331. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  233332. {
  233333. (void) sender;
  233334. return redirector->openFiles (filenames);
  233335. }
  233336. - (void) applicationDidBecomeActive: (NSNotification*) notification
  233337. {
  233338. (void) notification;
  233339. redirector->focusChanged();
  233340. }
  233341. - (void) applicationDidResignActive: (NSNotification*) notification
  233342. {
  233343. (void) notification;
  233344. redirector->focusChanged();
  233345. }
  233346. - (void) applicationWillUnhide: (NSNotification*) notification
  233347. {
  233348. (void) notification;
  233349. redirector->focusChanged();
  233350. }
  233351. - (void) performCallback: (id) info
  233352. {
  233353. if ([info isKindOfClass: [NSData class]])
  233354. {
  233355. AppDelegateRedirector::CallbackMessagePayload* pl
  233356. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  233357. if (pl != 0)
  233358. redirector->performCallback (pl);
  233359. }
  233360. else
  233361. {
  233362. jassertfalse; // should never get here!
  233363. }
  233364. }
  233365. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233366. @end
  233367. BEGIN_JUCE_NAMESPACE
  233368. static JuceAppDelegate* juceAppDelegate = 0;
  233369. void MessageManager::runDispatchLoop()
  233370. {
  233371. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233372. {
  233373. const ScopedAutoReleasePool pool;
  233374. // must only be called by the message thread!
  233375. jassert (isThisTheMessageThread());
  233376. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233377. @try
  233378. {
  233379. [NSApp run];
  233380. }
  233381. @catch (NSException* e)
  233382. {
  233383. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233384. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233385. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233386. }
  233387. @finally
  233388. {
  233389. }
  233390. #else
  233391. [NSApp run];
  233392. #endif
  233393. }
  233394. }
  233395. void MessageManager::stopDispatchLoop()
  233396. {
  233397. quitMessagePosted = true;
  233398. [NSApp stop: nil];
  233399. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233400. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233401. }
  233402. static bool isEventBlockedByModalComps (NSEvent* e)
  233403. {
  233404. if (Component::getNumCurrentlyModalComponents() == 0)
  233405. return false;
  233406. NSWindow* const w = [e window];
  233407. if (w == 0 || [w worksWhenModal])
  233408. return false;
  233409. bool isKey = false, isInputAttempt = false;
  233410. switch ([e type])
  233411. {
  233412. case NSKeyDown:
  233413. case NSKeyUp:
  233414. isKey = isInputAttempt = true;
  233415. break;
  233416. case NSLeftMouseDown:
  233417. case NSRightMouseDown:
  233418. case NSOtherMouseDown:
  233419. isInputAttempt = true;
  233420. break;
  233421. case NSLeftMouseDragged:
  233422. case NSRightMouseDragged:
  233423. case NSLeftMouseUp:
  233424. case NSRightMouseUp:
  233425. case NSOtherMouseUp:
  233426. case NSOtherMouseDragged:
  233427. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233428. return false;
  233429. break;
  233430. case NSMouseMoved:
  233431. case NSMouseEntered:
  233432. case NSMouseExited:
  233433. case NSCursorUpdate:
  233434. case NSScrollWheel:
  233435. case NSTabletPoint:
  233436. case NSTabletProximity:
  233437. break;
  233438. default:
  233439. return false;
  233440. }
  233441. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233442. {
  233443. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233444. NSView* const compView = (NSView*) peer->getNativeHandle();
  233445. if ([compView window] == w)
  233446. {
  233447. if (isKey)
  233448. {
  233449. if (compView == [w firstResponder])
  233450. return false;
  233451. }
  233452. else
  233453. {
  233454. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233455. [compView bounds]))
  233456. return false;
  233457. }
  233458. }
  233459. }
  233460. if (isInputAttempt)
  233461. {
  233462. if (! [NSApp isActive])
  233463. [NSApp activateIgnoringOtherApps: YES];
  233464. Component* const modal = Component::getCurrentlyModalComponent (0);
  233465. if (modal != 0)
  233466. modal->inputAttemptWhenModal();
  233467. }
  233468. return true;
  233469. }
  233470. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233471. {
  233472. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233473. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233474. while (! quitMessagePosted)
  233475. {
  233476. const ScopedAutoReleasePool pool;
  233477. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233478. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233479. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233480. inMode: NSDefaultRunLoopMode
  233481. dequeue: YES];
  233482. if (e != 0 && ! isEventBlockedByModalComps (e))
  233483. [NSApp sendEvent: e];
  233484. if (Time::getMillisecondCounter() >= endTime)
  233485. break;
  233486. }
  233487. return ! quitMessagePosted;
  233488. }
  233489. void MessageManager::doPlatformSpecificInitialisation()
  233490. {
  233491. if (juceAppDelegate == 0)
  233492. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233493. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233494. // correctly (needed prior to 10.5)
  233495. if (! [NSThread isMultiThreaded])
  233496. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233497. toTarget: juceAppDelegate
  233498. withObject: nil];
  233499. }
  233500. void MessageManager::doPlatformSpecificShutdown()
  233501. {
  233502. if (juceAppDelegate != 0)
  233503. {
  233504. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233505. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233506. [juceAppDelegate release];
  233507. juceAppDelegate = 0;
  233508. }
  233509. }
  233510. bool juce_postMessageToSystemQueue (Message* message)
  233511. {
  233512. juceAppDelegate->redirector->postMessage (message);
  233513. return true;
  233514. }
  233515. void MessageManager::broadcastMessage (const String& value) throw()
  233516. {
  233517. }
  233518. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  233519. {
  233520. if (isThisTheMessageThread())
  233521. {
  233522. return (*callback) (data);
  233523. }
  233524. else
  233525. {
  233526. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233527. // deadlock because the message manager is blocked from running, so can never
  233528. // call your function..
  233529. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233530. const ScopedAutoReleasePool pool;
  233531. AppDelegateRedirector::CallbackMessagePayload cmp;
  233532. cmp.function = callback;
  233533. cmp.parameter = data;
  233534. cmp.result = 0;
  233535. cmp.hasBeenExecuted = false;
  233536. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233537. withObject: [NSData dataWithBytesNoCopy: &cmp
  233538. length: sizeof (cmp)
  233539. freeWhenDone: NO]
  233540. waitUntilDone: YES];
  233541. return cmp.result;
  233542. }
  233543. }
  233544. #endif
  233545. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233546. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233547. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233548. // compiled on its own).
  233549. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233550. #if JUCE_MAC
  233551. END_JUCE_NAMESPACE
  233552. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233553. @interface DownloadClickDetector : NSObject
  233554. {
  233555. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233556. }
  233557. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233558. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233559. request: (NSURLRequest*) request
  233560. frame: (WebFrame*) frame
  233561. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233562. @end
  233563. @implementation DownloadClickDetector
  233564. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233565. {
  233566. [super init];
  233567. ownerComponent = ownerComponent_;
  233568. return self;
  233569. }
  233570. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233571. request: (NSURLRequest*) request
  233572. frame: (WebFrame*) frame
  233573. decisionListener: (id <WebPolicyDecisionListener>) listener
  233574. {
  233575. (void) sender;
  233576. (void) request;
  233577. (void) frame;
  233578. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233579. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233580. [listener use];
  233581. else
  233582. [listener ignore];
  233583. }
  233584. @end
  233585. BEGIN_JUCE_NAMESPACE
  233586. class WebBrowserComponentInternal : public NSViewComponent
  233587. {
  233588. public:
  233589. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233590. {
  233591. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233592. frameName: @""
  233593. groupName: @""];
  233594. setView (webView);
  233595. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233596. [webView setPolicyDelegate: clickListener];
  233597. }
  233598. ~WebBrowserComponentInternal()
  233599. {
  233600. [webView setPolicyDelegate: nil];
  233601. [clickListener release];
  233602. setView (0);
  233603. }
  233604. void goToURL (const String& url,
  233605. const StringArray* headers,
  233606. const MemoryBlock* postData)
  233607. {
  233608. NSMutableURLRequest* r
  233609. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233610. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233611. timeoutInterval: 30.0];
  233612. if (postData != 0 && postData->getSize() > 0)
  233613. {
  233614. [r setHTTPMethod: @"POST"];
  233615. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233616. length: postData->getSize()]];
  233617. }
  233618. if (headers != 0)
  233619. {
  233620. for (int i = 0; i < headers->size(); ++i)
  233621. {
  233622. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233623. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233624. [r setValue: juceStringToNS (headerValue)
  233625. forHTTPHeaderField: juceStringToNS (headerName)];
  233626. }
  233627. }
  233628. stop();
  233629. [[webView mainFrame] loadRequest: r];
  233630. }
  233631. void goBack()
  233632. {
  233633. [webView goBack];
  233634. }
  233635. void goForward()
  233636. {
  233637. [webView goForward];
  233638. }
  233639. void stop()
  233640. {
  233641. [webView stopLoading: nil];
  233642. }
  233643. void refresh()
  233644. {
  233645. [webView reload: nil];
  233646. }
  233647. private:
  233648. WebView* webView;
  233649. DownloadClickDetector* clickListener;
  233650. };
  233651. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233652. : browser (0),
  233653. blankPageShown (false),
  233654. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233655. {
  233656. setOpaque (true);
  233657. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233658. }
  233659. WebBrowserComponent::~WebBrowserComponent()
  233660. {
  233661. deleteAndZero (browser);
  233662. }
  233663. void WebBrowserComponent::goToURL (const String& url,
  233664. const StringArray* headers,
  233665. const MemoryBlock* postData)
  233666. {
  233667. lastURL = url;
  233668. lastHeaders.clear();
  233669. if (headers != 0)
  233670. lastHeaders = *headers;
  233671. lastPostData.setSize (0);
  233672. if (postData != 0)
  233673. lastPostData = *postData;
  233674. blankPageShown = false;
  233675. browser->goToURL (url, headers, postData);
  233676. }
  233677. void WebBrowserComponent::stop()
  233678. {
  233679. browser->stop();
  233680. }
  233681. void WebBrowserComponent::goBack()
  233682. {
  233683. lastURL = String::empty;
  233684. blankPageShown = false;
  233685. browser->goBack();
  233686. }
  233687. void WebBrowserComponent::goForward()
  233688. {
  233689. lastURL = String::empty;
  233690. browser->goForward();
  233691. }
  233692. void WebBrowserComponent::refresh()
  233693. {
  233694. browser->refresh();
  233695. }
  233696. void WebBrowserComponent::paint (Graphics&)
  233697. {
  233698. }
  233699. void WebBrowserComponent::checkWindowAssociation()
  233700. {
  233701. if (isShowing())
  233702. {
  233703. if (blankPageShown)
  233704. goBack();
  233705. }
  233706. else
  233707. {
  233708. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233709. {
  233710. // when the component becomes invisible, some stuff like flash
  233711. // carries on playing audio, so we need to force it onto a blank
  233712. // page to avoid this, (and send it back when it's made visible again).
  233713. blankPageShown = true;
  233714. browser->goToURL ("about:blank", 0, 0);
  233715. }
  233716. }
  233717. }
  233718. void WebBrowserComponent::reloadLastURL()
  233719. {
  233720. if (lastURL.isNotEmpty())
  233721. {
  233722. goToURL (lastURL, &lastHeaders, &lastPostData);
  233723. lastURL = String::empty;
  233724. }
  233725. }
  233726. void WebBrowserComponent::parentHierarchyChanged()
  233727. {
  233728. checkWindowAssociation();
  233729. }
  233730. void WebBrowserComponent::resized()
  233731. {
  233732. browser->setSize (getWidth(), getHeight());
  233733. }
  233734. void WebBrowserComponent::visibilityChanged()
  233735. {
  233736. checkWindowAssociation();
  233737. }
  233738. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233739. {
  233740. return true;
  233741. }
  233742. #else
  233743. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233744. {
  233745. }
  233746. WebBrowserComponent::~WebBrowserComponent()
  233747. {
  233748. }
  233749. void WebBrowserComponent::goToURL (const String& url,
  233750. const StringArray* headers,
  233751. const MemoryBlock* postData)
  233752. {
  233753. }
  233754. void WebBrowserComponent::stop()
  233755. {
  233756. }
  233757. void WebBrowserComponent::goBack()
  233758. {
  233759. }
  233760. void WebBrowserComponent::goForward()
  233761. {
  233762. }
  233763. void WebBrowserComponent::refresh()
  233764. {
  233765. }
  233766. void WebBrowserComponent::paint (Graphics& g)
  233767. {
  233768. }
  233769. void WebBrowserComponent::checkWindowAssociation()
  233770. {
  233771. }
  233772. void WebBrowserComponent::reloadLastURL()
  233773. {
  233774. }
  233775. void WebBrowserComponent::parentHierarchyChanged()
  233776. {
  233777. }
  233778. void WebBrowserComponent::resized()
  233779. {
  233780. }
  233781. void WebBrowserComponent::visibilityChanged()
  233782. {
  233783. }
  233784. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233785. {
  233786. return true;
  233787. }
  233788. #endif
  233789. #endif
  233790. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233791. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233792. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233793. // compiled on its own).
  233794. #if JUCE_INCLUDED_FILE
  233795. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233796. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233797. #endif
  233798. #undef log
  233799. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233800. #define log(a) Logger::writeToLog (a)
  233801. #else
  233802. #define log(a)
  233803. #endif
  233804. #undef OK
  233805. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233806. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233807. {
  233808. if (err == noErr)
  233809. return true;
  233810. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233811. jassertfalse;
  233812. return false;
  233813. }
  233814. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233815. #else
  233816. #define OK(a) (a == noErr)
  233817. #endif
  233818. class CoreAudioInternal : public Timer
  233819. {
  233820. public:
  233821. CoreAudioInternal (AudioDeviceID id)
  233822. : inputLatency (0),
  233823. outputLatency (0),
  233824. callback (0),
  233825. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233826. audioProcID (0),
  233827. #endif
  233828. isSlaveDevice (false),
  233829. deviceID (id),
  233830. started (false),
  233831. sampleRate (0),
  233832. bufferSize (512),
  233833. numInputChans (0),
  233834. numOutputChans (0),
  233835. callbacksAllowed (true),
  233836. numInputChannelInfos (0),
  233837. numOutputChannelInfos (0)
  233838. {
  233839. jassert (deviceID != 0);
  233840. updateDetailsFromDevice();
  233841. AudioObjectPropertyAddress pa;
  233842. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233843. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233844. pa.mElement = kAudioObjectPropertyElementWildcard;
  233845. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233846. }
  233847. ~CoreAudioInternal()
  233848. {
  233849. AudioObjectPropertyAddress pa;
  233850. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233851. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233852. pa.mElement = kAudioObjectPropertyElementWildcard;
  233853. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233854. stop (false);
  233855. }
  233856. void allocateTempBuffers()
  233857. {
  233858. const int tempBufSize = bufferSize + 4;
  233859. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233860. tempInputBuffers.calloc (numInputChans + 2);
  233861. tempOutputBuffers.calloc (numOutputChans + 2);
  233862. int i, count = 0;
  233863. for (i = 0; i < numInputChans; ++i)
  233864. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233865. for (i = 0; i < numOutputChans; ++i)
  233866. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233867. }
  233868. // returns the number of actual available channels
  233869. void fillInChannelInfo (const bool input)
  233870. {
  233871. int chanNum = 0;
  233872. UInt32 size;
  233873. AudioObjectPropertyAddress pa;
  233874. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233875. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233876. pa.mElement = kAudioObjectPropertyElementMaster;
  233877. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233878. {
  233879. HeapBlock <AudioBufferList> bufList;
  233880. bufList.calloc (size, 1);
  233881. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233882. {
  233883. const int numStreams = bufList->mNumberBuffers;
  233884. for (int i = 0; i < numStreams; ++i)
  233885. {
  233886. const AudioBuffer& b = bufList->mBuffers[i];
  233887. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233888. {
  233889. String name;
  233890. {
  233891. char channelName [256];
  233892. zerostruct (channelName);
  233893. UInt32 nameSize = sizeof (channelName);
  233894. UInt32 channelNum = chanNum + 1;
  233895. pa.mSelector = kAudioDevicePropertyChannelName;
  233896. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233897. name = String::fromUTF8 (channelName, nameSize);
  233898. }
  233899. if (input)
  233900. {
  233901. if (activeInputChans[chanNum])
  233902. {
  233903. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233904. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233905. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233906. ++numInputChannelInfos;
  233907. }
  233908. if (name.isEmpty())
  233909. name << "Input " << (chanNum + 1);
  233910. inChanNames.add (name);
  233911. }
  233912. else
  233913. {
  233914. if (activeOutputChans[chanNum])
  233915. {
  233916. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233917. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233918. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233919. ++numOutputChannelInfos;
  233920. }
  233921. if (name.isEmpty())
  233922. name << "Output " << (chanNum + 1);
  233923. outChanNames.add (name);
  233924. }
  233925. ++chanNum;
  233926. }
  233927. }
  233928. }
  233929. }
  233930. }
  233931. void updateDetailsFromDevice()
  233932. {
  233933. stopTimer();
  233934. if (deviceID == 0)
  233935. return;
  233936. const ScopedLock sl (callbackLock);
  233937. Float64 sr;
  233938. UInt32 size = sizeof (Float64);
  233939. AudioObjectPropertyAddress pa;
  233940. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233941. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233942. pa.mElement = kAudioObjectPropertyElementMaster;
  233943. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233944. sampleRate = sr;
  233945. UInt32 framesPerBuf;
  233946. size = sizeof (framesPerBuf);
  233947. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233948. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233949. {
  233950. bufferSize = framesPerBuf;
  233951. allocateTempBuffers();
  233952. }
  233953. bufferSizes.clear();
  233954. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233955. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233956. {
  233957. HeapBlock <AudioValueRange> ranges;
  233958. ranges.calloc (size, 1);
  233959. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233960. {
  233961. bufferSizes.add ((int) ranges[0].mMinimum);
  233962. for (int i = 32; i < 2048; i += 32)
  233963. {
  233964. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233965. {
  233966. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233967. {
  233968. bufferSizes.addIfNotAlreadyThere (i);
  233969. break;
  233970. }
  233971. }
  233972. }
  233973. if (bufferSize > 0)
  233974. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233975. }
  233976. }
  233977. if (bufferSizes.size() == 0 && bufferSize > 0)
  233978. bufferSizes.add (bufferSize);
  233979. sampleRates.clear();
  233980. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233981. String rates;
  233982. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  233983. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233984. {
  233985. HeapBlock <AudioValueRange> ranges;
  233986. ranges.calloc (size, 1);
  233987. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233988. {
  233989. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  233990. {
  233991. bool ok = false;
  233992. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233993. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  233994. ok = true;
  233995. if (ok)
  233996. {
  233997. sampleRates.add (possibleRates[i]);
  233998. rates << possibleRates[i] << ' ';
  233999. }
  234000. }
  234001. }
  234002. }
  234003. if (sampleRates.size() == 0 && sampleRate > 0)
  234004. {
  234005. sampleRates.add (sampleRate);
  234006. rates << sampleRate;
  234007. }
  234008. log ("sr: " + rates);
  234009. inputLatency = 0;
  234010. outputLatency = 0;
  234011. UInt32 lat;
  234012. size = sizeof (lat);
  234013. pa.mSelector = kAudioDevicePropertyLatency;
  234014. pa.mScope = kAudioDevicePropertyScopeInput;
  234015. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  234016. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234017. inputLatency = (int) lat;
  234018. pa.mScope = kAudioDevicePropertyScopeOutput;
  234019. size = sizeof (lat);
  234020. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234021. outputLatency = (int) lat;
  234022. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234023. inChanNames.clear();
  234024. outChanNames.clear();
  234025. inputChannelInfo.calloc (numInputChans + 2);
  234026. numInputChannelInfos = 0;
  234027. outputChannelInfo.calloc (numOutputChans + 2);
  234028. numOutputChannelInfos = 0;
  234029. fillInChannelInfo (true);
  234030. fillInChannelInfo (false);
  234031. }
  234032. const StringArray getSources (bool input)
  234033. {
  234034. StringArray s;
  234035. HeapBlock <OSType> types;
  234036. const int num = getAllDataSourcesForDevice (deviceID, types);
  234037. for (int i = 0; i < num; ++i)
  234038. {
  234039. AudioValueTranslation avt;
  234040. char buffer[256];
  234041. avt.mInputData = &(types[i]);
  234042. avt.mInputDataSize = sizeof (UInt32);
  234043. avt.mOutputData = buffer;
  234044. avt.mOutputDataSize = 256;
  234045. UInt32 transSize = sizeof (avt);
  234046. AudioObjectPropertyAddress pa;
  234047. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234048. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234049. pa.mElement = kAudioObjectPropertyElementMaster;
  234050. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234051. {
  234052. DBG (buffer);
  234053. s.add (buffer);
  234054. }
  234055. }
  234056. return s;
  234057. }
  234058. int getCurrentSourceIndex (bool input) const
  234059. {
  234060. OSType currentSourceID = 0;
  234061. UInt32 size = sizeof (currentSourceID);
  234062. int result = -1;
  234063. AudioObjectPropertyAddress pa;
  234064. pa.mSelector = kAudioDevicePropertyDataSource;
  234065. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234066. pa.mElement = kAudioObjectPropertyElementMaster;
  234067. if (deviceID != 0)
  234068. {
  234069. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234070. {
  234071. HeapBlock <OSType> types;
  234072. const int num = getAllDataSourcesForDevice (deviceID, types);
  234073. for (int i = 0; i < num; ++i)
  234074. {
  234075. if (types[num] == currentSourceID)
  234076. {
  234077. result = i;
  234078. break;
  234079. }
  234080. }
  234081. }
  234082. }
  234083. return result;
  234084. }
  234085. void setCurrentSourceIndex (int index, bool input)
  234086. {
  234087. if (deviceID != 0)
  234088. {
  234089. HeapBlock <OSType> types;
  234090. const int num = getAllDataSourcesForDevice (deviceID, types);
  234091. if (((unsigned int) index) < (unsigned int) num)
  234092. {
  234093. AudioObjectPropertyAddress pa;
  234094. pa.mSelector = kAudioDevicePropertyDataSource;
  234095. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234096. pa.mElement = kAudioObjectPropertyElementMaster;
  234097. OSType typeId = types[index];
  234098. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234099. }
  234100. }
  234101. }
  234102. const String reopen (const BigInteger& inputChannels,
  234103. const BigInteger& outputChannels,
  234104. double newSampleRate,
  234105. int bufferSizeSamples)
  234106. {
  234107. String error;
  234108. log ("CoreAudio reopen");
  234109. callbacksAllowed = false;
  234110. stopTimer();
  234111. stop (false);
  234112. activeInputChans = inputChannels;
  234113. activeInputChans.setRange (inChanNames.size(),
  234114. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234115. false);
  234116. activeOutputChans = outputChannels;
  234117. activeOutputChans.setRange (outChanNames.size(),
  234118. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234119. false);
  234120. numInputChans = activeInputChans.countNumberOfSetBits();
  234121. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234122. // set sample rate
  234123. AudioObjectPropertyAddress pa;
  234124. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234125. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234126. pa.mElement = kAudioObjectPropertyElementMaster;
  234127. Float64 sr = newSampleRate;
  234128. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234129. {
  234130. error = "Couldn't change sample rate";
  234131. }
  234132. else
  234133. {
  234134. // change buffer size
  234135. UInt32 framesPerBuf = bufferSizeSamples;
  234136. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234137. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234138. {
  234139. error = "Couldn't change buffer size";
  234140. }
  234141. else
  234142. {
  234143. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234144. // correctly report their new settings until some random time in the future, so
  234145. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234146. // to make sure we're using the correct numbers..
  234147. updateDetailsFromDevice();
  234148. sampleRate = newSampleRate;
  234149. bufferSize = bufferSizeSamples;
  234150. if (sampleRates.size() == 0)
  234151. error = "Device has no available sample-rates";
  234152. else if (bufferSizes.size() == 0)
  234153. error = "Device has no available buffer-sizes";
  234154. else if (inputDevice != 0)
  234155. error = inputDevice->reopen (inputChannels,
  234156. outputChannels,
  234157. newSampleRate,
  234158. bufferSizeSamples);
  234159. }
  234160. }
  234161. callbacksAllowed = true;
  234162. return error;
  234163. }
  234164. bool start (AudioIODeviceCallback* cb)
  234165. {
  234166. if (! started)
  234167. {
  234168. callback = 0;
  234169. if (deviceID != 0)
  234170. {
  234171. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234172. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234173. #else
  234174. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234175. #endif
  234176. {
  234177. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234178. {
  234179. started = true;
  234180. }
  234181. else
  234182. {
  234183. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234184. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234185. #else
  234186. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234187. audioProcID = 0;
  234188. #endif
  234189. }
  234190. }
  234191. }
  234192. }
  234193. if (started)
  234194. {
  234195. const ScopedLock sl (callbackLock);
  234196. callback = cb;
  234197. }
  234198. if (inputDevice != 0)
  234199. return started && inputDevice->start (cb);
  234200. else
  234201. return started;
  234202. }
  234203. void stop (bool leaveInterruptRunning)
  234204. {
  234205. {
  234206. const ScopedLock sl (callbackLock);
  234207. callback = 0;
  234208. }
  234209. if (started
  234210. && (deviceID != 0)
  234211. && ! leaveInterruptRunning)
  234212. {
  234213. OK (AudioDeviceStop (deviceID, audioIOProc));
  234214. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234215. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234216. #else
  234217. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234218. audioProcID = 0;
  234219. #endif
  234220. started = false;
  234221. { const ScopedLock sl (callbackLock); }
  234222. // wait until it's definately stopped calling back..
  234223. for (int i = 40; --i >= 0;)
  234224. {
  234225. Thread::sleep (50);
  234226. UInt32 running = 0;
  234227. UInt32 size = sizeof (running);
  234228. AudioObjectPropertyAddress pa;
  234229. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234230. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234231. pa.mElement = kAudioObjectPropertyElementMaster;
  234232. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234233. if (running == 0)
  234234. break;
  234235. }
  234236. const ScopedLock sl (callbackLock);
  234237. }
  234238. if (inputDevice != 0)
  234239. inputDevice->stop (leaveInterruptRunning);
  234240. }
  234241. double getSampleRate() const
  234242. {
  234243. return sampleRate;
  234244. }
  234245. int getBufferSize() const
  234246. {
  234247. return bufferSize;
  234248. }
  234249. void audioCallback (const AudioBufferList* inInputData,
  234250. AudioBufferList* outOutputData)
  234251. {
  234252. int i;
  234253. const ScopedLock sl (callbackLock);
  234254. if (callback != 0)
  234255. {
  234256. if (inputDevice == 0)
  234257. {
  234258. for (i = numInputChans; --i >= 0;)
  234259. {
  234260. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  234261. float* dest = tempInputBuffers [i];
  234262. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  234263. + info.dataOffsetSamples;
  234264. const int stride = info.dataStrideSamples;
  234265. if (stride != 0) // if this is zero, info is invalid
  234266. {
  234267. for (int j = bufferSize; --j >= 0;)
  234268. {
  234269. *dest++ = *src;
  234270. src += stride;
  234271. }
  234272. }
  234273. }
  234274. }
  234275. if (! isSlaveDevice)
  234276. {
  234277. if (inputDevice == 0)
  234278. {
  234279. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  234280. numInputChans,
  234281. tempOutputBuffers,
  234282. numOutputChans,
  234283. bufferSize);
  234284. }
  234285. else
  234286. {
  234287. jassert (inputDevice->bufferSize == bufferSize);
  234288. // Sometimes the two linked devices seem to get their callbacks in
  234289. // parallel, so we need to lock both devices to stop the input data being
  234290. // changed while inside our callback..
  234291. const ScopedLock sl2 (inputDevice->callbackLock);
  234292. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  234293. inputDevice->numInputChans,
  234294. tempOutputBuffers,
  234295. numOutputChans,
  234296. bufferSize);
  234297. }
  234298. for (i = numOutputChans; --i >= 0;)
  234299. {
  234300. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234301. const float* src = tempOutputBuffers [i];
  234302. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234303. + info.dataOffsetSamples;
  234304. const int stride = info.dataStrideSamples;
  234305. if (stride != 0) // if this is zero, info is invalid
  234306. {
  234307. for (int j = bufferSize; --j >= 0;)
  234308. {
  234309. *dest = *src++;
  234310. dest += stride;
  234311. }
  234312. }
  234313. }
  234314. }
  234315. }
  234316. else
  234317. {
  234318. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  234319. {
  234320. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234321. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234322. + info.dataOffsetSamples;
  234323. const int stride = info.dataStrideSamples;
  234324. if (stride != 0) // if this is zero, info is invalid
  234325. {
  234326. for (int j = bufferSize; --j >= 0;)
  234327. {
  234328. *dest = 0.0f;
  234329. dest += stride;
  234330. }
  234331. }
  234332. }
  234333. }
  234334. }
  234335. // called by callbacks
  234336. void deviceDetailsChanged()
  234337. {
  234338. if (callbacksAllowed)
  234339. startTimer (100);
  234340. }
  234341. void timerCallback()
  234342. {
  234343. stopTimer();
  234344. log ("CoreAudio device changed callback");
  234345. const double oldSampleRate = sampleRate;
  234346. const int oldBufferSize = bufferSize;
  234347. updateDetailsFromDevice();
  234348. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  234349. {
  234350. callbacksAllowed = false;
  234351. stop (false);
  234352. updateDetailsFromDevice();
  234353. callbacksAllowed = true;
  234354. }
  234355. }
  234356. CoreAudioInternal* getRelatedDevice() const
  234357. {
  234358. UInt32 size = 0;
  234359. ScopedPointer <CoreAudioInternal> result;
  234360. AudioObjectPropertyAddress pa;
  234361. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  234362. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234363. pa.mElement = kAudioObjectPropertyElementMaster;
  234364. if (deviceID != 0
  234365. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234366. && size > 0)
  234367. {
  234368. HeapBlock <AudioDeviceID> devs;
  234369. devs.calloc (size, 1);
  234370. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234371. {
  234372. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234373. {
  234374. if (devs[i] != deviceID && devs[i] != 0)
  234375. {
  234376. result = new CoreAudioInternal (devs[i]);
  234377. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234378. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234379. if (thisIsInput != otherIsInput
  234380. || (inChanNames.size() + outChanNames.size() == 0)
  234381. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234382. break;
  234383. result = 0;
  234384. }
  234385. }
  234386. }
  234387. }
  234388. return result.release();
  234389. }
  234390. juce_UseDebuggingNewOperator
  234391. int inputLatency, outputLatency;
  234392. BigInteger activeInputChans, activeOutputChans;
  234393. StringArray inChanNames, outChanNames;
  234394. Array <double> sampleRates;
  234395. Array <int> bufferSizes;
  234396. AudioIODeviceCallback* callback;
  234397. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234398. AudioDeviceIOProcID audioProcID;
  234399. #endif
  234400. ScopedPointer<CoreAudioInternal> inputDevice;
  234401. bool isSlaveDevice;
  234402. private:
  234403. CriticalSection callbackLock;
  234404. AudioDeviceID deviceID;
  234405. bool started;
  234406. double sampleRate;
  234407. int bufferSize;
  234408. HeapBlock <float> audioBuffer;
  234409. int numInputChans, numOutputChans;
  234410. bool callbacksAllowed;
  234411. struct CallbackDetailsForChannel
  234412. {
  234413. int streamNum;
  234414. int dataOffsetSamples;
  234415. int dataStrideSamples;
  234416. };
  234417. int numInputChannelInfos, numOutputChannelInfos;
  234418. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234419. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234420. CoreAudioInternal (const CoreAudioInternal&);
  234421. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234422. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234423. const AudioTimeStamp* /*inNow*/,
  234424. const AudioBufferList* inInputData,
  234425. const AudioTimeStamp* /*inInputTime*/,
  234426. AudioBufferList* outOutputData,
  234427. const AudioTimeStamp* /*inOutputTime*/,
  234428. void* device)
  234429. {
  234430. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234431. return noErr;
  234432. }
  234433. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234434. {
  234435. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234436. switch (pa->mSelector)
  234437. {
  234438. case kAudioDevicePropertyBufferSize:
  234439. case kAudioDevicePropertyBufferFrameSize:
  234440. case kAudioDevicePropertyNominalSampleRate:
  234441. case kAudioDevicePropertyStreamFormat:
  234442. case kAudioDevicePropertyDeviceIsAlive:
  234443. intern->deviceDetailsChanged();
  234444. break;
  234445. case kAudioDevicePropertyBufferSizeRange:
  234446. case kAudioDevicePropertyVolumeScalar:
  234447. case kAudioDevicePropertyMute:
  234448. case kAudioDevicePropertyPlayThru:
  234449. case kAudioDevicePropertyDataSource:
  234450. case kAudioDevicePropertyDeviceIsRunning:
  234451. break;
  234452. }
  234453. return noErr;
  234454. }
  234455. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234456. {
  234457. AudioObjectPropertyAddress pa;
  234458. pa.mSelector = kAudioDevicePropertyDataSources;
  234459. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234460. pa.mElement = kAudioObjectPropertyElementMaster;
  234461. UInt32 size = 0;
  234462. if (deviceID != 0
  234463. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234464. {
  234465. types.calloc (size, 1);
  234466. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234467. return size / (int) sizeof (OSType);
  234468. }
  234469. return 0;
  234470. }
  234471. };
  234472. class CoreAudioIODevice : public AudioIODevice
  234473. {
  234474. public:
  234475. CoreAudioIODevice (const String& deviceName,
  234476. AudioDeviceID inputDeviceId,
  234477. const int inputIndex_,
  234478. AudioDeviceID outputDeviceId,
  234479. const int outputIndex_)
  234480. : AudioIODevice (deviceName, "CoreAudio"),
  234481. inputIndex (inputIndex_),
  234482. outputIndex (outputIndex_),
  234483. isOpen_ (false),
  234484. isStarted (false)
  234485. {
  234486. CoreAudioInternal* device = 0;
  234487. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234488. {
  234489. jassert (inputDeviceId != 0);
  234490. device = new CoreAudioInternal (inputDeviceId);
  234491. }
  234492. else
  234493. {
  234494. device = new CoreAudioInternal (outputDeviceId);
  234495. if (inputDeviceId != 0)
  234496. {
  234497. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234498. device->inputDevice = secondDevice;
  234499. secondDevice->isSlaveDevice = true;
  234500. }
  234501. }
  234502. internal = device;
  234503. AudioObjectPropertyAddress pa;
  234504. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234505. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234506. pa.mElement = kAudioObjectPropertyElementWildcard;
  234507. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234508. }
  234509. ~CoreAudioIODevice()
  234510. {
  234511. AudioObjectPropertyAddress pa;
  234512. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234513. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234514. pa.mElement = kAudioObjectPropertyElementWildcard;
  234515. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234516. }
  234517. const StringArray getOutputChannelNames()
  234518. {
  234519. return internal->outChanNames;
  234520. }
  234521. const StringArray getInputChannelNames()
  234522. {
  234523. if (internal->inputDevice != 0)
  234524. return internal->inputDevice->inChanNames;
  234525. else
  234526. return internal->inChanNames;
  234527. }
  234528. int getNumSampleRates()
  234529. {
  234530. return internal->sampleRates.size();
  234531. }
  234532. double getSampleRate (int index)
  234533. {
  234534. return internal->sampleRates [index];
  234535. }
  234536. int getNumBufferSizesAvailable()
  234537. {
  234538. return internal->bufferSizes.size();
  234539. }
  234540. int getBufferSizeSamples (int index)
  234541. {
  234542. return internal->bufferSizes [index];
  234543. }
  234544. int getDefaultBufferSize()
  234545. {
  234546. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234547. if (getBufferSizeSamples(i) >= 512)
  234548. return getBufferSizeSamples(i);
  234549. return 512;
  234550. }
  234551. const String open (const BigInteger& inputChannels,
  234552. const BigInteger& outputChannels,
  234553. double sampleRate,
  234554. int bufferSizeSamples)
  234555. {
  234556. isOpen_ = true;
  234557. if (bufferSizeSamples <= 0)
  234558. bufferSizeSamples = getDefaultBufferSize();
  234559. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234560. isOpen_ = lastError.isEmpty();
  234561. return lastError;
  234562. }
  234563. void close()
  234564. {
  234565. isOpen_ = false;
  234566. internal->stop (false);
  234567. }
  234568. bool isOpen()
  234569. {
  234570. return isOpen_;
  234571. }
  234572. int getCurrentBufferSizeSamples()
  234573. {
  234574. return internal != 0 ? internal->getBufferSize() : 512;
  234575. }
  234576. double getCurrentSampleRate()
  234577. {
  234578. return internal != 0 ? internal->getSampleRate() : 0;
  234579. }
  234580. int getCurrentBitDepth()
  234581. {
  234582. return 32; // no way to find out, so just assume it's high..
  234583. }
  234584. const BigInteger getActiveOutputChannels() const
  234585. {
  234586. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234587. }
  234588. const BigInteger getActiveInputChannels() const
  234589. {
  234590. BigInteger chans;
  234591. if (internal != 0)
  234592. {
  234593. chans = internal->activeInputChans;
  234594. if (internal->inputDevice != 0)
  234595. chans |= internal->inputDevice->activeInputChans;
  234596. }
  234597. return chans;
  234598. }
  234599. int getOutputLatencyInSamples()
  234600. {
  234601. if (internal == 0)
  234602. return 0;
  234603. // this seems like a good guess at getting the latency right - comparing
  234604. // this with a round-trip measurement, it gets it to within a few millisecs
  234605. // for the built-in mac soundcard
  234606. return internal->outputLatency + internal->getBufferSize() * 2;
  234607. }
  234608. int getInputLatencyInSamples()
  234609. {
  234610. if (internal == 0)
  234611. return 0;
  234612. return internal->inputLatency + internal->getBufferSize() * 2;
  234613. }
  234614. void start (AudioIODeviceCallback* callback)
  234615. {
  234616. if (internal != 0 && ! isStarted)
  234617. {
  234618. if (callback != 0)
  234619. callback->audioDeviceAboutToStart (this);
  234620. isStarted = true;
  234621. internal->start (callback);
  234622. }
  234623. }
  234624. void stop()
  234625. {
  234626. if (isStarted && internal != 0)
  234627. {
  234628. AudioIODeviceCallback* const lastCallback = internal->callback;
  234629. isStarted = false;
  234630. internal->stop (true);
  234631. if (lastCallback != 0)
  234632. lastCallback->audioDeviceStopped();
  234633. }
  234634. }
  234635. bool isPlaying()
  234636. {
  234637. if (internal->callback == 0)
  234638. isStarted = false;
  234639. return isStarted;
  234640. }
  234641. const String getLastError()
  234642. {
  234643. return lastError;
  234644. }
  234645. int inputIndex, outputIndex;
  234646. juce_UseDebuggingNewOperator
  234647. private:
  234648. ScopedPointer<CoreAudioInternal> internal;
  234649. bool isOpen_, isStarted;
  234650. String lastError;
  234651. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234652. {
  234653. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234654. switch (pa->mSelector)
  234655. {
  234656. case kAudioHardwarePropertyDevices:
  234657. intern->deviceDetailsChanged();
  234658. break;
  234659. case kAudioHardwarePropertyDefaultOutputDevice:
  234660. case kAudioHardwarePropertyDefaultInputDevice:
  234661. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234662. break;
  234663. }
  234664. return noErr;
  234665. }
  234666. CoreAudioIODevice (const CoreAudioIODevice&);
  234667. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234668. };
  234669. class CoreAudioIODeviceType : public AudioIODeviceType
  234670. {
  234671. public:
  234672. CoreAudioIODeviceType()
  234673. : AudioIODeviceType ("CoreAudio"),
  234674. hasScanned (false)
  234675. {
  234676. }
  234677. ~CoreAudioIODeviceType()
  234678. {
  234679. }
  234680. void scanForDevices()
  234681. {
  234682. hasScanned = true;
  234683. inputDeviceNames.clear();
  234684. outputDeviceNames.clear();
  234685. inputIds.clear();
  234686. outputIds.clear();
  234687. UInt32 size;
  234688. AudioObjectPropertyAddress pa;
  234689. pa.mSelector = kAudioHardwarePropertyDevices;
  234690. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234691. pa.mElement = kAudioObjectPropertyElementMaster;
  234692. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234693. {
  234694. HeapBlock <AudioDeviceID> devs;
  234695. devs.calloc (size, 1);
  234696. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234697. {
  234698. const int num = size / (int) sizeof (AudioDeviceID);
  234699. for (int i = 0; i < num; ++i)
  234700. {
  234701. char name [1024];
  234702. size = sizeof (name);
  234703. pa.mSelector = kAudioDevicePropertyDeviceName;
  234704. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234705. {
  234706. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234707. const int numIns = getNumChannels (devs[i], true);
  234708. const int numOuts = getNumChannels (devs[i], false);
  234709. if (numIns > 0)
  234710. {
  234711. inputDeviceNames.add (nameString);
  234712. inputIds.add (devs[i]);
  234713. }
  234714. if (numOuts > 0)
  234715. {
  234716. outputDeviceNames.add (nameString);
  234717. outputIds.add (devs[i]);
  234718. }
  234719. }
  234720. }
  234721. }
  234722. }
  234723. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234724. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234725. }
  234726. const StringArray getDeviceNames (bool wantInputNames) const
  234727. {
  234728. jassert (hasScanned); // need to call scanForDevices() before doing this
  234729. if (wantInputNames)
  234730. return inputDeviceNames;
  234731. else
  234732. return outputDeviceNames;
  234733. }
  234734. int getDefaultDeviceIndex (bool forInput) const
  234735. {
  234736. jassert (hasScanned); // need to call scanForDevices() before doing this
  234737. AudioDeviceID deviceID;
  234738. UInt32 size = sizeof (deviceID);
  234739. // if they're asking for any input channels at all, use the default input, so we
  234740. // get the built-in mic rather than the built-in output with no inputs..
  234741. AudioObjectPropertyAddress pa;
  234742. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234743. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234744. pa.mElement = kAudioObjectPropertyElementMaster;
  234745. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234746. {
  234747. if (forInput)
  234748. {
  234749. for (int i = inputIds.size(); --i >= 0;)
  234750. if (inputIds[i] == deviceID)
  234751. return i;
  234752. }
  234753. else
  234754. {
  234755. for (int i = outputIds.size(); --i >= 0;)
  234756. if (outputIds[i] == deviceID)
  234757. return i;
  234758. }
  234759. }
  234760. return 0;
  234761. }
  234762. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234763. {
  234764. jassert (hasScanned); // need to call scanForDevices() before doing this
  234765. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234766. if (d == 0)
  234767. return -1;
  234768. return asInput ? d->inputIndex
  234769. : d->outputIndex;
  234770. }
  234771. bool hasSeparateInputsAndOutputs() const { return true; }
  234772. AudioIODevice* createDevice (const String& outputDeviceName,
  234773. const String& inputDeviceName)
  234774. {
  234775. jassert (hasScanned); // need to call scanForDevices() before doing this
  234776. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234777. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234778. String deviceName (outputDeviceName);
  234779. if (deviceName.isEmpty())
  234780. deviceName = inputDeviceName;
  234781. if (index >= 0)
  234782. return new CoreAudioIODevice (deviceName,
  234783. inputIds [inputIndex],
  234784. inputIndex,
  234785. outputIds [outputIndex],
  234786. outputIndex);
  234787. return 0;
  234788. }
  234789. juce_UseDebuggingNewOperator
  234790. private:
  234791. StringArray inputDeviceNames, outputDeviceNames;
  234792. Array <AudioDeviceID> inputIds, outputIds;
  234793. bool hasScanned;
  234794. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234795. {
  234796. int total = 0;
  234797. UInt32 size;
  234798. AudioObjectPropertyAddress pa;
  234799. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234800. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234801. pa.mElement = kAudioObjectPropertyElementMaster;
  234802. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234803. {
  234804. HeapBlock <AudioBufferList> bufList;
  234805. bufList.calloc (size, 1);
  234806. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234807. {
  234808. const int numStreams = bufList->mNumberBuffers;
  234809. for (int i = 0; i < numStreams; ++i)
  234810. {
  234811. const AudioBuffer& b = bufList->mBuffers[i];
  234812. total += b.mNumberChannels;
  234813. }
  234814. }
  234815. }
  234816. return total;
  234817. }
  234818. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234819. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234820. };
  234821. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234822. {
  234823. return new CoreAudioIODeviceType();
  234824. }
  234825. #undef log
  234826. #endif
  234827. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234828. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234829. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234830. // compiled on its own).
  234831. #if JUCE_INCLUDED_FILE
  234832. #if JUCE_MAC
  234833. #undef log
  234834. #define log(a) Logger::writeToLog(a)
  234835. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234836. {
  234837. if (err == noErr)
  234838. return true;
  234839. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234840. jassertfalse;
  234841. return false;
  234842. }
  234843. #undef OK
  234844. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234845. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234846. {
  234847. String result;
  234848. CFStringRef str = 0;
  234849. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234850. if (str != 0)
  234851. {
  234852. result = PlatformUtilities::cfStringToJuceString (str);
  234853. CFRelease (str);
  234854. str = 0;
  234855. }
  234856. MIDIEntityRef entity = 0;
  234857. MIDIEndpointGetEntity (endpoint, &entity);
  234858. if (entity == 0)
  234859. return result; // probably virtual
  234860. if (result.isEmpty())
  234861. {
  234862. // endpoint name has zero length - try the entity
  234863. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234864. if (str != 0)
  234865. {
  234866. result += PlatformUtilities::cfStringToJuceString (str);
  234867. CFRelease (str);
  234868. str = 0;
  234869. }
  234870. }
  234871. // now consider the device's name
  234872. MIDIDeviceRef device = 0;
  234873. MIDIEntityGetDevice (entity, &device);
  234874. if (device == 0)
  234875. return result;
  234876. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234877. if (str != 0)
  234878. {
  234879. const String s (PlatformUtilities::cfStringToJuceString (str));
  234880. CFRelease (str);
  234881. // if an external device has only one entity, throw away
  234882. // the endpoint name and just use the device name
  234883. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234884. {
  234885. result = s;
  234886. }
  234887. else if (! result.startsWithIgnoreCase (s))
  234888. {
  234889. // prepend the device name to the entity name
  234890. result = (s + " " + result).trimEnd();
  234891. }
  234892. }
  234893. return result;
  234894. }
  234895. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234896. {
  234897. String result;
  234898. // Does the endpoint have connections?
  234899. CFDataRef connections = 0;
  234900. int numConnections = 0;
  234901. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234902. if (connections != 0)
  234903. {
  234904. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234905. if (numConnections > 0)
  234906. {
  234907. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234908. for (int i = 0; i < numConnections; ++i, ++pid)
  234909. {
  234910. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234911. MIDIObjectRef connObject;
  234912. MIDIObjectType connObjectType;
  234913. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234914. if (err == noErr)
  234915. {
  234916. String s;
  234917. if (connObjectType == kMIDIObjectType_ExternalSource
  234918. || connObjectType == kMIDIObjectType_ExternalDestination)
  234919. {
  234920. // Connected to an external device's endpoint (10.3 and later).
  234921. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234922. }
  234923. else
  234924. {
  234925. // Connected to an external device (10.2) (or something else, catch-all)
  234926. CFStringRef str = 0;
  234927. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234928. if (str != 0)
  234929. {
  234930. s = PlatformUtilities::cfStringToJuceString (str);
  234931. CFRelease (str);
  234932. }
  234933. }
  234934. if (s.isNotEmpty())
  234935. {
  234936. if (result.isNotEmpty())
  234937. result += ", ";
  234938. result += s;
  234939. }
  234940. }
  234941. }
  234942. }
  234943. CFRelease (connections);
  234944. }
  234945. if (result.isNotEmpty())
  234946. return result;
  234947. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234948. return getEndpointName (endpoint, false);
  234949. }
  234950. const StringArray MidiOutput::getDevices()
  234951. {
  234952. StringArray s;
  234953. const ItemCount num = MIDIGetNumberOfDestinations();
  234954. for (ItemCount i = 0; i < num; ++i)
  234955. {
  234956. MIDIEndpointRef dest = MIDIGetDestination (i);
  234957. if (dest != 0)
  234958. {
  234959. String name (getConnectedEndpointName (dest));
  234960. if (name.isEmpty())
  234961. name = "<error>";
  234962. s.add (name);
  234963. }
  234964. else
  234965. {
  234966. s.add ("<error>");
  234967. }
  234968. }
  234969. return s;
  234970. }
  234971. int MidiOutput::getDefaultDeviceIndex()
  234972. {
  234973. return 0;
  234974. }
  234975. static MIDIClientRef globalMidiClient;
  234976. static bool hasGlobalClientBeenCreated = false;
  234977. static bool makeSureClientExists()
  234978. {
  234979. if (! hasGlobalClientBeenCreated)
  234980. {
  234981. String name ("JUCE");
  234982. if (JUCEApplication::getInstance() != 0)
  234983. name = JUCEApplication::getInstance()->getApplicationName();
  234984. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  234985. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  234986. CFRelease (appName);
  234987. }
  234988. return hasGlobalClientBeenCreated;
  234989. }
  234990. class MidiPortAndEndpoint
  234991. {
  234992. public:
  234993. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  234994. : port (port_), endPoint (endPoint_)
  234995. {
  234996. }
  234997. ~MidiPortAndEndpoint()
  234998. {
  234999. if (port != 0)
  235000. MIDIPortDispose (port);
  235001. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235002. MIDIEndpointDispose (endPoint);
  235003. }
  235004. MIDIPortRef port;
  235005. MIDIEndpointRef endPoint;
  235006. };
  235007. MidiOutput* MidiOutput::openDevice (int index)
  235008. {
  235009. MidiOutput* mo = 0;
  235010. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  235011. {
  235012. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235013. CFStringRef pname;
  235014. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235015. {
  235016. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  235017. if (makeSureClientExists())
  235018. {
  235019. MIDIPortRef port;
  235020. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  235021. {
  235022. mo = new MidiOutput();
  235023. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  235024. }
  235025. }
  235026. CFRelease (pname);
  235027. }
  235028. }
  235029. return mo;
  235030. }
  235031. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235032. {
  235033. MidiOutput* mo = 0;
  235034. if (makeSureClientExists())
  235035. {
  235036. MIDIEndpointRef endPoint;
  235037. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235038. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  235039. {
  235040. mo = new MidiOutput();
  235041. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  235042. }
  235043. CFRelease (name);
  235044. }
  235045. return mo;
  235046. }
  235047. MidiOutput::~MidiOutput()
  235048. {
  235049. delete (MidiPortAndEndpoint*) internal;
  235050. }
  235051. void MidiOutput::reset()
  235052. {
  235053. }
  235054. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235055. {
  235056. return false;
  235057. }
  235058. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235059. {
  235060. }
  235061. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235062. {
  235063. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  235064. if (message.isSysEx())
  235065. {
  235066. const int maxPacketSize = 256;
  235067. int pos = 0, bytesLeft = message.getRawDataSize();
  235068. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235069. HeapBlock <MIDIPacketList> packets;
  235070. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235071. packets->numPackets = numPackets;
  235072. MIDIPacket* p = packets->packet;
  235073. for (int i = 0; i < numPackets; ++i)
  235074. {
  235075. p->timeStamp = 0;
  235076. p->length = jmin (maxPacketSize, bytesLeft);
  235077. memcpy (p->data, message.getRawData() + pos, p->length);
  235078. pos += p->length;
  235079. bytesLeft -= p->length;
  235080. p = MIDIPacketNext (p);
  235081. }
  235082. if (mpe->port != 0)
  235083. MIDISend (mpe->port, mpe->endPoint, packets);
  235084. else
  235085. MIDIReceived (mpe->endPoint, packets);
  235086. }
  235087. else
  235088. {
  235089. MIDIPacketList packets;
  235090. packets.numPackets = 1;
  235091. packets.packet[0].timeStamp = 0;
  235092. packets.packet[0].length = message.getRawDataSize();
  235093. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235094. if (mpe->port != 0)
  235095. MIDISend (mpe->port, mpe->endPoint, &packets);
  235096. else
  235097. MIDIReceived (mpe->endPoint, &packets);
  235098. }
  235099. }
  235100. const StringArray MidiInput::getDevices()
  235101. {
  235102. StringArray s;
  235103. const ItemCount num = MIDIGetNumberOfSources();
  235104. for (ItemCount i = 0; i < num; ++i)
  235105. {
  235106. MIDIEndpointRef source = MIDIGetSource (i);
  235107. if (source != 0)
  235108. {
  235109. String name (getConnectedEndpointName (source));
  235110. if (name.isEmpty())
  235111. name = "<error>";
  235112. s.add (name);
  235113. }
  235114. else
  235115. {
  235116. s.add ("<error>");
  235117. }
  235118. }
  235119. return s;
  235120. }
  235121. int MidiInput::getDefaultDeviceIndex()
  235122. {
  235123. return 0;
  235124. }
  235125. struct MidiPortAndCallback
  235126. {
  235127. MidiInput* input;
  235128. MidiPortAndEndpoint* portAndEndpoint;
  235129. MidiInputCallback* callback;
  235130. MemoryBlock pendingData;
  235131. int pendingBytes;
  235132. double pendingDataTime;
  235133. bool active;
  235134. void processSysex (const uint8*& d, int& size, const double time)
  235135. {
  235136. if (*d == 0xf0)
  235137. {
  235138. pendingBytes = 0;
  235139. pendingDataTime = time;
  235140. }
  235141. pendingData.ensureSize (pendingBytes + size, false);
  235142. uint8* totalMessage = (uint8*) pendingData.getData();
  235143. uint8* dest = totalMessage + pendingBytes;
  235144. while (size > 0)
  235145. {
  235146. if (pendingBytes > 0 && *d >= 0x80)
  235147. {
  235148. if (*d >= 0xfa || *d == 0xf8)
  235149. {
  235150. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  235151. ++d;
  235152. --size;
  235153. }
  235154. else
  235155. {
  235156. if (*d == 0xf7)
  235157. {
  235158. *dest++ = *d++;
  235159. pendingBytes++;
  235160. --size;
  235161. }
  235162. break;
  235163. }
  235164. }
  235165. else
  235166. {
  235167. *dest++ = *d++;
  235168. pendingBytes++;
  235169. --size;
  235170. }
  235171. }
  235172. if (totalMessage [pendingBytes - 1] == 0xf7)
  235173. {
  235174. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  235175. pendingBytes = 0;
  235176. }
  235177. else
  235178. {
  235179. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  235180. }
  235181. }
  235182. };
  235183. namespace CoreMidiCallbacks
  235184. {
  235185. static CriticalSection callbackLock;
  235186. static Array<void*> activeCallbacks;
  235187. }
  235188. static void midiInputProc (const MIDIPacketList* pktlist,
  235189. void* readProcRefCon,
  235190. void* /*srcConnRefCon*/)
  235191. {
  235192. double time = Time::getMillisecondCounterHiRes() * 0.001;
  235193. const double originalTime = time;
  235194. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  235195. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235196. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  235197. {
  235198. const MIDIPacket* packet = &pktlist->packet[0];
  235199. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235200. {
  235201. const uint8* d = (const uint8*) (packet->data);
  235202. int size = packet->length;
  235203. while (size > 0)
  235204. {
  235205. time = originalTime;
  235206. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  235207. {
  235208. mpc->processSysex (d, size, time);
  235209. }
  235210. else
  235211. {
  235212. int used = 0;
  235213. const MidiMessage m (d, size, used, 0, time);
  235214. if (used <= 0)
  235215. {
  235216. jassertfalse; // malformed midi message
  235217. break;
  235218. }
  235219. else
  235220. {
  235221. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  235222. }
  235223. size -= used;
  235224. d += used;
  235225. }
  235226. }
  235227. packet = MIDIPacketNext (packet);
  235228. }
  235229. }
  235230. }
  235231. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235232. {
  235233. MidiInput* mi = 0;
  235234. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  235235. {
  235236. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235237. if (endPoint != 0)
  235238. {
  235239. CFStringRef pname;
  235240. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235241. {
  235242. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  235243. if (makeSureClientExists())
  235244. {
  235245. MIDIPortRef port;
  235246. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235247. mpc->active = false;
  235248. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  235249. {
  235250. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  235251. {
  235252. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235253. mpc->callback = callback;
  235254. mpc->pendingBytes = 0;
  235255. mpc->pendingData.ensureSize (128);
  235256. mi = new MidiInput (getDevices() [index]);
  235257. mpc->input = mi;
  235258. mi->internal = mpc;
  235259. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235260. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235261. }
  235262. else
  235263. {
  235264. OK (MIDIPortDispose (port));
  235265. }
  235266. }
  235267. }
  235268. }
  235269. CFRelease (pname);
  235270. }
  235271. }
  235272. return mi;
  235273. }
  235274. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235275. {
  235276. MidiInput* mi = 0;
  235277. if (makeSureClientExists())
  235278. {
  235279. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235280. mpc->active = false;
  235281. MIDIEndpointRef endPoint;
  235282. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235283. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  235284. {
  235285. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235286. mpc->callback = callback;
  235287. mpc->pendingBytes = 0;
  235288. mpc->pendingData.ensureSize (128);
  235289. mi = new MidiInput (deviceName);
  235290. mpc->input = mi;
  235291. mi->internal = mpc;
  235292. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235293. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235294. }
  235295. CFRelease (name);
  235296. }
  235297. return mi;
  235298. }
  235299. MidiInput::MidiInput (const String& name_)
  235300. : name (name_)
  235301. {
  235302. }
  235303. MidiInput::~MidiInput()
  235304. {
  235305. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  235306. mpc->active = false;
  235307. {
  235308. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235309. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  235310. }
  235311. if (mpc->portAndEndpoint->port != 0)
  235312. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  235313. delete mpc->portAndEndpoint;
  235314. delete mpc;
  235315. }
  235316. void MidiInput::start()
  235317. {
  235318. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235319. ((MidiPortAndCallback*) internal)->active = true;
  235320. }
  235321. void MidiInput::stop()
  235322. {
  235323. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235324. ((MidiPortAndCallback*) internal)->active = false;
  235325. }
  235326. #undef log
  235327. #else
  235328. MidiOutput::~MidiOutput()
  235329. {
  235330. }
  235331. void MidiOutput::reset()
  235332. {
  235333. }
  235334. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235335. {
  235336. return false;
  235337. }
  235338. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235339. {
  235340. }
  235341. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235342. {
  235343. }
  235344. const StringArray MidiOutput::getDevices()
  235345. {
  235346. return StringArray();
  235347. }
  235348. MidiOutput* MidiOutput::openDevice (int index)
  235349. {
  235350. return 0;
  235351. }
  235352. const StringArray MidiInput::getDevices()
  235353. {
  235354. return StringArray();
  235355. }
  235356. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235357. {
  235358. return 0;
  235359. }
  235360. #endif
  235361. #endif
  235362. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235363. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235364. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235365. // compiled on its own).
  235366. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235367. #if ! JUCE_QUICKTIME
  235368. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235369. #endif
  235370. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235371. class QTCameraDeviceInteral;
  235372. END_JUCE_NAMESPACE
  235373. @interface QTCaptureCallbackDelegate : NSObject
  235374. {
  235375. @public
  235376. CameraDevice* owner;
  235377. QTCameraDeviceInteral* internal;
  235378. int64 firstPresentationTime;
  235379. int64 averageTimeOffset;
  235380. }
  235381. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235382. - (void) dealloc;
  235383. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235384. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235385. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235386. fromConnection: (QTCaptureConnection*) connection;
  235387. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235388. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235389. fromConnection: (QTCaptureConnection*) connection;
  235390. @end
  235391. BEGIN_JUCE_NAMESPACE
  235392. class QTCameraDeviceInteral
  235393. {
  235394. public:
  235395. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235396. {
  235397. const ScopedAutoReleasePool pool;
  235398. session = [[QTCaptureSession alloc] init];
  235399. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235400. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235401. input = 0;
  235402. audioInput = 0;
  235403. audioDevice = 0;
  235404. fileOutput = 0;
  235405. imageOutput = 0;
  235406. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235407. internalDev: this];
  235408. NSError* err = 0;
  235409. [device retain];
  235410. [device open: &err];
  235411. if (err == 0)
  235412. {
  235413. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235414. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235415. [session addInput: input error: &err];
  235416. if (err == 0)
  235417. {
  235418. resetFile();
  235419. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235420. [imageOutput setDelegate: callbackDelegate];
  235421. if (err == 0)
  235422. {
  235423. [session startRunning];
  235424. return;
  235425. }
  235426. }
  235427. }
  235428. openingError = nsStringToJuce ([err description]);
  235429. DBG (openingError);
  235430. }
  235431. ~QTCameraDeviceInteral()
  235432. {
  235433. [session stopRunning];
  235434. [session removeOutput: imageOutput];
  235435. [session release];
  235436. [input release];
  235437. [device release];
  235438. [audioDevice release];
  235439. [audioInput release];
  235440. [fileOutput release];
  235441. [imageOutput release];
  235442. [callbackDelegate release];
  235443. }
  235444. void resetFile()
  235445. {
  235446. [fileOutput recordToOutputFileURL: nil];
  235447. [session removeOutput: fileOutput];
  235448. [fileOutput release];
  235449. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235450. [session removeInput: audioInput];
  235451. [audioInput release];
  235452. audioInput = 0;
  235453. [audioDevice release];
  235454. audioDevice = 0;
  235455. [fileOutput setDelegate: callbackDelegate];
  235456. }
  235457. void addDefaultAudioInput()
  235458. {
  235459. NSError* err = nil;
  235460. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235461. if ([audioDevice open: &err])
  235462. [audioDevice retain];
  235463. else
  235464. audioDevice = nil;
  235465. if (audioDevice != 0)
  235466. {
  235467. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235468. [session addInput: audioInput error: &err];
  235469. }
  235470. }
  235471. void addListener (CameraDevice::Listener* listenerToAdd)
  235472. {
  235473. const ScopedLock sl (listenerLock);
  235474. if (listeners.size() == 0)
  235475. [session addOutput: imageOutput error: nil];
  235476. listeners.addIfNotAlreadyThere (listenerToAdd);
  235477. }
  235478. void removeListener (CameraDevice::Listener* listenerToRemove)
  235479. {
  235480. const ScopedLock sl (listenerLock);
  235481. listeners.removeValue (listenerToRemove);
  235482. if (listeners.size() == 0)
  235483. [session removeOutput: imageOutput];
  235484. }
  235485. void callListeners (CIImage* frame, int w, int h)
  235486. {
  235487. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235488. Image image (cgImage);
  235489. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235490. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235491. CGContextFlush (cgImage->context);
  235492. const ScopedLock sl (listenerLock);
  235493. for (int i = listeners.size(); --i >= 0;)
  235494. {
  235495. CameraDevice::Listener* const l = listeners[i];
  235496. if (l != 0)
  235497. l->imageReceived (image);
  235498. }
  235499. }
  235500. QTCaptureDevice* device;
  235501. QTCaptureDeviceInput* input;
  235502. QTCaptureDevice* audioDevice;
  235503. QTCaptureDeviceInput* audioInput;
  235504. QTCaptureSession* session;
  235505. QTCaptureMovieFileOutput* fileOutput;
  235506. QTCaptureDecompressedVideoOutput* imageOutput;
  235507. QTCaptureCallbackDelegate* callbackDelegate;
  235508. String openingError;
  235509. Array<CameraDevice::Listener*> listeners;
  235510. CriticalSection listenerLock;
  235511. };
  235512. END_JUCE_NAMESPACE
  235513. @implementation QTCaptureCallbackDelegate
  235514. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235515. internalDev: (QTCameraDeviceInteral*) d
  235516. {
  235517. [super init];
  235518. owner = owner_;
  235519. internal = d;
  235520. firstPresentationTime = 0;
  235521. averageTimeOffset = 0;
  235522. return self;
  235523. }
  235524. - (void) dealloc
  235525. {
  235526. [super dealloc];
  235527. }
  235528. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235529. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235530. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235531. fromConnection: (QTCaptureConnection*) connection
  235532. {
  235533. if (internal->listeners.size() > 0)
  235534. {
  235535. const ScopedAutoReleasePool pool;
  235536. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235537. CVPixelBufferGetWidth (videoFrame),
  235538. CVPixelBufferGetHeight (videoFrame));
  235539. }
  235540. }
  235541. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235542. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235543. fromConnection: (QTCaptureConnection*) connection
  235544. {
  235545. const Time now (Time::getCurrentTime());
  235546. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235547. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235548. #else
  235549. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235550. #endif
  235551. int64 presentationTime = (hosttime != nil)
  235552. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235553. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235554. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235555. if (firstPresentationTime == 0)
  235556. {
  235557. firstPresentationTime = presentationTime;
  235558. averageTimeOffset = timeDiff;
  235559. }
  235560. else
  235561. {
  235562. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235563. }
  235564. }
  235565. @end
  235566. BEGIN_JUCE_NAMESPACE
  235567. class QTCaptureViewerComp : public NSViewComponent
  235568. {
  235569. public:
  235570. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235571. {
  235572. const ScopedAutoReleasePool pool;
  235573. captureView = [[QTCaptureView alloc] init];
  235574. [captureView setCaptureSession: internal->session];
  235575. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235576. setView (captureView);
  235577. }
  235578. ~QTCaptureViewerComp()
  235579. {
  235580. setView (0);
  235581. [captureView setCaptureSession: nil];
  235582. [captureView release];
  235583. }
  235584. QTCaptureView* captureView;
  235585. };
  235586. CameraDevice::CameraDevice (const String& name_, int index)
  235587. : name (name_)
  235588. {
  235589. isRecording = false;
  235590. internal = new QTCameraDeviceInteral (this, index);
  235591. }
  235592. CameraDevice::~CameraDevice()
  235593. {
  235594. stopRecording();
  235595. delete static_cast <QTCameraDeviceInteral*> (internal);
  235596. internal = 0;
  235597. }
  235598. Component* CameraDevice::createViewerComponent()
  235599. {
  235600. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235601. }
  235602. const String CameraDevice::getFileExtension()
  235603. {
  235604. return ".mov";
  235605. }
  235606. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235607. {
  235608. stopRecording();
  235609. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235610. d->callbackDelegate->firstPresentationTime = 0;
  235611. file.deleteFile();
  235612. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235613. // out wrong, so we'll put some audio in there too..,
  235614. d->addDefaultAudioInput();
  235615. [d->session addOutput: d->fileOutput error: nil];
  235616. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235617. for (;;)
  235618. {
  235619. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235620. if (connection == 0)
  235621. break;
  235622. QTCompressionOptions* options = 0;
  235623. NSString* mediaType = [connection mediaType];
  235624. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235625. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235626. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235627. : @"QTCompressionOptions240SizeH264Video"];
  235628. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235629. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235630. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235631. }
  235632. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235633. isRecording = true;
  235634. }
  235635. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235636. {
  235637. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235638. if (d->callbackDelegate->firstPresentationTime != 0)
  235639. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235640. return Time();
  235641. }
  235642. void CameraDevice::stopRecording()
  235643. {
  235644. if (isRecording)
  235645. {
  235646. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235647. isRecording = false;
  235648. }
  235649. }
  235650. void CameraDevice::addListener (Listener* listenerToAdd)
  235651. {
  235652. if (listenerToAdd != 0)
  235653. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235654. }
  235655. void CameraDevice::removeListener (Listener* listenerToRemove)
  235656. {
  235657. if (listenerToRemove != 0)
  235658. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235659. }
  235660. const StringArray CameraDevice::getAvailableDevices()
  235661. {
  235662. const ScopedAutoReleasePool pool;
  235663. StringArray results;
  235664. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235665. for (int i = 0; i < (int) [devs count]; ++i)
  235666. {
  235667. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235668. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235669. }
  235670. return results;
  235671. }
  235672. CameraDevice* CameraDevice::openDevice (int index,
  235673. int minWidth, int minHeight,
  235674. int maxWidth, int maxHeight)
  235675. {
  235676. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235677. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235678. return d.release();
  235679. return 0;
  235680. }
  235681. #endif
  235682. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235683. #endif
  235684. #endif
  235685. END_JUCE_NAMESPACE
  235686. #endif
  235687. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235688. #endif
  235689. #endif